VirtRegMap.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
  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 VirtRegMap class.
  11. //
  12. // It also contains implementations of the Spiller interface, which, given a
  13. // virtual register map and a machine function, eliminates all virtual
  14. // references by replacing them with physical register references - adding spill
  15. // code as necessary.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/CodeGen/VirtRegMap.h"
  19. #include "LiveDebugVariables.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SparseSet.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  24. #include "llvm/CodeGen/LiveStackAnalysis.h"
  25. #include "llvm/CodeGen/MachineFrameInfo.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineInstrBuilder.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/Passes.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/Compiler.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Target/TargetInstrInfo.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include "llvm/Target/TargetRegisterInfo.h"
  38. #include "llvm/Target/TargetSubtargetInfo.h"
  39. #include <algorithm>
  40. using namespace llvm;
  41. #define DEBUG_TYPE "regalloc"
  42. STATISTIC(NumSpillSlots, "Number of spill slots allocated");
  43. STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
  44. //===----------------------------------------------------------------------===//
  45. // VirtRegMap implementation
  46. //===----------------------------------------------------------------------===//
  47. char VirtRegMap::ID = 0;
  48. INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
  49. bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
  50. MRI = &mf.getRegInfo();
  51. TII = mf.getSubtarget().getInstrInfo();
  52. TRI = mf.getSubtarget().getRegisterInfo();
  53. MF = &mf;
  54. Virt2PhysMap.clear();
  55. Virt2StackSlotMap.clear();
  56. Virt2SplitMap.clear();
  57. grow();
  58. return false;
  59. }
  60. void VirtRegMap::grow() {
  61. unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
  62. Virt2PhysMap.resize(NumRegs);
  63. Virt2StackSlotMap.resize(NumRegs);
  64. Virt2SplitMap.resize(NumRegs);
  65. }
  66. unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
  67. int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
  68. RC->getAlignment());
  69. ++NumSpillSlots;
  70. return SS;
  71. }
  72. bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
  73. unsigned Hint = MRI->getSimpleHint(VirtReg);
  74. if (!Hint)
  75. return 0;
  76. if (TargetRegisterInfo::isVirtualRegister(Hint))
  77. Hint = getPhys(Hint);
  78. return getPhys(VirtReg) == Hint;
  79. }
  80. bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
  81. std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
  82. if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
  83. return true;
  84. if (TargetRegisterInfo::isVirtualRegister(Hint.second))
  85. return hasPhys(Hint.second);
  86. return false;
  87. }
  88. int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
  89. assert(TargetRegisterInfo::isVirtualRegister(virtReg));
  90. assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
  91. "attempt to assign stack slot to already spilled register");
  92. const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
  93. return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
  94. }
  95. void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
  96. assert(TargetRegisterInfo::isVirtualRegister(virtReg));
  97. assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
  98. "attempt to assign stack slot to already spilled register");
  99. assert((SS >= 0 ||
  100. (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
  101. "illegal fixed frame index");
  102. Virt2StackSlotMap[virtReg] = SS;
  103. }
  104. void VirtRegMap::print(raw_ostream &OS, const Module*) const {
  105. OS << "********** REGISTER MAP **********\n";
  106. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  107. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  108. if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
  109. OS << '[' << PrintReg(Reg, TRI) << " -> "
  110. << PrintReg(Virt2PhysMap[Reg], TRI) << "] "
  111. << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  112. }
  113. }
  114. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  115. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  116. if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
  117. OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
  118. << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  119. }
  120. }
  121. OS << '\n';
  122. }
  123. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  124. void VirtRegMap::dump() const {
  125. print(dbgs());
  126. }
  127. #endif
  128. //===----------------------------------------------------------------------===//
  129. // VirtRegRewriter
  130. //===----------------------------------------------------------------------===//
  131. //
  132. // The VirtRegRewriter is the last of the register allocator passes.
  133. // It rewrites virtual registers to physical registers as specified in the
  134. // VirtRegMap analysis. It also updates live-in information on basic blocks
  135. // according to LiveIntervals.
  136. //
  137. namespace {
  138. class VirtRegRewriter : public MachineFunctionPass {
  139. MachineFunction *MF;
  140. const TargetMachine *TM;
  141. const TargetRegisterInfo *TRI;
  142. const TargetInstrInfo *TII;
  143. MachineRegisterInfo *MRI;
  144. SlotIndexes *Indexes;
  145. LiveIntervals *LIS;
  146. VirtRegMap *VRM;
  147. void rewrite();
  148. void addMBBLiveIns();
  149. bool readsUndefSubreg(const MachineOperand &MO) const;
  150. public:
  151. static char ID;
  152. VirtRegRewriter() : MachineFunctionPass(ID) {}
  153. void getAnalysisUsage(AnalysisUsage &AU) const override;
  154. bool runOnMachineFunction(MachineFunction&) override;
  155. };
  156. } // end anonymous namespace
  157. char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
  158. INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
  159. "Virtual Register Rewriter", false, false)
  160. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  161. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  162. INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
  163. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  164. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  165. INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
  166. "Virtual Register Rewriter", false, false)
  167. char VirtRegRewriter::ID = 0;
  168. void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
  169. AU.setPreservesCFG();
  170. AU.addRequired<LiveIntervals>();
  171. AU.addRequired<SlotIndexes>();
  172. AU.addPreserved<SlotIndexes>();
  173. AU.addRequired<LiveDebugVariables>();
  174. AU.addRequired<LiveStacks>();
  175. AU.addPreserved<LiveStacks>();
  176. AU.addRequired<VirtRegMap>();
  177. MachineFunctionPass::getAnalysisUsage(AU);
  178. }
  179. bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
  180. MF = &fn;
  181. TM = &MF->getTarget();
  182. TRI = MF->getSubtarget().getRegisterInfo();
  183. TII = MF->getSubtarget().getInstrInfo();
  184. MRI = &MF->getRegInfo();
  185. Indexes = &getAnalysis<SlotIndexes>();
  186. LIS = &getAnalysis<LiveIntervals>();
  187. VRM = &getAnalysis<VirtRegMap>();
  188. DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
  189. << "********** Function: "
  190. << MF->getName() << '\n');
  191. DEBUG(VRM->dump());
  192. // Add kill flags while we still have virtual registers.
  193. LIS->addKillFlags(VRM);
  194. // Live-in lists on basic blocks are required for physregs.
  195. addMBBLiveIns();
  196. // Rewrite virtual registers.
  197. rewrite();
  198. // Write out new DBG_VALUE instructions.
  199. getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
  200. // All machine operands and other references to virtual registers have been
  201. // replaced. Remove the virtual registers and release all the transient data.
  202. VRM->clearAllVirt();
  203. MRI->clearVirtRegs();
  204. return true;
  205. }
  206. // Compute MBB live-in lists from virtual register live ranges and their
  207. // assignments.
  208. void VirtRegRewriter::addMBBLiveIns() {
  209. SmallVector<MachineBasicBlock*, 16> LiveIn;
  210. for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
  211. unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
  212. if (MRI->reg_nodbg_empty(VirtReg))
  213. continue;
  214. LiveInterval &LI = LIS->getInterval(VirtReg);
  215. if (LI.empty() || LIS->intervalIsInOneMBB(LI))
  216. continue;
  217. // This is a virtual register that is live across basic blocks. Its
  218. // assigned PhysReg must be marked as live-in to those blocks.
  219. unsigned PhysReg = VRM->getPhys(VirtReg);
  220. assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
  221. if (LI.hasSubRanges()) {
  222. for (LiveInterval::SubRange &S : LI.subranges()) {
  223. for (const auto &Seg : S.segments) {
  224. if (!Indexes->findLiveInMBBs(Seg.start, Seg.end, LiveIn))
  225. continue;
  226. for (MCSubRegIndexIterator SR(PhysReg, TRI); SR.isValid(); ++SR) {
  227. unsigned SubReg = SR.getSubReg();
  228. unsigned SubRegIndex = SR.getSubRegIndex();
  229. unsigned SubRegLaneMask = TRI->getSubRegIndexLaneMask(SubRegIndex);
  230. if ((SubRegLaneMask & S.LaneMask) == 0)
  231. continue;
  232. for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
  233. LiveIn[i]->addLiveIn(SubReg);
  234. }
  235. }
  236. LiveIn.clear();
  237. }
  238. }
  239. } else {
  240. // Scan the segments of LI.
  241. for (const auto &Seg : LI.segments) {
  242. if (!Indexes->findLiveInMBBs(Seg.start, Seg.end, LiveIn))
  243. continue;
  244. for (unsigned i = 0, e = LiveIn.size(); i != e; ++i)
  245. LiveIn[i]->addLiveIn(PhysReg);
  246. LiveIn.clear();
  247. }
  248. }
  249. }
  250. // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
  251. // each MBB's LiveIns set before calling addLiveIn on them.
  252. for (MachineBasicBlock &MBB : *MF)
  253. MBB.sortUniqueLiveIns();
  254. }
  255. /// Returns true if the given machine operand \p MO only reads undefined lanes.
  256. /// The function only works for use operands with a subregister set.
  257. bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
  258. // Shortcut if the operand is already marked undef.
  259. if (MO.isUndef())
  260. return true;
  261. unsigned Reg = MO.getReg();
  262. const LiveInterval &LI = LIS->getInterval(Reg);
  263. const MachineInstr &MI = *MO.getParent();
  264. SlotIndex BaseIndex = LIS->getInstructionIndex(&MI);
  265. // This code is only meant to handle reading undefined subregisters which
  266. // we couldn't properly detect before.
  267. assert(LI.liveAt(BaseIndex) &&
  268. "Reads of completely dead register should be marked undef already");
  269. unsigned SubRegIdx = MO.getSubReg();
  270. unsigned UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
  271. // See if any of the relevant subregister liveranges is defined at this point.
  272. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  273. if ((SR.LaneMask & UseMask) != 0 && SR.liveAt(BaseIndex))
  274. return false;
  275. }
  276. return true;
  277. }
  278. void VirtRegRewriter::rewrite() {
  279. bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
  280. SmallVector<unsigned, 8> SuperDeads;
  281. SmallVector<unsigned, 8> SuperDefs;
  282. SmallVector<unsigned, 8> SuperKills;
  283. for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
  284. MBBI != MBBE; ++MBBI) {
  285. DEBUG(MBBI->print(dbgs(), Indexes));
  286. for (MachineBasicBlock::instr_iterator
  287. MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
  288. MachineInstr *MI = MII;
  289. ++MII;
  290. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  291. MOE = MI->operands_end(); MOI != MOE; ++MOI) {
  292. MachineOperand &MO = *MOI;
  293. // Make sure MRI knows about registers clobbered by regmasks.
  294. if (MO.isRegMask())
  295. MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
  296. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  297. continue;
  298. unsigned VirtReg = MO.getReg();
  299. unsigned PhysReg = VRM->getPhys(VirtReg);
  300. assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
  301. "Instruction uses unmapped VirtReg");
  302. assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
  303. // Preserve semantics of sub-register operands.
  304. unsigned SubReg = MO.getSubReg();
  305. if (SubReg != 0) {
  306. if (NoSubRegLiveness) {
  307. // A virtual register kill refers to the whole register, so we may
  308. // have to add <imp-use,kill> operands for the super-register. A
  309. // partial redef always kills and redefines the super-register.
  310. if (MO.readsReg() && (MO.isDef() || MO.isKill()))
  311. SuperKills.push_back(PhysReg);
  312. if (MO.isDef()) {
  313. // Also add implicit defs for the super-register.
  314. if (MO.isDead())
  315. SuperDeads.push_back(PhysReg);
  316. else
  317. SuperDefs.push_back(PhysReg);
  318. }
  319. } else {
  320. if (MO.isUse()) {
  321. if (readsUndefSubreg(MO))
  322. // We need to add an <undef> flag if the subregister is
  323. // completely undefined (and we are not adding super-register
  324. // defs).
  325. MO.setIsUndef(true);
  326. } else if (!MO.isDead()) {
  327. assert(MO.isDef());
  328. // Things get tricky when we ran out of lane mask bits and
  329. // merged multiple lanes into the overflow bit: In this case
  330. // our subregister liveness tracking isn't precise and we can't
  331. // know what subregister parts are undefined, fall back to the
  332. // implicit super-register def then.
  333. unsigned LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
  334. if (TargetRegisterInfo::isImpreciseLaneMask(LaneMask))
  335. SuperDefs.push_back(PhysReg);
  336. }
  337. }
  338. // The <def,undef> flag only makes sense for sub-register defs, and
  339. // we are substituting a full physreg. An <imp-use,kill> operand
  340. // from the SuperKills list will represent the partial read of the
  341. // super-register.
  342. if (MO.isDef())
  343. MO.setIsUndef(false);
  344. // PhysReg operands cannot have subregister indexes.
  345. PhysReg = TRI->getSubReg(PhysReg, SubReg);
  346. assert(PhysReg && "Invalid SubReg for physical register");
  347. MO.setSubReg(0);
  348. }
  349. // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
  350. // we need the inlining here.
  351. MO.setReg(PhysReg);
  352. }
  353. // Add any missing super-register kills after rewriting the whole
  354. // instruction.
  355. while (!SuperKills.empty())
  356. MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
  357. while (!SuperDeads.empty())
  358. MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
  359. while (!SuperDefs.empty())
  360. MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
  361. DEBUG(dbgs() << "> " << *MI);
  362. // Finally, remove any identity copies.
  363. if (MI->isIdentityCopy()) {
  364. ++NumIdCopies;
  365. DEBUG(dbgs() << "Deleting identity copy.\n");
  366. if (Indexes)
  367. Indexes->removeMachineInstrFromMaps(MI);
  368. // It's safe to erase MI because MII has already been incremented.
  369. MI->eraseFromParent();
  370. }
  371. }
  372. }
  373. }