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 19 #define DEBUG_TYPE "regalloc" 20 #include "llvm/CodeGen/VirtRegMap.h" 21 #include "LiveDebugVariables.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SparseSet.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 26 #include "llvm/CodeGen/LiveStackAnalysis.h" 27 #include "llvm/CodeGen/MachineFrameInfo.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineInstrBuilder.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/Passes.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Compiler.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetInstrInfo.h" 38 #include "llvm/Target/TargetMachine.h" 39 #include "llvm/Target/TargetRegisterInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 STATISTIC(NumSpillSlots, "Number of spill slots allocated"); 44 STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting"); 45 46 //===----------------------------------------------------------------------===// 47 // VirtRegMap implementation 48 //===----------------------------------------------------------------------===// 49 50 char VirtRegMap::ID = 0; 51 52 INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false) 53 54 bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) { 55 MRI = &mf.getRegInfo(); 56 TII = mf.getTarget().getInstrInfo(); 57 TRI = mf.getTarget().getRegisterInfo(); 58 MF = &mf; 59 60 Virt2PhysMap.clear(); 61 Virt2StackSlotMap.clear(); 62 Virt2SplitMap.clear(); 63 64 grow(); 65 return false; 66 } 67 68 void VirtRegMap::grow() { 69 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs(); 70 Virt2PhysMap.resize(NumRegs); 71 Virt2StackSlotMap.resize(NumRegs); 72 Virt2SplitMap.resize(NumRegs); 73 } 74 75 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) { 76 int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(), 77 RC->getAlignment()); 78 ++NumSpillSlots; 79 return SS; 80 } 81 82 bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) { 83 unsigned Hint = MRI->getSimpleHint(VirtReg); 84 if (!Hint) 85 return 0; 86 if (TargetRegisterInfo::isVirtualRegister(Hint)) 87 Hint = getPhys(Hint); 88 return getPhys(VirtReg) == Hint; 89 } 90 91 bool VirtRegMap::hasKnownPreference(unsigned VirtReg) { 92 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg); 93 if (TargetRegisterInfo::isPhysicalRegister(Hint.second)) 94 return true; 95 if (TargetRegisterInfo::isVirtualRegister(Hint.second)) 96 return hasPhys(Hint.second); 97 return false; 98 } 99 100 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) { 101 assert(TargetRegisterInfo::isVirtualRegister(virtReg)); 102 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT && 103 "attempt to assign stack slot to already spilled register"); 104 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg); 105 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC); 106 } 107 108 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) { 109 assert(TargetRegisterInfo::isVirtualRegister(virtReg)); 110 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT && 111 "attempt to assign stack slot to already spilled register"); 112 assert((SS >= 0 || 113 (SS >= MF->getFrameInfo()->getObjectIndexBegin())) && 114 "illegal fixed frame index"); 115 Virt2StackSlotMap[virtReg] = SS; 116 } 117 118 void VirtRegMap::print(raw_ostream &OS, const Module*) const { 119 OS << "********** REGISTER MAP **********\n"; 120 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 121 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 122 if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) { 123 OS << '[' << PrintReg(Reg, TRI) << " -> " 124 << PrintReg(Virt2PhysMap[Reg], TRI) << "] " 125 << MRI->getRegClass(Reg)->getName() << "\n"; 126 } 127 } 128 129 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 130 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 131 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) { 132 OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg] 133 << "] " << MRI->getRegClass(Reg)->getName() << "\n"; 134 } 135 } 136 OS << '\n'; 137 } 138 139 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 140 void VirtRegMap::dump() const { 141 print(dbgs()); 142 } 143 #endif 144 145 //===----------------------------------------------------------------------===// 146 // VirtRegRewriter 147 //===----------------------------------------------------------------------===// 148 // 149 // The VirtRegRewriter is the last of the register allocator passes. 150 // It rewrites virtual registers to physical registers as specified in the 151 // VirtRegMap analysis. It also updates live-in information on basic blocks 152 // according to LiveIntervals. 153 // 154 namespace { 155 class VirtRegRewriter : public MachineFunctionPass { 156 MachineFunction *MF; 157 const TargetMachine *TM; 158 const TargetRegisterInfo *TRI; 159 const TargetInstrInfo *TII; 160 MachineRegisterInfo *MRI; 161 SlotIndexes *Indexes; 162 LiveIntervals *LIS; 163 VirtRegMap *VRM; 164 SparseSet<unsigned> PhysRegs; 165 166 void rewrite(); 167 void addMBBLiveIns(); 168 public: 169 static char ID; 170 VirtRegRewriter() : MachineFunctionPass(ID) {} 171 172 void getAnalysisUsage(AnalysisUsage &AU) const override; 173 174 bool runOnMachineFunction(MachineFunction&) override; 175 }; 176 } // end anonymous namespace 177 178 char &llvm::VirtRegRewriterID = VirtRegRewriter::ID; 179 180 INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter", 181 "Virtual Register Rewriter", false, false) 182 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 183 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 184 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables) 185 INITIALIZE_PASS_DEPENDENCY(LiveStacks) 186 INITIALIZE_PASS_DEPENDENCY(VirtRegMap) 187 INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter", 188 "Virtual Register Rewriter", false, false) 189 190 char VirtRegRewriter::ID = 0; 191 192 void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const { 193 AU.setPreservesCFG(); 194 AU.addRequired<LiveIntervals>(); 195 AU.addRequired<SlotIndexes>(); 196 AU.addPreserved<SlotIndexes>(); 197 AU.addRequired<LiveDebugVariables>(); 198 AU.addRequired<LiveStacks>(); 199 AU.addPreserved<LiveStacks>(); 200 AU.addRequired<VirtRegMap>(); 201 MachineFunctionPass::getAnalysisUsage(AU); 202 } 203 204 bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) { 205 MF = &fn; 206 TM = &MF->getTarget(); 207 TRI = TM->getRegisterInfo(); 208 TII = TM->getInstrInfo(); 209 MRI = &MF->getRegInfo(); 210 Indexes = &getAnalysis<SlotIndexes>(); 211 LIS = &getAnalysis<LiveIntervals>(); 212 VRM = &getAnalysis<VirtRegMap>(); 213 DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n" 214 << "********** Function: " 215 << MF->getName() << '\n'); 216 DEBUG(VRM->dump()); 217 218 // Add kill flags while we still have virtual registers. 219 LIS->addKillFlags(VRM); 220 221 // Live-in lists on basic blocks are required for physregs. 222 addMBBLiveIns(); 223 224 // Rewrite virtual registers. 225 rewrite(); 226 227 // Write out new DBG_VALUE instructions. 228 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM); 229 230 // All machine operands and other references to virtual registers have been 231 // replaced. Remove the virtual registers and release all the transient data. 232 VRM->clearAllVirt(); 233 MRI->clearVirtRegs(); 234 return true; 235 } 236 237 // Compute MBB live-in lists from virtual register live ranges and their 238 // assignments. 239 void VirtRegRewriter::addMBBLiveIns() { 240 SmallVector<MachineBasicBlock*, 16> LiveIn; 241 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) { 242 unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx); 243 if (MRI->reg_nodbg_empty(VirtReg)) 244 continue; 245 LiveInterval &LI = LIS->getInterval(VirtReg); 246 if (LI.empty() || LIS->intervalIsInOneMBB(LI)) 247 continue; 248 // This is a virtual register that is live across basic blocks. Its 249 // assigned PhysReg must be marked as live-in to those blocks. 250 unsigned PhysReg = VRM->getPhys(VirtReg); 251 assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register."); 252 253 // Scan the segments of LI. 254 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I != E; 255 ++I) { 256 if (!Indexes->findLiveInMBBs(I->start, I->end, LiveIn)) 257 continue; 258 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) 259 if (!LiveIn[i]->isLiveIn(PhysReg)) 260 LiveIn[i]->addLiveIn(PhysReg); 261 LiveIn.clear(); 262 } 263 } 264 } 265 266 void VirtRegRewriter::rewrite() { 267 SmallVector<unsigned, 8> SuperDeads; 268 SmallVector<unsigned, 8> SuperDefs; 269 SmallVector<unsigned, 8> SuperKills; 270 SmallPtrSet<const MachineInstr *, 4> NoReturnInsts; 271 272 // Here we have a SparseSet to hold which PhysRegs are actually encountered 273 // in the MF we are about to iterate over so that later when we call 274 // setPhysRegUsed, we are only doing it for physRegs that were actually found 275 // in the program and not for all of the possible physRegs for the given 276 // target architecture. If the target has a lot of physRegs, then for a small 277 // program there will be a significant compile time reduction here. 278 PhysRegs.clear(); 279 PhysRegs.setUniverse(TRI->getNumRegs()); 280 281 // The function with uwtable should guarantee that the stack unwinder 282 // can unwind the stack to the previous frame. Thus, we can't apply the 283 // noreturn optimization if the caller function has uwtable attribute. 284 bool HasUWTable = MF->getFunction()->hasFnAttribute(Attribute::UWTable); 285 286 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end(); 287 MBBI != MBBE; ++MBBI) { 288 DEBUG(MBBI->print(dbgs(), Indexes)); 289 bool IsExitBB = MBBI->succ_empty(); 290 for (MachineBasicBlock::instr_iterator 291 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) { 292 MachineInstr *MI = MII; 293 ++MII; 294 295 // Check if this instruction is a call to a noreturn function. If this 296 // is a call to noreturn function and we don't need the stack unwinding 297 // functionality (i.e. this function does not have uwtable attribute and 298 // the callee function has the nounwind attribute), then we can ignore 299 // the definitions set by this instruction. 300 if (!HasUWTable && IsExitBB && MI->isCall()) { 301 for (MachineInstr::mop_iterator MOI = MI->operands_begin(), 302 MOE = MI->operands_end(); MOI != MOE; ++MOI) { 303 MachineOperand &MO = *MOI; 304 if (!MO.isGlobal()) 305 continue; 306 const Function *Func = dyn_cast<Function>(MO.getGlobal()); 307 if (!Func || !Func->hasFnAttribute(Attribute::NoReturn) || 308 // We need to keep correct unwind information 309 // even if the function will not return, since the 310 // runtime may need it. 311 !Func->hasFnAttribute(Attribute::NoUnwind)) 312 continue; 313 NoReturnInsts.insert(MI); 314 break; 315 } 316 } 317 318 for (MachineInstr::mop_iterator MOI = MI->operands_begin(), 319 MOE = MI->operands_end(); MOI != MOE; ++MOI) { 320 MachineOperand &MO = *MOI; 321 322 // Make sure MRI knows about registers clobbered by regmasks. 323 if (MO.isRegMask()) 324 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask()); 325 326 // If we encounter a VirtReg or PhysReg then get at the PhysReg and add 327 // it to the physreg bitset. Later we use only the PhysRegs that were 328 // actually encountered in the MF to populate the MRI's used physregs. 329 if (MO.isReg() && MO.getReg()) 330 PhysRegs.insert( 331 TargetRegisterInfo::isVirtualRegister(MO.getReg()) ? 332 VRM->getPhys(MO.getReg()) : 333 MO.getReg()); 334 335 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg())) 336 continue; 337 unsigned VirtReg = MO.getReg(); 338 unsigned PhysReg = VRM->getPhys(VirtReg); 339 assert(PhysReg != VirtRegMap::NO_PHYS_REG && 340 "Instruction uses unmapped VirtReg"); 341 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment"); 342 343 // Preserve semantics of sub-register operands. 344 if (MO.getSubReg()) { 345 // A virtual register kill refers to the whole register, so we may 346 // have to add <imp-use,kill> operands for the super-register. A 347 // partial redef always kills and redefines the super-register. 348 if (MO.readsReg() && (MO.isDef() || MO.isKill())) 349 SuperKills.push_back(PhysReg); 350 351 if (MO.isDef()) { 352 // The <def,undef> flag only makes sense for sub-register defs, and 353 // we are substituting a full physreg. An <imp-use,kill> operand 354 // from the SuperKills list will represent the partial read of the 355 // super-register. 356 MO.setIsUndef(false); 357 358 // Also add implicit defs for the super-register. 359 if (MO.isDead()) 360 SuperDeads.push_back(PhysReg); 361 else 362 SuperDefs.push_back(PhysReg); 363 } 364 365 // PhysReg operands cannot have subregister indexes. 366 PhysReg = TRI->getSubReg(PhysReg, MO.getSubReg()); 367 assert(PhysReg && "Invalid SubReg for physical register"); 368 MO.setSubReg(0); 369 } 370 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but 371 // we need the inlining here. 372 MO.setReg(PhysReg); 373 } 374 375 // Add any missing super-register kills after rewriting the whole 376 // instruction. 377 while (!SuperKills.empty()) 378 MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true); 379 380 while (!SuperDeads.empty()) 381 MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true); 382 383 while (!SuperDefs.empty()) 384 MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI); 385 386 DEBUG(dbgs() << "> " << *MI); 387 388 // Finally, remove any identity copies. 389 if (MI->isIdentityCopy()) { 390 ++NumIdCopies; 391 if (MI->getNumOperands() == 2) { 392 DEBUG(dbgs() << "Deleting identity copy.\n"); 393 if (Indexes) 394 Indexes->removeMachineInstrFromMaps(MI); 395 // It's safe to erase MI because MII has already been incremented. 396 MI->eraseFromParent(); 397 } else { 398 // Transform identity copy to a KILL to deal with subregisters. 399 MI->setDesc(TII->get(TargetOpcode::KILL)); 400 DEBUG(dbgs() << "Identity copy: " << *MI); 401 } 402 } 403 } 404 } 405 406 // Tell MRI about physical registers in use. 407 if (NoReturnInsts.empty()) { 408 for (SparseSet<unsigned>::iterator 409 RegI = PhysRegs.begin(), E = PhysRegs.end(); RegI != E; ++RegI) 410 if (!MRI->reg_nodbg_empty(*RegI)) 411 MRI->setPhysRegUsed(*RegI); 412 } else { 413 for (SparseSet<unsigned>::iterator 414 I = PhysRegs.begin(), E = PhysRegs.end(); I != E; ++I) { 415 unsigned Reg = *I; 416 if (MRI->reg_nodbg_empty(Reg)) 417 continue; 418 // Check if this register has a use that will impact the rest of the 419 // code. Uses in debug and noreturn instructions do not impact the 420 // generated code. 421 for (MachineInstr &It : MRI->reg_nodbg_instructions(Reg)) { 422 if (!NoReturnInsts.count(&It)) { 423 MRI->setPhysRegUsed(Reg); 424 break; 425 } 426 } 427 } 428 } 429 } 430 431