2
0

TargetInstrInfo.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the TargetInstrInfo class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Target/TargetInstrInfo.h"
  14. #include "llvm/CodeGen/MachineFrameInfo.h"
  15. #include "llvm/CodeGen/MachineInstrBuilder.h"
  16. #include "llvm/CodeGen/MachineMemOperand.h"
  17. #include "llvm/CodeGen/MachineRegisterInfo.h"
  18. #include "llvm/CodeGen/PseudoSourceValue.h"
  19. #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
  20. #include "llvm/CodeGen/StackMaps.h"
  21. #include "llvm/CodeGen/TargetSchedule.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/MC/MCAsmInfo.h"
  24. #include "llvm/MC/MCInstrItineraries.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include "llvm/Target/TargetFrameLowering.h"
  29. #include "llvm/Target/TargetLowering.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/Target/TargetRegisterInfo.h"
  32. #include <cctype>
  33. using namespace llvm;
  34. static cl::opt<bool> DisableHazardRecognizer(
  35. "disable-sched-hazard", cl::Hidden, cl::init(false),
  36. cl::desc("Disable hazard detection during preRA scheduling"));
  37. TargetInstrInfo::~TargetInstrInfo() {
  38. }
  39. const TargetRegisterClass*
  40. TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
  41. const TargetRegisterInfo *TRI,
  42. const MachineFunction &MF) const {
  43. if (OpNum >= MCID.getNumOperands())
  44. return nullptr;
  45. short RegClass = MCID.OpInfo[OpNum].RegClass;
  46. if (MCID.OpInfo[OpNum].isLookupPtrRegClass())
  47. return TRI->getPointerRegClass(MF, RegClass);
  48. // Instructions like INSERT_SUBREG do not have fixed register classes.
  49. if (RegClass < 0)
  50. return nullptr;
  51. // Otherwise just look it up normally.
  52. return TRI->getRegClass(RegClass);
  53. }
  54. /// insertNoop - Insert a noop into the instruction stream at the specified
  55. /// point.
  56. void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
  57. MachineBasicBlock::iterator MI) const {
  58. llvm_unreachable("Target didn't implement insertNoop!");
  59. }
  60. /// Measure the specified inline asm to determine an approximation of its
  61. /// length.
  62. /// Comments (which run till the next SeparatorString or newline) do not
  63. /// count as an instruction.
  64. /// Any other non-whitespace text is considered an instruction, with
  65. /// multiple instructions separated by SeparatorString or newlines.
  66. /// Variable-length instructions are not handled here; this function
  67. /// may be overloaded in the target code to do that.
  68. unsigned TargetInstrInfo::getInlineAsmLength(const char *Str,
  69. const MCAsmInfo &MAI) const {
  70. // Count the number of instructions in the asm.
  71. bool atInsnStart = true;
  72. unsigned Length = 0;
  73. for (; *Str; ++Str) {
  74. if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
  75. strlen(MAI.getSeparatorString())) == 0)
  76. atInsnStart = true;
  77. if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
  78. Length += MAI.getMaxInstLength();
  79. atInsnStart = false;
  80. }
  81. if (atInsnStart && strncmp(Str, MAI.getCommentString(),
  82. strlen(MAI.getCommentString())) == 0)
  83. atInsnStart = false;
  84. }
  85. return Length;
  86. }
  87. /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
  88. /// after it, replacing it with an unconditional branch to NewDest.
  89. void
  90. TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
  91. MachineBasicBlock *NewDest) const {
  92. MachineBasicBlock *MBB = Tail->getParent();
  93. // Remove all the old successors of MBB from the CFG.
  94. while (!MBB->succ_empty())
  95. MBB->removeSuccessor(MBB->succ_begin());
  96. // Remove all the dead instructions from the end of MBB.
  97. MBB->erase(Tail, MBB->end());
  98. // If MBB isn't immediately before MBB, insert a branch to it.
  99. if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
  100. InsertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(),
  101. Tail->getDebugLoc());
  102. MBB->addSuccessor(NewDest);
  103. }
  104. // commuteInstruction - The default implementation of this method just exchanges
  105. // the two operands returned by findCommutedOpIndices.
  106. MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr *MI,
  107. bool NewMI) const {
  108. const MCInstrDesc &MCID = MI->getDesc();
  109. bool HasDef = MCID.getNumDefs();
  110. if (HasDef && !MI->getOperand(0).isReg())
  111. // No idea how to commute this instruction. Target should implement its own.
  112. return nullptr;
  113. unsigned Idx1, Idx2;
  114. if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
  115. assert(MI->isCommutable() && "Precondition violation: MI must be commutable.");
  116. return nullptr;
  117. }
  118. assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
  119. "This only knows how to commute register operands so far");
  120. unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
  121. unsigned Reg1 = MI->getOperand(Idx1).getReg();
  122. unsigned Reg2 = MI->getOperand(Idx2).getReg();
  123. unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0;
  124. unsigned SubReg1 = MI->getOperand(Idx1).getSubReg();
  125. unsigned SubReg2 = MI->getOperand(Idx2).getSubReg();
  126. bool Reg1IsKill = MI->getOperand(Idx1).isKill();
  127. bool Reg2IsKill = MI->getOperand(Idx2).isKill();
  128. bool Reg1IsUndef = MI->getOperand(Idx1).isUndef();
  129. bool Reg2IsUndef = MI->getOperand(Idx2).isUndef();
  130. bool Reg1IsInternal = MI->getOperand(Idx1).isInternalRead();
  131. bool Reg2IsInternal = MI->getOperand(Idx2).isInternalRead();
  132. // If destination is tied to either of the commuted source register, then
  133. // it must be updated.
  134. if (HasDef && Reg0 == Reg1 &&
  135. MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
  136. Reg2IsKill = false;
  137. Reg0 = Reg2;
  138. SubReg0 = SubReg2;
  139. } else if (HasDef && Reg0 == Reg2 &&
  140. MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
  141. Reg1IsKill = false;
  142. Reg0 = Reg1;
  143. SubReg0 = SubReg1;
  144. }
  145. if (NewMI) {
  146. // Create a new instruction.
  147. MachineFunction &MF = *MI->getParent()->getParent();
  148. MI = MF.CloneMachineInstr(MI);
  149. }
  150. if (HasDef) {
  151. MI->getOperand(0).setReg(Reg0);
  152. MI->getOperand(0).setSubReg(SubReg0);
  153. }
  154. MI->getOperand(Idx2).setReg(Reg1);
  155. MI->getOperand(Idx1).setReg(Reg2);
  156. MI->getOperand(Idx2).setSubReg(SubReg1);
  157. MI->getOperand(Idx1).setSubReg(SubReg2);
  158. MI->getOperand(Idx2).setIsKill(Reg1IsKill);
  159. MI->getOperand(Idx1).setIsKill(Reg2IsKill);
  160. MI->getOperand(Idx2).setIsUndef(Reg1IsUndef);
  161. MI->getOperand(Idx1).setIsUndef(Reg2IsUndef);
  162. MI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal);
  163. MI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal);
  164. return MI;
  165. }
  166. /// findCommutedOpIndices - If specified MI is commutable, return the two
  167. /// operand indices that would swap value. Return true if the instruction
  168. /// is not in a form which this routine understands.
  169. bool TargetInstrInfo::findCommutedOpIndices(MachineInstr *MI,
  170. unsigned &SrcOpIdx1,
  171. unsigned &SrcOpIdx2) const {
  172. assert(!MI->isBundle() &&
  173. "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
  174. const MCInstrDesc &MCID = MI->getDesc();
  175. if (!MCID.isCommutable())
  176. return false;
  177. // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
  178. // is not true, then the target must implement this.
  179. SrcOpIdx1 = MCID.getNumDefs();
  180. SrcOpIdx2 = SrcOpIdx1 + 1;
  181. if (!MI->getOperand(SrcOpIdx1).isReg() ||
  182. !MI->getOperand(SrcOpIdx2).isReg())
  183. // No idea.
  184. return false;
  185. return true;
  186. }
  187. bool
  188. TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
  189. if (!MI->isTerminator()) return false;
  190. // Conditional branch is a special case.
  191. if (MI->isBranch() && !MI->isBarrier())
  192. return true;
  193. if (!MI->isPredicable())
  194. return true;
  195. return !isPredicated(MI);
  196. }
  197. bool TargetInstrInfo::PredicateInstruction(
  198. MachineInstr *MI, ArrayRef<MachineOperand> Pred) const {
  199. bool MadeChange = false;
  200. assert(!MI->isBundle() &&
  201. "TargetInstrInfo::PredicateInstruction() can't handle bundles");
  202. const MCInstrDesc &MCID = MI->getDesc();
  203. if (!MI->isPredicable())
  204. return false;
  205. for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
  206. if (MCID.OpInfo[i].isPredicate()) {
  207. MachineOperand &MO = MI->getOperand(i);
  208. if (MO.isReg()) {
  209. MO.setReg(Pred[j].getReg());
  210. MadeChange = true;
  211. } else if (MO.isImm()) {
  212. MO.setImm(Pred[j].getImm());
  213. MadeChange = true;
  214. } else if (MO.isMBB()) {
  215. MO.setMBB(Pred[j].getMBB());
  216. MadeChange = true;
  217. }
  218. ++j;
  219. }
  220. }
  221. return MadeChange;
  222. }
  223. bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr *MI,
  224. const MachineMemOperand *&MMO,
  225. int &FrameIndex) const {
  226. for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
  227. oe = MI->memoperands_end();
  228. o != oe;
  229. ++o) {
  230. if ((*o)->isLoad()) {
  231. if (const FixedStackPseudoSourceValue *Value =
  232. dyn_cast_or_null<FixedStackPseudoSourceValue>(
  233. (*o)->getPseudoValue())) {
  234. FrameIndex = Value->getFrameIndex();
  235. MMO = *o;
  236. return true;
  237. }
  238. }
  239. }
  240. return false;
  241. }
  242. bool TargetInstrInfo::hasStoreToStackSlot(const MachineInstr *MI,
  243. const MachineMemOperand *&MMO,
  244. int &FrameIndex) const {
  245. for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
  246. oe = MI->memoperands_end();
  247. o != oe;
  248. ++o) {
  249. if ((*o)->isStore()) {
  250. if (const FixedStackPseudoSourceValue *Value =
  251. dyn_cast_or_null<FixedStackPseudoSourceValue>(
  252. (*o)->getPseudoValue())) {
  253. FrameIndex = Value->getFrameIndex();
  254. MMO = *o;
  255. return true;
  256. }
  257. }
  258. }
  259. return false;
  260. }
  261. bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
  262. unsigned SubIdx, unsigned &Size,
  263. unsigned &Offset,
  264. const MachineFunction &MF) const {
  265. if (!SubIdx) {
  266. Size = RC->getSize();
  267. Offset = 0;
  268. return true;
  269. }
  270. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  271. unsigned BitSize = TRI->getSubRegIdxSize(SubIdx);
  272. // Convert bit size to byte size to be consistent with
  273. // MCRegisterClass::getSize().
  274. if (BitSize % 8)
  275. return false;
  276. int BitOffset = TRI->getSubRegIdxOffset(SubIdx);
  277. if (BitOffset < 0 || BitOffset % 8)
  278. return false;
  279. Size = BitSize /= 8;
  280. Offset = (unsigned)BitOffset / 8;
  281. assert(RC->getSize() >= (Offset + Size) && "bad subregister range");
  282. if (!MF.getTarget().getDataLayout()->isLittleEndian()) {
  283. Offset = RC->getSize() - (Offset + Size);
  284. }
  285. return true;
  286. }
  287. void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
  288. MachineBasicBlock::iterator I,
  289. unsigned DestReg,
  290. unsigned SubIdx,
  291. const MachineInstr *Orig,
  292. const TargetRegisterInfo &TRI) const {
  293. MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
  294. MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
  295. MBB.insert(I, MI);
  296. }
  297. bool
  298. TargetInstrInfo::produceSameValue(const MachineInstr *MI0,
  299. const MachineInstr *MI1,
  300. const MachineRegisterInfo *MRI) const {
  301. return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
  302. }
  303. MachineInstr *TargetInstrInfo::duplicate(MachineInstr *Orig,
  304. MachineFunction &MF) const {
  305. assert(!Orig->isNotDuplicable() &&
  306. "Instruction cannot be duplicated");
  307. return MF.CloneMachineInstr(Orig);
  308. }
  309. // If the COPY instruction in MI can be folded to a stack operation, return
  310. // the register class to use.
  311. static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
  312. unsigned FoldIdx) {
  313. assert(MI->isCopy() && "MI must be a COPY instruction");
  314. if (MI->getNumOperands() != 2)
  315. return nullptr;
  316. assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
  317. const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
  318. const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
  319. if (FoldOp.getSubReg() || LiveOp.getSubReg())
  320. return nullptr;
  321. unsigned FoldReg = FoldOp.getReg();
  322. unsigned LiveReg = LiveOp.getReg();
  323. assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
  324. "Cannot fold physregs");
  325. const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
  326. const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
  327. if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
  328. return RC->contains(LiveOp.getReg()) ? RC : nullptr;
  329. if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
  330. return RC;
  331. // FIXME: Allow folding when register classes are memory compatible.
  332. return nullptr;
  333. }
  334. void TargetInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
  335. llvm_unreachable("Not a MachO target");
  336. }
  337. bool TargetInstrInfo::canFoldMemoryOperand(const MachineInstr *MI,
  338. ArrayRef<unsigned> Ops) const {
  339. return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
  340. }
  341. static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr *MI,
  342. ArrayRef<unsigned> Ops, int FrameIndex,
  343. const TargetInstrInfo &TII) {
  344. unsigned StartIdx = 0;
  345. switch (MI->getOpcode()) {
  346. case TargetOpcode::STACKMAP:
  347. StartIdx = 2; // Skip ID, nShadowBytes.
  348. break;
  349. case TargetOpcode::PATCHPOINT: {
  350. // For PatchPoint, the call args are not foldable.
  351. PatchPointOpers opers(MI);
  352. StartIdx = opers.getVarIdx();
  353. break;
  354. }
  355. default:
  356. llvm_unreachable("unexpected stackmap opcode");
  357. }
  358. // Return false if any operands requested for folding are not foldable (not
  359. // part of the stackmap's live values).
  360. for (unsigned Op : Ops) {
  361. if (Op < StartIdx)
  362. return nullptr;
  363. }
  364. MachineInstr *NewMI =
  365. MF.CreateMachineInstr(TII.get(MI->getOpcode()), MI->getDebugLoc(), true);
  366. MachineInstrBuilder MIB(MF, NewMI);
  367. // No need to fold return, the meta data, and function arguments
  368. for (unsigned i = 0; i < StartIdx; ++i)
  369. MIB.addOperand(MI->getOperand(i));
  370. for (unsigned i = StartIdx; i < MI->getNumOperands(); ++i) {
  371. MachineOperand &MO = MI->getOperand(i);
  372. if (std::find(Ops.begin(), Ops.end(), i) != Ops.end()) {
  373. unsigned SpillSize;
  374. unsigned SpillOffset;
  375. // Compute the spill slot size and offset.
  376. const TargetRegisterClass *RC =
  377. MF.getRegInfo().getRegClass(MO.getReg());
  378. bool Valid =
  379. TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF);
  380. if (!Valid)
  381. report_fatal_error("cannot spill patchpoint subregister operand");
  382. MIB.addImm(StackMaps::IndirectMemRefOp);
  383. MIB.addImm(SpillSize);
  384. MIB.addFrameIndex(FrameIndex);
  385. MIB.addImm(SpillOffset);
  386. }
  387. else
  388. MIB.addOperand(MO);
  389. }
  390. return NewMI;
  391. }
  392. /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
  393. /// slot into the specified machine instruction for the specified operand(s).
  394. /// If this is possible, a new instruction is returned with the specified
  395. /// operand folded, otherwise NULL is returned. The client is responsible for
  396. /// removing the old instruction and adding the new one in the instruction
  397. /// stream.
  398. MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
  399. ArrayRef<unsigned> Ops,
  400. int FI) const {
  401. unsigned Flags = 0;
  402. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  403. if (MI->getOperand(Ops[i]).isDef())
  404. Flags |= MachineMemOperand::MOStore;
  405. else
  406. Flags |= MachineMemOperand::MOLoad;
  407. MachineBasicBlock *MBB = MI->getParent();
  408. assert(MBB && "foldMemoryOperand needs an inserted instruction");
  409. MachineFunction &MF = *MBB->getParent();
  410. MachineInstr *NewMI = nullptr;
  411. if (MI->getOpcode() == TargetOpcode::STACKMAP ||
  412. MI->getOpcode() == TargetOpcode::PATCHPOINT) {
  413. // Fold stackmap/patchpoint.
  414. NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
  415. if (NewMI)
  416. MBB->insert(MI, NewMI);
  417. } else {
  418. // Ask the target to do the actual folding.
  419. NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, FI);
  420. }
  421. if (NewMI) {
  422. NewMI->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
  423. // Add a memory operand, foldMemoryOperandImpl doesn't do that.
  424. assert((!(Flags & MachineMemOperand::MOStore) ||
  425. NewMI->mayStore()) &&
  426. "Folded a def to a non-store!");
  427. assert((!(Flags & MachineMemOperand::MOLoad) ||
  428. NewMI->mayLoad()) &&
  429. "Folded a use to a non-load!");
  430. const MachineFrameInfo &MFI = *MF.getFrameInfo();
  431. assert(MFI.getObjectOffset(FI) != -1);
  432. MachineMemOperand *MMO =
  433. MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
  434. Flags, MFI.getObjectSize(FI),
  435. MFI.getObjectAlignment(FI));
  436. NewMI->addMemOperand(MF, MMO);
  437. return NewMI;
  438. }
  439. // Straight COPY may fold as load/store.
  440. if (!MI->isCopy() || Ops.size() != 1)
  441. return nullptr;
  442. const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
  443. if (!RC)
  444. return nullptr;
  445. const MachineOperand &MO = MI->getOperand(1-Ops[0]);
  446. MachineBasicBlock::iterator Pos = MI;
  447. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  448. if (Flags == MachineMemOperand::MOStore)
  449. storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
  450. else
  451. loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
  452. return --Pos;
  453. }
  454. /// foldMemoryOperand - Same as the previous version except it allows folding
  455. /// of any load and store from / to any address, not just from a specific
  456. /// stack slot.
  457. MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
  458. ArrayRef<unsigned> Ops,
  459. MachineInstr *LoadMI) const {
  460. assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
  461. #ifndef NDEBUG
  462. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  463. assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
  464. #endif
  465. MachineBasicBlock &MBB = *MI->getParent();
  466. MachineFunction &MF = *MBB.getParent();
  467. // Ask the target to do the actual folding.
  468. MachineInstr *NewMI = nullptr;
  469. int FrameIndex = 0;
  470. if ((MI->getOpcode() == TargetOpcode::STACKMAP ||
  471. MI->getOpcode() == TargetOpcode::PATCHPOINT) &&
  472. isLoadFromStackSlot(LoadMI, FrameIndex)) {
  473. // Fold stackmap/patchpoint.
  474. NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
  475. if (NewMI)
  476. NewMI = MBB.insert(MI, NewMI);
  477. } else {
  478. // Ask the target to do the actual folding.
  479. NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, LoadMI);
  480. }
  481. if (!NewMI) return nullptr;
  482. // Copy the memoperands from the load to the folded instruction.
  483. if (MI->memoperands_empty()) {
  484. NewMI->setMemRefs(LoadMI->memoperands_begin(),
  485. LoadMI->memoperands_end());
  486. }
  487. else {
  488. // Handle the rare case of folding multiple loads.
  489. NewMI->setMemRefs(MI->memoperands_begin(),
  490. MI->memoperands_end());
  491. for (MachineInstr::mmo_iterator I = LoadMI->memoperands_begin(),
  492. E = LoadMI->memoperands_end(); I != E; ++I) {
  493. NewMI->addMemOperand(MF, *I);
  494. }
  495. }
  496. return NewMI;
  497. }
  498. bool TargetInstrInfo::
  499. isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
  500. AliasAnalysis *AA) const {
  501. const MachineFunction &MF = *MI->getParent()->getParent();
  502. const MachineRegisterInfo &MRI = MF.getRegInfo();
  503. // Remat clients assume operand 0 is the defined register.
  504. if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
  505. return false;
  506. unsigned DefReg = MI->getOperand(0).getReg();
  507. // A sub-register definition can only be rematerialized if the instruction
  508. // doesn't read the other parts of the register. Otherwise it is really a
  509. // read-modify-write operation on the full virtual register which cannot be
  510. // moved safely.
  511. if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
  512. MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
  513. return false;
  514. // A load from a fixed stack slot can be rematerialized. This may be
  515. // redundant with subsequent checks, but it's target-independent,
  516. // simple, and a common case.
  517. int FrameIdx = 0;
  518. if (isLoadFromStackSlot(MI, FrameIdx) &&
  519. MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
  520. return true;
  521. // Avoid instructions obviously unsafe for remat.
  522. if (MI->isNotDuplicable() || MI->mayStore() ||
  523. MI->hasUnmodeledSideEffects())
  524. return false;
  525. // Don't remat inline asm. We have no idea how expensive it is
  526. // even if it's side effect free.
  527. if (MI->isInlineAsm())
  528. return false;
  529. // Avoid instructions which load from potentially varying memory.
  530. if (MI->mayLoad() && !MI->isInvariantLoad(AA))
  531. return false;
  532. // If any of the registers accessed are non-constant, conservatively assume
  533. // the instruction is not rematerializable.
  534. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  535. const MachineOperand &MO = MI->getOperand(i);
  536. if (!MO.isReg()) continue;
  537. unsigned Reg = MO.getReg();
  538. if (Reg == 0)
  539. continue;
  540. // Check for a well-behaved physical register.
  541. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  542. if (MO.isUse()) {
  543. // If the physreg has no defs anywhere, it's just an ambient register
  544. // and we can freely move its uses. Alternatively, if it's allocatable,
  545. // it could get allocated to something with a def during allocation.
  546. if (!MRI.isConstantPhysReg(Reg, MF))
  547. return false;
  548. } else {
  549. // A physreg def. We can't remat it.
  550. return false;
  551. }
  552. continue;
  553. }
  554. // Only allow one virtual-register def. There may be multiple defs of the
  555. // same virtual register, though.
  556. if (MO.isDef() && Reg != DefReg)
  557. return false;
  558. // Don't allow any virtual-register uses. Rematting an instruction with
  559. // virtual register uses would length the live ranges of the uses, which
  560. // is not necessarily a good idea, certainly not "trivial".
  561. if (MO.isUse())
  562. return false;
  563. }
  564. // Everything checked out.
  565. return true;
  566. }
  567. int TargetInstrInfo::getSPAdjust(const MachineInstr *MI) const {
  568. const MachineFunction *MF = MI->getParent()->getParent();
  569. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  570. bool StackGrowsDown =
  571. TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  572. unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
  573. unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
  574. if (MI->getOpcode() != FrameSetupOpcode &&
  575. MI->getOpcode() != FrameDestroyOpcode)
  576. return 0;
  577. int SPAdj = MI->getOperand(0).getImm();
  578. if ((!StackGrowsDown && MI->getOpcode() == FrameSetupOpcode) ||
  579. (StackGrowsDown && MI->getOpcode() == FrameDestroyOpcode))
  580. SPAdj = -SPAdj;
  581. return SPAdj;
  582. }
  583. /// isSchedulingBoundary - Test if the given instruction should be
  584. /// considered a scheduling boundary. This primarily includes labels
  585. /// and terminators.
  586. bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
  587. const MachineBasicBlock *MBB,
  588. const MachineFunction &MF) const {
  589. // Terminators and labels can't be scheduled around.
  590. if (MI->isTerminator() || MI->isPosition())
  591. return true;
  592. // Don't attempt to schedule around any instruction that defines
  593. // a stack-oriented pointer, as it's unlikely to be profitable. This
  594. // saves compile time, because it doesn't require every single
  595. // stack slot reference to depend on the instruction that does the
  596. // modification.
  597. const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
  598. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  599. if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI))
  600. return true;
  601. return false;
  602. }
  603. // Provide a global flag for disabling the PreRA hazard recognizer that targets
  604. // may choose to honor.
  605. bool TargetInstrInfo::usePreRAHazardRecognizer() const {
  606. return !DisableHazardRecognizer;
  607. }
  608. // Default implementation of CreateTargetRAHazardRecognizer.
  609. ScheduleHazardRecognizer *TargetInstrInfo::
  610. CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
  611. const ScheduleDAG *DAG) const {
  612. // Dummy hazard recognizer allows all instructions to issue.
  613. return new ScheduleHazardRecognizer();
  614. }
  615. // Default implementation of CreateTargetMIHazardRecognizer.
  616. ScheduleHazardRecognizer *TargetInstrInfo::
  617. CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
  618. const ScheduleDAG *DAG) const {
  619. return (ScheduleHazardRecognizer *)
  620. new ScoreboardHazardRecognizer(II, DAG, "misched");
  621. }
  622. // Default implementation of CreateTargetPostRAHazardRecognizer.
  623. ScheduleHazardRecognizer *TargetInstrInfo::
  624. CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
  625. const ScheduleDAG *DAG) const {
  626. return (ScheduleHazardRecognizer *)
  627. new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
  628. }
  629. //===----------------------------------------------------------------------===//
  630. // SelectionDAG latency interface.
  631. //===----------------------------------------------------------------------===//
  632. int
  633. TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  634. SDNode *DefNode, unsigned DefIdx,
  635. SDNode *UseNode, unsigned UseIdx) const {
  636. if (!ItinData || ItinData->isEmpty())
  637. return -1;
  638. if (!DefNode->isMachineOpcode())
  639. return -1;
  640. unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
  641. if (!UseNode->isMachineOpcode())
  642. return ItinData->getOperandCycle(DefClass, DefIdx);
  643. unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
  644. return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
  645. }
  646. int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
  647. SDNode *N) const {
  648. if (!ItinData || ItinData->isEmpty())
  649. return 1;
  650. if (!N->isMachineOpcode())
  651. return 1;
  652. return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
  653. }
  654. //===----------------------------------------------------------------------===//
  655. // MachineInstr latency interface.
  656. //===----------------------------------------------------------------------===//
  657. unsigned
  658. TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
  659. const MachineInstr *MI) const {
  660. if (!ItinData || ItinData->isEmpty())
  661. return 1;
  662. unsigned Class = MI->getDesc().getSchedClass();
  663. int UOps = ItinData->Itineraries[Class].NumMicroOps;
  664. if (UOps >= 0)
  665. return UOps;
  666. // The # of u-ops is dynamically determined. The specific target should
  667. // override this function to return the right number.
  668. return 1;
  669. }
  670. /// Return the default expected latency for a def based on it's opcode.
  671. unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
  672. const MachineInstr *DefMI) const {
  673. if (DefMI->isTransient())
  674. return 0;
  675. if (DefMI->mayLoad())
  676. return SchedModel.LoadLatency;
  677. if (isHighLatencyDef(DefMI->getOpcode()))
  678. return SchedModel.HighLatency;
  679. return 1;
  680. }
  681. unsigned TargetInstrInfo::getPredicationCost(const MachineInstr *) const {
  682. return 0;
  683. }
  684. unsigned TargetInstrInfo::
  685. getInstrLatency(const InstrItineraryData *ItinData,
  686. const MachineInstr *MI,
  687. unsigned *PredCost) const {
  688. // Default to one cycle for no itinerary. However, an "empty" itinerary may
  689. // still have a MinLatency property, which getStageLatency checks.
  690. if (!ItinData)
  691. return MI->mayLoad() ? 2 : 1;
  692. return ItinData->getStageLatency(MI->getDesc().getSchedClass());
  693. }
  694. bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
  695. const MachineInstr *DefMI,
  696. unsigned DefIdx) const {
  697. const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
  698. if (!ItinData || ItinData->isEmpty())
  699. return false;
  700. unsigned DefClass = DefMI->getDesc().getSchedClass();
  701. int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
  702. return (DefCycle != -1 && DefCycle <= 1);
  703. }
  704. /// Both DefMI and UseMI must be valid. By default, call directly to the
  705. /// itinerary. This may be overriden by the target.
  706. int TargetInstrInfo::
  707. getOperandLatency(const InstrItineraryData *ItinData,
  708. const MachineInstr *DefMI, unsigned DefIdx,
  709. const MachineInstr *UseMI, unsigned UseIdx) const {
  710. unsigned DefClass = DefMI->getDesc().getSchedClass();
  711. unsigned UseClass = UseMI->getDesc().getSchedClass();
  712. return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
  713. }
  714. /// If we can determine the operand latency from the def only, without itinerary
  715. /// lookup, do so. Otherwise return -1.
  716. int TargetInstrInfo::computeDefOperandLatency(
  717. const InstrItineraryData *ItinData,
  718. const MachineInstr *DefMI) const {
  719. // Let the target hook getInstrLatency handle missing itineraries.
  720. if (!ItinData)
  721. return getInstrLatency(ItinData, DefMI);
  722. if(ItinData->isEmpty())
  723. return defaultDefLatency(ItinData->SchedModel, DefMI);
  724. // ...operand lookup required
  725. return -1;
  726. }
  727. /// computeOperandLatency - Compute and return the latency of the given data
  728. /// dependent def and use when the operand indices are already known. UseMI may
  729. /// be NULL for an unknown use.
  730. ///
  731. /// FindMin may be set to get the minimum vs. expected latency. Minimum
  732. /// latency is used for scheduling groups, while expected latency is for
  733. /// instruction cost and critical path.
  734. ///
  735. /// Depending on the subtarget's itinerary properties, this may or may not need
  736. /// to call getOperandLatency(). For most subtargets, we don't need DefIdx or
  737. /// UseIdx to compute min latency.
  738. unsigned TargetInstrInfo::
  739. computeOperandLatency(const InstrItineraryData *ItinData,
  740. const MachineInstr *DefMI, unsigned DefIdx,
  741. const MachineInstr *UseMI, unsigned UseIdx) const {
  742. int DefLatency = computeDefOperandLatency(ItinData, DefMI);
  743. if (DefLatency >= 0)
  744. return DefLatency;
  745. assert(ItinData && !ItinData->isEmpty() && "computeDefOperandLatency fail");
  746. int OperLatency = 0;
  747. if (UseMI)
  748. OperLatency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
  749. else {
  750. unsigned DefClass = DefMI->getDesc().getSchedClass();
  751. OperLatency = ItinData->getOperandCycle(DefClass, DefIdx);
  752. }
  753. if (OperLatency >= 0)
  754. return OperLatency;
  755. // No operand latency was found.
  756. unsigned InstrLatency = getInstrLatency(ItinData, DefMI);
  757. // Expected latency is the max of the stage latency and itinerary props.
  758. InstrLatency = std::max(InstrLatency,
  759. defaultDefLatency(ItinData->SchedModel, DefMI));
  760. return InstrLatency;
  761. }
  762. bool TargetInstrInfo::getRegSequenceInputs(
  763. const MachineInstr &MI, unsigned DefIdx,
  764. SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
  765. assert((MI.isRegSequence() ||
  766. MI.isRegSequenceLike()) && "Instruction do not have the proper type");
  767. if (!MI.isRegSequence())
  768. return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
  769. // We are looking at:
  770. // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
  771. assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
  772. for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
  773. OpIdx += 2) {
  774. const MachineOperand &MOReg = MI.getOperand(OpIdx);
  775. const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
  776. assert(MOSubIdx.isImm() &&
  777. "One of the subindex of the reg_sequence is not an immediate");
  778. // Record Reg:SubReg, SubIdx.
  779. InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
  780. (unsigned)MOSubIdx.getImm()));
  781. }
  782. return true;
  783. }
  784. bool TargetInstrInfo::getExtractSubregInputs(
  785. const MachineInstr &MI, unsigned DefIdx,
  786. RegSubRegPairAndIdx &InputReg) const {
  787. assert((MI.isExtractSubreg() ||
  788. MI.isExtractSubregLike()) && "Instruction do not have the proper type");
  789. if (!MI.isExtractSubreg())
  790. return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
  791. // We are looking at:
  792. // Def = EXTRACT_SUBREG v0.sub1, sub0.
  793. assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
  794. const MachineOperand &MOReg = MI.getOperand(1);
  795. const MachineOperand &MOSubIdx = MI.getOperand(2);
  796. assert(MOSubIdx.isImm() &&
  797. "The subindex of the extract_subreg is not an immediate");
  798. InputReg.Reg = MOReg.getReg();
  799. InputReg.SubReg = MOReg.getSubReg();
  800. InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
  801. return true;
  802. }
  803. bool TargetInstrInfo::getInsertSubregInputs(
  804. const MachineInstr &MI, unsigned DefIdx,
  805. RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
  806. assert((MI.isInsertSubreg() ||
  807. MI.isInsertSubregLike()) && "Instruction do not have the proper type");
  808. if (!MI.isInsertSubreg())
  809. return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
  810. // We are looking at:
  811. // Def = INSERT_SEQUENCE v0, v1, sub0.
  812. assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
  813. const MachineOperand &MOBaseReg = MI.getOperand(1);
  814. const MachineOperand &MOInsertedReg = MI.getOperand(2);
  815. const MachineOperand &MOSubIdx = MI.getOperand(3);
  816. assert(MOSubIdx.isImm() &&
  817. "One of the subindex of the reg_sequence is not an immediate");
  818. BaseReg.Reg = MOBaseReg.getReg();
  819. BaseReg.SubReg = MOBaseReg.getSubReg();
  820. InsertedReg.Reg = MOInsertedReg.getReg();
  821. InsertedReg.SubReg = MOInsertedReg.getSubReg();
  822. InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
  823. return true;
  824. }