VirtRegMap.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. //===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the VirtRegMap class.
  10. //
  11. // It also contains implementations of the Spiller interface, which, given a
  12. // virtual register map and a machine function, eliminates all virtual
  13. // references by replacing them with physical register references - adding spill
  14. // code as necessary.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/CodeGen/VirtRegMap.h"
  18. #include "LiveDebugVariables.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/CodeGen/LiveInterval.h"
  22. #include "llvm/CodeGen/LiveIntervals.h"
  23. #include "llvm/CodeGen/LiveStacks.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineFrameInfo.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineOperand.h"
  30. #include "llvm/CodeGen/MachineRegisterInfo.h"
  31. #include "llvm/CodeGen/SlotIndexes.h"
  32. #include "llvm/CodeGen/TargetInstrInfo.h"
  33. #include "llvm/CodeGen/TargetOpcodes.h"
  34. #include "llvm/CodeGen/TargetRegisterInfo.h"
  35. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  36. #include "llvm/Config/llvm-config.h"
  37. #include "llvm/MC/LaneBitmask.h"
  38. #include "llvm/Pass.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include <cassert>
  43. #include <iterator>
  44. #include <utility>
  45. using namespace llvm;
  46. #define DEBUG_TYPE "regalloc"
  47. STATISTIC(NumSpillSlots, "Number of spill slots allocated");
  48. STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
  49. //===----------------------------------------------------------------------===//
  50. // VirtRegMap implementation
  51. //===----------------------------------------------------------------------===//
  52. char VirtRegMap::ID = 0;
  53. INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
  54. bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
  55. MRI = &mf.getRegInfo();
  56. TII = mf.getSubtarget().getInstrInfo();
  57. TRI = mf.getSubtarget().getRegisterInfo();
  58. MF = &mf;
  59. Virt2PhysMap.clear();
  60. Virt2StackSlotMap.clear();
  61. Virt2SplitMap.clear();
  62. grow();
  63. return false;
  64. }
  65. void VirtRegMap::grow() {
  66. unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
  67. Virt2PhysMap.resize(NumRegs);
  68. Virt2StackSlotMap.resize(NumRegs);
  69. Virt2SplitMap.resize(NumRegs);
  70. }
  71. void VirtRegMap::assignVirt2Phys(Register virtReg, MCPhysReg physReg) {
  72. assert(virtReg.isVirtual() && Register::isPhysicalRegister(physReg));
  73. assert(Virt2PhysMap[virtReg.id()] == NO_PHYS_REG &&
  74. "attempt to assign physical register to already mapped "
  75. "virtual register");
  76. assert(!getRegInfo().isReserved(physReg) &&
  77. "Attempt to map virtReg to a reserved physReg");
  78. Virt2PhysMap[virtReg.id()] = physReg;
  79. }
  80. unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
  81. unsigned Size = TRI->getSpillSize(*RC);
  82. unsigned Align = TRI->getSpillAlignment(*RC);
  83. int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Align);
  84. ++NumSpillSlots;
  85. return SS;
  86. }
  87. bool VirtRegMap::hasPreferredPhys(Register VirtReg) {
  88. Register Hint = MRI->getSimpleHint(VirtReg);
  89. if (!Hint.isValid())
  90. return false;
  91. if (Hint.isVirtual())
  92. Hint = getPhys(Hint);
  93. return getPhys(VirtReg) == Hint;
  94. }
  95. bool VirtRegMap::hasKnownPreference(Register VirtReg) {
  96. std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
  97. if (Register::isPhysicalRegister(Hint.second))
  98. return true;
  99. if (Register::isVirtualRegister(Hint.second))
  100. return hasPhys(Hint.second);
  101. return false;
  102. }
  103. int VirtRegMap::assignVirt2StackSlot(Register virtReg) {
  104. assert(virtReg.isVirtual());
  105. assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT &&
  106. "attempt to assign stack slot to already spilled register");
  107. const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
  108. return Virt2StackSlotMap[virtReg.id()] = createSpillSlot(RC);
  109. }
  110. void VirtRegMap::assignVirt2StackSlot(Register virtReg, int SS) {
  111. assert(virtReg.isVirtual());
  112. assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT &&
  113. "attempt to assign stack slot to already spilled register");
  114. assert((SS >= 0 ||
  115. (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
  116. "illegal fixed frame index");
  117. Virt2StackSlotMap[virtReg.id()] = SS;
  118. }
  119. void VirtRegMap::print(raw_ostream &OS, const Module*) const {
  120. OS << "********** REGISTER MAP **********\n";
  121. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  122. unsigned Reg = Register::index2VirtReg(i);
  123. if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
  124. OS << '[' << printReg(Reg, TRI) << " -> "
  125. << printReg(Virt2PhysMap[Reg], TRI) << "] "
  126. << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  127. }
  128. }
  129. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  130. unsigned Reg = Register::index2VirtReg(i);
  131. if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
  132. OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
  133. << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  134. }
  135. }
  136. OS << '\n';
  137. }
  138. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  139. LLVM_DUMP_METHOD void VirtRegMap::dump() const {
  140. print(dbgs());
  141. }
  142. #endif
  143. //===----------------------------------------------------------------------===//
  144. // VirtRegRewriter
  145. //===----------------------------------------------------------------------===//
  146. //
  147. // The VirtRegRewriter is the last of the register allocator passes.
  148. // It rewrites virtual registers to physical registers as specified in the
  149. // VirtRegMap analysis. It also updates live-in information on basic blocks
  150. // according to LiveIntervals.
  151. //
  152. namespace {
  153. class VirtRegRewriter : public MachineFunctionPass {
  154. MachineFunction *MF;
  155. const TargetRegisterInfo *TRI;
  156. const TargetInstrInfo *TII;
  157. MachineRegisterInfo *MRI;
  158. SlotIndexes *Indexes;
  159. LiveIntervals *LIS;
  160. VirtRegMap *VRM;
  161. void rewrite();
  162. void addMBBLiveIns();
  163. bool readsUndefSubreg(const MachineOperand &MO) const;
  164. void addLiveInsForSubRanges(const LiveInterval &LI, Register PhysReg) const;
  165. void handleIdentityCopy(MachineInstr &MI) const;
  166. void expandCopyBundle(MachineInstr &MI) const;
  167. bool subRegLiveThrough(const MachineInstr &MI, Register SuperPhysReg) const;
  168. public:
  169. static char ID;
  170. VirtRegRewriter() : MachineFunctionPass(ID) {}
  171. void getAnalysisUsage(AnalysisUsage &AU) const override;
  172. bool runOnMachineFunction(MachineFunction&) override;
  173. MachineFunctionProperties getSetProperties() const override {
  174. return MachineFunctionProperties().set(
  175. MachineFunctionProperties::Property::NoVRegs);
  176. }
  177. };
  178. } // end anonymous namespace
  179. char VirtRegRewriter::ID = 0;
  180. char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
  181. INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
  182. "Virtual Register Rewriter", false, false)
  183. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  184. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  185. INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
  186. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  187. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  188. INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
  189. "Virtual Register Rewriter", false, false)
  190. void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
  191. AU.setPreservesCFG();
  192. AU.addRequired<LiveIntervals>();
  193. AU.addRequired<SlotIndexes>();
  194. AU.addPreserved<SlotIndexes>();
  195. AU.addRequired<LiveDebugVariables>();
  196. AU.addRequired<LiveStacks>();
  197. AU.addPreserved<LiveStacks>();
  198. AU.addRequired<VirtRegMap>();
  199. MachineFunctionPass::getAnalysisUsage(AU);
  200. }
  201. bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
  202. MF = &fn;
  203. TRI = MF->getSubtarget().getRegisterInfo();
  204. TII = MF->getSubtarget().getInstrInfo();
  205. MRI = &MF->getRegInfo();
  206. Indexes = &getAnalysis<SlotIndexes>();
  207. LIS = &getAnalysis<LiveIntervals>();
  208. VRM = &getAnalysis<VirtRegMap>();
  209. LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
  210. << "********** Function: " << MF->getName() << '\n');
  211. LLVM_DEBUG(VRM->dump());
  212. // Add kill flags while we still have virtual registers.
  213. LIS->addKillFlags(VRM);
  214. // Live-in lists on basic blocks are required for physregs.
  215. addMBBLiveIns();
  216. // Rewrite virtual registers.
  217. rewrite();
  218. // Write out new DBG_VALUE instructions.
  219. getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
  220. // All machine operands and other references to virtual registers have been
  221. // replaced. Remove the virtual registers and release all the transient data.
  222. VRM->clearAllVirt();
  223. MRI->clearVirtRegs();
  224. return true;
  225. }
  226. void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
  227. Register PhysReg) const {
  228. assert(!LI.empty());
  229. assert(LI.hasSubRanges());
  230. using SubRangeIteratorPair =
  231. std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
  232. SmallVector<SubRangeIteratorPair, 4> SubRanges;
  233. SlotIndex First;
  234. SlotIndex Last;
  235. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  236. SubRanges.push_back(std::make_pair(&SR, SR.begin()));
  237. if (!First.isValid() || SR.segments.front().start < First)
  238. First = SR.segments.front().start;
  239. if (!Last.isValid() || SR.segments.back().end > Last)
  240. Last = SR.segments.back().end;
  241. }
  242. // Check all mbb start positions between First and Last while
  243. // simulatenously advancing an iterator for each subrange.
  244. for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
  245. MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
  246. SlotIndex MBBBegin = MBBI->first;
  247. // Advance all subrange iterators so that their end position is just
  248. // behind MBBBegin (or the iterator is at the end).
  249. LaneBitmask LaneMask;
  250. for (auto &RangeIterPair : SubRanges) {
  251. const LiveInterval::SubRange *SR = RangeIterPair.first;
  252. LiveInterval::const_iterator &SRI = RangeIterPair.second;
  253. while (SRI != SR->end() && SRI->end <= MBBBegin)
  254. ++SRI;
  255. if (SRI == SR->end())
  256. continue;
  257. if (SRI->start <= MBBBegin)
  258. LaneMask |= SR->LaneMask;
  259. }
  260. if (LaneMask.none())
  261. continue;
  262. MachineBasicBlock *MBB = MBBI->second;
  263. MBB->addLiveIn(PhysReg, LaneMask);
  264. }
  265. }
  266. // Compute MBB live-in lists from virtual register live ranges and their
  267. // assignments.
  268. void VirtRegRewriter::addMBBLiveIns() {
  269. for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
  270. Register VirtReg = Register::index2VirtReg(Idx);
  271. if (MRI->reg_nodbg_empty(VirtReg))
  272. continue;
  273. LiveInterval &LI = LIS->getInterval(VirtReg);
  274. if (LI.empty() || LIS->intervalIsInOneMBB(LI))
  275. continue;
  276. // This is a virtual register that is live across basic blocks. Its
  277. // assigned PhysReg must be marked as live-in to those blocks.
  278. Register PhysReg = VRM->getPhys(VirtReg);
  279. assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
  280. if (LI.hasSubRanges()) {
  281. addLiveInsForSubRanges(LI, PhysReg);
  282. } else {
  283. // Go over MBB begin positions and see if we have segments covering them.
  284. // The following works because segments and the MBBIndex list are both
  285. // sorted by slot indexes.
  286. SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
  287. for (const auto &Seg : LI) {
  288. I = Indexes->advanceMBBIndex(I, Seg.start);
  289. for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
  290. MachineBasicBlock *MBB = I->second;
  291. MBB->addLiveIn(PhysReg);
  292. }
  293. }
  294. }
  295. }
  296. // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
  297. // each MBB's LiveIns set before calling addLiveIn on them.
  298. for (MachineBasicBlock &MBB : *MF)
  299. MBB.sortUniqueLiveIns();
  300. }
  301. /// Returns true if the given machine operand \p MO only reads undefined lanes.
  302. /// The function only works for use operands with a subregister set.
  303. bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
  304. // Shortcut if the operand is already marked undef.
  305. if (MO.isUndef())
  306. return true;
  307. Register Reg = MO.getReg();
  308. const LiveInterval &LI = LIS->getInterval(Reg);
  309. const MachineInstr &MI = *MO.getParent();
  310. SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
  311. // This code is only meant to handle reading undefined subregisters which
  312. // we couldn't properly detect before.
  313. assert(LI.liveAt(BaseIndex) &&
  314. "Reads of completely dead register should be marked undef already");
  315. unsigned SubRegIdx = MO.getSubReg();
  316. assert(SubRegIdx != 0 && LI.hasSubRanges());
  317. LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
  318. // See if any of the relevant subregister liveranges is defined at this point.
  319. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  320. if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
  321. return false;
  322. }
  323. return true;
  324. }
  325. void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) const {
  326. if (!MI.isIdentityCopy())
  327. return;
  328. LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
  329. ++NumIdCopies;
  330. // Copies like:
  331. // %r0 = COPY undef %r0
  332. // %al = COPY %al, implicit-def %eax
  333. // give us additional liveness information: The target (super-)register
  334. // must not be valid before this point. Replace the COPY with a KILL
  335. // instruction to maintain this information.
  336. if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
  337. MI.setDesc(TII->get(TargetOpcode::KILL));
  338. LLVM_DEBUG(dbgs() << " replace by: " << MI);
  339. return;
  340. }
  341. if (Indexes)
  342. Indexes->removeSingleMachineInstrFromMaps(MI);
  343. MI.eraseFromBundle();
  344. LLVM_DEBUG(dbgs() << " deleted.\n");
  345. }
  346. /// The liverange splitting logic sometimes produces bundles of copies when
  347. /// subregisters are involved. Expand these into a sequence of copy instructions
  348. /// after processing the last in the bundle. Does not update LiveIntervals
  349. /// which we shouldn't need for this instruction anymore.
  350. void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
  351. if (!MI.isCopy())
  352. return;
  353. if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
  354. SmallVector<MachineInstr *, 2> MIs({&MI});
  355. // Only do this when the complete bundle is made out of COPYs.
  356. MachineBasicBlock &MBB = *MI.getParent();
  357. for (MachineBasicBlock::reverse_instr_iterator I =
  358. std::next(MI.getReverseIterator()), E = MBB.instr_rend();
  359. I != E && I->isBundledWithSucc(); ++I) {
  360. if (!I->isCopy())
  361. return;
  362. MIs.push_back(&*I);
  363. }
  364. MachineInstr *FirstMI = MIs.back();
  365. auto anyRegsAlias = [](const MachineInstr *Dst,
  366. ArrayRef<MachineInstr *> Srcs,
  367. const TargetRegisterInfo *TRI) {
  368. for (const MachineInstr *Src : Srcs)
  369. if (Src != Dst)
  370. if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
  371. Src->getOperand(1).getReg()))
  372. return true;
  373. return false;
  374. };
  375. // If any of the destination registers in the bundle of copies alias any of
  376. // the source registers, try to schedule the instructions to avoid any
  377. // clobbering.
  378. for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
  379. for (int I = E; I--; )
  380. if (!anyRegsAlias(MIs[I], makeArrayRef(MIs).take_front(E), TRI)) {
  381. if (I + 1 != E)
  382. std::swap(MIs[I], MIs[E - 1]);
  383. --E;
  384. }
  385. if (PrevE == E) {
  386. MF->getFunction().getContext().emitError(
  387. "register rewriting failed: cycle in copy bundle");
  388. break;
  389. }
  390. }
  391. MachineInstr *BundleStart = FirstMI;
  392. for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
  393. // If instruction is in the middle of the bundle, move it before the
  394. // bundle starts, otherwise, just unbundle it. When we get to the last
  395. // instruction, the bundle will have been completely undone.
  396. if (BundledMI != BundleStart) {
  397. BundledMI->removeFromBundle();
  398. MBB.insert(FirstMI, BundledMI);
  399. } else if (BundledMI->isBundledWithSucc()) {
  400. BundledMI->unbundleFromSucc();
  401. BundleStart = &*std::next(BundledMI->getIterator());
  402. }
  403. if (Indexes && BundledMI != FirstMI)
  404. Indexes->insertMachineInstrInMaps(*BundledMI);
  405. }
  406. }
  407. }
  408. /// Check whether (part of) \p SuperPhysReg is live through \p MI.
  409. /// \pre \p MI defines a subregister of a virtual register that
  410. /// has been assigned to \p SuperPhysReg.
  411. bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
  412. Register SuperPhysReg) const {
  413. SlotIndex MIIndex = LIS->getInstructionIndex(MI);
  414. SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
  415. SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
  416. for (MCRegUnitIterator Unit(SuperPhysReg, TRI); Unit.isValid(); ++Unit) {
  417. const LiveRange &UnitRange = LIS->getRegUnit(*Unit);
  418. // If the regunit is live both before and after MI,
  419. // we assume it is live through.
  420. // Generally speaking, this is not true, because something like
  421. // "RU = op RU" would match that description.
  422. // However, we know that we are trying to assess whether
  423. // a def of a virtual reg, vreg, is live at the same time of RU.
  424. // If we are in the "RU = op RU" situation, that means that vreg
  425. // is defined at the same time as RU (i.e., "vreg, RU = op RU").
  426. // Thus, vreg and RU interferes and vreg cannot be assigned to
  427. // SuperPhysReg. Therefore, this situation cannot happen.
  428. if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
  429. return true;
  430. }
  431. return false;
  432. }
  433. void VirtRegRewriter::rewrite() {
  434. bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
  435. SmallVector<Register, 8> SuperDeads;
  436. SmallVector<Register, 8> SuperDefs;
  437. SmallVector<Register, 8> SuperKills;
  438. for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
  439. MBBI != MBBE; ++MBBI) {
  440. LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
  441. for (MachineBasicBlock::instr_iterator
  442. MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
  443. MachineInstr *MI = &*MII;
  444. ++MII;
  445. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  446. MOE = MI->operands_end(); MOI != MOE; ++MOI) {
  447. MachineOperand &MO = *MOI;
  448. // Make sure MRI knows about registers clobbered by regmasks.
  449. if (MO.isRegMask())
  450. MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
  451. if (!MO.isReg() || !MO.getReg().isVirtual())
  452. continue;
  453. Register VirtReg = MO.getReg();
  454. Register PhysReg = VRM->getPhys(VirtReg);
  455. assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
  456. "Instruction uses unmapped VirtReg");
  457. assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
  458. // Preserve semantics of sub-register operands.
  459. unsigned SubReg = MO.getSubReg();
  460. if (SubReg != 0) {
  461. if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
  462. // A virtual register kill refers to the whole register, so we may
  463. // have to add implicit killed operands for the super-register. A
  464. // partial redef always kills and redefines the super-register.
  465. if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
  466. (MO.isDef() && subRegLiveThrough(*MI, PhysReg)))
  467. SuperKills.push_back(PhysReg);
  468. if (MO.isDef()) {
  469. // Also add implicit defs for the super-register.
  470. if (MO.isDead())
  471. SuperDeads.push_back(PhysReg);
  472. else
  473. SuperDefs.push_back(PhysReg);
  474. }
  475. } else {
  476. if (MO.isUse()) {
  477. if (readsUndefSubreg(MO))
  478. // We need to add an <undef> flag if the subregister is
  479. // completely undefined (and we are not adding super-register
  480. // defs).
  481. MO.setIsUndef(true);
  482. } else if (!MO.isDead()) {
  483. assert(MO.isDef());
  484. }
  485. }
  486. // The def undef and def internal flags only make sense for
  487. // sub-register defs, and we are substituting a full physreg. An
  488. // implicit killed operand from the SuperKills list will represent the
  489. // partial read of the super-register.
  490. if (MO.isDef()) {
  491. MO.setIsUndef(false);
  492. MO.setIsInternalRead(false);
  493. }
  494. // PhysReg operands cannot have subregister indexes.
  495. PhysReg = TRI->getSubReg(PhysReg, SubReg);
  496. assert(PhysReg.isValid() && "Invalid SubReg for physical register");
  497. MO.setSubReg(0);
  498. }
  499. // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
  500. // we need the inlining here.
  501. MO.setReg(PhysReg);
  502. MO.setIsRenamable(true);
  503. }
  504. // Add any missing super-register kills after rewriting the whole
  505. // instruction.
  506. while (!SuperKills.empty())
  507. MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
  508. while (!SuperDeads.empty())
  509. MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
  510. while (!SuperDefs.empty())
  511. MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
  512. LLVM_DEBUG(dbgs() << "> " << *MI);
  513. expandCopyBundle(*MI);
  514. // We can remove identity copies right now.
  515. handleIdentityCopy(*MI);
  516. }
  517. }
  518. }