LLVM API Documentation
00001 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the LiveInterval analysis pass which is used 00011 // by the Linear Scan Register allocator. This pass linearizes the 00012 // basic blocks of the function in DFS order and uses the 00013 // LiveVariables pass to conservatively compute live intervals for 00014 // each virtual and physical register. 00015 // 00016 //===----------------------------------------------------------------------===// 00017 00018 #define DEBUG_TYPE "liveintervals" 00019 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 00020 #include "VirtRegMap.h" 00021 #include "llvm/Value.h" 00022 #include "llvm/Analysis/AliasAnalysis.h" 00023 #include "llvm/CodeGen/LiveVariables.h" 00024 #include "llvm/CodeGen/MachineFrameInfo.h" 00025 #include "llvm/CodeGen/MachineInstr.h" 00026 #include "llvm/CodeGen/MachineLoopInfo.h" 00027 #include "llvm/CodeGen/MachineRegisterInfo.h" 00028 #include "llvm/CodeGen/Passes.h" 00029 #include "llvm/CodeGen/PseudoSourceValue.h" 00030 #include "llvm/Target/TargetRegisterInfo.h" 00031 #include "llvm/Target/TargetInstrInfo.h" 00032 #include "llvm/Target/TargetMachine.h" 00033 #include "llvm/Target/TargetOptions.h" 00034 #include "llvm/Support/CommandLine.h" 00035 #include "llvm/Support/Debug.h" 00036 #include "llvm/ADT/Statistic.h" 00037 #include "llvm/ADT/STLExtras.h" 00038 #include <algorithm> 00039 #include <cmath> 00040 using namespace llvm; 00041 00042 // Hidden options for help debugging. 00043 static cl::opt<bool> DisableReMat("disable-rematerialization", 00044 cl::init(false), cl::Hidden); 00045 00046 static cl::opt<bool> SplitAtBB("split-intervals-at-bb", 00047 cl::init(true), cl::Hidden); 00048 static cl::opt<int> SplitLimit("split-limit", 00049 cl::init(-1), cl::Hidden); 00050 00051 static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden); 00052 00053 static cl::opt<bool> EnableFastSpilling("fast-spill", 00054 cl::init(false), cl::Hidden); 00055 00056 STATISTIC(numIntervals, "Number of original intervals"); 00057 STATISTIC(numFolds , "Number of loads/stores folded into instructions"); 00058 STATISTIC(numSplits , "Number of intervals split"); 00059 00060 char LiveIntervals::ID = 0; 00061 static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis"); 00062 00063 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const { 00064 AU.addRequired<AliasAnalysis>(); 00065 AU.addPreserved<AliasAnalysis>(); 00066 AU.addPreserved<LiveVariables>(); 00067 AU.addRequired<LiveVariables>(); 00068 AU.addPreservedID(MachineLoopInfoID); 00069 AU.addPreservedID(MachineDominatorsID); 00070 00071 if (!StrongPHIElim) { 00072 AU.addPreservedID(PHIEliminationID); 00073 AU.addRequiredID(PHIEliminationID); 00074 } 00075 00076 AU.addRequiredID(TwoAddressInstructionPassID); 00077 MachineFunctionPass::getAnalysisUsage(AU); 00078 } 00079 00080 void LiveIntervals::releaseMemory() { 00081 // Free the live intervals themselves. 00082 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(), 00083 E = r2iMap_.end(); I != E; ++I) 00084 delete I->second; 00085 00086 MBB2IdxMap.clear(); 00087 Idx2MBBMap.clear(); 00088 mi2iMap_.clear(); 00089 i2miMap_.clear(); 00090 r2iMap_.clear(); 00091 // Release VNInfo memroy regions after all VNInfo objects are dtor'd. 00092 VNInfoAllocator.Reset(); 00093 while (!ClonedMIs.empty()) { 00094 MachineInstr *MI = ClonedMIs.back(); 00095 ClonedMIs.pop_back(); 00096 mf_->DeleteMachineInstr(MI); 00097 } 00098 } 00099 00100 void LiveIntervals::computeNumbering() { 00101 Index2MiMap OldI2MI = i2miMap_; 00102 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap; 00103 00104 Idx2MBBMap.clear(); 00105 MBB2IdxMap.clear(); 00106 mi2iMap_.clear(); 00107 i2miMap_.clear(); 00108 00109 FunctionSize = 0; 00110 00111 // Number MachineInstrs and MachineBasicBlocks. 00112 // Initialize MBB indexes to a sentinal. 00113 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U)); 00114 00115 unsigned MIIndex = 0; 00116 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end(); 00117 MBB != E; ++MBB) { 00118 unsigned StartIdx = MIIndex; 00119 00120 // Insert an empty slot at the beginning of each block. 00121 MIIndex += InstrSlots::NUM; 00122 i2miMap_.push_back(0); 00123 00124 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); 00125 I != E; ++I) { 00126 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second; 00127 assert(inserted && "multiple MachineInstr -> index mappings"); 00128 inserted = true; 00129 i2miMap_.push_back(I); 00130 MIIndex += InstrSlots::NUM; 00131 FunctionSize++; 00132 00133 // Insert max(1, numdefs) empty slots after every instruction. 00134 unsigned Slots = I->getDesc().getNumDefs(); 00135 if (Slots == 0) 00136 Slots = 1; 00137 MIIndex += InstrSlots::NUM * Slots; 00138 while (Slots--) 00139 i2miMap_.push_back(0); 00140 } 00141 00142 // Set the MBB2IdxMap entry for this MBB. 00143 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1); 00144 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB)); 00145 } 00146 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare()); 00147 00148 if (!OldI2MI.empty()) 00149 for (iterator OI = begin(), OE = end(); OI != OE; ++OI) { 00150 for (LiveInterval::iterator LI = OI->second->begin(), 00151 LE = OI->second->end(); LI != LE; ++LI) { 00152 00153 // Remap the start index of the live range to the corresponding new 00154 // number, or our best guess at what it _should_ correspond to if the 00155 // original instruction has been erased. This is either the following 00156 // instruction or its predecessor. 00157 unsigned index = LI->start / InstrSlots::NUM; 00158 unsigned offset = LI->start % InstrSlots::NUM; 00159 if (offset == InstrSlots::LOAD) { 00160 std::vector<IdxMBBPair>::const_iterator I = 00161 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start); 00162 // Take the pair containing the index 00163 std::vector<IdxMBBPair>::const_iterator J = 00164 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I; 00165 00166 LI->start = getMBBStartIdx(J->second); 00167 } else { 00168 LI->start = mi2iMap_[OldI2MI[index]] + offset; 00169 } 00170 00171 // Remap the ending index in the same way that we remapped the start, 00172 // except for the final step where we always map to the immediately 00173 // following instruction. 00174 index = (LI->end - 1) / InstrSlots::NUM; 00175 offset = LI->end % InstrSlots::NUM; 00176 if (offset == InstrSlots::LOAD) { 00177 // VReg dies at end of block. 00178 std::vector<IdxMBBPair>::const_iterator I = 00179 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end); 00180 --I; 00181 00182 LI->end = getMBBEndIdx(I->second) + 1; 00183 } else { 00184 unsigned idx = index; 00185 while (index < OldI2MI.size() && !OldI2MI[index]) ++index; 00186 00187 if (index != OldI2MI.size()) 00188 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0); 00189 else 00190 LI->end = InstrSlots::NUM * i2miMap_.size(); 00191 } 00192 } 00193 00194 for (LiveInterval::vni_iterator VNI = OI->second->vni_begin(), 00195 VNE = OI->second->vni_end(); VNI != VNE; ++VNI) { 00196 VNInfo* vni = *VNI; 00197 00198 // Remap the VNInfo def index, which works the same as the 00199 // start indices above. VN's with special sentinel defs 00200 // don't need to be remapped. 00201 if (vni->def != ~0U && vni->def != ~1U) { 00202 unsigned index = vni->def / InstrSlots::NUM; 00203 unsigned offset = vni->def % InstrSlots::NUM; 00204 if (offset == InstrSlots::LOAD) { 00205 std::vector<IdxMBBPair>::const_iterator I = 00206 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def); 00207 // Take the pair containing the index 00208 std::vector<IdxMBBPair>::const_iterator J = 00209 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I; 00210 00211 vni->def = getMBBStartIdx(J->second); 00212 } else { 00213 vni->def = mi2iMap_[OldI2MI[index]] + offset; 00214 } 00215 } 00216 00217 // Remap the VNInfo kill indices, which works the same as 00218 // the end indices above. 00219 for (size_t i = 0; i < vni->kills.size(); ++i) { 00220 // PHI kills don't need to be remapped. 00221 if (!vni->kills[i]) continue; 00222 00223 unsigned index = (vni->kills[i]-1) / InstrSlots::NUM; 00224 unsigned offset = vni->kills[i] % InstrSlots::NUM; 00225 if (offset == InstrSlots::LOAD) { 00226 std::vector<IdxMBBPair>::const_iterator I = 00227 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]); 00228 --I; 00229 00230 vni->kills[i] = getMBBEndIdx(I->second); 00231 } else { 00232 unsigned idx = index; 00233 while (index < OldI2MI.size() && !OldI2MI[index]) ++index; 00234 00235 if (index != OldI2MI.size()) 00236 vni->kills[i] = mi2iMap_[OldI2MI[index]] + 00237 (idx == index ? offset : 0); 00238 else 00239 vni->kills[i] = InstrSlots::NUM * i2miMap_.size(); 00240 } 00241 } 00242 } 00243 } 00244 } 00245 00246 /// runOnMachineFunction - Register allocate the whole function 00247 /// 00248 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) { 00249 mf_ = &fn; 00250 mri_ = &mf_->getRegInfo(); 00251 tm_ = &fn.getTarget(); 00252 tri_ = tm_->getRegisterInfo(); 00253 tii_ = tm_->getInstrInfo(); 00254 aa_ = &getAnalysis<AliasAnalysis>(); 00255 lv_ = &getAnalysis<LiveVariables>(); 00256 allocatableRegs_ = tri_->getAllocatableSet(fn); 00257 00258 computeNumbering(); 00259 computeIntervals(); 00260 00261 numIntervals += getNumIntervals(); 00262 00263 DEBUG(dump()); 00264 return true; 00265 } 00266 00267 /// print - Implement the dump method. 00268 void LiveIntervals::print(std::ostream &O, const Module* ) const { 00269 O << "********** INTERVALS **********\n"; 00270 for (const_iterator I = begin(), E = end(); I != E; ++I) { 00271 I->second->print(O, tri_); 00272 O << "\n"; 00273 } 00274 00275 O << "********** MACHINEINSTRS **********\n"; 00276 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end(); 00277 mbbi != mbbe; ++mbbi) { 00278 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n"; 00279 for (MachineBasicBlock::iterator mii = mbbi->begin(), 00280 mie = mbbi->end(); mii != mie; ++mii) { 00281 O << getInstructionIndex(mii) << '\t' << *mii; 00282 } 00283 } 00284 } 00285 00286 /// conflictsWithPhysRegDef - Returns true if the specified register 00287 /// is defined during the duration of the specified interval. 00288 bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li, 00289 VirtRegMap &vrm, unsigned reg) { 00290 for (LiveInterval::Ranges::const_iterator 00291 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) { 00292 for (unsigned index = getBaseIndex(I->start), 00293 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end; 00294 index += InstrSlots::NUM) { 00295 // skip deleted instructions 00296 while (index != end && !getInstructionFromIndex(index)) 00297 index += InstrSlots::NUM; 00298 if (index == end) break; 00299 00300 MachineInstr *MI = getInstructionFromIndex(index); 00301 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg; 00302 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg)) 00303 if (SrcReg == li.reg || DstReg == li.reg) 00304 continue; 00305 for (unsigned i = 0; i != MI->getNumOperands(); ++i) { 00306 MachineOperand& mop = MI->getOperand(i); 00307 if (!mop.isReg()) 00308 continue; 00309 unsigned PhysReg = mop.getReg(); 00310 if (PhysReg == 0 || PhysReg == li.reg) 00311 continue; 00312 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) { 00313 if (!vrm.hasPhys(PhysReg)) 00314 continue; 00315 PhysReg = vrm.getPhys(PhysReg); 00316 } 00317 if (PhysReg && tri_->regsOverlap(PhysReg, reg)) 00318 return true; 00319 } 00320 } 00321 } 00322 00323 return false; 00324 } 00325 00326 /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except 00327 /// it can check use as well. 00328 bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li, 00329 unsigned Reg, bool CheckUse, 00330 SmallPtrSet<MachineInstr*,32> &JoinedCopies) { 00331 for (LiveInterval::Ranges::const_iterator 00332 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) { 00333 for (unsigned index = getBaseIndex(I->start), 00334 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end; 00335 index += InstrSlots::NUM) { 00336 // Skip deleted instructions. 00337 MachineInstr *MI = 0; 00338 while (index != end) { 00339 MI = getInstructionFromIndex(index); 00340 if (MI) 00341 break; 00342 index += InstrSlots::NUM; 00343 } 00344 if (index == end) break; 00345 00346 if (JoinedCopies.count(MI)) 00347 continue; 00348 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 00349 MachineOperand& MO = MI->getOperand(i); 00350 if (!MO.isReg()) 00351 continue; 00352 if (MO.isUse() && !CheckUse) 00353 continue; 00354 unsigned PhysReg = MO.getReg(); 00355 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg)) 00356 continue; 00357 if (tri_->isSubRegister(Reg, PhysReg)) 00358 return true; 00359 } 00360 } 00361 } 00362 00363 return false; 00364 } 00365 00366 00367 void LiveIntervals::printRegName(unsigned reg) const { 00368 if (TargetRegisterInfo::isPhysicalRegister(reg)) 00369 cerr << tri_->getName(reg); 00370 else 00371 cerr << "%reg" << reg; 00372 } 00373 00374 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb, 00375 MachineBasicBlock::iterator mi, 00376 unsigned MIIdx, MachineOperand& MO, 00377 unsigned MOIdx, 00378 LiveInterval &interval) { 00379 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg)); 00380 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg); 00381 00382 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) { 00383 DOUT << "is a implicit_def\n"; 00384 return; 00385 } 00386 00387 // Virtual registers may be defined multiple times (due to phi 00388 // elimination and 2-addr elimination). Much of what we do only has to be 00389 // done once for the vreg. We use an empty interval to detect the first 00390 // time we see a vreg. 00391 if (interval.empty()) { 00392 // Get the Idx of the defining instructions. 00393 unsigned defIndex = getDefIndex(MIIdx); 00394 // Earlyclobbers move back one. 00395 if (MO.isEarlyClobber()) 00396 defIndex = getUseIndex(MIIdx); 00397 VNInfo *ValNo; 00398 MachineInstr *CopyMI = NULL; 00399 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg; 00400 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG || 00401 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG || 00402 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg)) 00403 CopyMI = mi; 00404 // Earlyclobbers move back one. 00405 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator); 00406 00407 assert(ValNo->id == 0 && "First value in interval is not 0?"); 00408 00409 // Loop over all of the blocks that the vreg is defined in. There are 00410 // two cases we have to handle here. The most common case is a vreg 00411 // whose lifetime is contained within a basic block. In this case there 00412 // will be a single kill, in MBB, which comes after the definition. 00413 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) { 00414 // FIXME: what about dead vars? 00415 unsigned killIdx; 00416 if (vi.Kills[0] != mi) 00417 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1; 00418 else 00419 killIdx = defIndex+1; 00420 00421 // If the kill happens after the definition, we have an intra-block 00422 // live range. 00423 if (killIdx > defIndex) { 00424 assert(vi.AliveBlocks.none() && 00425 "Shouldn't be alive across any blocks!"); 00426 LiveRange LR(defIndex, killIdx, ValNo); 00427 interval.addRange(LR); 00428 DOUT << " +" << LR << "\n"; 00429 interval.addKill(ValNo, killIdx); 00430 return; 00431 } 00432 } 00433 00434 // The other case we handle is when a virtual register lives to the end 00435 // of the defining block, potentially live across some blocks, then is 00436 // live into some number of blocks, but gets killed. Start by adding a 00437 // range that goes from this definition to the end of the defining block. 00438 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo); 00439 DOUT << " +" << NewLR; 00440 interval.addRange(NewLR); 00441 00442 // Iterate over all of the blocks that the variable is completely 00443 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the 00444 // live interval. 00445 for (int i = vi.AliveBlocks.find_first(); i != -1; 00446 i = vi.AliveBlocks.find_next(i)) { 00447 LiveRange LR(getMBBStartIdx(i), 00448 getMBBEndIdx(i)+1, // MBB ends at -1. 00449 ValNo); 00450 interval.addRange(LR); 00451 DOUT << " +" << LR; 00452 } 00453 00454 // Finally, this virtual register is live from the start of any killing 00455 // block to the 'use' slot of the killing instruction. 00456 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) { 00457 MachineInstr *Kill = vi.Kills[i]; 00458 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1; 00459 LiveRange LR(getMBBStartIdx(Kill->getParent()), 00460 killIdx, ValNo); 00461 interval.addRange(LR); 00462 interval.addKill(ValNo, killIdx); 00463 DOUT << " +" << LR; 00464 } 00465 00466 } else { 00467 // If this is the second time we see a virtual register definition, it 00468 // must be due to phi elimination or two addr elimination. If this is 00469 // the result of two address elimination, then the vreg is one of the 00470 // def-and-use register operand. 00471 if (mi->isRegReDefinedByTwoAddr(MOIdx)) { 00472 // If this is a two-address definition, then we have already processed 00473 // the live range. The only problem is that we didn't realize there 00474 // are actually two values in the live interval. Because of this we 00475 // need to take the LiveRegion that defines this register and split it 00476 // into two values. 00477 assert(interval.containsOneValue()); 00478 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def); 00479 unsigned RedefIndex = getDefIndex(MIIdx); 00480 // It cannot be an early clobber MO. 00481 assert(!MO.isEarlyClobber() && "Unexpected early clobber!"); 00482 00483 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1); 00484 VNInfo *OldValNo = OldLR->valno; 00485 00486 // Delete the initial value, which should be short and continuous, 00487 // because the 2-addr copy must be in the same MBB as the redef. 00488 interval.removeRange(DefIndex, RedefIndex); 00489 00490 // Two-address vregs should always only be redefined once. This means 00491 // that at this point, there should be exactly one value number in it. 00492 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!"); 00493 00494 // The new value number (#1) is defined by the instruction we claimed 00495 // defined value #0. 00496 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy, 00497 VNInfoAllocator); 00498 00499 // Value#0 is now defined by the 2-addr instruction. 00500 OldValNo->def = RedefIndex; 00501 OldValNo->copy = 0; 00502 00503 // Add the new live interval which replaces the range for the input copy. 00504 LiveRange LR(DefIndex, RedefIndex, ValNo); 00505 DOUT << " replace range with " << LR; 00506 interval.addRange(LR); 00507 interval.addKill(ValNo, RedefIndex); 00508 00509 // If this redefinition is dead, we need to add a dummy unit live 00510 // range covering the def slot. 00511 if (MO.isDead()) 00512 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo)); 00513 00514 DOUT << " RESULT: "; 00515 interval.print(DOUT, tri_); 00516 00517 } else { 00518 // Otherwise, this must be because of phi elimination. If this is the 00519 // first redefinition of the vreg that we have seen, go back and change 00520 // the live range in the PHI block to be a different value number. 00521 if (interval.containsOneValue()) { 00522 assert(vi.Kills.size() == 1 && 00523 "PHI elimination vreg should have one kill, the PHI itself!"); 00524 00525 // Remove the old range that we now know has an incorrect number. 00526 VNInfo *VNI = interval.getValNumInfo(0); 00527 MachineInstr *Killer = vi.Kills[0]; 00528 unsigned Start = getMBBStartIdx(Killer->getParent()); 00529 unsigned End = getUseIndex(getInstructionIndex(Killer))+1; 00530 DOUT << " Removing [" << Start << "," << End << "] from: "; 00531 interval.print(DOUT, tri_); DOUT << "\n"; 00532 interval.removeRange(Start, End); 00533 VNI->hasPHIKill = true; 00534 DOUT << " RESULT: "; interval.print(DOUT, tri_); 00535 00536 // Replace the interval with one of a NEW value number. Note that this 00537 // value number isn't actually defined by an instruction, weird huh? :) 00538 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator)); 00539 DOUT << " replace range with " << LR; 00540 interval.addRange(LR); 00541 interval.addKill(LR.valno, End); 00542 DOUT << " RESULT: "; interval.print(DOUT, tri_); 00543 } 00544 00545 // In the case of PHI elimination, each variable definition is only 00546 // live until the end of the block. We've already taken care of the 00547 // rest of the live range. 00548 unsigned defIndex = getDefIndex(MIIdx); 00549 // It cannot be an early clobber MO. 00550 assert(!MO.isEarlyClobber() && "Unexpected early clobber!"); 00551 00552 VNInfo *ValNo; 00553 MachineInstr *CopyMI = NULL; 00554 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg; 00555 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG || 00556 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG || 00557 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg)) 00558 CopyMI = mi; 00559 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator); 00560 00561 unsigned killIndex = getMBBEndIdx(mbb) + 1; 00562 LiveRange LR(defIndex, killIndex, ValNo); 00563 interval.addRange(LR); 00564 interval.addKill(ValNo, killIndex); 00565 ValNo->hasPHIKill = true; 00566 DOUT << " +" << LR; 00567 } 00568 } 00569 00570 DOUT << '\n'; 00571 } 00572 00573 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB, 00574 MachineBasicBlock::iterator mi, 00575 unsigned MIIdx, 00576 MachineOperand& MO, 00577 LiveInterval &interval, 00578 MachineInstr *CopyMI) { 00579 // A physical register cannot be live across basic block, so its 00580 // lifetime must end somewhere in its defining basic block. 00581 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg)); 00582 00583 unsigned baseIndex = MIIdx; 00584 unsigned start = getDefIndex(baseIndex); 00585 // Earlyclobbers move back one. 00586 if (MO.isEarlyClobber()) 00587 start = getUseIndex(MIIdx); 00588 unsigned end = start; 00589 00590 // If it is not used after definition, it is considered dead at 00591 // the instruction defining it. Hence its interval is: 00592 // [defSlot(def), defSlot(def)+1) 00593 if (MO.isDead()) { 00594 DOUT << " dead"; 00595 end = start + 1; 00596 goto exit; 00597 } 00598 00599 // If it is not dead on definition, it must be killed by a 00600 // subsequent instruction. Hence its interval is: 00601 // [defSlot(def), useSlot(kill)+1) 00602 baseIndex += InstrSlots::NUM; 00603 while (++mi != MBB->end()) { 00604 while (baseIndex / InstrSlots::NUM < i2miMap_.size() && 00605 getInstructionFromIndex(baseIndex) == 0) 00606 baseIndex += InstrSlots::NUM; 00607 if (mi->killsRegister(interval.reg, tri_)) { 00608 DOUT << " killed"; 00609 end = getUseIndex(baseIndex) + 1; 00610 goto exit; 00611 } else if (mi->modifiesRegister(interval.reg, tri_)) { 00612 // Another instruction redefines the register before it is ever read. 00613 // Then the register is essentially dead at the instruction that defines 00614 // it. Hence its interval is: 00615 // [defSlot(def), defSlot(def)+1) 00616 DOUT << " dead"; 00617 end = start + 1; 00618 goto exit; 00619 } 00620 00621 baseIndex += InstrSlots::NUM; 00622 } 00623 00624 // The only case we should have a dead physreg here without a killing or 00625 // instruction where we know it's dead is if it is live-in to the function 00626 // and never used. 00627 assert(!CopyMI && "physreg was not killed in defining block!"); 00628 end = start + 1; 00629 00630 exit: 00631 assert(start < end && "did not find end of interval?"); 00632 00633 // Already exists? Extend old live interval. 00634 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start); 00635 bool Extend = OldLR != interval.end(); 00636 VNInfo *ValNo = Extend 00637 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator); 00638 if (MO.isEarlyClobber() && Extend) 00639 ValNo->redefByEC = true; 00640 LiveRange LR(start, end, ValNo); 00641 interval.addRange(LR); 00642 interval.addKill(LR.valno, end); 00643 DOUT << " +" << LR << '\n'; 00644 } 00645 00646 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB, 00647 MachineBasicBlock::iterator MI, 00648 unsigned MIIdx, 00649 MachineOperand& MO, 00650 unsigned MOIdx) { 00651 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) 00652 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx, 00653 getOrCreateInterval(MO.getReg())); 00654 else if (allocatableRegs_[MO.getReg()]) { 00655 MachineInstr *CopyMI = NULL; 00656 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg; 00657 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG || 00658 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG || 00659 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg)) 00660 CopyMI = MI; 00661 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO, 00662 getOrCreateInterval(MO.getReg()), CopyMI); 00663 // Def of a register also defines its sub-registers. 00664 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS) 00665 // If MI also modifies the sub-register explicitly, avoid processing it 00666 // more than once. Do not pass in TRI here so it checks for exact match. 00667 if (!MI->modifiesRegister(*AS)) 00668 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO, 00669 getOrCreateInterval(*AS), 0); 00670 } 00671 } 00672 00673 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB, 00674 unsigned MIIdx, 00675 LiveInterval &interval, bool isAlias) { 00676 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg)); 00677 00678 // Look for kills, if it reaches a def before it's killed, then it shouldn't 00679 // be considered a livein. 00680 MachineBasicBlock::iterator mi = MBB->begin(); 00681 unsigned baseIndex = MIIdx; 00682 unsigned start = baseIndex; 00683 while (baseIndex / InstrSlots::NUM < i2miMap_.size() && 00684 getInstructionFromIndex(baseIndex) == 0) 00685 baseIndex += InstrSlots::NUM; 00686 unsigned end = baseIndex; 00687 00688 while (mi != MBB->end()) { 00689 if (mi->killsRegister(interval.reg, tri_)) { 00690 DOUT << " killed"; 00691 end = getUseIndex(baseIndex) + 1; 00692 goto exit; 00693 } else if (mi->modifiesRegister(interval.reg, tri_)) { 00694 // Another instruction redefines the register before it is ever read. 00695 // Then the register is essentially dead at the instruction that defines 00696 // it. Hence its interval is: 00697 // [defSlot(def), defSlot(def)+1) 00698 DOUT << " dead"; 00699 end = getDefIndex(start) + 1; 00700 goto exit; 00701 } 00702 00703 baseIndex += InstrSlots::NUM; 00704 while (baseIndex / InstrSlots::NUM < i2miMap_.size() && 00705 getInstructionFromIndex(baseIndex) == 0) 00706 baseIndex += InstrSlots::NUM; 00707 ++mi; 00708 } 00709 00710 exit: 00711 // Live-in register might not be used at all. 00712 if (end == MIIdx) { 00713 if (isAlias) { 00714 DOUT << " dead"; 00715 end = getDefIndex(MIIdx) + 1; 00716 } else { 00717 DOUT << " live through"; 00718 end = baseIndex; 00719 } 00720 } 00721 00722 LiveRange LR(start, end, interval.getNextValue(~0U, 0, VNInfoAllocator)); 00723 interval.addRange(LR); 00724 interval.addKill(LR.valno, end); 00725 DOUT << " +" << LR << '\n'; 00726 } 00727 00728 /// computeIntervals - computes the live intervals for virtual 00729 /// registers. for some ordering of the machine instructions [1,N] a 00730 /// live interval is an interval [i, j) where 1 <= i <= j < N for 00731 /// which a variable is live 00732 void LiveIntervals::computeIntervals() { 00733 00734 DOUT << "********** COMPUTING LIVE INTERVALS **********\n" 00735 << "********** Function: " 00736 << ((Value*)mf_->getFunction())->getName() << '\n'; 00737 00738 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end(); 00739 MBBI != E; ++MBBI) { 00740 MachineBasicBlock *MBB = MBBI; 00741 // Track the index of the current machine instr. 00742 unsigned MIIndex = getMBBStartIdx(MBB); 00743 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n"; 00744 00745 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end(); 00746 00747 // Create intervals for live-ins to this BB first. 00748 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(), 00749 LE = MBB->livein_end(); LI != LE; ++LI) { 00750 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI)); 00751 // Multiple live-ins can alias the same register. 00752 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS) 00753 if (!hasInterval(*AS)) 00754 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS), 00755 true); 00756 } 00757 00758 // Skip over empty initial indices. 00759 while (MIIndex / InstrSlots::NUM < i2miMap_.size() && 00760 getInstructionFromIndex(MIIndex) == 0) 00761 MIIndex += InstrSlots::NUM; 00762 00763 for (; MI != miEnd; ++MI) { 00764 DOUT << MIIndex << "\t" << *MI; 00765 00766 // Handle defs. 00767 for (int i = MI->getNumOperands() - 1; i >= 0; --i) { 00768 MachineOperand &MO = MI->getOperand(i); 00769 // handle register defs - build intervals 00770 if (MO.isReg() && MO.getReg() && MO.isDef()) { 00771 handleRegisterDef(MBB, MI, MIIndex, MO, i); 00772 } 00773 } 00774 00775 // Skip over the empty slots after each instruction. 00776 unsigned Slots = MI->getDesc().getNumDefs(); 00777 if (Slots == 0) 00778 Slots = 1; 00779 MIIndex += InstrSlots::NUM * Slots; 00780 00781 // Skip over empty indices. 00782 while (MIIndex / InstrSlots::NUM < i2miMap_.size() && 00783 getInstructionFromIndex(MIIndex) == 0) 00784 MIIndex += InstrSlots::NUM; 00785 } 00786 } 00787 } 00788 00789 bool LiveIntervals::findLiveInMBBs(unsigned Start, unsigned End, 00790 SmallVectorImpl<MachineBasicBlock*> &MBBs) const { 00791 std::vector<IdxMBBPair>::const_iterator I = 00792 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start); 00793 00794 bool ResVal = false; 00795 while (I != Idx2MBBMap.end()) { 00796 if (I->first >= End) 00797 break; 00798 MBBs.push_back(I->second); 00799 ResVal = true; 00800 ++I; 00801 } 00802 return ResVal; 00803 } 00804 00805 bool LiveIntervals::findReachableMBBs(unsigned Start, unsigned End, 00806 SmallVectorImpl<MachineBasicBlock*> &MBBs) const { 00807 std::vector<IdxMBBPair>::const_iterator I = 00808 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start); 00809 00810 bool ResVal = false; 00811 while (I != Idx2MBBMap.end()) { 00812 if (I->first > End) 00813 break; 00814 MachineBasicBlock *MBB = I->second; 00815 if (getMBBEndIdx(MBB) > End) 00816 break; 00817 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), 00818 SE = MBB->succ_end(); SI != SE; ++SI) 00819 MBBs.push_back(*SI); 00820 ResVal = true; 00821 ++I; 00822 } 00823 return ResVal; 00824 } 00825 00826 LiveInterval* LiveIntervals::createInterval(unsigned reg) { 00827 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F; 00828 return new LiveInterval(reg, Weight); 00829 } 00830 00831 /// dupInterval - Duplicate a live interval. The caller is responsible for 00832 /// managing the allocated memory. 00833 LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) { 00834 LiveInterval *NewLI = createInterval(li->reg); 00835 NewLI->Copy(*li, getVNInfoAllocator()); 00836 return NewLI; 00837 } 00838 00839 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo 00840 /// copy field and returns the source register that defines it. 00841 unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const { 00842 if (!VNI->copy) 00843 return 0; 00844 00845 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) { 00846 // If it's extracting out of a physical register, return the sub-register. 00847 unsigned Reg = VNI->copy->getOperand(1).getReg(); 00848 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 00849 Reg = tri_->getSubReg(Reg, VNI->copy->getOperand(2).getImm()); 00850 return Reg; 00851 } else if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG) 00852 return VNI->copy->getOperand(2).getReg(); 00853 00854 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg; 00855 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg, SrcSubReg, DstSubReg)) 00856 return SrcReg; 00857 assert(0 && "Unrecognized copy instruction!"); 00858 return 0; 00859 } 00860 00861 //===----------------------------------------------------------------------===// 00862 // Register allocator hooks. 00863 // 00864 00865 /// getReMatImplicitUse - If the remat definition MI has one (for now, we only 00866 /// allow one) virtual register operand, then its uses are implicitly using 00867 /// the register. Returns the virtual register. 00868 unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li, 00869 MachineInstr *MI) const { 00870 unsigned RegOp = 0; 00871 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 00872 MachineOperand &MO = MI->getOperand(i); 00873 if (!MO.isReg() || !MO.isUse()) 00874 continue; 00875 unsigned Reg = MO.getReg(); 00876 if (Reg == 0 || Reg == li.reg) 00877 continue; 00878 // FIXME: For now, only remat MI with at most one register operand. 00879 assert(!RegOp && 00880 "Can't rematerialize instruction with multiple register operand!"); 00881 RegOp = MO.getReg(); 00882 #ifndef NDEBUG 00883 break; 00884 #endif 00885 } 00886 return RegOp; 00887 } 00888 00889 /// isValNoAvailableAt - Return true if the val# of the specified interval 00890 /// which reaches the given instruction also reaches the specified use index. 00891 bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI, 00892 unsigned UseIdx) const { 00893 unsigned Index = getInstructionIndex(MI); 00894 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno; 00895 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx); 00896 return UI != li.end() && UI->valno == ValNo; 00897 } 00898 00899 /// isReMaterializable - Returns true if the definition MI of the specified 00900 /// val# of the specified interval is re-materializable. 00901 bool LiveIntervals::isReMaterializable(const LiveInterval &li, 00902 const VNInfo *ValNo, MachineInstr *MI, 00903 SmallVectorImpl<LiveInterval*> &SpillIs, 00904 bool &isLoad) { 00905 if (DisableReMat) 00906 return false; 00907 00908 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) 00909 return true; 00910 00911 int FrameIdx = 0; 00912 if (tii_->isLoadFromStackSlot(MI, FrameIdx) && 00913 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx)) 00914 // FIXME: Let target specific isReallyTriviallyReMaterializable determines 00915 // this but remember this is not safe to fold into a two-address 00916 // instruction. 00917 // This is a load from fixed stack slot. It can be rematerialized. 00918 return true; 00919 00920 // If the target-specific rules don't identify an instruction as 00921 // being trivially rematerializable, use some target-independent 00922 // rules. 00923 if (!MI->getDesc().isRematerializable() || 00924 !tii_->isTriviallyReMaterializable(MI)) { 00925 if (!EnableAggressiveRemat) 00926 return false; 00927 00928 // If the instruction accesses memory but the memoperands have been lost, 00929 // we can't analyze it. 00930 const TargetInstrDesc &TID = MI->getDesc(); 00931 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty()) 00932 return false; 00933 00934 // Avoid instructions obviously unsafe for remat. 00935 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable()) 00936 return false; 00937 00938 // If the instruction accesses memory and the memory could be non-constant, 00939 // assume the instruction is not rematerializable. 00940 for (std::list<MachineMemOperand>::const_iterator 00941 I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I){ 00942 const MachineMemOperand &MMO = *I; 00943 if (MMO.isVolatile() || MMO.isStore()) 00944 return false; 00945 const Value *V = MMO.getValue(); 00946 if (!V) 00947 return false; 00948 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) { 00949 if (!PSV->isConstant(mf_->getFrameInfo())) 00950 return false; 00951 } else if (!aa_->pointsToConstantMemory(V)) 00952 return false; 00953 } 00954 00955 // If any of the registers accessed are non-constant, conservatively assume 00956 // the instruction is not rematerializable. 00957 unsigned ImpUse = 0; 00958 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 00959 const MachineOperand &MO = MI->getOperand(i); 00960 if (MO.isReg()) { 00961 unsigned Reg = MO.getReg(); 00962 if (Reg == 0) 00963 continue; 00964 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 00965 return false; 00966 00967 // Only allow one def, and that in the first operand. 00968 if (MO.isDef() != (i == 0)) 00969 return false; 00970 00971 // Only allow constant-valued registers. 00972 bool IsLiveIn = mri_->isLiveIn(Reg); 00973 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg), 00974 E = mri_->def_end(); 00975 00976 // For the def, it should be the only def of that register. 00977 if (MO.isDef() && (next(I) != E || IsLiveIn)) 00978 return false; 00979 00980 if (MO.isUse()) { 00981 // Only allow one use other register use, as that's all the 00982 // remat mechanisms support currently. 00983 if (Reg != li.reg) { 00984 if (ImpUse == 0) 00985 ImpUse = Reg; 00986 else if (Reg != ImpUse) 00987 return false; 00988 } 00989 // For the use, there should be only one associated def. 00990 if (I != E && (next(I) != E || IsLiveIn)) 00991 return false; 00992 } 00993 } 00994 } 00995 } 00996 00997 unsigned ImpUse = getReMatImplicitUse(li, MI); 00998 if (ImpUse) { 00999 const LiveInterval &ImpLi = getInterval(ImpUse); 01000 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg), 01001 re = mri_->use_end(); ri != re; ++ri) { 01002 MachineInstr *UseMI = &*ri; 01003 unsigned UseIdx = getInstructionIndex(UseMI); 01004 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo) 01005 continue; 01006 if (!isValNoAvailableAt(ImpLi, MI, UseIdx)) 01007 return false; 01008 } 01009 01010 // If a register operand of the re-materialized instruction is going to 01011 // be spilled next, then it's not legal to re-materialize this instruction. 01012 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i) 01013 if (ImpUse == SpillIs[i]->reg) 01014 return false; 01015 } 01016 return true; 01017 } 01018 01019 /// isReMaterializable - Returns true if the definition MI of the specified 01020 /// val# of the specified interval is re-materializable. 01021 bool LiveIntervals::isReMaterializable(const LiveInterval &li, 01022 const VNInfo *ValNo, MachineInstr *MI) { 01023 SmallVector<LiveInterval*, 4> Dummy1; 01024 bool Dummy2; 01025 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2); 01026 } 01027 01028 /// isReMaterializable - Returns true if every definition of MI of every 01029 /// val# of the specified interval is re-materializable. 01030 bool LiveIntervals::isReMaterializable(const LiveInterval &li, 01031 SmallVectorImpl<LiveInterval*> &SpillIs, 01032 bool &isLoad) { 01033 isLoad = false; 01034 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end(); 01035 i != e; ++i) { 01036 const VNInfo *VNI = *i; 01037 unsigned DefIdx = VNI->def; 01038 if (DefIdx == ~1U) 01039 continue; // Dead val#. 01040 // Is the def for the val# rematerializable? 01041 if (DefIdx == ~0u) 01042 return false; 01043 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx); 01044 bool DefIsLoad = false; 01045 if (!ReMatDefMI || 01046 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad)) 01047 return false; 01048 isLoad |= DefIsLoad; 01049 } 01050 return true; 01051 } 01052 01053 /// FilterFoldedOps - Filter out two-address use operands. Return 01054 /// true if it finds any issue with the operands that ought to prevent 01055 /// folding. 01056 static bool FilterFoldedOps(MachineInstr *MI, 01057 SmallVector<unsigned, 2> &Ops, 01058 unsigned &MRInfo, 01059 SmallVector<unsigned, 2> &FoldOps) { 01060 const TargetInstrDesc &TID = MI->getDesc(); 01061 01062 MRInfo = 0; 01063 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 01064 unsigned OpIdx = Ops[i]; 01065 MachineOperand &MO = MI->getOperand(OpIdx); 01066 // FIXME: fold subreg use. 01067 if (MO.getSubReg()) 01068 return true; 01069 if (MO.isDef()) 01070 MRInfo |= (unsigned)VirtRegMap::isMod; 01071 else { 01072 // Filter out two-address use operand(s). 01073 if (!MO.isImplicit() && 01074 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) { 01075 MRInfo = VirtRegMap::isModRef; 01076 continue; 01077 } 01078 MRInfo |= (unsigned)VirtRegMap::isRef; 01079 } 01080 FoldOps.push_back(OpIdx); 01081 } 01082 return false; 01083 } 01084 01085 01086 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from 01087 /// slot / to reg or any rematerialized load into ith operand of specified 01088 /// MI. If it is successul, MI is updated with the newly created MI and 01089 /// returns true. 01090 bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI, 01091 VirtRegMap &vrm, MachineInstr *DefMI, 01092 unsigned InstrIdx, 01093 SmallVector<unsigned, 2> &Ops, 01094 bool isSS, int Slot, unsigned Reg) { 01095 // If it is an implicit def instruction, just delete it. 01096 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) { 01097 RemoveMachineInstrFromMaps(MI); 01098 vrm.RemoveMachineInstrFromMaps(MI); 01099 MI->eraseFromParent(); 01100 ++numFolds; 01101 return true; 01102 } 01103 01104 // Filter the list of operand indexes that are to be folded. Abort if 01105 // any operand will prevent folding. 01106 unsigned MRInfo = 0; 01107 SmallVector<unsigned, 2> FoldOps; 01108 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps)) 01109 return false; 01110 01111 // The only time it's safe to fold into a two address instruction is when 01112 // it's folding reload and spill from / into a spill stack slot. 01113 if (DefMI && (MRInfo & VirtRegMap::isMod)) 01114 return false; 01115 01116 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot) 01117 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI); 01118 if (fmi) { 01119 // Remember this instruction uses the spill slot. 01120 if (isSS) vrm.addSpillSlotUse(Slot, fmi); 01121 01122 // Attempt to fold the memory reference into the instruction. If 01123 // we can do this, we don't need to insert spill code. 01124 MachineBasicBlock &MBB = *MI->getParent(); 01125 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot)) 01126 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo); 01127 vrm.transferSpillPts(MI, fmi); 01128 vrm.transferRestorePts(MI, fmi); 01129 vrm.transferEmergencySpills(MI, fmi); 01130 mi2iMap_.erase(MI); 01131 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi; 01132 mi2iMap_[fmi] = InstrIdx; 01133 MI = MBB.insert(MBB.erase(MI), fmi); 01134 ++numFolds; 01135 return true; 01136 } 01137 return false; 01138 } 01139 01140 /// canFoldMemoryOperand - Returns true if the specified load / store 01141 /// folding is possible. 01142 bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI, 01143 SmallVector<unsigned, 2> &Ops, 01144 bool ReMat) const { 01145 // Filter the list of operand indexes that are to be folded. Abort if 01146 // any operand will prevent folding. 01147 unsigned MRInfo = 0; 01148 SmallVector<unsigned, 2> FoldOps; 01149 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps)) 01150 return false; 01151 01152 // It's only legal to remat for a use, not a def. 01153 if (ReMat && (MRInfo & VirtRegMap::isMod)) 01154 return false; 01155 01156 return tii_->canFoldMemoryOperand(MI, FoldOps); 01157 } 01158 01159 bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const { 01160 SmallPtrSet<MachineBasicBlock*, 4> MBBs; 01161 for (LiveInterval::Ranges::const_iterator 01162 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) { 01163 std::vector<IdxMBBPair>::const_iterator II = 01164 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start); 01165 if (II == Idx2MBBMap.end()) 01166 continue; 01167 if (I->end > II->first) // crossing a MBB. 01168 return false; 01169 MBBs.insert(II->second); 01170 if (MBBs.size() > 1) 01171 return false; 01172 } 01173 return true; 01174 } 01175 01176 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of 01177 /// interval on to-be re-materialized operands of MI) with new register. 01178 void LiveIntervals::rewriteImplicitOps(const LiveInterval &li, 01179 MachineInstr *MI, unsigned NewVReg, 01180 VirtRegMap &vrm) { 01181 // There is an implicit use. That means one of the other operand is 01182 // being remat'ed and the remat'ed instruction has li.reg as an 01183 // use operand. Make sure we rewrite that as well. 01184 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 01185 MachineOperand &MO = MI->getOperand(i); 01186 if (!MO.isReg()) 01187 continue; 01188 unsigned Reg = MO.getReg(); 01189 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg)) 01190 continue; 01191 if (!vrm.isReMaterialized(Reg)) 01192 continue; 01193 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg); 01194 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg); 01195 if (UseMO) 01196 UseMO->setReg(NewVReg); 01197 } 01198 } 01199 01200 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions 01201 /// for addIntervalsForSpills to rewrite uses / defs for the given live range. 01202 bool LiveIntervals:: 01203 rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI, 01204 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI, 01205 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI, 01206 unsigned Slot, int LdSlot, 01207 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete, 01208 VirtRegMap &vrm, 01209 const TargetRegisterClass* rc, 01210 SmallVector<int, 4> &ReMatIds, 01211 const MachineLoopInfo *loopInfo, 01212 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse, 01213 DenseMap<unsigned,unsigned> &MBBVRegsMap, 01214 std::vector<LiveInterval*> &NewLIs, float &SSWeight) { 01215 MachineBasicBlock *MBB = MI->getParent(); 01216 unsigned loopDepth = loopInfo->getLoopDepth(MBB); 01217 bool CanFold = false; 01218 RestartInstruction: 01219 for (unsigned i = 0; i != MI->getNumOperands(); ++i) { 01220 MachineOperand& mop = MI->getOperand(i); 01221 if (!mop.isReg()) 01222 continue; 01223 unsigned Reg = mop.getReg(); 01224 unsigned RegI = Reg; 01225 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg)) 01226 continue; 01227 if (Reg != li.reg) 01228 continue; 01229 01230 bool TryFold = !DefIsReMat; 01231 bool FoldSS = true; // Default behavior unless it's a remat. 01232 int FoldSlot = Slot; 01233 if (DefIsReMat) { 01234 // If this is the rematerializable definition MI itself and 01235 // all of its uses are rematerialized, simply delete it. 01236 if (MI == ReMatOrigDefMI && CanDelete) { 01237 DOUT << "\t\t\t\tErasing re-materlizable def: "; 01238 DOUT << MI << '\n'; 01239 RemoveMachineInstrFromMaps(MI); 01240 vrm.RemoveMachineInstrFromMaps(MI); 01241 MI->eraseFromParent(); 01242 break; 01243 } 01244 01245 // If def for this use can't be rematerialized, then try folding. 01246 // If def is rematerializable and it's a load, also try folding. 01247 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad)); 01248 if (isLoad) { 01249 // Try fold loads (from stack slot, constant pool, etc.) into uses. 01250 FoldSS = isLoadSS; 01251 FoldSlot = LdSlot; 01252 } 01253 } 01254 01255 // Scan all of the operands of this instruction rewriting operands 01256 // to use NewVReg instead of li.reg as appropriate. We do this for 01257 // two reasons: 01258 // 01259 // 1. If the instr reads the same spilled vreg multiple times, we 01260 // want to reuse the NewVReg. 01261 // 2. If the instr is a two-addr instruction, we are required to 01262 // keep the src/dst regs pinned. 01263 // 01264 // Keep track of whether we replace a use and/or def so that we can 01265 // create the spill interval with the appropriate range. 01266 01267 HasUse = mop.isUse(); 01268 HasDef = mop.isDef(); 01269 SmallVector<unsigned, 2> Ops; 01270 Ops.push_back(i); 01271 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) { 01272 const MachineOperand &MOj = MI->getOperand(j); 01273 if (!MOj.isReg()) 01274 continue; 01275 unsigned RegJ = MOj.getReg(); 01276 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ)) 01277 continue; 01278 if (RegJ == RegI) { 01279 Ops.push_back(j); 01280 HasUse |= MOj.isUse(); 01281 HasDef |= MOj.isDef(); 01282 } 01283 } 01284 01285 if (HasUse && !li.liveAt(getUseIndex(index))) 01286 // Must be defined by an implicit def. It should not be spilled. Note, 01287 // this is for correctness reason. e.g. 01288 // 8 %reg1024<def> = IMPLICIT_DEF 01289 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2 01290 // The live range [12, 14) are not part of the r1024 live interval since 01291 // it's defined by an implicit def. It will not conflicts with live 01292 // interval of r1025. Now suppose both registers are spilled, you can 01293 // easily see a situation where both registers are reloaded before 01294 // the INSERT_SUBREG and both target registers that would overlap. 01295 HasUse = false; 01296 01297 // Update stack slot spill weight if we are splitting. 01298 float Weight = getSpillWeight(HasDef, HasUse, loopDepth); 01299 if (!TrySplit) 01300 SSWeight += Weight; 01301 01302 // Create a new virtual register for the spill interval. 01303 // Create the new register now so we can map the fold instruction 01304 // to the new register so when it is unfolded we get the correct 01305 // answer. 01306 bool CreatedNewVReg = false; 01307 if (NewVReg == 0) { 01308 NewVReg = mri_->createVirtualRegister(rc); 01309 vrm.grow(); 01310 CreatedNewVReg = true; 01311 } 01312 01313 if (!TryFold) 01314 CanFold = false; 01315 else { 01316 // Do not fold load / store here if we are splitting. We'll find an 01317 // optimal point to insert a load / store later. 01318 if (!TrySplit) { 01319 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index, 01320 Ops, FoldSS, FoldSlot, NewVReg)) { 01321 // Folding the load/store can completely change the instruction in 01322 // unpredictable ways, rescan it from the beginning. 01323 01324 if (FoldSS) { 01325 // We need to give the new vreg the same stack slot as the 01326 // spilled interval. 01327 vrm.assignVirt2StackSlot(NewVReg, FoldSlot); 01328 } 01329 01330 HasUse = false; 01331 HasDef = false; 01332 CanFold = false; 01333 if (isRemoved(MI)) { 01334 SSWeight -= Weight; 01335 break; 01336 } 01337 goto RestartInstruction; 01338 } 01339 } else { 01340 // We'll try to fold it later if it's profitable. 01341 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat); 01342 } 01343 } 01344 01345 mop.setReg(NewVReg); 01346 if (mop.isImplicit()) 01347 rewriteImplicitOps(li, MI, NewVReg, vrm); 01348 01349 // Reuse NewVReg for other reads. 01350 for (unsigned j = 0, e = Ops.size(); j != e; ++j) { 01351 MachineOperand &mopj = MI->getOperand(Ops[j]); 01352 mopj.setReg(NewVReg); 01353 if (mopj.isImplicit()) 01354 rewriteImplicitOps(li, MI, NewVReg, vrm); 01355 } 01356 01357 if (CreatedNewVReg) { 01358 if (DefIsReMat) { 01359 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/); 01360 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) { 01361 // Each valnum may have its own remat id. 01362 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg); 01363 } else { 01364 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]); 01365 } 01366 if (!CanDelete || (HasUse && HasDef)) { 01367 // If this is a two-addr instruction then its use operands are 01368 // rematerializable but its def is not. It should be assigned a 01369 // stack slot. 01370 vrm.assignVirt2StackSlot(NewVReg, Slot); 01371 } 01372 } else { 01373 vrm.assignVirt2StackSlot(NewVReg, Slot); 01374 } 01375 } else if (HasUse && HasDef && 01376 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) { 01377 // If this interval hasn't been assigned a stack slot (because earlier 01378 // def is a deleted remat def), do it now. 01379 assert(Slot != VirtRegMap::NO_STACK_SLOT); 01380 vrm.assignVirt2StackSlot(NewVReg, Slot); 01381 } 01382 01383 // Re-matting an instruction with virtual register use. Add the 01384 // register as an implicit use on the use MI. 01385 if (DefIsReMat && ImpUse) 01386 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true)); 01387 01388 // create a new register interval for this spill / remat. 01389 LiveInterval &nI = getOrCreateInterval(NewVReg); 01390 if (CreatedNewVReg) { 01391 NewLIs.push_back(&nI); 01392 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg)); 01393 if (TrySplit) 01394 vrm.setIsSplitFromReg(NewVReg, li.reg); 01395 } 01396 01397 if (HasUse) { 01398 if (CreatedNewVReg) { 01399 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1, 01400 nI.getNextValue(~0U, 0, VNInfoAllocator)); 01401 DOUT << " +" << LR; 01402 nI.addRange(LR); 01403 } else { 01404 // Extend the split live interval to this def / use. 01405 unsigned End = getUseIndex(index)+1; 01406 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End, 01407 nI.getValNumInfo(nI.getNumValNums()-1)); 01408 DOUT << " +" << LR; 01409 nI.addRange(LR); 01410 } 01411 } 01412 if (HasDef) { 01413 LiveRange LR(getDefIndex(index), getStoreIndex(index), 01414 nI.getNextValue(~0U, 0, VNInfoAllocator)); 01415 DOUT << " +" << LR; 01416 nI.addRange(LR); 01417 } 01418 01419 DOUT << "\t\t\t\tAdded new interval: "; 01420 nI.print(DOUT, tri_); 01421 DOUT << '\n'; 01422 } 01423 return CanFold; 01424 } 01425 bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li, 01426 const VNInfo *VNI, 01427 MachineBasicBlock *MBB, unsigned Idx) const { 01428 unsigned End = getMBBEndIdx(MBB); 01429 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) { 01430 unsigned KillIdx = VNI->kills[j]; 01431 if (KillIdx > Idx && KillIdx < End) 01432 return true; 01433 } 01434 return false; 01435 } 01436 01437 /// RewriteInfo - Keep track of machine instrs that will be rewritten 01438 /// during spilling. 01439 namespace { 01440 struct RewriteInfo { 01441 unsigned Index; 01442 MachineInstr *MI; 01443 bool HasUse; 01444 bool HasDef; 01445 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d) 01446 : Index(i), MI(mi), HasUse(u), HasDef(d) {} 01447 }; 01448 01449 struct RewriteInfoCompare { 01450 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const { 01451 return LHS.Index < RHS.Index; 01452 } 01453 }; 01454 } 01455 01456 void LiveIntervals:: 01457 rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit, 01458 LiveInterval::Ranges::const_iterator &I, 01459 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI, 01460 unsigned Slot, int LdSlot, 01461 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete, 01462 VirtRegMap &vrm, 01463 const TargetRegisterClass* rc, 01464 SmallVector<int, 4> &ReMatIds, 01465 const MachineLoopInfo *loopInfo, 01466 BitVector &SpillMBBs, 01467 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes, 01468 BitVector &RestoreMBBs, 01469 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes, 01470 DenseMap<unsigned,unsigned> &MBBVRegsMap, 01471 std::vector<LiveInterval*> &NewLIs, float &SSWeight) { 01472 bool AllCanFold = true; 01473 unsigned NewVReg = 0; 01474 unsigned start = getBaseIndex(I->start); 01475 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM; 01476 01477 // First collect all the def / use in this live range that will be rewritten. 01478 // Make sure they are sorted according to instruction index. 01479 std::vector<RewriteInfo> RewriteMIs; 01480 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg), 01481 re = mri_->reg_end(); ri != re; ) { 01482 MachineInstr *MI = &*ri; 01483 MachineOperand &O = ri.getOperand(); 01484 ++ri; 01485 assert(!O.isImplicit() && "Spilling register that's used as implicit use?"); 01486 unsigned index = getInstructionIndex(MI); 01487 if (index < start || index >= end) 01488 continue; 01489 if (O.isUse() && !li.liveAt(getUseIndex(index))) 01490 // Must be defined by an implicit def. It should not be spilled. Note, 01491 // this is for correctness reason. e.g. 01492 // 8 %reg1024<def> = IMPLICIT_DEF 01493 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2 01494 // The live range [12, 14) are not part of the r1024 live interval since 01495 // it's defined by an implicit def. It will not conflicts with live 01496 // interval of r1025. Now suppose both registers are spilled, you can 01497 // easily see a situation where both registers are reloaded before 01498 // the INSERT_SUBREG and both target registers that would overlap. 01499 continue; 01500 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef())); 01501 } 01502 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare()); 01503 01504 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0; 01505 // Now rewrite the defs and uses. 01506 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) { 01507 RewriteInfo &rwi = RewriteMIs[i]; 01508 ++i; 01509 unsigned index = rwi.Index; 01510 bool MIHasUse = rwi.HasUse; 01511 bool MIHasDef = rwi.HasDef; 01512 MachineInstr *MI = rwi.MI; 01513 // If MI def and/or use the same register multiple times, then there 01514 // are multiple entries. 01515 unsigned NumUses = MIHasUse; 01516 while (i != e && RewriteMIs[i].MI == MI) { 01517 assert(RewriteMIs[i].Index == index); 01518 bool isUse = RewriteMIs[i].HasUse; 01519 if (isUse) ++NumUses; 01520 MIHasUse |= isUse; 01521 MIHasDef |= RewriteMIs[i].HasDef; 01522 ++i; 01523 } 01524 MachineBasicBlock *MBB = MI->getParent(); 01525 01526 if (ImpUse && MI != ReMatDefMI) { 01527 // Re-matting an instruction with virtual register use. Update the 01528 // register interval's spill weight to HUGE_VALF to prevent it from 01529 // being spilled. 01530 LiveInterval &ImpLi = getInterval(ImpUse); 01531 ImpLi.weight = HUGE_VALF; 01532 } 01533 01534 unsigned MBBId = MBB->getNumber(); 01535 unsigned ThisVReg = 0; 01536 if (TrySplit) { 01537 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId); 01538 if (NVI != MBBVRegsMap.end()) { 01539 ThisVReg = NVI->second; 01540 // One common case: 01541 // x = use 01542 // ... 01543 // ... 01544 // def = ... 01545 // = use 01546 // It's better to start a new interval to avoid artifically 01547 // extend the new interval. 01548 if (MIHasDef && !MIHasUse) { 01549 MBBVRegsMap.erase(MBB->getNumber()); 01550 ThisVReg = 0; 01551 } 01552 } 01553 } 01554 01555 bool IsNew = ThisVReg == 0; 01556 if (IsNew) { 01557 // This ends the previous live interval. If all of its def / use 01558 // can be folded, give it a low spill weight. 01559 if (NewVReg && TrySplit && AllCanFold) { 01560 LiveInterval &nI = getOrCreateInterval(NewVReg); 01561 nI.weight /= 10.0F; 01562 } 01563 AllCanFold = true; 01564 } 01565 NewVReg = ThisVReg; 01566 01567 bool HasDef = false; 01568 bool HasUse = false; 01569 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit, 01570 index, end, MI, ReMatOrigDefMI, ReMatDefMI, 01571 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat, 01572 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg, 01573 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight); 01574 if (!HasDef && !HasUse) 01575 continue; 01576 01577 AllCanFold &= CanFold; 01578 01579 // Update weight of spill interval. 01580 LiveInterval &nI = getOrCreateInterval(NewVReg); 01581 if (!TrySplit) { 01582 // The spill weight is now infinity as it cannot be spilled again. 01583 nI.weight = HUGE_VALF; 01584 continue; 01585 } 01586 01587 // Keep track of the last def and first use in each MBB. 01588 if (HasDef) { 01589 if (MI != ReMatOrigDefMI || !CanDelete) { 01590 bool HasKill = false; 01591 if (!HasUse) 01592 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index)); 01593 else { 01594 // If this is a two-address code, then this index starts a new VNInfo. 01595 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index)); 01596 if (VNI) 01597 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index)); 01598 } 01599 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII = 01600 SpillIdxes.find(MBBId); 01601 if (!HasKill) { 01602 if (SII == SpillIdxes.end()) { 01603 std::vector<SRInfo> S; 01604 S.push_back(SRInfo(index, NewVReg, true)); 01605 SpillIdxes.insert(std::make_pair(MBBId, S)); 01606 } else if (SII->second.back().vreg != NewVReg) { 01607 SII->second.push_back(SRInfo(index, NewVReg, true)); 01608 } else if ((int)index > SII->second.back().index) { 01609 // If there is an earlier def and this is a two-address 01610 // instruction, then it's not possible to fold the store (which 01611 // would also fold the load). 01612 SRInfo &Info = SII->second.back(); 01613 Info.index = index; 01614 Info.canFold = !HasUse; 01615 } 01616 SpillMBBs.set(MBBId); 01617 } else if (SII != SpillIdxes.end() && 01618 SII->second.back().vreg == NewVReg && 01619 (int)index > SII->second.back().index) { 01620 // There is an earlier def that's not killed (must be two-address). 01621 // The spill is no longer needed. 01622 SII->second.pop_back(); 01623 if (SII->second.empty()) { 01624 SpillIdxes.erase(MBBId); 01625 SpillMBBs.reset(MBBId); 01626 } 01627 } 01628 } 01629 } 01630 01631 if (HasUse) { 01632 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII = 01633 SpillIdxes.find(MBBId); 01634 if (SII != SpillIdxes.end() && 01635 SII->second.back().vreg == NewVReg && 01636 (int)index > SII->second.back().index) 01637 // Use(s) following the last def, it's not safe to fold the spill. 01638 SII->second.back().canFold = false; 01639 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII = 01640 RestoreIdxes.find(MBBId); 01641 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg) 01642 // If we are splitting live intervals, only fold if it's the first 01643 // use and there isn't another use later in the MBB. 01644 RII->second.back().canFold = false; 01645 else if (IsNew) { 01646 // Only need a reload if there isn't an earlier def / use. 01647 if (RII == RestoreIdxes.end()) { 01648 std::vector<SRInfo> Infos; 01649 Infos.push_back(SRInfo(index, NewVReg, true)); 01650 RestoreIdxes.insert(std::make_pair(MBBId, Infos)); 01651 } else { 01652 RII->second.push_back(SRInfo(index, NewVReg, true)); 01653 } 01654 RestoreMBBs.set(MBBId); 01655 } 01656 } 01657 01658 // Update spill weight. 01659 unsigned loopDepth = loopInfo->getLoopDepth(MBB); 01660 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth); 01661 } 01662 01663 if (NewVReg && TrySplit && AllCanFold) { 01664 // If all of its def / use can be folded, give it a low spill weight. 01665 LiveInterval &nI = getOrCreateInterval(NewVReg); 01666 nI.weight /= 10.0F; 01667 } 01668 } 01669 01670 bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr, 01671 BitVector &RestoreMBBs, 01672 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) { 01673 if (!RestoreMBBs[Id]) 01674 return false; 01675 std::vector<SRInfo> &Restores = RestoreIdxes[Id]; 01676 for (unsigned i = 0, e = Restores.size(); i != e; ++i) 01677 if (Restores[i].index == index && 01678 Restores[i].vreg == vr && 01679 Restores[i].canFold) 01680 return true; 01681 return false; 01682 } 01683 01684 void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr, 01685 BitVector &RestoreMBBs, 01686 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) { 01687 if (!RestoreMBBs[Id]) 01688 return; 01689 std::vector<SRInfo> &Restores = RestoreIdxes[Id]; 01690 for (unsigned i = 0, e = Restores.size(); i != e; ++i) 01691 if (Restores[i].index == index && Restores[i].vreg) 01692 Restores[i].index = -1; 01693 } 01694 01695 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being 01696 /// spilled and create empty intervals for their uses. 01697 void 01698 LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm, 01699 const TargetRegisterClass* rc, 01700 std::vector<LiveInterval*> &NewLIs) { 01701 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg), 01702 re = mri_->reg_end(); ri != re; ) { 01703 MachineOperand &O = ri.getOperand(); 01704 MachineInstr *MI = &*ri; 01705 ++ri; 01706 if (O.isDef()) { 01707 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF && 01708 "Register def was not rewritten?"); 01709 RemoveMachineInstrFromMaps(MI); 01710 vrm.RemoveMachineInstrFromMaps(MI); 01711 MI->eraseFromParent(); 01712 } else { 01713 // This must be an use of an implicit_def so it's not part of the live 01714 // interval. Create a new empty live interval for it. 01715 // FIXME: Can we simply erase some of the instructions? e.g. Stores? 01716 unsigned NewVReg = mri_->createVirtualRegister(rc); 01717 vrm.grow(); 01718 vrm.setIsImplicitlyDefined(NewVReg); 01719 NewLIs.push_back(&getOrCreateInterval(NewVReg)); 01720 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 01721 MachineOperand &MO = MI->getOperand(i); 01722 if (MO.isReg() && MO.getReg() == li.reg) 01723 MO.setReg(NewVReg); 01724 } 01725 } 01726 } 01727 } 01728 01729 namespace { 01730 struct LISorter { 01731 bool operator()(LiveInterval* A, LiveInterval* B) { 01732 return A->beginNumber() < B->beginNumber(); 01733 } 01734 }; 01735 } 01736 01737 std::vector<LiveInterval*> LiveIntervals:: 01738 addIntervalsForSpillsFast(const LiveInterval &li, 01739 const MachineLoopInfo *loopInfo, 01740 VirtRegMap &vrm, float& SSWeight) { 01741 unsigned slot = vrm.assignVirt2StackSlot(li.reg); 01742 01743 std::vector<LiveInterval*> added; 01744 01745 assert(li.weight != HUGE_VALF && 01746 "attempt to spill already spilled interval!"); 01747 01748 DOUT << "\t\t\t\tadding intervals for spills for interval: "; 01749 DEBUG(li.dump()); 01750 DOUT << '\n'; 01751 01752 const TargetRegisterClass* rc = mri_->getRegClass(li.reg); 01753 01754 SSWeight = 0.0f; 01755 01756 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg); 01757 while (RI != mri_->reg_end()) { 01758 MachineInstr* MI = &*RI; 01759 01760 SmallVector<unsigned, 2> Indices; 01761 bool HasUse = false; 01762 bool HasDef = false; 01763 01764 for (unsigned i = 0; i != MI->getNumOperands(); ++i) { 01765 MachineOperand& mop = MI->getOperand(i); 01766 if (!mop.isReg() || mop.getReg() != li.reg) continue; 01767 01768 HasUse |= MI->getOperand(i).isUse(); 01769 HasDef |= MI->getOperand(i).isDef(); 01770 01771 Indices.push_back(i); 01772 } 01773 01774 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI), 01775 Indices, true, slot, li.reg)) { 01776 unsigned NewVReg = mri_->createVirtualRegister(rc); 01777 vrm.grow(); 01778 vrm.assignVirt2StackSlot(NewVReg, slot); 01779 01780 // create a new register for this spill 01781 LiveInterval &nI = getOrCreateInterval(NewVReg); 01782 01783 // the spill weight is now infinity as it 01784 // cannot be spilled again 01785 nI.weight = HUGE_VALF; 01786 01787 // Rewrite register operands to use the new vreg. 01788 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(), 01789 E = Indices.end(); I != E; ++I) { 01790 MI->getOperand(*I).setReg(NewVReg); 01791 01792 if (MI->getOperand(*I).isUse()) 01793 MI->getOperand(*I).setIsKill(true); 01794 } 01795 01796 // Fill in the new live interval. 01797 unsigned index = getInstructionIndex(MI); 01798 if (HasUse) { 01799 LiveRange LR(getLoadIndex(index), getUseIndex(index), 01800 nI.getNextValue(~0U, 0, getVNInfoAllocator())); 01801 DOUT << " +" << LR; 01802 nI.addRange(LR); 01803 vrm.addRestorePoint(NewVReg, MI); 01804 } 01805 if (HasDef) { 01806 LiveRange LR(getDefIndex(index), getStoreIndex(index), 01807 nI.getNextValue(~0U, 0, getVNInfoAllocator())); 01808 DOUT << " +" << LR; 01809 nI.addRange(LR); 01810 vrm.addSpillPoint(NewVReg, true, MI); 01811 } 01812 01813 added.push_back(&nI); 01814 01815 DOUT << "\t\t\t\tadded new interval: "; 01816 DEBUG(nI.dump()); 01817 DOUT << '\n'; 01818 01819 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent()); 01820 if (HasUse) { 01821 if (HasDef) 01822 SSWeight += getSpillWeight(true, true, loopDepth); 01823 else 01824 SSWeight += getSpillWeight(false, true, loopDepth); 01825 } else 01826 SSWeight += getSpillWeight(true, false, loopDepth); 01827 } 01828 01829 01830 RI = mri_->reg_begin(li.reg); 01831 } 01832 01833 // Clients expect the new intervals to be returned in sorted order. 01834 std::sort(added.begin(), added.end(), LISorter()); 01835 01836 return added; 01837 } 01838 01839 std::vector<LiveInterval*> LiveIntervals:: 01840 addIntervalsForSpills(const LiveInterval &li, 01841 SmallVectorImpl<LiveInterval*> &SpillIs, 01842 const MachineLoopInfo *loopInfo, VirtRegMap &vrm, 01843 float &SSWeight) { 01844 01845 if (EnableFastSpilling) 01846 return addIntervalsForSpillsFast(li, loopInfo, vrm, SSWeight); 01847 01848 assert(li.weight != HUGE_VALF && 01849 "attempt to spill already spilled interval!"); 01850 01851 DOUT << "\t\t\t\tadding intervals for spills for interval: "; 01852 li.print(DOUT, tri_); 01853 DOUT << '\n'; 01854 01855 // Spill slot weight. 01856 SSWeight = 0.0f; 01857 01858 // Each bit specify whether a spill is required in the MBB. 01859 BitVector SpillMBBs(mf_->getNumBlockIDs()); 01860 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes; 01861 BitVector RestoreMBBs(mf_->getNumBlockIDs()); 01862 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes; 01863 DenseMap<unsigned,unsigned> MBBVRegsMap; 01864 std::vector<LiveInterval*> NewLIs; 01865 const TargetRegisterClass* rc = mri_->getRegClass(li.reg); 01866 01867 unsigned NumValNums = li.getNumValNums(); 01868 SmallVector<MachineInstr*, 4> ReMatDefs; 01869 ReMatDefs.resize(NumValNums, NULL); 01870 SmallVector<MachineInstr*, 4> ReMatOrigDefs; 01871 ReMatOrigDefs.resize(NumValNums, NULL); 01872 SmallVector<int, 4> ReMatIds; 01873 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT); 01874 BitVector ReMatDelete(NumValNums); 01875 unsigned Slot = VirtRegMap::MAX_STACK_SLOT; 01876 01877 // Spilling a split live interval. It cannot be split any further. Also, 01878 // it's also guaranteed to be a single val# / range interval. 01879 if (vrm.getPreSplitReg(li.reg)) { 01880 vrm.setIsSplitFromReg(li.reg, 0); 01881 // Unset the split kill marker on the last use. 01882 unsigned KillIdx = vrm.getKillPoint(li.reg); 01883 if (KillIdx) { 01884 MachineInstr *KillMI = getInstructionFromIndex(KillIdx); 01885 assert(KillMI && "Last use disappeared?"); 01886 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true); 01887 assert(KillOp != -1 && "Last use disappeared?"); 01888 KillMI->getOperand(KillOp).setIsKill(false); 01889 } 01890 vrm.removeKillPoint(li.reg); 01891 bool DefIsReMat = vrm.isReMaterialized(li.reg); 01892 Slot = vrm.getStackSlot(li.reg); 01893 assert(Slot != VirtRegMap::MAX_STACK_SLOT); 01894 MachineInstr *ReMatDefMI = DefIsReMat ? 01895 vrm.getReMaterializedMI(li.reg) : NULL; 01896 int LdSlot = 0; 01897 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot); 01898 bool isLoad = isLoadSS || 01899 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad())); 01900 bool IsFirstRange = true; 01901 for (LiveInterval::Ranges::const_iterator 01902 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) { 01903 // If this is a split live interval with multiple ranges, it means there 01904 // are two-address instructions that re-defined the value. Only the 01905 // first def can be rematerialized! 01906 if (IsFirstRange) { 01907 // Note ReMatOrigDefMI has already been deleted. 01908 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI, 01909 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat, 01910 false, vrm, rc, ReMatIds, loopInfo, 01911 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes, 01912 MBBVRegsMap, NewLIs, SSWeight); 01913 } else { 01914 rewriteInstructionsForSpills(li, false, I, NULL, 0, 01915 Slot, 0, false, false, false, 01916 false, vrm, rc, ReMatIds, loopInfo, 01917 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes, 01918 MBBVRegsMap, NewLIs, SSWeight); 01919 } 01920 IsFirstRange = false; 01921 } 01922 01923 SSWeight = 0.0f; // Already accounted for when split. 01924 handleSpilledImpDefs(li, vrm, rc, NewLIs); 01925 return NewLIs; 01926 } 01927 01928 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li); 01929 if (SplitLimit != -1 && (int)numSplits >= SplitLimit) 01930 TrySplit = false; 01931 if (TrySplit) 01932 ++numSplits; 01933 bool NeedStackSlot = false; 01934 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end(); 01935 i != e; ++i) { 01936 const VNInfo *VNI = *i; 01937 unsigned VN = VNI->id; 01938 unsigned DefIdx = VNI->def; 01939 if (DefIdx == ~1U) 01940 continue; // Dead val#. 01941 // Is the def for the val# rematerializable? 01942 MachineInstr *ReMatDefMI = (DefIdx == ~0u) 01943 ? 0 : getInstructionFromIndex(DefIdx); 01944 bool dummy; 01945 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) { 01946 // Remember how to remat the def of this val#. 01947 ReMatOrigDefs[VN] = ReMatDefMI; 01948 // Original def may be modified so we have to make a copy here. 01949 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI); 01950 ClonedMIs.push_back(Clone); 01951 ReMatDefs[VN] = Clone; 01952 01953 bool CanDelete = true; 01954 if (VNI->hasPHIKill) { 01955 // A kill is a phi node, not all of its uses can be rematerialized. 01956 // It must not be deleted. 01957 CanDelete = false; 01958 // Need a stack slot if there is any live range where uses cannot be 01959 // rematerialized. 01960 NeedStackSlot = true; 01961 } 01962 if (CanDelete) 01963 ReMatDelete.set(VN); 01964 } else { 01965 // Need a stack slot if there is any live range where uses cannot be 01966 // rematerialized. 01967 NeedStackSlot = true; 01968 } 01969 } 01970 01971 // One stack slot per live interval. 01972 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) 01973 Slot = vrm.assignVirt2StackSlot(li.reg); 01974 01975 // Create new intervals and rewrite defs and uses. 01976 for (LiveInterval::Ranges::const_iterator 01977 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) { 01978 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id]; 01979 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id]; 01980 bool DefIsReMat = ReMatDefMI != NULL; 01981 bool CanDelete = ReMatDelete[I->valno->id]; 01982 int LdSlot = 0; 01983 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot); 01984 bool isLoad = isLoadSS || 01985 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad()); 01986 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI, 01987 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat, 01988 CanDelete, vrm, rc, ReMatIds, loopInfo, 01989 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes, 01990 MBBVRegsMap, NewLIs, SSWeight); 01991 } 01992 01993 // Insert spills / restores if we are splitting. 01994 if (!TrySplit) { 01995 handleSpilledImpDefs(li, vrm, rc, NewLIs); 01996 return NewLIs; 01997 } 01998 01999 SmallPtrSet<LiveInterval*, 4> AddedKill; 02000 SmallVector<unsigned, 2> Ops; 02001 if (NeedStackSlot) { 02002 int Id = SpillMBBs.find_first(); 02003 while (Id != -1) { 02004 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id); 02005 unsigned loopDepth = loopInfo->getLoopDepth(MBB); 02006 std::vector<SRInfo> &spills = SpillIdxes[Id]; 02007 for (unsigned i = 0, e = spills.size(); i != e; ++i) { 02008 int index = spills[i].index; 02009 unsigned VReg = spills[i].vreg; 02010 LiveInterval &nI = getOrCreateInterval(VReg); 02011 bool isReMat = vrm.isReMaterialized(VReg); 02012 MachineInstr *MI = getInstructionFromIndex(index); 02013 bool CanFold = false; 02014 bool FoundUse = false; 02015 Ops.clear(); 02016 if (spills[i].canFold) { 02017 CanFold = true; 02018 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) { 02019 MachineOperand &MO = MI->getOperand(j); 02020 if (!MO.isReg() || MO.getReg() != VReg) 02021 continue; 02022 02023 Ops.push_back(j); 02024 if (MO.isDef()) 02025 continue; 02026 if (isReMat || 02027 (!FoundUse && !alsoFoldARestore(Id, index, VReg, 02028 RestoreMBBs, RestoreIdxes))) { 02029 // MI has two-address uses of the same register. If the use 02030 // isn't the first and only use in the BB, then we can't fold 02031 // it. FIXME: Move this to rewriteInstructionsForSpills. 02032 CanFold = false; 02033 break; 02034 } 02035 FoundUse = true; 02036 } 02037 } 02038 // Fold the store into the def if possible. 02039 bool Folded = false; 02040 if (CanFold && !Ops.empty()) { 02041 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){ 02042 Folded = true; 02043 if (FoundUse > 0) { 02044 // Also folded uses, do not issue a load. 02045 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes); 02046 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1); 02047 } 02048 nI.removeRange(getDefIndex(index), getStoreIndex(index)); 02049 } 02050 } 02051 02052 // Otherwise tell the spiller to issue a spill. 02053 if (!Folded) { 02054 LiveRange *LR = &nI.ranges[nI.ranges.size()-1]; 02055 bool isKill = LR->end == getStoreIndex(index); 02056 if (!MI->registerDefIsDead(nI.reg)) 02057 // No need to spill a dead def. 02058 vrm.addSpillPoint(VReg, isKill, MI); 02059 if (isKill) 02060 AddedKill.insert(&nI); 02061 } 02062 02063 // Update spill slot weight. 02064 if (!isReMat) 02065 SSWeight += getSpillWeight(true, false, loopDepth); 02066 } 02067 Id = SpillMBBs.find_next(Id); 02068 } 02069 } 02070 02071 int Id = RestoreMBBs.find_first(); 02072 while (Id != -1) { 02073 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id); 02074 unsigned loopDepth = loopInfo->getLoopDepth(MBB); 02075 02076 std::vector<SRInfo> &restores = RestoreIdxes[Id]; 02077 for (unsigned i = 0, e = restores.size(); i != e; ++i) { 02078 int index = restores[i].index; 02079 if (index == -1) 02080 continue; 02081 unsigned VReg = restores[i].vreg; 02082 LiveInterval &nI = getOrCreateInterval(VReg); 02083 bool isReMat = vrm.isReMaterialized(VReg); 02084 MachineInstr *MI = getInstructionFromIndex(index); 02085 bool CanFold = false; 02086 Ops.clear(); 02087 if (restores[i].canFold) { 02088 CanFold = true; 02089 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) { 02090 MachineOperand &MO = MI->getOperand(j); 02091 if (!MO.isReg() || MO.getReg() != VReg) 02092 continue; 02093 02094 if (MO.isDef()) { 02095 // If this restore were to be folded, it would have been folded 02096 // already. 02097 CanFold = false; 02098 break; 02099 } 02100 Ops.push_back(j); 02101 } 02102 } 02103 02104 // Fold the load into the use if possible. 02105 bool Folded = false; 02106 if (CanFold && !Ops.empty()) { 02107 if (!isReMat) 02108 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg); 02109 else { 02110 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg); 02111 int LdSlot = 0; 02112 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot); 02113 // If the rematerializable def is a load, also try to fold it. 02114 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad()) 02115 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index, 02116 Ops, isLoadSS, LdSlot, VReg); 02117 if (!Folded) { 02118 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI); 02119 if (ImpUse) { 02120 // Re-matting an instruction with virtual register use. Add the 02121 // register as an implicit use on the use MI and update the register 02122 // interval's spill weight to HUGE_VALF to prevent it from being 02123 // spilled. 02124 LiveInterval &ImpLi = getInterval(ImpUse); 02125 ImpLi.weight = HUGE_VALF; 02126 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true)); 02127 } 02128 } 02129 } 02130 } 02131 // If folding is not possible / failed, then tell the spiller to issue a 02132 // load / rematerialization for us. 02133 if (Folded) 02134 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1); 02135 else 02136 vrm.addRestorePoint(VReg, MI); 02137 02138 // Update spill slot weight. 02139 if (!isReMat) 02140 SSWeight += getSpillWeight(false, true, loopDepth); 02141 } 02142 Id = RestoreMBBs.find_next(Id); 02143 } 02144 02145 // Finalize intervals: add kills, finalize spill weights, and filter out 02146 // dead intervals. 02147 std::vector<LiveInterval*> RetNewLIs; 02148 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) { 02149 LiveInterval *LI = NewLIs[i]; 02150 if (!LI->empty()) { 02151 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI); 02152 if (!AddedKill.count(LI)) { 02153 LiveRange *LR = &LI->ranges[LI->ranges.size()-1]; 02154 unsigned LastUseIdx = getBaseIndex(LR->end); 02155 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx); 02156 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false); 02157 assert(UseIdx != -1); 02158 if (LastUse->getOperand(UseIdx).isImplicit() || 02159 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){ 02160 LastUse->getOperand(UseIdx).setIsKill(); 02161 vrm.addKillPoint(LI->reg, LastUseIdx); 02162 } 02163 } 02164 RetNewLIs.push_back(LI); 02165 } 02166 } 02167 02168 handleSpilledImpDefs(li, vrm, rc, RetNewLIs); 02169 return RetNewLIs; 02170 } 02171 02172 /// hasAllocatableSuperReg - Return true if the specified physical register has 02173 /// any super register that's allocatable. 02174 bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const { 02175 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) 02176 if (allocatableRegs_[*AS] && hasInterval(*AS)) 02177 return true; 02178 return false; 02179 } 02180 02181 /// getRepresentativeReg - Find the largest super register of the specified 02182 /// physical register. 02183 unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const { 02184 // Find the largest super-register that is allocatable. 02185 unsigned BestReg = Reg; 02186 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) { 02187 unsigned SuperReg = *AS; 02188 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) { 02189 BestReg = SuperReg; 02190 break; 02191 } 02192 } 02193 return BestReg; 02194 } 02195 02196 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the 02197 /// specified interval that conflicts with the specified physical register. 02198 unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li, 02199 unsigned PhysReg) const { 02200 unsigned NumConflicts = 0; 02201 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg)); 02202 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg), 02203 E = mri_->reg_end(); I != E; ++I) { 02204 MachineOperand &O = I.getOperand(); 02205 MachineInstr *MI = O.getParent(); 02206 unsigned Index = getInstructionIndex(MI); 02207 if (pli.liveAt(Index)) 02208 ++NumConflicts; 02209 } 02210 return NumConflicts; 02211 } 02212 02213 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register 02214 /// around all defs and uses of the specified interval. 02215 void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li, 02216 unsigned PhysReg, VirtRegMap &vrm) { 02217 unsigned SpillReg = getRepresentativeReg(PhysReg); 02218 02219 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS) 02220 // If there are registers which alias PhysReg, but which are not a 02221 // sub-register of the chosen representative super register. Assert 02222 // since we can't handle it yet. 02223 assert(*AS == SpillReg || !allocatableRegs_[*AS] || 02224 tri_->isSuperRegister(*AS, SpillReg)); 02225 02226 LiveInterval &pli = getInterval(SpillReg); 02227 SmallPtrSet<MachineInstr*, 8> SeenMIs; 02228 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg), 02229 E = mri_->reg_end(); I != E; ++I) { 02230 MachineOperand &O = I.getOperand(); 02231 MachineInstr *MI = O.getParent(); 02232 if (SeenMIs.count(MI)) 02233 continue; 02234 SeenMIs.insert(MI); 02235 unsigned Index = getInstructionIndex(MI); 02236 if (pli.liveAt(Index)) { 02237 vrm.addEmergencySpill(SpillReg, MI); 02238 unsigned StartIdx = getLoadIndex(Index); 02239 unsigned EndIdx = getStoreIndex(Index)+1; 02240 if (pli.isInOneLiveRange(StartIdx, EndIdx)) 02241 pli.removeRange(StartIdx, EndIdx); 02242 else { 02243 cerr << "Ran out of registers during register allocation!\n"; 02244 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) { 02245 cerr << "Please check your inline asm statement for invalid " 02246 << "constraints:\n"; 02247 MI->print(cerr.stream(), tm_); 02248 } 02249 exit(1); 02250 } 02251 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) { 02252 if (!hasInterval(*AS)) 02253 continue; 02254 LiveInterval &spli = getInterval(*AS); 02255 if (spli.liveAt(Index)) 02256 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1); 02257 } 02258 } 02259 } 02260 } 02261 02262 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg, 02263 MachineInstr* startInst) { 02264 LiveInterval& Interval = getOrCreateInterval(reg); 02265 VNInfo* VN = Interval.getNextValue( 02266 getInstructionIndex(startInst) + InstrSlots::DEF, 02267 startInst, getVNInfoAllocator()); 02268 VN->hasPHIKill = true; 02269 VN->kills.push_back(getMBBEndIdx(startInst->getParent())); 02270 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF, 02271 getMBBEndIdx(startInst->getParent()) + 1, VN); 02272 Interval.addRange(LR); 02273 02274 return LR; 02275 }