TwoAddressInstructionPass.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  1. //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
  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 TwoAddress instruction pass which is used
  11. // by most register allocators. Two-Address instructions are rewritten
  12. // from:
  13. //
  14. // A = B op C
  15. //
  16. // to:
  17. //
  18. // A = B
  19. // A op= C
  20. //
  21. // Note that if a register allocator chooses to use this pass, that it
  22. // has to be capable of handling the non-SSA nature of these rewritten
  23. // virtual registers.
  24. //
  25. // It is also worth noting that the duplicate operand of the two
  26. // address instruction is removed.
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #define DEBUG_TYPE "twoaddrinstr"
  30. #include "llvm/CodeGen/Passes.h"
  31. #include "llvm/ADT/BitVector.h"
  32. #include "llvm/ADT/DenseMap.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/ADT/SmallSet.h"
  35. #include "llvm/ADT/Statistic.h"
  36. #include "llvm/Analysis/AliasAnalysis.h"
  37. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  38. #include "llvm/CodeGen/LiveVariables.h"
  39. #include "llvm/CodeGen/MachineFunctionPass.h"
  40. #include "llvm/CodeGen/MachineInstr.h"
  41. #include "llvm/CodeGen/MachineInstrBuilder.h"
  42. #include "llvm/CodeGen/MachineRegisterInfo.h"
  43. #include "llvm/IR/Function.h"
  44. #include "llvm/MC/MCInstrItineraries.h"
  45. #include "llvm/Support/CommandLine.h"
  46. #include "llvm/Support/Debug.h"
  47. #include "llvm/Support/ErrorHandling.h"
  48. #include "llvm/Target/TargetInstrInfo.h"
  49. #include "llvm/Target/TargetMachine.h"
  50. #include "llvm/Target/TargetRegisterInfo.h"
  51. using namespace llvm;
  52. STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
  53. STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
  54. STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
  55. STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
  56. STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
  57. STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
  58. STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
  59. // Temporary flag to disable rescheduling.
  60. static cl::opt<bool>
  61. EnableRescheduling("twoaddr-reschedule",
  62. cl::desc("Coalesce copies by rescheduling (default=true)"),
  63. cl::init(true), cl::Hidden);
  64. namespace {
  65. class TwoAddressInstructionPass : public MachineFunctionPass {
  66. MachineFunction *MF;
  67. const TargetInstrInfo *TII;
  68. const TargetRegisterInfo *TRI;
  69. const InstrItineraryData *InstrItins;
  70. MachineRegisterInfo *MRI;
  71. LiveVariables *LV;
  72. LiveIntervals *LIS;
  73. AliasAnalysis *AA;
  74. CodeGenOpt::Level OptLevel;
  75. // The current basic block being processed.
  76. MachineBasicBlock *MBB;
  77. // DistanceMap - Keep track the distance of a MI from the start of the
  78. // current basic block.
  79. DenseMap<MachineInstr*, unsigned> DistanceMap;
  80. // Set of already processed instructions in the current block.
  81. SmallPtrSet<MachineInstr*, 8> Processed;
  82. // SrcRegMap - A map from virtual registers to physical registers which are
  83. // likely targets to be coalesced to due to copies from physical registers to
  84. // virtual registers. e.g. v1024 = move r0.
  85. DenseMap<unsigned, unsigned> SrcRegMap;
  86. // DstRegMap - A map from virtual registers to physical registers which are
  87. // likely targets to be coalesced to due to copies to physical registers from
  88. // virtual registers. e.g. r1 = move v1024.
  89. DenseMap<unsigned, unsigned> DstRegMap;
  90. bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
  91. MachineBasicBlock::iterator OldPos);
  92. bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
  93. bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
  94. MachineInstr *MI, unsigned Dist);
  95. bool commuteInstruction(MachineBasicBlock::iterator &mi,
  96. unsigned RegB, unsigned RegC, unsigned Dist);
  97. bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
  98. bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
  99. MachineBasicBlock::iterator &nmi,
  100. unsigned RegA, unsigned RegB, unsigned Dist);
  101. bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
  102. bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
  103. MachineBasicBlock::iterator &nmi,
  104. unsigned Reg);
  105. bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
  106. MachineBasicBlock::iterator &nmi,
  107. unsigned Reg);
  108. bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
  109. MachineBasicBlock::iterator &nmi,
  110. unsigned SrcIdx, unsigned DstIdx,
  111. unsigned Dist, bool shouldOnlyCommute);
  112. void scanUses(unsigned DstReg);
  113. void processCopy(MachineInstr *MI);
  114. typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
  115. typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
  116. bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
  117. void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
  118. void eliminateRegSequence(MachineBasicBlock::iterator&);
  119. public:
  120. static char ID; // Pass identification, replacement for typeid
  121. TwoAddressInstructionPass() : MachineFunctionPass(ID) {
  122. initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
  123. }
  124. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  125. AU.setPreservesCFG();
  126. AU.addRequired<AliasAnalysis>();
  127. AU.addPreserved<LiveVariables>();
  128. AU.addPreserved<SlotIndexes>();
  129. AU.addPreserved<LiveIntervals>();
  130. AU.addPreservedID(MachineLoopInfoID);
  131. AU.addPreservedID(MachineDominatorsID);
  132. MachineFunctionPass::getAnalysisUsage(AU);
  133. }
  134. /// runOnMachineFunction - Pass entry point.
  135. bool runOnMachineFunction(MachineFunction&);
  136. };
  137. } // end anonymous namespace
  138. char TwoAddressInstructionPass::ID = 0;
  139. INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
  140. "Two-Address instruction pass", false, false)
  141. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  142. INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
  143. "Two-Address instruction pass", false, false)
  144. char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
  145. static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
  146. /// sink3AddrInstruction - A two-address instruction has been converted to a
  147. /// three-address instruction to avoid clobbering a register. Try to sink it
  148. /// past the instruction that would kill the above mentioned register to reduce
  149. /// register pressure.
  150. bool TwoAddressInstructionPass::
  151. sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
  152. MachineBasicBlock::iterator OldPos) {
  153. // FIXME: Shouldn't we be trying to do this before we three-addressify the
  154. // instruction? After this transformation is done, we no longer need
  155. // the instruction to be in three-address form.
  156. // Check if it's safe to move this instruction.
  157. bool SeenStore = true; // Be conservative.
  158. if (!MI->isSafeToMove(TII, AA, SeenStore))
  159. return false;
  160. unsigned DefReg = 0;
  161. SmallSet<unsigned, 4> UseRegs;
  162. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  163. const MachineOperand &MO = MI->getOperand(i);
  164. if (!MO.isReg())
  165. continue;
  166. unsigned MOReg = MO.getReg();
  167. if (!MOReg)
  168. continue;
  169. if (MO.isUse() && MOReg != SavedReg)
  170. UseRegs.insert(MO.getReg());
  171. if (!MO.isDef())
  172. continue;
  173. if (MO.isImplicit())
  174. // Don't try to move it if it implicitly defines a register.
  175. return false;
  176. if (DefReg)
  177. // For now, don't move any instructions that define multiple registers.
  178. return false;
  179. DefReg = MO.getReg();
  180. }
  181. // Find the instruction that kills SavedReg.
  182. MachineInstr *KillMI = NULL;
  183. if (LIS) {
  184. LiveInterval &LI = LIS->getInterval(SavedReg);
  185. assert(LI.end() != LI.begin() &&
  186. "Reg should not have empty live interval.");
  187. SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
  188. LiveInterval::const_iterator I = LI.find(MBBEndIdx);
  189. if (I != LI.end() && I->start < MBBEndIdx)
  190. return false;
  191. --I;
  192. KillMI = LIS->getInstructionFromIndex(I->end);
  193. }
  194. if (!KillMI) {
  195. for (MachineRegisterInfo::use_nodbg_iterator
  196. UI = MRI->use_nodbg_begin(SavedReg),
  197. UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
  198. MachineOperand &UseMO = UI.getOperand();
  199. if (!UseMO.isKill())
  200. continue;
  201. KillMI = UseMO.getParent();
  202. break;
  203. }
  204. }
  205. // If we find the instruction that kills SavedReg, and it is in an
  206. // appropriate location, we can try to sink the current instruction
  207. // past it.
  208. if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
  209. KillMI == OldPos || KillMI->isTerminator())
  210. return false;
  211. // If any of the definitions are used by another instruction between the
  212. // position and the kill use, then it's not safe to sink it.
  213. //
  214. // FIXME: This can be sped up if there is an easy way to query whether an
  215. // instruction is before or after another instruction. Then we can use
  216. // MachineRegisterInfo def / use instead.
  217. MachineOperand *KillMO = NULL;
  218. MachineBasicBlock::iterator KillPos = KillMI;
  219. ++KillPos;
  220. unsigned NumVisited = 0;
  221. for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
  222. MachineInstr *OtherMI = I;
  223. // DBG_VALUE cannot be counted against the limit.
  224. if (OtherMI->isDebugValue())
  225. continue;
  226. if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
  227. return false;
  228. ++NumVisited;
  229. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  230. MachineOperand &MO = OtherMI->getOperand(i);
  231. if (!MO.isReg())
  232. continue;
  233. unsigned MOReg = MO.getReg();
  234. if (!MOReg)
  235. continue;
  236. if (DefReg == MOReg)
  237. return false;
  238. if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
  239. if (OtherMI == KillMI && MOReg == SavedReg)
  240. // Save the operand that kills the register. We want to unset the kill
  241. // marker if we can sink MI past it.
  242. KillMO = &MO;
  243. else if (UseRegs.count(MOReg))
  244. // One of the uses is killed before the destination.
  245. return false;
  246. }
  247. }
  248. }
  249. assert(KillMO && "Didn't find kill");
  250. if (!LIS) {
  251. // Update kill and LV information.
  252. KillMO->setIsKill(false);
  253. KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
  254. KillMO->setIsKill(true);
  255. if (LV)
  256. LV->replaceKillInstruction(SavedReg, KillMI, MI);
  257. }
  258. // Move instruction to its destination.
  259. MBB->remove(MI);
  260. MBB->insert(KillPos, MI);
  261. if (LIS)
  262. LIS->handleMove(MI);
  263. ++Num3AddrSunk;
  264. return true;
  265. }
  266. /// noUseAfterLastDef - Return true if there are no intervening uses between the
  267. /// last instruction in the MBB that defines the specified register and the
  268. /// two-address instruction which is being processed. It also returns the last
  269. /// def location by reference
  270. bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
  271. unsigned &LastDef) {
  272. LastDef = 0;
  273. unsigned LastUse = Dist;
  274. for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
  275. E = MRI->reg_end(); I != E; ++I) {
  276. MachineOperand &MO = I.getOperand();
  277. MachineInstr *MI = MO.getParent();
  278. if (MI->getParent() != MBB || MI->isDebugValue())
  279. continue;
  280. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  281. if (DI == DistanceMap.end())
  282. continue;
  283. if (MO.isUse() && DI->second < LastUse)
  284. LastUse = DI->second;
  285. if (MO.isDef() && DI->second > LastDef)
  286. LastDef = DI->second;
  287. }
  288. return !(LastUse > LastDef && LastUse < Dist);
  289. }
  290. /// isCopyToReg - Return true if the specified MI is a copy instruction or
  291. /// a extract_subreg instruction. It also returns the source and destination
  292. /// registers and whether they are physical registers by reference.
  293. static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
  294. unsigned &SrcReg, unsigned &DstReg,
  295. bool &IsSrcPhys, bool &IsDstPhys) {
  296. SrcReg = 0;
  297. DstReg = 0;
  298. if (MI.isCopy()) {
  299. DstReg = MI.getOperand(0).getReg();
  300. SrcReg = MI.getOperand(1).getReg();
  301. } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
  302. DstReg = MI.getOperand(0).getReg();
  303. SrcReg = MI.getOperand(2).getReg();
  304. } else
  305. return false;
  306. IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
  307. IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
  308. return true;
  309. }
  310. /// isPLainlyKilled - Test if the given register value, which is used by the
  311. // given instruction, is killed by the given instruction.
  312. static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
  313. LiveIntervals *LIS) {
  314. if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
  315. !LIS->isNotInMIMap(MI)) {
  316. // FIXME: Sometimes tryInstructionTransform() will add instructions and
  317. // test whether they can be folded before keeping them. In this case it
  318. // sets a kill before recursively calling tryInstructionTransform() again.
  319. // If there is no interval available, we assume that this instruction is
  320. // one of those. A kill flag is manually inserted on the operand so the
  321. // check below will handle it.
  322. LiveInterval &LI = LIS->getInterval(Reg);
  323. // This is to match the kill flag version where undefs don't have kill
  324. // flags.
  325. if (!LI.hasAtLeastOneValue())
  326. return false;
  327. SlotIndex useIdx = LIS->getInstructionIndex(MI);
  328. LiveInterval::const_iterator I = LI.find(useIdx);
  329. assert(I != LI.end() && "Reg must be live-in to use.");
  330. return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
  331. }
  332. return MI->killsRegister(Reg);
  333. }
  334. /// isKilled - Test if the given register value, which is used by the given
  335. /// instruction, is killed by the given instruction. This looks through
  336. /// coalescable copies to see if the original value is potentially not killed.
  337. ///
  338. /// For example, in this code:
  339. ///
  340. /// %reg1034 = copy %reg1024
  341. /// %reg1035 = copy %reg1025<kill>
  342. /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
  343. ///
  344. /// %reg1034 is not considered to be killed, since it is copied from a
  345. /// register which is not killed. Treating it as not killed lets the
  346. /// normal heuristics commute the (two-address) add, which lets
  347. /// coalescing eliminate the extra copy.
  348. ///
  349. /// If allowFalsePositives is true then likely kills are treated as kills even
  350. /// if it can't be proven that they are kills.
  351. static bool isKilled(MachineInstr &MI, unsigned Reg,
  352. const MachineRegisterInfo *MRI,
  353. const TargetInstrInfo *TII,
  354. LiveIntervals *LIS,
  355. bool allowFalsePositives) {
  356. MachineInstr *DefMI = &MI;
  357. for (;;) {
  358. // All uses of physical registers are likely to be kills.
  359. if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
  360. (allowFalsePositives || MRI->hasOneUse(Reg)))
  361. return true;
  362. if (!isPlainlyKilled(DefMI, Reg, LIS))
  363. return false;
  364. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  365. return true;
  366. MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
  367. // If there are multiple defs, we can't do a simple analysis, so just
  368. // go with what the kill flag says.
  369. if (std::next(Begin) != MRI->def_end())
  370. return true;
  371. DefMI = &*Begin;
  372. bool IsSrcPhys, IsDstPhys;
  373. unsigned SrcReg, DstReg;
  374. // If the def is something other than a copy, then it isn't going to
  375. // be coalesced, so follow the kill flag.
  376. if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
  377. return true;
  378. Reg = SrcReg;
  379. }
  380. }
  381. /// isTwoAddrUse - Return true if the specified MI uses the specified register
  382. /// as a two-address use. If so, return the destination register by reference.
  383. static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
  384. for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
  385. const MachineOperand &MO = MI.getOperand(i);
  386. if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
  387. continue;
  388. unsigned ti;
  389. if (MI.isRegTiedToDefOperand(i, &ti)) {
  390. DstReg = MI.getOperand(ti).getReg();
  391. return true;
  392. }
  393. }
  394. return false;
  395. }
  396. /// findOnlyInterestingUse - Given a register, if has a single in-basic block
  397. /// use, return the use instruction if it's a copy or a two-address use.
  398. static
  399. MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
  400. MachineRegisterInfo *MRI,
  401. const TargetInstrInfo *TII,
  402. bool &IsCopy,
  403. unsigned &DstReg, bool &IsDstPhys) {
  404. if (!MRI->hasOneNonDBGUse(Reg))
  405. // None or more than one use.
  406. return 0;
  407. MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
  408. if (UseMI.getParent() != MBB)
  409. return 0;
  410. unsigned SrcReg;
  411. bool IsSrcPhys;
  412. if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
  413. IsCopy = true;
  414. return &UseMI;
  415. }
  416. IsDstPhys = false;
  417. if (isTwoAddrUse(UseMI, Reg, DstReg)) {
  418. IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
  419. return &UseMI;
  420. }
  421. return 0;
  422. }
  423. /// getMappedReg - Return the physical register the specified virtual register
  424. /// might be mapped to.
  425. static unsigned
  426. getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
  427. while (TargetRegisterInfo::isVirtualRegister(Reg)) {
  428. DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
  429. if (SI == RegMap.end())
  430. return 0;
  431. Reg = SI->second;
  432. }
  433. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  434. return Reg;
  435. return 0;
  436. }
  437. /// regsAreCompatible - Return true if the two registers are equal or aliased.
  438. ///
  439. static bool
  440. regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
  441. if (RegA == RegB)
  442. return true;
  443. if (!RegA || !RegB)
  444. return false;
  445. return TRI->regsOverlap(RegA, RegB);
  446. }
  447. /// isProfitableToCommute - Return true if it's potentially profitable to commute
  448. /// the two-address instruction that's being processed.
  449. bool
  450. TwoAddressInstructionPass::
  451. isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
  452. MachineInstr *MI, unsigned Dist) {
  453. if (OptLevel == CodeGenOpt::None)
  454. return false;
  455. // Determine if it's profitable to commute this two address instruction. In
  456. // general, we want no uses between this instruction and the definition of
  457. // the two-address register.
  458. // e.g.
  459. // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
  460. // %reg1029<def> = MOV8rr %reg1028
  461. // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
  462. // insert => %reg1030<def> = MOV8rr %reg1028
  463. // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
  464. // In this case, it might not be possible to coalesce the second MOV8rr
  465. // instruction if the first one is coalesced. So it would be profitable to
  466. // commute it:
  467. // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
  468. // %reg1029<def> = MOV8rr %reg1028
  469. // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
  470. // insert => %reg1030<def> = MOV8rr %reg1029
  471. // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
  472. if (!isPlainlyKilled(MI, regC, LIS))
  473. return false;
  474. // Ok, we have something like:
  475. // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
  476. // let's see if it's worth commuting it.
  477. // Look for situations like this:
  478. // %reg1024<def> = MOV r1
  479. // %reg1025<def> = MOV r0
  480. // %reg1026<def> = ADD %reg1024, %reg1025
  481. // r0 = MOV %reg1026
  482. // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
  483. unsigned ToRegA = getMappedReg(regA, DstRegMap);
  484. if (ToRegA) {
  485. unsigned FromRegB = getMappedReg(regB, SrcRegMap);
  486. unsigned FromRegC = getMappedReg(regC, SrcRegMap);
  487. bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
  488. bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
  489. if (BComp != CComp)
  490. return !BComp && CComp;
  491. }
  492. // If there is a use of regC between its last def (could be livein) and this
  493. // instruction, then bail.
  494. unsigned LastDefC = 0;
  495. if (!noUseAfterLastDef(regC, Dist, LastDefC))
  496. return false;
  497. // If there is a use of regB between its last def (could be livein) and this
  498. // instruction, then go ahead and make this transformation.
  499. unsigned LastDefB = 0;
  500. if (!noUseAfterLastDef(regB, Dist, LastDefB))
  501. return true;
  502. // Since there are no intervening uses for both registers, then commute
  503. // if the def of regC is closer. Its live interval is shorter.
  504. return LastDefB && LastDefC && LastDefC > LastDefB;
  505. }
  506. /// commuteInstruction - Commute a two-address instruction and update the basic
  507. /// block, distance map, and live variables if needed. Return true if it is
  508. /// successful.
  509. bool TwoAddressInstructionPass::
  510. commuteInstruction(MachineBasicBlock::iterator &mi,
  511. unsigned RegB, unsigned RegC, unsigned Dist) {
  512. MachineInstr *MI = mi;
  513. DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
  514. MachineInstr *NewMI = TII->commuteInstruction(MI);
  515. if (NewMI == 0) {
  516. DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
  517. return false;
  518. }
  519. DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
  520. assert(NewMI == MI &&
  521. "TargetInstrInfo::commuteInstruction() should not return a new "
  522. "instruction unless it was requested.");
  523. // Update source register map.
  524. unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
  525. if (FromRegC) {
  526. unsigned RegA = MI->getOperand(0).getReg();
  527. SrcRegMap[RegA] = FromRegC;
  528. }
  529. return true;
  530. }
  531. /// isProfitableToConv3Addr - Return true if it is profitable to convert the
  532. /// given 2-address instruction to a 3-address one.
  533. bool
  534. TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
  535. // Look for situations like this:
  536. // %reg1024<def> = MOV r1
  537. // %reg1025<def> = MOV r0
  538. // %reg1026<def> = ADD %reg1024, %reg1025
  539. // r2 = MOV %reg1026
  540. // Turn ADD into a 3-address instruction to avoid a copy.
  541. unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
  542. if (!FromRegB)
  543. return false;
  544. unsigned ToRegA = getMappedReg(RegA, DstRegMap);
  545. return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
  546. }
  547. /// convertInstTo3Addr - Convert the specified two-address instruction into a
  548. /// three address one. Return true if this transformation was successful.
  549. bool
  550. TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
  551. MachineBasicBlock::iterator &nmi,
  552. unsigned RegA, unsigned RegB,
  553. unsigned Dist) {
  554. // FIXME: Why does convertToThreeAddress() need an iterator reference?
  555. MachineFunction::iterator MFI = MBB;
  556. MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
  557. assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
  558. if (!NewMI)
  559. return false;
  560. DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
  561. DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
  562. bool Sunk = false;
  563. if (LIS)
  564. LIS->ReplaceMachineInstrInMaps(mi, NewMI);
  565. if (NewMI->findRegisterUseOperand(RegB, false, TRI))
  566. // FIXME: Temporary workaround. If the new instruction doesn't
  567. // uses RegB, convertToThreeAddress must have created more
  568. // then one instruction.
  569. Sunk = sink3AddrInstruction(NewMI, RegB, mi);
  570. MBB->erase(mi); // Nuke the old inst.
  571. if (!Sunk) {
  572. DistanceMap.insert(std::make_pair(NewMI, Dist));
  573. mi = NewMI;
  574. nmi = std::next(mi);
  575. }
  576. // Update source and destination register maps.
  577. SrcRegMap.erase(RegA);
  578. DstRegMap.erase(RegB);
  579. return true;
  580. }
  581. /// scanUses - Scan forward recursively for only uses, update maps if the use
  582. /// is a copy or a two-address instruction.
  583. void
  584. TwoAddressInstructionPass::scanUses(unsigned DstReg) {
  585. SmallVector<unsigned, 4> VirtRegPairs;
  586. bool IsDstPhys;
  587. bool IsCopy = false;
  588. unsigned NewReg = 0;
  589. unsigned Reg = DstReg;
  590. while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
  591. NewReg, IsDstPhys)) {
  592. if (IsCopy && !Processed.insert(UseMI))
  593. break;
  594. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
  595. if (DI != DistanceMap.end())
  596. // Earlier in the same MBB.Reached via a back edge.
  597. break;
  598. if (IsDstPhys) {
  599. VirtRegPairs.push_back(NewReg);
  600. break;
  601. }
  602. bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
  603. if (!isNew)
  604. assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
  605. VirtRegPairs.push_back(NewReg);
  606. Reg = NewReg;
  607. }
  608. if (!VirtRegPairs.empty()) {
  609. unsigned ToReg = VirtRegPairs.back();
  610. VirtRegPairs.pop_back();
  611. while (!VirtRegPairs.empty()) {
  612. unsigned FromReg = VirtRegPairs.back();
  613. VirtRegPairs.pop_back();
  614. bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
  615. if (!isNew)
  616. assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
  617. ToReg = FromReg;
  618. }
  619. bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
  620. if (!isNew)
  621. assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
  622. }
  623. }
  624. /// processCopy - If the specified instruction is not yet processed, process it
  625. /// if it's a copy. For a copy instruction, we find the physical registers the
  626. /// source and destination registers might be mapped to. These are kept in
  627. /// point-to maps used to determine future optimizations. e.g.
  628. /// v1024 = mov r0
  629. /// v1025 = mov r1
  630. /// v1026 = add v1024, v1025
  631. /// r1 = mov r1026
  632. /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
  633. /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
  634. /// potentially joined with r1 on the output side. It's worthwhile to commute
  635. /// 'add' to eliminate a copy.
  636. void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
  637. if (Processed.count(MI))
  638. return;
  639. bool IsSrcPhys, IsDstPhys;
  640. unsigned SrcReg, DstReg;
  641. if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
  642. return;
  643. if (IsDstPhys && !IsSrcPhys)
  644. DstRegMap.insert(std::make_pair(SrcReg, DstReg));
  645. else if (!IsDstPhys && IsSrcPhys) {
  646. bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
  647. if (!isNew)
  648. assert(SrcRegMap[DstReg] == SrcReg &&
  649. "Can't map to two src physical registers!");
  650. scanUses(DstReg);
  651. }
  652. Processed.insert(MI);
  653. return;
  654. }
  655. /// rescheduleMIBelowKill - If there is one more local instruction that reads
  656. /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
  657. /// instruction in order to eliminate the need for the copy.
  658. bool TwoAddressInstructionPass::
  659. rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
  660. MachineBasicBlock::iterator &nmi,
  661. unsigned Reg) {
  662. // Bail immediately if we don't have LV or LIS available. We use them to find
  663. // kills efficiently.
  664. if (!LV && !LIS)
  665. return false;
  666. MachineInstr *MI = &*mi;
  667. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  668. if (DI == DistanceMap.end())
  669. // Must be created from unfolded load. Don't waste time trying this.
  670. return false;
  671. MachineInstr *KillMI = 0;
  672. if (LIS) {
  673. LiveInterval &LI = LIS->getInterval(Reg);
  674. assert(LI.end() != LI.begin() &&
  675. "Reg should not have empty live interval.");
  676. SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
  677. LiveInterval::const_iterator I = LI.find(MBBEndIdx);
  678. if (I != LI.end() && I->start < MBBEndIdx)
  679. return false;
  680. --I;
  681. KillMI = LIS->getInstructionFromIndex(I->end);
  682. } else {
  683. KillMI = LV->getVarInfo(Reg).findKill(MBB);
  684. }
  685. if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
  686. // Don't mess with copies, they may be coalesced later.
  687. return false;
  688. if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
  689. KillMI->isBranch() || KillMI->isTerminator())
  690. // Don't move pass calls, etc.
  691. return false;
  692. unsigned DstReg;
  693. if (isTwoAddrUse(*KillMI, Reg, DstReg))
  694. return false;
  695. bool SeenStore = true;
  696. if (!MI->isSafeToMove(TII, AA, SeenStore))
  697. return false;
  698. if (TII->getInstrLatency(InstrItins, MI) > 1)
  699. // FIXME: Needs more sophisticated heuristics.
  700. return false;
  701. SmallSet<unsigned, 2> Uses;
  702. SmallSet<unsigned, 2> Kills;
  703. SmallSet<unsigned, 2> Defs;
  704. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  705. const MachineOperand &MO = MI->getOperand(i);
  706. if (!MO.isReg())
  707. continue;
  708. unsigned MOReg = MO.getReg();
  709. if (!MOReg)
  710. continue;
  711. if (MO.isDef())
  712. Defs.insert(MOReg);
  713. else {
  714. Uses.insert(MOReg);
  715. if (MOReg != Reg && (MO.isKill() ||
  716. (LIS && isPlainlyKilled(MI, MOReg, LIS))))
  717. Kills.insert(MOReg);
  718. }
  719. }
  720. // Move the copies connected to MI down as well.
  721. MachineBasicBlock::iterator Begin = MI;
  722. MachineBasicBlock::iterator AfterMI = std::next(Begin);
  723. MachineBasicBlock::iterator End = AfterMI;
  724. while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
  725. Defs.insert(End->getOperand(0).getReg());
  726. ++End;
  727. }
  728. // Check if the reschedule will not break depedencies.
  729. unsigned NumVisited = 0;
  730. MachineBasicBlock::iterator KillPos = KillMI;
  731. ++KillPos;
  732. for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
  733. MachineInstr *OtherMI = I;
  734. // DBG_VALUE cannot be counted against the limit.
  735. if (OtherMI->isDebugValue())
  736. continue;
  737. if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
  738. return false;
  739. ++NumVisited;
  740. if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
  741. OtherMI->isBranch() || OtherMI->isTerminator())
  742. // Don't move pass calls, etc.
  743. return false;
  744. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  745. const MachineOperand &MO = OtherMI->getOperand(i);
  746. if (!MO.isReg())
  747. continue;
  748. unsigned MOReg = MO.getReg();
  749. if (!MOReg)
  750. continue;
  751. if (MO.isDef()) {
  752. if (Uses.count(MOReg))
  753. // Physical register use would be clobbered.
  754. return false;
  755. if (!MO.isDead() && Defs.count(MOReg))
  756. // May clobber a physical register def.
  757. // FIXME: This may be too conservative. It's ok if the instruction
  758. // is sunken completely below the use.
  759. return false;
  760. } else {
  761. if (Defs.count(MOReg))
  762. return false;
  763. bool isKill = MO.isKill() ||
  764. (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
  765. if (MOReg != Reg &&
  766. ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
  767. // Don't want to extend other live ranges and update kills.
  768. return false;
  769. if (MOReg == Reg && !isKill)
  770. // We can't schedule across a use of the register in question.
  771. return false;
  772. // Ensure that if this is register in question, its the kill we expect.
  773. assert((MOReg != Reg || OtherMI == KillMI) &&
  774. "Found multiple kills of a register in a basic block");
  775. }
  776. }
  777. }
  778. // Move debug info as well.
  779. while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
  780. --Begin;
  781. nmi = End;
  782. MachineBasicBlock::iterator InsertPos = KillPos;
  783. if (LIS) {
  784. // We have to move the copies first so that the MBB is still well-formed
  785. // when calling handleMove().
  786. for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
  787. MachineInstr *CopyMI = MBBI;
  788. ++MBBI;
  789. MBB->splice(InsertPos, MBB, CopyMI);
  790. LIS->handleMove(CopyMI);
  791. InsertPos = CopyMI;
  792. }
  793. End = std::next(MachineBasicBlock::iterator(MI));
  794. }
  795. // Copies following MI may have been moved as well.
  796. MBB->splice(InsertPos, MBB, Begin, End);
  797. DistanceMap.erase(DI);
  798. // Update live variables
  799. if (LIS) {
  800. LIS->handleMove(MI);
  801. } else {
  802. LV->removeVirtualRegisterKilled(Reg, KillMI);
  803. LV->addVirtualRegisterKilled(Reg, MI);
  804. }
  805. DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
  806. return true;
  807. }
  808. /// isDefTooClose - Return true if the re-scheduling will put the given
  809. /// instruction too close to the defs of its register dependencies.
  810. bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
  811. MachineInstr *MI) {
  812. for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
  813. DE = MRI->def_end(); DI != DE; ++DI) {
  814. MachineInstr *DefMI = &*DI;
  815. if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
  816. continue;
  817. if (DefMI == MI)
  818. return true; // MI is defining something KillMI uses
  819. DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
  820. if (DDI == DistanceMap.end())
  821. return true; // Below MI
  822. unsigned DefDist = DDI->second;
  823. assert(Dist > DefDist && "Visited def already?");
  824. if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
  825. return true;
  826. }
  827. return false;
  828. }
  829. /// rescheduleKillAboveMI - If there is one more local instruction that reads
  830. /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
  831. /// current two-address instruction in order to eliminate the need for the
  832. /// copy.
  833. bool TwoAddressInstructionPass::
  834. rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
  835. MachineBasicBlock::iterator &nmi,
  836. unsigned Reg) {
  837. // Bail immediately if we don't have LV or LIS available. We use them to find
  838. // kills efficiently.
  839. if (!LV && !LIS)
  840. return false;
  841. MachineInstr *MI = &*mi;
  842. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  843. if (DI == DistanceMap.end())
  844. // Must be created from unfolded load. Don't waste time trying this.
  845. return false;
  846. MachineInstr *KillMI = 0;
  847. if (LIS) {
  848. LiveInterval &LI = LIS->getInterval(Reg);
  849. assert(LI.end() != LI.begin() &&
  850. "Reg should not have empty live interval.");
  851. SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
  852. LiveInterval::const_iterator I = LI.find(MBBEndIdx);
  853. if (I != LI.end() && I->start < MBBEndIdx)
  854. return false;
  855. --I;
  856. KillMI = LIS->getInstructionFromIndex(I->end);
  857. } else {
  858. KillMI = LV->getVarInfo(Reg).findKill(MBB);
  859. }
  860. if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
  861. // Don't mess with copies, they may be coalesced later.
  862. return false;
  863. unsigned DstReg;
  864. if (isTwoAddrUse(*KillMI, Reg, DstReg))
  865. return false;
  866. bool SeenStore = true;
  867. if (!KillMI->isSafeToMove(TII, AA, SeenStore))
  868. return false;
  869. SmallSet<unsigned, 2> Uses;
  870. SmallSet<unsigned, 2> Kills;
  871. SmallSet<unsigned, 2> Defs;
  872. SmallSet<unsigned, 2> LiveDefs;
  873. for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
  874. const MachineOperand &MO = KillMI->getOperand(i);
  875. if (!MO.isReg())
  876. continue;
  877. unsigned MOReg = MO.getReg();
  878. if (MO.isUse()) {
  879. if (!MOReg)
  880. continue;
  881. if (isDefTooClose(MOReg, DI->second, MI))
  882. return false;
  883. bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
  884. if (MOReg == Reg && !isKill)
  885. return false;
  886. Uses.insert(MOReg);
  887. if (isKill && MOReg != Reg)
  888. Kills.insert(MOReg);
  889. } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  890. Defs.insert(MOReg);
  891. if (!MO.isDead())
  892. LiveDefs.insert(MOReg);
  893. }
  894. }
  895. // Check if the reschedule will not break depedencies.
  896. unsigned NumVisited = 0;
  897. MachineBasicBlock::iterator KillPos = KillMI;
  898. for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
  899. MachineInstr *OtherMI = I;
  900. // DBG_VALUE cannot be counted against the limit.
  901. if (OtherMI->isDebugValue())
  902. continue;
  903. if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
  904. return false;
  905. ++NumVisited;
  906. if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
  907. OtherMI->isBranch() || OtherMI->isTerminator())
  908. // Don't move pass calls, etc.
  909. return false;
  910. SmallVector<unsigned, 2> OtherDefs;
  911. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  912. const MachineOperand &MO = OtherMI->getOperand(i);
  913. if (!MO.isReg())
  914. continue;
  915. unsigned MOReg = MO.getReg();
  916. if (!MOReg)
  917. continue;
  918. if (MO.isUse()) {
  919. if (Defs.count(MOReg))
  920. // Moving KillMI can clobber the physical register if the def has
  921. // not been seen.
  922. return false;
  923. if (Kills.count(MOReg))
  924. // Don't want to extend other live ranges and update kills.
  925. return false;
  926. if (OtherMI != MI && MOReg == Reg &&
  927. !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
  928. // We can't schedule across a use of the register in question.
  929. return false;
  930. } else {
  931. OtherDefs.push_back(MOReg);
  932. }
  933. }
  934. for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
  935. unsigned MOReg = OtherDefs[i];
  936. if (Uses.count(MOReg))
  937. return false;
  938. if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  939. LiveDefs.count(MOReg))
  940. return false;
  941. // Physical register def is seen.
  942. Defs.erase(MOReg);
  943. }
  944. }
  945. // Move the old kill above MI, don't forget to move debug info as well.
  946. MachineBasicBlock::iterator InsertPos = mi;
  947. while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
  948. --InsertPos;
  949. MachineBasicBlock::iterator From = KillMI;
  950. MachineBasicBlock::iterator To = std::next(From);
  951. while (std::prev(From)->isDebugValue())
  952. --From;
  953. MBB->splice(InsertPos, MBB, From, To);
  954. nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
  955. DistanceMap.erase(DI);
  956. // Update live variables
  957. if (LIS) {
  958. LIS->handleMove(KillMI);
  959. } else {
  960. LV->removeVirtualRegisterKilled(Reg, KillMI);
  961. LV->addVirtualRegisterKilled(Reg, MI);
  962. }
  963. DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
  964. return true;
  965. }
  966. /// tryInstructionTransform - For the case where an instruction has a single
  967. /// pair of tied register operands, attempt some transformations that may
  968. /// either eliminate the tied operands or improve the opportunities for
  969. /// coalescing away the register copy. Returns true if no copy needs to be
  970. /// inserted to untie mi's operands (either because they were untied, or
  971. /// because mi was rescheduled, and will be visited again later). If the
  972. /// shouldOnlyCommute flag is true, only instruction commutation is attempted.
  973. bool TwoAddressInstructionPass::
  974. tryInstructionTransform(MachineBasicBlock::iterator &mi,
  975. MachineBasicBlock::iterator &nmi,
  976. unsigned SrcIdx, unsigned DstIdx,
  977. unsigned Dist, bool shouldOnlyCommute) {
  978. if (OptLevel == CodeGenOpt::None)
  979. return false;
  980. MachineInstr &MI = *mi;
  981. unsigned regA = MI.getOperand(DstIdx).getReg();
  982. unsigned regB = MI.getOperand(SrcIdx).getReg();
  983. assert(TargetRegisterInfo::isVirtualRegister(regB) &&
  984. "cannot make instruction into two-address form");
  985. bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
  986. if (TargetRegisterInfo::isVirtualRegister(regA))
  987. scanUses(regA);
  988. // Check if it is profitable to commute the operands.
  989. unsigned SrcOp1, SrcOp2;
  990. unsigned regC = 0;
  991. unsigned regCIdx = ~0U;
  992. bool TryCommute = false;
  993. bool AggressiveCommute = false;
  994. if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
  995. TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
  996. if (SrcIdx == SrcOp1)
  997. regCIdx = SrcOp2;
  998. else if (SrcIdx == SrcOp2)
  999. regCIdx = SrcOp1;
  1000. if (regCIdx != ~0U) {
  1001. regC = MI.getOperand(regCIdx).getReg();
  1002. if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
  1003. // If C dies but B does not, swap the B and C operands.
  1004. // This makes the live ranges of A and C joinable.
  1005. TryCommute = true;
  1006. else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
  1007. TryCommute = true;
  1008. AggressiveCommute = true;
  1009. }
  1010. }
  1011. }
  1012. // If it's profitable to commute, try to do so.
  1013. if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
  1014. ++NumCommuted;
  1015. if (AggressiveCommute)
  1016. ++NumAggrCommuted;
  1017. return false;
  1018. }
  1019. if (shouldOnlyCommute)
  1020. return false;
  1021. // If there is one more use of regB later in the same MBB, consider
  1022. // re-schedule this MI below it.
  1023. if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
  1024. ++NumReSchedDowns;
  1025. return true;
  1026. }
  1027. if (MI.isConvertibleTo3Addr()) {
  1028. // This instruction is potentially convertible to a true
  1029. // three-address instruction. Check if it is profitable.
  1030. if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
  1031. // Try to convert it.
  1032. if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
  1033. ++NumConvertedTo3Addr;
  1034. return true; // Done with this instruction.
  1035. }
  1036. }
  1037. }
  1038. // If there is one more use of regB later in the same MBB, consider
  1039. // re-schedule it before this MI if it's legal.
  1040. if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
  1041. ++NumReSchedUps;
  1042. return true;
  1043. }
  1044. // If this is an instruction with a load folded into it, try unfolding
  1045. // the load, e.g. avoid this:
  1046. // movq %rdx, %rcx
  1047. // addq (%rax), %rcx
  1048. // in favor of this:
  1049. // movq (%rax), %rcx
  1050. // addq %rdx, %rcx
  1051. // because it's preferable to schedule a load than a register copy.
  1052. if (MI.mayLoad() && !regBKilled) {
  1053. // Determine if a load can be unfolded.
  1054. unsigned LoadRegIndex;
  1055. unsigned NewOpc =
  1056. TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
  1057. /*UnfoldLoad=*/true,
  1058. /*UnfoldStore=*/false,
  1059. &LoadRegIndex);
  1060. if (NewOpc != 0) {
  1061. const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
  1062. if (UnfoldMCID.getNumDefs() == 1) {
  1063. // Unfold the load.
  1064. DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
  1065. const TargetRegisterClass *RC =
  1066. TRI->getAllocatableClass(
  1067. TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
  1068. unsigned Reg = MRI->createVirtualRegister(RC);
  1069. SmallVector<MachineInstr *, 2> NewMIs;
  1070. if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
  1071. /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
  1072. NewMIs)) {
  1073. DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
  1074. return false;
  1075. }
  1076. assert(NewMIs.size() == 2 &&
  1077. "Unfolded a load into multiple instructions!");
  1078. // The load was previously folded, so this is the only use.
  1079. NewMIs[1]->addRegisterKilled(Reg, TRI);
  1080. // Tentatively insert the instructions into the block so that they
  1081. // look "normal" to the transformation logic.
  1082. MBB->insert(mi, NewMIs[0]);
  1083. MBB->insert(mi, NewMIs[1]);
  1084. DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
  1085. << "2addr: NEW INST: " << *NewMIs[1]);
  1086. // Transform the instruction, now that it no longer has a load.
  1087. unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
  1088. unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
  1089. MachineBasicBlock::iterator NewMI = NewMIs[1];
  1090. bool TransformResult =
  1091. tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
  1092. (void)TransformResult;
  1093. assert(!TransformResult &&
  1094. "tryInstructionTransform() should return false.");
  1095. if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
  1096. // Success, or at least we made an improvement. Keep the unfolded
  1097. // instructions and discard the original.
  1098. if (LV) {
  1099. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  1100. MachineOperand &MO = MI.getOperand(i);
  1101. if (MO.isReg() &&
  1102. TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  1103. if (MO.isUse()) {
  1104. if (MO.isKill()) {
  1105. if (NewMIs[0]->killsRegister(MO.getReg()))
  1106. LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
  1107. else {
  1108. assert(NewMIs[1]->killsRegister(MO.getReg()) &&
  1109. "Kill missing after load unfold!");
  1110. LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
  1111. }
  1112. }
  1113. } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
  1114. if (NewMIs[1]->registerDefIsDead(MO.getReg()))
  1115. LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
  1116. else {
  1117. assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
  1118. "Dead flag missing after load unfold!");
  1119. LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
  1120. }
  1121. }
  1122. }
  1123. }
  1124. LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
  1125. }
  1126. SmallVector<unsigned, 4> OrigRegs;
  1127. if (LIS) {
  1128. for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
  1129. MOE = MI.operands_end(); MOI != MOE; ++MOI) {
  1130. if (MOI->isReg())
  1131. OrigRegs.push_back(MOI->getReg());
  1132. }
  1133. }
  1134. MI.eraseFromParent();
  1135. // Update LiveIntervals.
  1136. if (LIS) {
  1137. MachineBasicBlock::iterator Begin(NewMIs[0]);
  1138. MachineBasicBlock::iterator End(NewMIs[1]);
  1139. LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
  1140. }
  1141. mi = NewMIs[1];
  1142. } else {
  1143. // Transforming didn't eliminate the tie and didn't lead to an
  1144. // improvement. Clean up the unfolded instructions and keep the
  1145. // original.
  1146. DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
  1147. NewMIs[0]->eraseFromParent();
  1148. NewMIs[1]->eraseFromParent();
  1149. }
  1150. }
  1151. }
  1152. }
  1153. return false;
  1154. }
  1155. // Collect tied operands of MI that need to be handled.
  1156. // Rewrite trivial cases immediately.
  1157. // Return true if any tied operands where found, including the trivial ones.
  1158. bool TwoAddressInstructionPass::
  1159. collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
  1160. const MCInstrDesc &MCID = MI->getDesc();
  1161. bool AnyOps = false;
  1162. unsigned NumOps = MI->getNumOperands();
  1163. for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
  1164. unsigned DstIdx = 0;
  1165. if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
  1166. continue;
  1167. AnyOps = true;
  1168. MachineOperand &SrcMO = MI->getOperand(SrcIdx);
  1169. MachineOperand &DstMO = MI->getOperand(DstIdx);
  1170. unsigned SrcReg = SrcMO.getReg();
  1171. unsigned DstReg = DstMO.getReg();
  1172. // Tied constraint already satisfied?
  1173. if (SrcReg == DstReg)
  1174. continue;
  1175. assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
  1176. // Deal with <undef> uses immediately - simply rewrite the src operand.
  1177. if (SrcMO.isUndef() && !DstMO.getSubReg()) {
  1178. // Constrain the DstReg register class if required.
  1179. if (TargetRegisterInfo::isVirtualRegister(DstReg))
  1180. if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
  1181. TRI, *MF))
  1182. MRI->constrainRegClass(DstReg, RC);
  1183. SrcMO.setReg(DstReg);
  1184. SrcMO.setSubReg(0);
  1185. DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
  1186. continue;
  1187. }
  1188. TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
  1189. }
  1190. return AnyOps;
  1191. }
  1192. // Process a list of tied MI operands that all use the same source register.
  1193. // The tied pairs are of the form (SrcIdx, DstIdx).
  1194. void
  1195. TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
  1196. TiedPairList &TiedPairs,
  1197. unsigned &Dist) {
  1198. bool IsEarlyClobber = false;
  1199. for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
  1200. const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
  1201. IsEarlyClobber |= DstMO.isEarlyClobber();
  1202. }
  1203. bool RemovedKillFlag = false;
  1204. bool AllUsesCopied = true;
  1205. unsigned LastCopiedReg = 0;
  1206. SlotIndex LastCopyIdx;
  1207. unsigned RegB = 0;
  1208. unsigned SubRegB = 0;
  1209. for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
  1210. unsigned SrcIdx = TiedPairs[tpi].first;
  1211. unsigned DstIdx = TiedPairs[tpi].second;
  1212. const MachineOperand &DstMO = MI->getOperand(DstIdx);
  1213. unsigned RegA = DstMO.getReg();
  1214. // Grab RegB from the instruction because it may have changed if the
  1215. // instruction was commuted.
  1216. RegB = MI->getOperand(SrcIdx).getReg();
  1217. SubRegB = MI->getOperand(SrcIdx).getSubReg();
  1218. if (RegA == RegB) {
  1219. // The register is tied to multiple destinations (or else we would
  1220. // not have continued this far), but this use of the register
  1221. // already matches the tied destination. Leave it.
  1222. AllUsesCopied = false;
  1223. continue;
  1224. }
  1225. LastCopiedReg = RegA;
  1226. assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
  1227. "cannot make instruction into two-address form");
  1228. #ifndef NDEBUG
  1229. // First, verify that we don't have a use of "a" in the instruction
  1230. // (a = b + a for example) because our transformation will not
  1231. // work. This should never occur because we are in SSA form.
  1232. for (unsigned i = 0; i != MI->getNumOperands(); ++i)
  1233. assert(i == DstIdx ||
  1234. !MI->getOperand(i).isReg() ||
  1235. MI->getOperand(i).getReg() != RegA);
  1236. #endif
  1237. // Emit a copy.
  1238. MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
  1239. TII->get(TargetOpcode::COPY), RegA);
  1240. // If this operand is folding a truncation, the truncation now moves to the
  1241. // copy so that the register classes remain valid for the operands.
  1242. MIB.addReg(RegB, 0, SubRegB);
  1243. const TargetRegisterClass *RC = MRI->getRegClass(RegB);
  1244. if (SubRegB) {
  1245. if (TargetRegisterInfo::isVirtualRegister(RegA)) {
  1246. assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
  1247. SubRegB) &&
  1248. "tied subregister must be a truncation");
  1249. // The superreg class will not be used to constrain the subreg class.
  1250. RC = 0;
  1251. }
  1252. else {
  1253. assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
  1254. && "tied subregister must be a truncation");
  1255. }
  1256. }
  1257. // Update DistanceMap.
  1258. MachineBasicBlock::iterator PrevMI = MI;
  1259. --PrevMI;
  1260. DistanceMap.insert(std::make_pair(PrevMI, Dist));
  1261. DistanceMap[MI] = ++Dist;
  1262. if (LIS) {
  1263. LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
  1264. if (TargetRegisterInfo::isVirtualRegister(RegA)) {
  1265. LiveInterval &LI = LIS->getInterval(RegA);
  1266. VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
  1267. SlotIndex endIdx =
  1268. LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
  1269. LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
  1270. }
  1271. }
  1272. DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
  1273. MachineOperand &MO = MI->getOperand(SrcIdx);
  1274. assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
  1275. "inconsistent operand info for 2-reg pass");
  1276. if (MO.isKill()) {
  1277. MO.setIsKill(false);
  1278. RemovedKillFlag = true;
  1279. }
  1280. // Make sure regA is a legal regclass for the SrcIdx operand.
  1281. if (TargetRegisterInfo::isVirtualRegister(RegA) &&
  1282. TargetRegisterInfo::isVirtualRegister(RegB))
  1283. MRI->constrainRegClass(RegA, RC);
  1284. MO.setReg(RegA);
  1285. // The getMatchingSuper asserts guarantee that the register class projected
  1286. // by SubRegB is compatible with RegA with no subregister. So regardless of
  1287. // whether the dest oper writes a subreg, the source oper should not.
  1288. MO.setSubReg(0);
  1289. // Propagate SrcRegMap.
  1290. SrcRegMap[RegA] = RegB;
  1291. }
  1292. if (AllUsesCopied) {
  1293. if (!IsEarlyClobber) {
  1294. // Replace other (un-tied) uses of regB with LastCopiedReg.
  1295. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1296. MachineOperand &MO = MI->getOperand(i);
  1297. if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
  1298. MO.isUse()) {
  1299. if (MO.isKill()) {
  1300. MO.setIsKill(false);
  1301. RemovedKillFlag = true;
  1302. }
  1303. MO.setReg(LastCopiedReg);
  1304. MO.setSubReg(0);
  1305. }
  1306. }
  1307. }
  1308. // Update live variables for regB.
  1309. if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
  1310. MachineBasicBlock::iterator PrevMI = MI;
  1311. --PrevMI;
  1312. LV->addVirtualRegisterKilled(RegB, PrevMI);
  1313. }
  1314. // Update LiveIntervals.
  1315. if (LIS) {
  1316. LiveInterval &LI = LIS->getInterval(RegB);
  1317. SlotIndex MIIdx = LIS->getInstructionIndex(MI);
  1318. LiveInterval::const_iterator I = LI.find(MIIdx);
  1319. assert(I != LI.end() && "RegB must be live-in to use.");
  1320. SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
  1321. if (I->end == UseIdx)
  1322. LI.removeSegment(LastCopyIdx, UseIdx);
  1323. }
  1324. } else if (RemovedKillFlag) {
  1325. // Some tied uses of regB matched their destination registers, so
  1326. // regB is still used in this instruction, but a kill flag was
  1327. // removed from a different tied use of regB, so now we need to add
  1328. // a kill flag to one of the remaining uses of regB.
  1329. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1330. MachineOperand &MO = MI->getOperand(i);
  1331. if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
  1332. MO.setIsKill(true);
  1333. break;
  1334. }
  1335. }
  1336. }
  1337. }
  1338. /// runOnMachineFunction - Reduce two-address instructions to two operands.
  1339. ///
  1340. bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
  1341. MF = &Func;
  1342. const TargetMachine &TM = MF->getTarget();
  1343. MRI = &MF->getRegInfo();
  1344. TII = TM.getInstrInfo();
  1345. TRI = TM.getRegisterInfo();
  1346. InstrItins = TM.getInstrItineraryData();
  1347. LV = getAnalysisIfAvailable<LiveVariables>();
  1348. LIS = getAnalysisIfAvailable<LiveIntervals>();
  1349. AA = &getAnalysis<AliasAnalysis>();
  1350. OptLevel = TM.getOptLevel();
  1351. bool MadeChange = false;
  1352. DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
  1353. DEBUG(dbgs() << "********** Function: "
  1354. << MF->getName() << '\n');
  1355. // This pass takes the function out of SSA form.
  1356. MRI->leaveSSA();
  1357. TiedOperandMap TiedOperands;
  1358. for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
  1359. MBBI != MBBE; ++MBBI) {
  1360. MBB = MBBI;
  1361. unsigned Dist = 0;
  1362. DistanceMap.clear();
  1363. SrcRegMap.clear();
  1364. DstRegMap.clear();
  1365. Processed.clear();
  1366. for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
  1367. mi != me; ) {
  1368. MachineBasicBlock::iterator nmi = std::next(mi);
  1369. if (mi->isDebugValue()) {
  1370. mi = nmi;
  1371. continue;
  1372. }
  1373. // Expand REG_SEQUENCE instructions. This will position mi at the first
  1374. // expanded instruction.
  1375. if (mi->isRegSequence())
  1376. eliminateRegSequence(mi);
  1377. DistanceMap.insert(std::make_pair(mi, ++Dist));
  1378. processCopy(&*mi);
  1379. // First scan through all the tied register uses in this instruction
  1380. // and record a list of pairs of tied operands for each register.
  1381. if (!collectTiedOperands(mi, TiedOperands)) {
  1382. mi = nmi;
  1383. continue;
  1384. }
  1385. ++NumTwoAddressInstrs;
  1386. MadeChange = true;
  1387. DEBUG(dbgs() << '\t' << *mi);
  1388. // If the instruction has a single pair of tied operands, try some
  1389. // transformations that may either eliminate the tied operands or
  1390. // improve the opportunities for coalescing away the register copy.
  1391. if (TiedOperands.size() == 1) {
  1392. SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
  1393. = TiedOperands.begin()->second;
  1394. if (TiedPairs.size() == 1) {
  1395. unsigned SrcIdx = TiedPairs[0].first;
  1396. unsigned DstIdx = TiedPairs[0].second;
  1397. unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
  1398. unsigned DstReg = mi->getOperand(DstIdx).getReg();
  1399. if (SrcReg != DstReg &&
  1400. tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
  1401. // The tied operands have been eliminated or shifted further down the
  1402. // block to ease elimination. Continue processing with 'nmi'.
  1403. TiedOperands.clear();
  1404. mi = nmi;
  1405. continue;
  1406. }
  1407. }
  1408. }
  1409. // Now iterate over the information collected above.
  1410. for (TiedOperandMap::iterator OI = TiedOperands.begin(),
  1411. OE = TiedOperands.end(); OI != OE; ++OI) {
  1412. processTiedPairs(mi, OI->second, Dist);
  1413. DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
  1414. }
  1415. // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
  1416. if (mi->isInsertSubreg()) {
  1417. // From %reg = INSERT_SUBREG %reg, %subreg, subidx
  1418. // To %reg:subidx = COPY %subreg
  1419. unsigned SubIdx = mi->getOperand(3).getImm();
  1420. mi->RemoveOperand(3);
  1421. assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
  1422. mi->getOperand(0).setSubReg(SubIdx);
  1423. mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
  1424. mi->RemoveOperand(1);
  1425. mi->setDesc(TII->get(TargetOpcode::COPY));
  1426. DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
  1427. }
  1428. // Clear TiedOperands here instead of at the top of the loop
  1429. // since most instructions do not have tied operands.
  1430. TiedOperands.clear();
  1431. mi = nmi;
  1432. }
  1433. }
  1434. if (LIS)
  1435. MF->verify(this, "After two-address instruction pass");
  1436. return MadeChange;
  1437. }
  1438. /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
  1439. ///
  1440. /// The instruction is turned into a sequence of sub-register copies:
  1441. ///
  1442. /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
  1443. ///
  1444. /// Becomes:
  1445. ///
  1446. /// %dst:ssub0<def,undef> = COPY %v1
  1447. /// %dst:ssub1<def> = COPY %v2
  1448. ///
  1449. void TwoAddressInstructionPass::
  1450. eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
  1451. MachineInstr *MI = MBBI;
  1452. unsigned DstReg = MI->getOperand(0).getReg();
  1453. if (MI->getOperand(0).getSubReg() ||
  1454. TargetRegisterInfo::isPhysicalRegister(DstReg) ||
  1455. !(MI->getNumOperands() & 1)) {
  1456. DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
  1457. llvm_unreachable(0);
  1458. }
  1459. SmallVector<unsigned, 4> OrigRegs;
  1460. if (LIS) {
  1461. OrigRegs.push_back(MI->getOperand(0).getReg());
  1462. for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
  1463. OrigRegs.push_back(MI->getOperand(i).getReg());
  1464. }
  1465. bool DefEmitted = false;
  1466. for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
  1467. MachineOperand &UseMO = MI->getOperand(i);
  1468. unsigned SrcReg = UseMO.getReg();
  1469. unsigned SubIdx = MI->getOperand(i+1).getImm();
  1470. // Nothing needs to be inserted for <undef> operands.
  1471. if (UseMO.isUndef())
  1472. continue;
  1473. // Defer any kill flag to the last operand using SrcReg. Otherwise, we
  1474. // might insert a COPY that uses SrcReg after is was killed.
  1475. bool isKill = UseMO.isKill();
  1476. if (isKill)
  1477. for (unsigned j = i + 2; j < e; j += 2)
  1478. if (MI->getOperand(j).getReg() == SrcReg) {
  1479. MI->getOperand(j).setIsKill();
  1480. UseMO.setIsKill(false);
  1481. isKill = false;
  1482. break;
  1483. }
  1484. // Insert the sub-register copy.
  1485. MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
  1486. TII->get(TargetOpcode::COPY))
  1487. .addReg(DstReg, RegState::Define, SubIdx)
  1488. .addOperand(UseMO);
  1489. // The first def needs an <undef> flag because there is no live register
  1490. // before it.
  1491. if (!DefEmitted) {
  1492. CopyMI->getOperand(0).setIsUndef(true);
  1493. // Return an iterator pointing to the first inserted instr.
  1494. MBBI = CopyMI;
  1495. }
  1496. DefEmitted = true;
  1497. // Update LiveVariables' kill info.
  1498. if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
  1499. LV->replaceKillInstruction(SrcReg, MI, CopyMI);
  1500. DEBUG(dbgs() << "Inserted: " << *CopyMI);
  1501. }
  1502. MachineBasicBlock::iterator EndMBBI =
  1503. std::next(MachineBasicBlock::iterator(MI));
  1504. if (!DefEmitted) {
  1505. DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
  1506. MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
  1507. for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
  1508. MI->RemoveOperand(j);
  1509. } else {
  1510. DEBUG(dbgs() << "Eliminated: " << *MI);
  1511. MI->eraseFromParent();
  1512. }
  1513. // Udpate LiveIntervals.
  1514. if (LIS)
  1515. LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
  1516. }