TwoAddressInstructionPass.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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/Function.h"
  32. #include "llvm/CodeGen/LiveVariables.h"
  33. #include "llvm/CodeGen/MachineFunctionPass.h"
  34. #include "llvm/CodeGen/MachineInstr.h"
  35. #include "llvm/CodeGen/MachineRegisterInfo.h"
  36. #include "llvm/Target/TargetRegisterInfo.h"
  37. #include "llvm/Target/TargetInstrInfo.h"
  38. #include "llvm/Target/TargetMachine.h"
  39. #include "llvm/Target/TargetOptions.h"
  40. #include "llvm/Support/Compiler.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/ADT/BitVector.h"
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/SmallSet.h"
  45. #include "llvm/ADT/Statistic.h"
  46. #include "llvm/ADT/STLExtras.h"
  47. using namespace llvm;
  48. STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
  49. STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
  50. STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
  51. STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
  52. STATISTIC(NumReMats, "Number of instructions re-materialized");
  53. namespace {
  54. class VISIBILITY_HIDDEN TwoAddressInstructionPass
  55. : public MachineFunctionPass {
  56. const TargetInstrInfo *TII;
  57. const TargetRegisterInfo *TRI;
  58. MachineRegisterInfo *MRI;
  59. LiveVariables *LV;
  60. bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
  61. unsigned Reg,
  62. MachineBasicBlock::iterator OldPos);
  63. bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
  64. MachineInstr *MI, MachineInstr *DefMI,
  65. MachineBasicBlock *MBB, unsigned Loc,
  66. DenseMap<MachineInstr*, unsigned> &DistanceMap);
  67. public:
  68. static char ID; // Pass identification, replacement for typeid
  69. TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
  70. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  71. AU.addPreserved<LiveVariables>();
  72. AU.addPreservedID(MachineLoopInfoID);
  73. AU.addPreservedID(MachineDominatorsID);
  74. if (StrongPHIElim)
  75. AU.addPreservedID(StrongPHIEliminationID);
  76. else
  77. AU.addPreservedID(PHIEliminationID);
  78. MachineFunctionPass::getAnalysisUsage(AU);
  79. }
  80. /// runOnMachineFunction - Pass entry point.
  81. bool runOnMachineFunction(MachineFunction&);
  82. };
  83. }
  84. char TwoAddressInstructionPass::ID = 0;
  85. static RegisterPass<TwoAddressInstructionPass>
  86. X("twoaddressinstruction", "Two-Address instruction pass");
  87. const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
  88. /// Sink3AddrInstruction - A two-address instruction has been converted to a
  89. /// three-address instruction to avoid clobbering a register. Try to sink it
  90. /// past the instruction that would kill the above mentioned register to reduce
  91. /// register pressure.
  92. bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
  93. MachineInstr *MI, unsigned SavedReg,
  94. MachineBasicBlock::iterator OldPos) {
  95. // Check if it's safe to move this instruction.
  96. bool SeenStore = true; // Be conservative.
  97. if (!MI->isSafeToMove(TII, SeenStore))
  98. return false;
  99. unsigned DefReg = 0;
  100. SmallSet<unsigned, 4> UseRegs;
  101. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  102. const MachineOperand &MO = MI->getOperand(i);
  103. if (!MO.isReg())
  104. continue;
  105. unsigned MOReg = MO.getReg();
  106. if (!MOReg)
  107. continue;
  108. if (MO.isUse() && MOReg != SavedReg)
  109. UseRegs.insert(MO.getReg());
  110. if (!MO.isDef())
  111. continue;
  112. if (MO.isImplicit())
  113. // Don't try to move it if it implicitly defines a register.
  114. return false;
  115. if (DefReg)
  116. // For now, don't move any instructions that define multiple registers.
  117. return false;
  118. DefReg = MO.getReg();
  119. }
  120. // Find the instruction that kills SavedReg.
  121. MachineInstr *KillMI = NULL;
  122. for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
  123. UE = MRI->use_end(); UI != UE; ++UI) {
  124. MachineOperand &UseMO = UI.getOperand();
  125. if (!UseMO.isKill())
  126. continue;
  127. KillMI = UseMO.getParent();
  128. break;
  129. }
  130. if (!KillMI || KillMI->getParent() != MBB)
  131. return false;
  132. // If any of the definitions are used by another instruction between the
  133. // position and the kill use, then it's not safe to sink it.
  134. //
  135. // FIXME: This can be sped up if there is an easy way to query whether an
  136. // instruction is before or after another instruction. Then we can use
  137. // MachineRegisterInfo def / use instead.
  138. MachineOperand *KillMO = NULL;
  139. MachineBasicBlock::iterator KillPos = KillMI;
  140. ++KillPos;
  141. unsigned NumVisited = 0;
  142. for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
  143. MachineInstr *OtherMI = I;
  144. if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
  145. return false;
  146. ++NumVisited;
  147. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  148. MachineOperand &MO = OtherMI->getOperand(i);
  149. if (!MO.isReg())
  150. continue;
  151. unsigned MOReg = MO.getReg();
  152. if (!MOReg)
  153. continue;
  154. if (DefReg == MOReg)
  155. return false;
  156. if (MO.isKill()) {
  157. if (OtherMI == KillMI && MOReg == SavedReg)
  158. // Save the operand that kills the register. We want to unset the kill
  159. // marker if we can sink MI past it.
  160. KillMO = &MO;
  161. else if (UseRegs.count(MOReg))
  162. // One of the uses is killed before the destination.
  163. return false;
  164. }
  165. }
  166. }
  167. // Update kill and LV information.
  168. KillMO->setIsKill(false);
  169. KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
  170. KillMO->setIsKill(true);
  171. if (LV)
  172. LV->replaceKillInstruction(SavedReg, KillMI, MI);
  173. // Move instruction to its destination.
  174. MBB->remove(MI);
  175. MBB->insert(KillPos, MI);
  176. ++Num3AddrSunk;
  177. return true;
  178. }
  179. /// isTwoAddrUse - Return true if the specified MI is using the specified
  180. /// register as a two-address operand.
  181. static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
  182. const TargetInstrDesc &TID = UseMI->getDesc();
  183. for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
  184. MachineOperand &MO = UseMI->getOperand(i);
  185. if (MO.isReg() && MO.getReg() == Reg &&
  186. (MO.isDef() || TID.getOperandConstraint(i, TOI::TIED_TO) != -1))
  187. // Earlier use is a two-address one.
  188. return true;
  189. }
  190. return false;
  191. }
  192. /// isProfitableToReMat - Return true if the heuristics determines it is likely
  193. /// to be profitable to re-materialize the definition of Reg rather than copy
  194. /// the register.
  195. bool
  196. TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
  197. const TargetRegisterClass *RC,
  198. MachineInstr *MI, MachineInstr *DefMI,
  199. MachineBasicBlock *MBB, unsigned Loc,
  200. DenseMap<MachineInstr*, unsigned> &DistanceMap){
  201. bool OtherUse = false;
  202. for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
  203. UE = MRI->use_end(); UI != UE; ++UI) {
  204. MachineOperand &UseMO = UI.getOperand();
  205. if (!UseMO.isUse())
  206. continue;
  207. MachineInstr *UseMI = UseMO.getParent();
  208. MachineBasicBlock *UseMBB = UseMI->getParent();
  209. if (UseMBB == MBB) {
  210. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
  211. if (DI != DistanceMap.end() && DI->second == Loc)
  212. continue; // Current use.
  213. OtherUse = true;
  214. // There is at least one other use in the MBB that will clobber the
  215. // register.
  216. if (isTwoAddrUse(UseMI, Reg))
  217. return true;
  218. }
  219. }
  220. // If other uses in MBB are not two-address uses, then don't remat.
  221. if (OtherUse)
  222. return false;
  223. // No other uses in the same block, remat if it's defined in the same
  224. // block so it does not unnecessarily extend the live range.
  225. return MBB == DefMI->getParent();
  226. }
  227. /// runOnMachineFunction - Reduce two-address instructions to two operands.
  228. ///
  229. bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
  230. DOUT << "Machine Function\n";
  231. const TargetMachine &TM = MF.getTarget();
  232. MRI = &MF.getRegInfo();
  233. TII = TM.getInstrInfo();
  234. TRI = TM.getRegisterInfo();
  235. LV = getAnalysisToUpdate<LiveVariables>();
  236. bool MadeChange = false;
  237. DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
  238. DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
  239. // ReMatRegs - Keep track of the registers whose def's are remat'ed.
  240. BitVector ReMatRegs;
  241. ReMatRegs.resize(MRI->getLastVirtReg()+1);
  242. // DistanceMap - Keep track the distance of a MI from the start of the
  243. // current basic block.
  244. DenseMap<MachineInstr*, unsigned> DistanceMap;
  245. for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
  246. mbbi != mbbe; ++mbbi) {
  247. unsigned Dist = 0;
  248. DistanceMap.clear();
  249. for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
  250. mi != me; ) {
  251. MachineBasicBlock::iterator nmi = next(mi);
  252. const TargetInstrDesc &TID = mi->getDesc();
  253. bool FirstTied = true;
  254. DistanceMap.insert(std::make_pair(mi, ++Dist));
  255. for (unsigned si = 1, e = TID.getNumOperands(); si < e; ++si) {
  256. int ti = TID.getOperandConstraint(si, TOI::TIED_TO);
  257. if (ti == -1)
  258. continue;
  259. if (FirstTied) {
  260. ++NumTwoAddressInstrs;
  261. DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
  262. }
  263. FirstTied = false;
  264. assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
  265. mi->getOperand(si).isUse() && "two address instruction invalid");
  266. // If the two operands are the same we just remove the use
  267. // and mark the def as def&use, otherwise we have to insert a copy.
  268. if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
  269. // Rewrite:
  270. // a = b op c
  271. // to:
  272. // a = b
  273. // a = a op c
  274. unsigned regA = mi->getOperand(ti).getReg();
  275. unsigned regB = mi->getOperand(si).getReg();
  276. assert(TargetRegisterInfo::isVirtualRegister(regA) &&
  277. TargetRegisterInfo::isVirtualRegister(regB) &&
  278. "cannot update physical register live information");
  279. #ifndef NDEBUG
  280. // First, verify that we don't have a use of a in the instruction (a =
  281. // b + a for example) because our transformation will not work. This
  282. // should never occur because we are in SSA form.
  283. for (unsigned i = 0; i != mi->getNumOperands(); ++i)
  284. assert((int)i == ti ||
  285. !mi->getOperand(i).isReg() ||
  286. mi->getOperand(i).getReg() != regA);
  287. #endif
  288. // If this instruction is not the killing user of B, see if we can
  289. // rearrange the code to make it so. Making it the killing user will
  290. // allow us to coalesce A and B together, eliminating the copy we are
  291. // about to insert.
  292. if (!mi->killsRegister(regB)) {
  293. // If this instruction is commutative, check to see if C dies. If
  294. // so, swap the B and C operands. This makes the live ranges of A
  295. // and C joinable.
  296. // FIXME: This code also works for A := B op C instructions.
  297. if (TID.isCommutable() && mi->getNumOperands() >= 3) {
  298. assert(mi->getOperand(3-si).isReg() &&
  299. "Not a proper commutative instruction!");
  300. unsigned regC = mi->getOperand(3-si).getReg();
  301. if (mi->killsRegister(regC)) {
  302. DOUT << "2addr: COMMUTING : " << *mi;
  303. MachineInstr *NewMI = TII->commuteInstruction(mi);
  304. if (NewMI == 0) {
  305. DOUT << "2addr: COMMUTING FAILED!\n";
  306. } else {
  307. DOUT << "2addr: COMMUTED TO: " << *NewMI;
  308. // If the instruction changed to commute it, update livevar.
  309. if (NewMI != mi) {
  310. if (LV)
  311. // Update live variables
  312. LV->replaceKillInstruction(regC, mi, NewMI);
  313. mbbi->insert(mi, NewMI); // Insert the new inst
  314. mbbi->erase(mi); // Nuke the old inst.
  315. mi = NewMI;
  316. DistanceMap.insert(std::make_pair(NewMI, Dist));
  317. }
  318. ++NumCommuted;
  319. regB = regC;
  320. goto InstructionRearranged;
  321. }
  322. }
  323. }
  324. // If this instruction is potentially convertible to a true
  325. // three-address instruction,
  326. if (TID.isConvertibleTo3Addr()) {
  327. // FIXME: This assumes there are no more operands which are tied
  328. // to another register.
  329. #ifndef NDEBUG
  330. for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
  331. assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
  332. #endif
  333. MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
  334. if (NewMI) {
  335. DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
  336. DOUT << "2addr: TO 3-ADDR: " << *NewMI;
  337. bool Sunk = false;
  338. if (NewMI->findRegisterUseOperand(regB, false, TRI))
  339. // FIXME: Temporary workaround. If the new instruction doesn't
  340. // uses regB, convertToThreeAddress must have created more
  341. // then one instruction.
  342. Sunk = Sink3AddrInstruction(mbbi, NewMI, regB, mi);
  343. mbbi->erase(mi); // Nuke the old inst.
  344. if (!Sunk) {
  345. DistanceMap.insert(std::make_pair(NewMI, Dist));
  346. mi = NewMI;
  347. nmi = next(mi);
  348. }
  349. ++NumConvertedTo3Addr;
  350. break; // Done with this instruction.
  351. }
  352. }
  353. }
  354. InstructionRearranged:
  355. const TargetRegisterClass* rc = MRI->getRegClass(regA);
  356. MachineInstr *DefMI = MRI->getVRegDef(regB);
  357. // If it's safe and profitable, remat the definition instead of
  358. // copying it.
  359. if (DefMI &&
  360. DefMI->getDesc().isAsCheapAsAMove() &&
  361. DefMI->isSafeToReMat(TII, regB) &&
  362. isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist,DistanceMap)){
  363. DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
  364. TII->reMaterialize(*mbbi, mi, regA, DefMI);
  365. ReMatRegs.set(regB);
  366. ++NumReMats;
  367. } else {
  368. TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
  369. }
  370. MachineBasicBlock::iterator prevMi = prior(mi);
  371. // Update live variables for regB.
  372. if (LV) {
  373. LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
  374. // regB is used in this BB.
  375. varInfoB.UsedBlocks[mbbi->getNumber()] = true;
  376. if (LV->removeVirtualRegisterKilled(regB, mi))
  377. LV->addVirtualRegisterKilled(regB, prevMi);
  378. if (LV->removeVirtualRegisterDead(regB, mi))
  379. LV->addVirtualRegisterDead(regB, prevMi);
  380. }
  381. DOUT << "\t\tprepend:\t"; DEBUG(prevMi->print(*cerr.stream(), &TM));
  382. // Replace all occurences of regB with regA.
  383. for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
  384. if (mi->getOperand(i).isReg() &&
  385. mi->getOperand(i).getReg() == regB)
  386. mi->getOperand(i).setReg(regA);
  387. }
  388. }
  389. assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
  390. mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
  391. MadeChange = true;
  392. DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
  393. }
  394. mi = nmi;
  395. }
  396. }
  397. // Some remat'ed instructions are dead.
  398. int VReg = ReMatRegs.find_first();
  399. while (VReg != -1) {
  400. if (MRI->use_empty(VReg)) {
  401. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  402. DefMI->eraseFromParent();
  403. }
  404. VReg = ReMatRegs.find_next(VReg);
  405. }
  406. return MadeChange;
  407. }