LLVM API Documentation
00001 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===// 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 a simple register coalescing pass that attempts to 00011 // aggressively coalesce every register copy that it can. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "regcoalescing" 00016 #include "SimpleRegisterCoalescing.h" 00017 #include "VirtRegMap.h" 00018 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 00019 #include "llvm/Value.h" 00020 #include "llvm/CodeGen/MachineFrameInfo.h" 00021 #include "llvm/CodeGen/MachineInstr.h" 00022 #include "llvm/CodeGen/MachineLoopInfo.h" 00023 #include "llvm/CodeGen/MachineRegisterInfo.h" 00024 #include "llvm/CodeGen/Passes.h" 00025 #include "llvm/CodeGen/RegisterCoalescer.h" 00026 #include "llvm/Target/TargetInstrInfo.h" 00027 #include "llvm/Target/TargetMachine.h" 00028 #include "llvm/Target/TargetOptions.h" 00029 #include "llvm/Support/CommandLine.h" 00030 #include "llvm/Support/Debug.h" 00031 #include "llvm/ADT/SmallSet.h" 00032 #include "llvm/ADT/Statistic.h" 00033 #include "llvm/ADT/STLExtras.h" 00034 #include <algorithm> 00035 #include <cmath> 00036 using namespace llvm; 00037 00038 STATISTIC(numJoins , "Number of interval joins performed"); 00039 STATISTIC(numCrossRCs , "Number of cross class joins performed"); 00040 STATISTIC(numCommutes , "Number of instruction commuting performed"); 00041 STATISTIC(numExtends , "Number of copies extended"); 00042 STATISTIC(NumReMats , "Number of instructions re-materialized"); 00043 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing"); 00044 STATISTIC(numAborts , "Number of times interval joining aborted"); 00045 STATISTIC(numDeadValNo, "Number of valno def marked dead"); 00046 00047 char SimpleRegisterCoalescing::ID = 0; 00048 static cl::opt<bool> 00049 EnableJoining("join-liveintervals", 00050 cl::desc("Coalesce copies (default=true)"), 00051 cl::init(true)); 00052 00053 static cl::opt<bool> 00054 NewHeuristic("new-coalescer-heuristic", 00055 cl::desc("Use new coalescer heuristic"), 00056 cl::init(false), cl::Hidden); 00057 00058 static cl::opt<bool> 00059 CrossClassJoin("join-cross-class-copies", 00060 cl::desc("Coalesce cross register class copies"), 00061 cl::init(false), cl::Hidden); 00062 00063 static RegisterPass<SimpleRegisterCoalescing> 00064 X("simple-register-coalescing", "Simple Register Coalescing"); 00065 00066 // Declare that we implement the RegisterCoalescer interface 00067 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X); 00068 00069 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X; 00070 00071 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const { 00072 AU.addRequired<LiveIntervals>(); 00073 AU.addPreserved<LiveIntervals>(); 00074 AU.addRequired<MachineLoopInfo>(); 00075 AU.addPreserved<MachineLoopInfo>(); 00076 AU.addPreservedID(MachineDominatorsID); 00077 if (StrongPHIElim) 00078 AU.addPreservedID(StrongPHIEliminationID); 00079 else 00080 AU.addPreservedID(PHIEliminationID); 00081 AU.addPreservedID(TwoAddressInstructionPassID); 00082 MachineFunctionPass::getAnalysisUsage(AU); 00083 } 00084 00085 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA 00086 /// being the source and IntB being the dest, thus this defines a value number 00087 /// in IntB. If the source value number (in IntA) is defined by a copy from B, 00088 /// see if we can merge these two pieces of B into a single value number, 00089 /// eliminating a copy. For example: 00090 /// 00091 /// A3 = B0 00092 /// ... 00093 /// B1 = A3 <- this copy 00094 /// 00095 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1 00096 /// value number to be replaced with B0 (which simplifies the B liveinterval). 00097 /// 00098 /// This returns true if an interval was modified. 00099 /// 00100 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, 00101 LiveInterval &IntB, 00102 MachineInstr *CopyMI) { 00103 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI)); 00104 00105 // BValNo is a value number in B that is defined by a copy from A. 'B3' in 00106 // the example above. 00107 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx); 00108 assert(BLR != IntB.end() && "Live range not found!"); 00109 VNInfo *BValNo = BLR->valno; 00110 00111 // Get the location that B is defined at. Two options: either this value has 00112 // an unknown definition point or it is defined at CopyIdx. If unknown, we 00113 // can't process it. 00114 if (!BValNo->copy) return false; 00115 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?"); 00116 00117 // AValNo is the value number in A that defines the copy, A3 in the example. 00118 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1); 00119 assert(ALR != IntA.end() && "Live range not found!"); 00120 VNInfo *AValNo = ALR->valno; 00121 // If it's re-defined by an early clobber somewhere in the live range, then 00122 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround. 00123 // See PR3149: 00124 // 172 %ECX<def> = MOV32rr %reg1039<kill> 00125 // 180 INLINEASM <es:subl $5,$1 00126 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>, 00127 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0 00128 // 188 %EAX<def> = MOV32rr %EAX<kill> 00129 // 196 %ECX<def> = MOV32rr %ECX<kill> 00130 // 204 %ECX<def> = MOV32rr %ECX<kill> 00131 // 212 %EAX<def> = MOV32rr %EAX<kill> 00132 // 220 %EAX<def> = MOV32rr %EAX 00133 // 228 %reg1039<def> = MOV32rr %ECX<kill> 00134 // The early clobber operand ties ECX input to the ECX def. 00135 // 00136 // The live interval of ECX is represented as this: 00137 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47) 00138 // The coalescer has no idea there was a def in the middle of [174,230]. 00139 if (AValNo->redefByEC) 00140 return false; 00141 00142 // If AValNo is defined as a copy from IntB, we can potentially process this. 00143 // Get the instruction that defines this value number. 00144 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo); 00145 if (!SrcReg) return false; // Not defined by a copy. 00146 00147 // If the value number is not defined by a copy instruction, ignore it. 00148 00149 // If the source register comes from an interval other than IntB, we can't 00150 // handle this. 00151 if (SrcReg != IntB.reg) return false; 00152 00153 // Get the LiveRange in IntB that this value number starts with. 00154 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1); 00155 assert(ValLR != IntB.end() && "Live range not found!"); 00156 00157 // Make sure that the end of the live range is inside the same block as 00158 // CopyMI. 00159 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1); 00160 if (!ValLREndInst || 00161 ValLREndInst->getParent() != CopyMI->getParent()) return false; 00162 00163 // Okay, we now know that ValLR ends in the same block that the CopyMI 00164 // live-range starts. If there are no intervening live ranges between them in 00165 // IntB, we can merge them. 00166 if (ValLR+1 != BLR) return false; 00167 00168 // If a live interval is a physical register, conservatively check if any 00169 // of its sub-registers is overlapping the live interval of the virtual 00170 // register. If so, do not coalesce. 00171 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) && 00172 *tri_->getSubRegisters(IntB.reg)) { 00173 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) 00174 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) { 00175 DOUT << "Interfere with sub-register "; 00176 DEBUG(li_->getInterval(*SR).print(DOUT, tri_)); 00177 return false; 00178 } 00179 } 00180 00181 DOUT << "\nExtending: "; IntB.print(DOUT, tri_); 00182 00183 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start; 00184 // We are about to delete CopyMI, so need to remove it as the 'instruction 00185 // that defines this value #'. Update the the valnum with the new defining 00186 // instruction #. 00187 BValNo->def = FillerStart; 00188 BValNo->copy = NULL; 00189 00190 // Okay, we can merge them. We need to insert a new liverange: 00191 // [ValLR.end, BLR.begin) of either value number, then we merge the 00192 // two value numbers. 00193 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo)); 00194 00195 // If the IntB live range is assigned to a physical register, and if that 00196 // physreg has aliases, 00197 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) { 00198 // Update the liveintervals of sub-registers. 00199 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) { 00200 LiveInterval &AliasLI = li_->getInterval(*AS); 00201 AliasLI.addRange(LiveRange(FillerStart, FillerEnd, 00202 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator()))); 00203 } 00204 } 00205 00206 // Okay, merge "B1" into the same value number as "B0". 00207 if (BValNo != ValLR->valno) { 00208 IntB.addKills(ValLR->valno, BValNo->kills); 00209 IntB.MergeValueNumberInto(BValNo, ValLR->valno); 00210 } 00211 DOUT << " result = "; IntB.print(DOUT, tri_); 00212 DOUT << "\n"; 00213 00214 // If the source instruction was killing the source register before the 00215 // merge, unset the isKill marker given the live range has been extended. 00216 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true); 00217 if (UIdx != -1) { 00218 ValLREndInst->getOperand(UIdx).setIsKill(false); 00219 IntB.removeKill(ValLR->valno, FillerStart); 00220 } 00221 00222 ++numExtends; 00223 return true; 00224 } 00225 00226 /// HasOtherReachingDefs - Return true if there are definitions of IntB 00227 /// other than BValNo val# that can reach uses of AValno val# of IntA. 00228 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA, 00229 LiveInterval &IntB, 00230 VNInfo *AValNo, 00231 VNInfo *BValNo) { 00232 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end(); 00233 AI != AE; ++AI) { 00234 if (AI->valno != AValNo) continue; 00235 LiveInterval::Ranges::iterator BI = 00236 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start); 00237 if (BI != IntB.ranges.begin()) 00238 --BI; 00239 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) { 00240 if (BI->valno == BValNo) 00241 continue; 00242 if (BI->start <= AI->start && BI->end > AI->start) 00243 return true; 00244 if (BI->start > AI->start && BI->start < AI->end) 00245 return true; 00246 } 00247 } 00248 return false; 00249 } 00250 00251 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA 00252 /// being the source and IntB being the dest, thus this defines a value number 00253 /// in IntB. If the source value number (in IntA) is defined by a commutable 00254 /// instruction and its other operand is coalesced to the copy dest register, 00255 /// see if we can transform the copy into a noop by commuting the definition. For 00256 /// example, 00257 /// 00258 /// A3 = op A2 B0<kill> 00259 /// ... 00260 /// B1 = A3 <- this copy 00261 /// ... 00262 /// = op A3 <- more uses 00263 /// 00264 /// ==> 00265 /// 00266 /// B2 = op B0 A2<kill> 00267 /// ... 00268 /// B1 = B2 <- now an identify copy 00269 /// ... 00270 /// = op B2 <- more uses 00271 /// 00272 /// This returns true if an interval was modified. 00273 /// 00274 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA, 00275 LiveInterval &IntB, 00276 MachineInstr *CopyMI) { 00277 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI)); 00278 00279 // FIXME: For now, only eliminate the copy by commuting its def when the 00280 // source register is a virtual register. We want to guard against cases 00281 // where the copy is a back edge copy and commuting the def lengthen the 00282 // live interval of the source register to the entire loop. 00283 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg)) 00284 return false; 00285 00286 // BValNo is a value number in B that is defined by a copy from A. 'B3' in 00287 // the example above. 00288 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx); 00289 assert(BLR != IntB.end() && "Live range not found!"); 00290 VNInfo *BValNo = BLR->valno; 00291 00292 // Get the location that B is defined at. Two options: either this value has 00293 // an unknown definition point or it is defined at CopyIdx. If unknown, we 00294 // can't process it. 00295 if (!BValNo->copy) return false; 00296 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?"); 00297 00298 // AValNo is the value number in A that defines the copy, A3 in the example. 00299 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1); 00300 assert(ALR != IntA.end() && "Live range not found!"); 00301 VNInfo *AValNo = ALR->valno; 00302 // If other defs can reach uses of this def, then it's not safe to perform 00303 // the optimization. 00304 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill) 00305 return false; 00306 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def); 00307 const TargetInstrDesc &TID = DefMI->getDesc(); 00308 unsigned NewDstIdx; 00309 if (!TID.isCommutable() || 00310 !tii_->CommuteChangesDestination(DefMI, NewDstIdx)) 00311 return false; 00312 00313 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx); 00314 unsigned NewReg = NewDstMO.getReg(); 00315 if (NewReg != IntB.reg || !NewDstMO.isKill()) 00316 return false; 00317 00318 // Make sure there are no other definitions of IntB that would reach the 00319 // uses which the new definition can reach. 00320 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo)) 00321 return false; 00322 00323 // If some of the uses of IntA.reg is already coalesced away, return false. 00324 // It's not possible to determine whether it's safe to perform the coalescing. 00325 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg), 00326 UE = mri_->use_end(); UI != UE; ++UI) { 00327 MachineInstr *UseMI = &*UI; 00328 unsigned UseIdx = li_->getInstructionIndex(UseMI); 00329 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx); 00330 if (ULR == IntA.end()) 00331 continue; 00332 if (ULR->valno == AValNo && JoinedCopies.count(UseMI)) 00333 return false; 00334 } 00335 00336 // At this point we have decided that it is legal to do this 00337 // transformation. Start by commuting the instruction. 00338 MachineBasicBlock *MBB = DefMI->getParent(); 00339 MachineInstr *NewMI = tii_->commuteInstruction(DefMI); 00340 if (!NewMI) 00341 return false; 00342 if (NewMI != DefMI) { 00343 li_->ReplaceMachineInstrInMaps(DefMI, NewMI); 00344 MBB->insert(DefMI, NewMI); 00345 MBB->erase(DefMI); 00346 } 00347 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false); 00348 NewMI->getOperand(OpIdx).setIsKill(); 00349 00350 bool BHasPHIKill = BValNo->hasPHIKill; 00351 SmallVector<VNInfo*, 4> BDeadValNos; 00352 SmallVector<unsigned, 4> BKills; 00353 std::map<unsigned, unsigned> BExtend; 00354 00355 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g. 00356 // A = or A, B 00357 // ... 00358 // B = A 00359 // ... 00360 // C = A<kill> 00361 // ... 00362 // = B 00363 // 00364 // then do not add kills of A to the newly created B interval. 00365 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start; 00366 if (Extended) 00367 BExtend[ALR->end] = BLR->end; 00368 00369 // Update uses of IntA of the specific Val# with IntB. 00370 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg), 00371 UE = mri_->use_end(); UI != UE;) { 00372 MachineOperand &UseMO = UI.getOperand(); 00373 MachineInstr *UseMI = &*UI; 00374 ++UI; 00375 if (JoinedCopies.count(UseMI)) 00376 continue; 00377 unsigned UseIdx = li_->getInstructionIndex(UseMI); 00378 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx); 00379 if (ULR == IntA.end() || ULR->valno != AValNo) 00380 continue; 00381 UseMO.setReg(NewReg); 00382 if (UseMI == CopyMI) 00383 continue; 00384 if (UseMO.isKill()) { 00385 if (Extended) 00386 UseMO.setIsKill(false); 00387 else 00388 BKills.push_back(li_->getUseIndex(UseIdx)+1); 00389 } 00390 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 00391 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) 00392 continue; 00393 if (DstReg == IntB.reg) { 00394 // This copy will become a noop. If it's defining a new val#, 00395 // remove that val# as well. However this live range is being 00396 // extended to the end of the existing live range defined by the copy. 00397 unsigned DefIdx = li_->getDefIndex(UseIdx); 00398 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx); 00399 BHasPHIKill |= DLR->valno->hasPHIKill; 00400 assert(DLR->valno->def == DefIdx); 00401 BDeadValNos.push_back(DLR->valno); 00402 BExtend[DLR->start] = DLR->end; 00403 JoinedCopies.insert(UseMI); 00404 // If this is a kill but it's going to be removed, the last use 00405 // of the same val# is the new kill. 00406 if (UseMO.isKill()) 00407 BKills.pop_back(); 00408 } 00409 } 00410 00411 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can 00412 // simply extend BLR if CopyMI doesn't end the range. 00413 DOUT << "\nExtending: "; IntB.print(DOUT, tri_); 00414 00415 // Remove val#'s defined by copies that will be coalesced away. 00416 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) 00417 IntB.removeValNo(BDeadValNos[i]); 00418 00419 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition 00420 // is updated. Kills are also updated. 00421 VNInfo *ValNo = BValNo; 00422 ValNo->def = AValNo->def; 00423 ValNo->copy = NULL; 00424 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) { 00425 unsigned Kill = ValNo->kills[j]; 00426 if (Kill != BLR->end) 00427 BKills.push_back(Kill); 00428 } 00429 ValNo->kills.clear(); 00430 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end(); 00431 AI != AE; ++AI) { 00432 if (AI->valno != AValNo) continue; 00433 unsigned End = AI->end; 00434 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End); 00435 if (EI != BExtend.end()) 00436 End = EI->second; 00437 IntB.addRange(LiveRange(AI->start, End, ValNo)); 00438 } 00439 IntB.addKills(ValNo, BKills); 00440 ValNo->hasPHIKill = BHasPHIKill; 00441 00442 DOUT << " result = "; IntB.print(DOUT, tri_); 00443 DOUT << "\n"; 00444 00445 DOUT << "\nShortening: "; IntA.print(DOUT, tri_); 00446 IntA.removeValNo(AValNo); 00447 DOUT << " result = "; IntA.print(DOUT, tri_); 00448 DOUT << "\n"; 00449 00450 ++numCommutes; 00451 return true; 00452 } 00453 00454 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply 00455 /// fallthoughs to SuccMBB. 00456 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB, 00457 MachineBasicBlock *SuccMBB, 00458 const TargetInstrInfo *tii_) { 00459 if (MBB == SuccMBB) 00460 return true; 00461 MachineBasicBlock *TBB = 0, *FBB = 0; 00462 SmallVector<MachineOperand, 4> Cond; 00463 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB && 00464 MBB->isSuccessor(SuccMBB); 00465 } 00466 00467 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range 00468 /// from a physical register live interval as well as from the live intervals 00469 /// of its sub-registers. 00470 static void removeRange(LiveInterval &li, unsigned Start, unsigned End, 00471 LiveIntervals *li_, const TargetRegisterInfo *tri_) { 00472 li.removeRange(Start, End, true); 00473 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) { 00474 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) { 00475 if (!li_->hasInterval(*SR)) 00476 continue; 00477 LiveInterval &sli = li_->getInterval(*SR); 00478 unsigned RemoveEnd = Start; 00479 while (RemoveEnd != End) { 00480 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start); 00481 if (LR == sli.end()) 00482 break; 00483 RemoveEnd = (LR->end < End) ? LR->end : End; 00484 sli.removeRange(Start, RemoveEnd, true); 00485 Start = RemoveEnd; 00486 } 00487 } 00488 } 00489 } 00490 00491 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block 00492 /// as the copy instruction, trim the live interval to the last use and return 00493 /// true. 00494 bool 00495 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(unsigned CopyIdx, 00496 MachineBasicBlock *CopyMBB, 00497 LiveInterval &li, 00498 const LiveRange *LR) { 00499 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB); 00500 unsigned LastUseIdx; 00501 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg, 00502 LastUseIdx); 00503 if (LastUse) { 00504 MachineInstr *LastUseMI = LastUse->getParent(); 00505 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) { 00506 // r1024 = op 00507 // ... 00508 // BB1: 00509 // = r1024 00510 // 00511 // BB2: 00512 // r1025<dead> = r1024<kill> 00513 if (MBBStart < LR->end) 00514 removeRange(li, MBBStart, LR->end, li_, tri_); 00515 return true; 00516 } 00517 00518 // There are uses before the copy, just shorten the live range to the end 00519 // of last use. 00520 LastUse->setIsKill(); 00521 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_); 00522 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 00523 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) && 00524 DstReg == li.reg) { 00525 // Last use is itself an identity code. 00526 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_); 00527 LastUseMI->getOperand(DeadIdx).setIsDead(); 00528 } 00529 return true; 00530 } 00531 00532 // Is it livein? 00533 if (LR->start <= MBBStart && LR->end > MBBStart) { 00534 if (LR->start == 0) { 00535 assert(TargetRegisterInfo::isPhysicalRegister(li.reg)); 00536 // Live-in to the function but dead. Remove it from entry live-in set. 00537 mf_->begin()->removeLiveIn(li.reg); 00538 } 00539 // FIXME: Shorten intervals in BBs that reaches this BB. 00540 } 00541 00542 return false; 00543 } 00544 00545 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial 00546 /// computation, replace the copy by rematerialize the definition. 00547 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt, 00548 unsigned DstReg, 00549 MachineInstr *CopyMI) { 00550 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI)); 00551 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx); 00552 assert(SrcLR != SrcInt.end() && "Live range not found!"); 00553 VNInfo *ValNo = SrcLR->valno; 00554 // If other defs can reach uses of this def, then it's not safe to perform 00555 // the optimization. 00556 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill) 00557 return false; 00558 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def); 00559 const TargetInstrDesc &TID = DefMI->getDesc(); 00560 if (!TID.isAsCheapAsAMove()) 00561 return false; 00562 if (!DefMI->getDesc().isRematerializable() || 00563 !tii_->isTriviallyReMaterializable(DefMI)) 00564 return false; 00565 bool SawStore = false; 00566 if (!DefMI->isSafeToMove(tii_, SawStore)) 00567 return false; 00568 00569 unsigned DefIdx = li_->getDefIndex(CopyIdx); 00570 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx); 00571 DLR->valno->copy = NULL; 00572 // Don't forget to update sub-register intervals. 00573 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { 00574 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) { 00575 if (!li_->hasInterval(*SR)) 00576 continue; 00577 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx); 00578 if (DLR && DLR->valno->copy == CopyMI) 00579 DLR->valno->copy = NULL; 00580 } 00581 } 00582 00583 // If copy kills the source register, find the last use and propagate 00584 // kill. 00585 MachineBasicBlock *MBB = CopyMI->getParent(); 00586 if (CopyMI->killsRegister(SrcInt.reg)) 00587 TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR); 00588 00589 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI)); 00590 CopyMI->removeFromParent(); 00591 tii_->reMaterialize(*MBB, MII, DstReg, DefMI); 00592 MachineInstr *NewMI = prior(MII); 00593 // CopyMI may have implicit operands, transfer them over to the newly 00594 // rematerialized instruction. And update implicit def interval valnos. 00595 for (unsigned i = CopyMI->getDesc().getNumOperands(), 00596 e = CopyMI->getNumOperands(); i != e; ++i) { 00597 MachineOperand &MO = CopyMI->getOperand(i); 00598 if (MO.isReg() && MO.isImplicit()) 00599 NewMI->addOperand(MO); 00600 if (MO.isDef() && li_->hasInterval(MO.getReg())) { 00601 unsigned Reg = MO.getReg(); 00602 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx); 00603 if (DLR && DLR->valno->copy == CopyMI) 00604 DLR->valno->copy = NULL; 00605 } 00606 } 00607 00608 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI); 00609 MBB->getParent()->DeleteMachineInstr(CopyMI); 00610 ReMatCopies.insert(CopyMI); 00611 ReMatDefs.insert(DefMI); 00612 ++NumReMats; 00613 return true; 00614 } 00615 00616 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy. 00617 /// 00618 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI, 00619 unsigned DstReg) const { 00620 MachineBasicBlock *MBB = CopyMI->getParent(); 00621 const MachineLoop *L = loopInfo->getLoopFor(MBB); 00622 if (!L) 00623 return false; 00624 if (MBB != L->getLoopLatch()) 00625 return false; 00626 00627 LiveInterval &LI = li_->getInterval(DstReg); 00628 unsigned DefIdx = li_->getInstructionIndex(CopyMI); 00629 LiveInterval::const_iterator DstLR = 00630 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx)); 00631 if (DstLR == LI.end()) 00632 return false; 00633 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1; 00634 if (DstLR->valno->kills.size() == 1 && 00635 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill) 00636 return true; 00637 return false; 00638 } 00639 00640 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and 00641 /// update the subregister number if it is not zero. If DstReg is a 00642 /// physical register and the existing subregister number of the def / use 00643 /// being updated is not zero, make sure to set it to the correct physical 00644 /// subregister. 00645 void 00646 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg, 00647 unsigned SubIdx) { 00648 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 00649 if (DstIsPhys && SubIdx) { 00650 // Figure out the real physical register we are updating with. 00651 DstReg = tri_->getSubReg(DstReg, SubIdx); 00652 SubIdx = 0; 00653 } 00654 00655 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg), 00656 E = mri_->reg_end(); I != E; ) { 00657 MachineOperand &O = I.getOperand(); 00658 MachineInstr *UseMI = &*I; 00659 ++I; 00660 unsigned OldSubIdx = O.getSubReg(); 00661 if (DstIsPhys) { 00662 unsigned UseDstReg = DstReg; 00663 if (OldSubIdx) 00664 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx); 00665 00666 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx; 00667 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg, 00668 CopySrcSubIdx, CopyDstSubIdx) && 00669 CopySrcReg != CopyDstReg && 00670 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) { 00671 // If the use is a copy and it won't be coalesced away, and its source 00672 // is defined by a trivial computation, try to rematerialize it instead. 00673 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI)) 00674 continue; 00675 } 00676 00677 O.setReg(UseDstReg); 00678 O.setSubReg(0); 00679 continue; 00680 } 00681 00682 // Sub-register indexes goes from small to large. e.g. 00683 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX 00684 // EAX: 1 -> AL, 2 -> AX 00685 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose 00686 // sub-register 2 is also AX. 00687 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx) 00688 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!"); 00689 else if (SubIdx) 00690 O.setSubReg(SubIdx); 00691 // Remove would-be duplicated kill marker. 00692 if (O.isKill() && UseMI->killsRegister(DstReg)) 00693 O.setIsKill(false); 00694 O.setReg(DstReg); 00695 00696 // After updating the operand, check if the machine instruction has 00697 // become a copy. If so, update its val# information. 00698 const TargetInstrDesc &TID = UseMI->getDesc(); 00699 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx; 00700 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 && 00701 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg, 00702 CopySrcSubIdx, CopyDstSubIdx) && 00703 CopySrcReg != CopyDstReg && 00704 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) || 00705 allocatableRegs_[CopyDstReg])) { 00706 LiveInterval &LI = li_->getInterval(CopyDstReg); 00707 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI)); 00708 const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx); 00709 if (DLR->valno->def == DefIdx) 00710 DLR->valno->copy = UseMI; 00711 } 00712 } 00713 } 00714 00715 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining" 00716 /// registers due to insert_subreg coalescing. e.g. 00717 /// r1024 = op 00718 /// r1025 = implicit_def 00719 /// r1025 = insert_subreg r1025, r1024 00720 /// = op r1025 00721 /// => 00722 /// r1025 = op 00723 /// r1025 = implicit_def 00724 /// r1025 = insert_subreg r1025, r1025 00725 /// = op r1025 00726 void 00727 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) { 00728 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg), 00729 E = mri_->reg_end(); I != E; ) { 00730 MachineOperand &O = I.getOperand(); 00731 MachineInstr *DefMI = &*I; 00732 ++I; 00733 if (!O.isDef()) 00734 continue; 00735 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) 00736 continue; 00737 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI))) 00738 continue; 00739 li_->RemoveMachineInstrFromMaps(DefMI); 00740 DefMI->eraseFromParent(); 00741 } 00742 } 00743 00744 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate 00745 /// due to live range lengthening as the result of coalescing. 00746 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg, 00747 LiveInterval &LI) { 00748 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg), 00749 UE = mri_->use_end(); UI != UE; ++UI) { 00750 MachineOperand &UseMO = UI.getOperand(); 00751 if (UseMO.isKill()) { 00752 MachineInstr *UseMI = UseMO.getParent(); 00753 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI)); 00754 if (JoinedCopies.count(UseMI)) 00755 continue; 00756 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx); 00757 if (!UI || !LI.isKill(UI->valno, UseIdx+1)) 00758 UseMO.setIsKill(false); 00759 } 00760 } 00761 } 00762 00763 /// removeIntervalIfEmpty - Check if the live interval of a physical register 00764 /// is empty, if so remove it and also remove the empty intervals of its 00765 /// sub-registers. Return true if live interval is removed. 00766 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_, 00767 const TargetRegisterInfo *tri_) { 00768 if (li.empty()) { 00769 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) 00770 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) { 00771 if (!li_->hasInterval(*SR)) 00772 continue; 00773 LiveInterval &sli = li_->getInterval(*SR); 00774 if (sli.empty()) 00775 li_->removeInterval(*SR); 00776 } 00777 li_->removeInterval(li.reg); 00778 return true; 00779 } 00780 return false; 00781 } 00782 00783 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy. 00784 /// Return true if live interval is removed. 00785 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li, 00786 MachineInstr *CopyMI) { 00787 unsigned CopyIdx = li_->getInstructionIndex(CopyMI); 00788 LiveInterval::iterator MLR = 00789 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx)); 00790 if (MLR == li.end()) 00791 return false; // Already removed by ShortenDeadCopySrcLiveRange. 00792 unsigned RemoveStart = MLR->start; 00793 unsigned RemoveEnd = MLR->end; 00794 // Remove the liverange that's defined by this. 00795 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) { 00796 removeRange(li, RemoveStart, RemoveEnd, li_, tri_); 00797 return removeIntervalIfEmpty(li, li_, tri_); 00798 } 00799 return false; 00800 } 00801 00802 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove 00803 /// the val# it defines. If the live interval becomes empty, remove it as well. 00804 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li, 00805 MachineInstr *DefMI) { 00806 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI)); 00807 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx); 00808 if (DefIdx != MLR->valno->def) 00809 return false; 00810 li.removeValNo(MLR->valno); 00811 return removeIntervalIfEmpty(li, li_, tri_); 00812 } 00813 00814 /// PropagateDeadness - Propagate the dead marker to the instruction which 00815 /// defines the val#. 00816 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI, 00817 unsigned &LRStart, LiveIntervals *li_, 00818 const TargetRegisterInfo* tri_) { 00819 MachineInstr *DefMI = 00820 li_->getInstructionFromIndex(li_->getDefIndex(LRStart)); 00821 if (DefMI && DefMI != CopyMI) { 00822 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_); 00823 if (DeadIdx != -1) { 00824 DefMI->getOperand(DeadIdx).setIsDead(); 00825 // A dead def should have a single cycle interval. 00826 ++LRStart; 00827 } 00828 } 00829 } 00830 00831 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially 00832 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as 00833 /// ends the live range there. If there isn't another use, then this live range 00834 /// is dead. Return true if live interval is removed. 00835 bool 00836 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li, 00837 MachineInstr *CopyMI) { 00838 unsigned CopyIdx = li_->getInstructionIndex(CopyMI); 00839 if (CopyIdx == 0) { 00840 // FIXME: special case: function live in. It can be a general case if the 00841 // first instruction index starts at > 0 value. 00842 assert(TargetRegisterInfo::isPhysicalRegister(li.reg)); 00843 // Live-in to the function but dead. Remove it from entry live-in set. 00844 if (mf_->begin()->isLiveIn(li.reg)) 00845 mf_->begin()->removeLiveIn(li.reg); 00846 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx); 00847 removeRange(li, LR->start, LR->end, li_, tri_); 00848 return removeIntervalIfEmpty(li, li_, tri_); 00849 } 00850 00851 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1); 00852 if (LR == li.end()) 00853 // Livein but defined by a phi. 00854 return false; 00855 00856 unsigned RemoveStart = LR->start; 00857 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1; 00858 if (LR->end > RemoveEnd) 00859 // More uses past this copy? Nothing to do. 00860 return false; 00861 00862 // If there is a last use in the same bb, we can't remove the live range. 00863 // Shorten the live interval and return. 00864 MachineBasicBlock *CopyMBB = CopyMI->getParent(); 00865 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR)) 00866 return false; 00867 00868 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart); 00869 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_)) 00870 // If the live range starts in another mbb and the copy mbb is not a fall 00871 // through mbb, then we can only cut the range from the beginning of the 00872 // copy mbb. 00873 RemoveStart = li_->getMBBStartIdx(CopyMBB) + 1; 00874 00875 if (LR->valno->def == RemoveStart) { 00876 // If the def MI defines the val# and this copy is the only kill of the 00877 // val#, then propagate the dead marker. 00878 if (li.isOnlyLROfValNo(LR)) { 00879 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_); 00880 ++numDeadValNo; 00881 } 00882 if (li.isKill(LR->valno, RemoveEnd)) 00883 li.removeKill(LR->valno, RemoveEnd); 00884 } 00885 00886 removeRange(li, RemoveStart, RemoveEnd, li_, tri_); 00887 return removeIntervalIfEmpty(li, li_, tri_); 00888 } 00889 00890 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction 00891 /// from an implicit def to another register can be coalesced away. 00892 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI, 00893 LiveInterval &li, 00894 LiveInterval &ImpLi) const{ 00895 if (!CopyMI->killsRegister(ImpLi.reg)) 00896 return false; 00897 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI)); 00898 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx); 00899 if (LR == li.end()) 00900 return false; 00901 if (LR->valno->hasPHIKill) 00902 return false; 00903 if (LR->valno->def != CopyIdx) 00904 return false; 00905 // Make sure all of val# uses are copies. 00906 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg), 00907 UE = mri_->use_end(); UI != UE;) { 00908 MachineInstr *UseMI = &*UI; 00909 ++UI; 00910 if (JoinedCopies.count(UseMI)) 00911 continue; 00912 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI)); 00913 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx); 00914 if (ULR == li.end() || ULR->valno != LR->valno) 00915 continue; 00916 // If the use is not a use, then it's not safe to coalesce the move. 00917 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 00918 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) { 00919 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG && 00920 UseMI->getOperand(1).getReg() == li.reg) 00921 continue; 00922 return false; 00923 } 00924 } 00925 return true; 00926 } 00927 00928 00929 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit 00930 /// def and it is being removed. Turn all copies from this value# into 00931 /// identity copies so they will be removed. 00932 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li, 00933 VNInfo *VNI) { 00934 SmallVector<MachineInstr*, 4> ImpDefs; 00935 MachineOperand *LastUse = NULL; 00936 unsigned LastUseIdx = li_->getUseIndex(VNI->def); 00937 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg), 00938 RE = mri_->reg_end(); RI != RE;) { 00939 MachineOperand *MO = &RI.getOperand(); 00940 MachineInstr *MI = &*RI; 00941 ++RI; 00942 if (MO->isDef()) { 00943 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) { 00944 ImpDefs.push_back(MI); 00945 } 00946 continue; 00947 } 00948 if (JoinedCopies.count(MI)) 00949 continue; 00950 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI)); 00951 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx); 00952 if (ULR == li.end() || ULR->valno != VNI) 00953 continue; 00954 // If the use is a copy, turn it into an identity copy. 00955 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 00956 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) && 00957 SrcReg == li.reg) { 00958 // Each use MI may have multiple uses of this register. Change them all. 00959 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 00960 MachineOperand &MO = MI->getOperand(i); 00961 if (MO.isReg() && MO.getReg() == li.reg) 00962 MO.setReg(DstReg); 00963 } 00964 JoinedCopies.insert(MI); 00965 } else if (UseIdx > LastUseIdx) { 00966 LastUseIdx = UseIdx; 00967 LastUse = MO; 00968 } 00969 } 00970 if (LastUse) 00971 LastUse->setIsKill(); 00972 else { 00973 // Remove dead implicit_def's. 00974 while (!ImpDefs.empty()) { 00975 MachineInstr *ImpDef = ImpDefs.back(); 00976 ImpDefs.pop_back(); 00977 li_->RemoveMachineInstrFromMaps(ImpDef); 00978 ImpDef->eraseFromParent(); 00979 } 00980 } 00981 } 00982 00983 /// getMatchingSuperReg - Return a super-register of the specified register 00984 /// Reg so its sub-register of index SubIdx is Reg. 00985 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx, 00986 const TargetRegisterClass *RC, 00987 const TargetRegisterInfo* TRI) { 00988 for (const unsigned *SRs = TRI->getSuperRegisters(Reg); 00989 unsigned SR = *SRs; ++SRs) 00990 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR)) 00991 return SR; 00992 return 0; 00993 } 00994 00995 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce 00996 /// two virtual registers from different register classes. 00997 bool 00998 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg, 00999 unsigned SmallReg, 01000 unsigned Threshold) { 01001 // Then make sure the intervals are *short*. 01002 LiveInterval &LargeInt = li_->getInterval(LargeReg); 01003 LiveInterval &SmallInt = li_->getInterval(SmallReg); 01004 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt); 01005 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt); 01006 if (SmallSize > Threshold || LargeSize > Threshold) 01007 if ((float)std::distance(mri_->use_begin(SmallReg), 01008 mri_->use_end()) / SmallSize < 01009 (float)std::distance(mri_->use_begin(LargeReg), 01010 mri_->use_end()) / LargeSize) 01011 return false; 01012 return true; 01013 } 01014 01015 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual 01016 /// register with a physical register, check if any of the virtual register 01017 /// operand is a sub-register use or def. If so, make sure it won't result 01018 /// in an illegal extract_subreg or insert_subreg instruction. e.g. 01019 /// vr1024 = extract_subreg vr1025, 1 01020 /// ... 01021 /// vr1024 = mov8rr AH 01022 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since 01023 /// AH does not have a super-reg whose sub-register 1 is AH. 01024 bool 01025 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI, 01026 unsigned VirtReg, 01027 unsigned PhysReg) { 01028 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg), 01029 E = mri_->reg_end(); I != E; ++I) { 01030 MachineOperand &O = I.getOperand(); 01031 MachineInstr *MI = &*I; 01032 if (MI == CopyMI || JoinedCopies.count(MI)) 01033 continue; 01034 unsigned SubIdx = O.getSubReg(); 01035 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx)) 01036 return true; 01037 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) { 01038 SubIdx = MI->getOperand(2).getImm(); 01039 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx)) 01040 return true; 01041 if (O.isDef()) { 01042 unsigned SrcReg = MI->getOperand(1).getReg(); 01043 const TargetRegisterClass *RC = 01044 TargetRegisterInfo::isPhysicalRegister(SrcReg) 01045 ? tri_->getPhysicalRegisterRegClass(SrcReg) 01046 : mri_->getRegClass(SrcReg); 01047 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_)) 01048 return true; 01049 } 01050 } 01051 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) { 01052 SubIdx = MI->getOperand(3).getImm(); 01053 if (VirtReg == MI->getOperand(0).getReg()) { 01054 if (!tri_->getSubReg(PhysReg, SubIdx)) 01055 return true; 01056 } else { 01057 unsigned DstReg = MI->getOperand(0).getReg(); 01058 const TargetRegisterClass *RC = 01059 TargetRegisterInfo::isPhysicalRegister(DstReg) 01060 ? tri_->getPhysicalRegisterRegClass(DstReg) 01061 : mri_->getRegClass(DstReg); 01062 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_)) 01063 return true; 01064 } 01065 } 01066 } 01067 return false; 01068 } 01069 01070 01071 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce 01072 /// an extract_subreg where dst is a physical register, e.g. 01073 /// cl = EXTRACT_SUBREG reg1024, 1 01074 bool 01075 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg, 01076 unsigned SrcReg, unsigned SubIdx, 01077 unsigned &RealDstReg) { 01078 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg); 01079 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_); 01080 assert(RealDstReg && "Invalid extract_subreg instruction!"); 01081 01082 // For this type of EXTRACT_SUBREG, conservatively 01083 // check if the live interval of the source register interfere with the 01084 // actual super physical register we are trying to coalesce with. 01085 LiveInterval &RHS = li_->getInterval(SrcReg); 01086 if (li_->hasInterval(RealDstReg) && 01087 RHS.overlaps(li_->getInterval(RealDstReg))) { 01088 DOUT << "Interfere with register "; 01089 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_)); 01090 return false; // Not coalescable 01091 } 01092 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR) 01093 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) { 01094 DOUT << "Interfere with sub-register "; 01095 DEBUG(li_->getInterval(*SR).print(DOUT, tri_)); 01096 return false; // Not coalescable 01097 } 01098 return true; 01099 } 01100 01101 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce 01102 /// an insert_subreg where src is a physical register, e.g. 01103 /// reg1024 = INSERT_SUBREG reg1024, c1, 0 01104 bool 01105 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg, 01106 unsigned SrcReg, unsigned SubIdx, 01107 unsigned &RealSrcReg) { 01108 const TargetRegisterClass *RC = mri_->getRegClass(DstReg); 01109 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_); 01110 assert(RealSrcReg && "Invalid extract_subreg instruction!"); 01111 01112 LiveInterval &RHS = li_->getInterval(DstReg); 01113 if (li_->hasInterval(RealSrcReg) && 01114 RHS.overlaps(li_->getInterval(RealSrcReg))) { 01115 DOUT << "Interfere with register "; 01116 DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_)); 01117 return false; // Not coalescable 01118 } 01119 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR) 01120 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) { 01121 DOUT << "Interfere with sub-register "; 01122 DEBUG(li_->getInterval(*SR).print(DOUT, tri_)); 01123 return false; // Not coalescable 01124 } 01125 return true; 01126 } 01127 01128 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg, 01129 /// which are the src/dst of the copy instruction CopyMI. This returns true 01130 /// if the copy was successfully coalesced away. If it is not currently 01131 /// possible to coalesce this interval, but it may be possible if other 01132 /// things get coalesced, then it returns true by reference in 'Again'. 01133 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { 01134 MachineInstr *CopyMI = TheCopy.MI; 01135 01136 Again = false; 01137 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI)) 01138 return false; // Already done. 01139 01140 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI; 01141 01142 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 01143 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG; 01144 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG; 01145 unsigned SubIdx = 0; 01146 if (isExtSubReg) { 01147 DstReg = CopyMI->getOperand(0).getReg(); 01148 SrcReg = CopyMI->getOperand(1).getReg(); 01149 } else if (isInsSubReg) { 01150 if (CopyMI->getOperand(2).getSubReg()) { 01151 DOUT << "\tSource of insert_subreg is already coalesced " 01152 << "to another register.\n"; 01153 return false; // Not coalescable. 01154 } 01155 DstReg = CopyMI->getOperand(0).getReg(); 01156 SrcReg = CopyMI->getOperand(2).getReg(); 01157 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){ 01158 assert(0 && "Unrecognized copy instruction!"); 01159 return false; 01160 } 01161 01162 // If they are already joined we continue. 01163 if (SrcReg == DstReg) { 01164 DOUT << "\tCopy already coalesced.\n"; 01165 return false; // Not coalescable. 01166 } 01167 01168 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg); 01169 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 01170 01171 // If they are both physical registers, we cannot join them. 01172 if (SrcIsPhys && DstIsPhys) { 01173 DOUT << "\tCan not coalesce physregs.\n"; 01174 return false; // Not coalescable. 01175 } 01176 01177 // We only join virtual registers with allocatable physical registers. 01178 if (SrcIsPhys && !allocatableRegs_[SrcReg]) { 01179 DOUT << "\tSrc reg is unallocatable physreg.\n"; 01180 return false; // Not coalescable. 01181 } 01182 if (DstIsPhys && !allocatableRegs_[DstReg]) { 01183 DOUT << "\tDst reg is unallocatable physreg.\n"; 01184 return false; // Not coalescable. 01185 } 01186 01187 // Should be non-null only when coalescing to a sub-register class. 01188 bool CrossRC = false; 01189 const TargetRegisterClass *NewRC = NULL; 01190 MachineBasicBlock *CopyMBB = CopyMI->getParent(); 01191 unsigned RealDstReg = 0; 01192 unsigned RealSrcReg = 0; 01193 if (isExtSubReg || isInsSubReg) { 01194 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm(); 01195 if (SrcIsPhys && isExtSubReg) { 01196 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be 01197 // coalesced with AX. 01198 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg(); 01199 if (DstSubIdx) { 01200 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been 01201 // coalesced to a larger register so the subreg indices cancel out. 01202 if (DstSubIdx != SubIdx) { 01203 DOUT << "\t Sub-register indices mismatch.\n"; 01204 return false; // Not coalescable. 01205 } 01206 } else 01207 SrcReg = tri_->getSubReg(SrcReg, SubIdx); 01208 SubIdx = 0; 01209 } else if (DstIsPhys && isInsSubReg) { 01210 // EAX = INSERT_SUBREG EAX, r1024, 0 01211 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg(); 01212 if (SrcSubIdx) { 01213 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been 01214 // coalesced to a larger register so the subreg indices cancel out. 01215 if (SrcSubIdx != SubIdx) { 01216 DOUT << "\t Sub-register indices mismatch.\n"; 01217 return false; // Not coalescable. 01218 } 01219 } else 01220 DstReg = tri_->getSubReg(DstReg, SubIdx); 01221 SubIdx = 0; 01222 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) { 01223 if (CopyMI->getOperand(1).getSubReg()) { 01224 DOUT << "\tSrc of extract_subreg already coalesced with reg" 01225 << " of a super-class.\n"; 01226 return false; // Not coalescable. 01227 } 01228 01229 if (isExtSubReg) { 01230 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg)) 01231 return false; // Not coalescable 01232 } else { 01233 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg)) 01234 return false; // Not coalescable 01235 } 01236 SubIdx = 0; 01237 } else { 01238 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg() 01239 : CopyMI->getOperand(2).getSubReg(); 01240 if (OldSubIdx) { 01241 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg)) 01242 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been 01243 // coalesced to a larger register so the subreg indices cancel out. 01244 // Also check if the other larger register is of the same register 01245 // class as the would be resulting register. 01246 SubIdx = 0; 01247 else { 01248 DOUT << "\t Sub-register indices mismatch.\n"; 01249 return false; // Not coalescable. 01250 } 01251 } 01252 if (SubIdx) { 01253 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg; 01254 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg; 01255 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count(); 01256 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) { 01257 Again = true; // May be possible to coalesce later. 01258 return false; 01259 } 01260 } 01261 } 01262 } else if (differingRegisterClasses(SrcReg, DstReg)) { 01263 if (!CrossClassJoin) 01264 return false; 01265 CrossRC = true; 01266 01267 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced 01268 // with another? If it's the resulting destination register, then 01269 // the subidx must be propagated to uses (but only those defined 01270 // by the EXTRACT_SUBREG). If it's being coalesced into another 01271 // register, it should be safe because register is assumed to have 01272 // the register class of the super-register. 01273 01274 // Process moves where one of the registers have a sub-register index. 01275 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg); 01276 if (DstMO->getSubReg()) 01277 // FIXME: Can we handle this? 01278 return false; 01279 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg); 01280 SubIdx = SrcMO->getSubReg(); 01281 if (SubIdx) { 01282 // This is not a extract_subreg but it looks like one. 01283 // e.g. %cl = MOV16rr %reg1024:2 01284 isExtSubReg = true; 01285 if (DstIsPhys) { 01286 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg)) 01287 return false; // Not coalescable 01288 SubIdx = 0; 01289 } 01290 } 01291 01292 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg); 01293 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg); 01294 unsigned LargeReg = SrcReg; 01295 unsigned SmallReg = DstReg; 01296 unsigned Limit = 0; 01297 01298 // Now determine the register class of the joined register. 01299 if (isExtSubReg) { 01300 if (SubIdx && DstRC && DstRC->isASubClass()) { 01301 // This is a move to a sub-register class. However, the source is a 01302 // sub-register of a larger register class. We don't know what should 01303 // the register class be. FIXME. 01304 Again = true; 01305 return false; 01306 } 01307 Limit = allocatableRCRegs_[DstRC].count(); 01308 } else if (!SrcIsPhys && !SrcIsPhys) { 01309 unsigned SrcSize = SrcRC->getSize(); 01310 unsigned DstSize = DstRC->getSize(); 01311 if (SrcSize < DstSize) 01312 // For example X86::MOVSD2PDrr copies from FR64 to VR128. 01313 NewRC = DstRC; 01314 else if (DstSize > SrcSize) { 01315 NewRC = SrcRC; 01316 std::swap(LargeReg, SmallReg); 01317 } else { 01318 unsigned SrcNumRegs = SrcRC->getNumRegs(); 01319 unsigned DstNumRegs = DstRC->getNumRegs(); 01320 if (DstNumRegs < SrcNumRegs) 01321 // Sub-register class? 01322 NewRC = DstRC; 01323 else if (SrcNumRegs < DstNumRegs) { 01324 NewRC = SrcRC; 01325 std::swap(LargeReg, SmallReg); 01326 } else 01327 // No idea what's the right register class to use. 01328 return false; 01329 } 01330 } 01331 01332 // If we are joining two virtual registers and the resulting register 01333 // class is more restrictive (fewer register, smaller size). Check if it's 01334 // worth doing the merge. 01335 if (!SrcIsPhys && !DstIsPhys && 01336 (isExtSubReg || DstRC->isASubClass()) && 01337 !isWinToJoinCrossClass(LargeReg, SmallReg, 01338 allocatableRCRegs_[NewRC].count())) { 01339 DOUT << "\tSrc/Dest are different register classes.\n"; 01340 // Allow the coalescer to try again in case either side gets coalesced to 01341 // a physical register that's compatible with the other side. e.g. 01342 // r1024 = MOV32to32_ r1025 01343 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX. 01344 Again = true; // May be possible to coalesce later. 01345 return false; 01346 } 01347 } 01348 01349 // Will it create illegal extract_subreg / insert_subreg? 01350 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg)) 01351 return false; 01352 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg)) 01353 return false; 01354 01355 LiveInterval &SrcInt = li_->getInterval(SrcReg); 01356 LiveInterval &DstInt = li_->getInterval(DstReg); 01357 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg && 01358 "Register mapping is horribly broken!"); 01359 01360 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_); 01361 DOUT << " and "; DstInt.print(DOUT, tri_); 01362 DOUT << ": "; 01363 01364 // Save a copy of the virtual register live interval. We'll manually 01365 // merge this into the "real" physical register live interval this is 01366 // coalesced with. 01367 LiveInterval *SavedLI = 0; 01368 if (RealDstReg) 01369 SavedLI = li_->dupInterval(&SrcInt); 01370 else if (RealSrcReg) 01371 SavedLI = li_->dupInterval(&DstInt); 01372 01373 // Check if it is necessary to propagate "isDead" property. 01374 if (!isExtSubReg && !isInsSubReg) { 01375 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false); 01376 bool isDead = mopd->isDead(); 01377 01378 // We need to be careful about coalescing a source physical register with a 01379 // virtual register. Once the coalescing is done, it cannot be broken and 01380 // these are not spillable! If the destination interval uses are far away, 01381 // think twice about coalescing them! 01382 if (!isDead && (SrcIsPhys || DstIsPhys)) { 01383 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt; 01384 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg; 01385 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg; 01386 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg); 01387 unsigned Threshold = allocatableRCRegs_[RC].count() * 2; 01388 if (TheCopy.isBackEdge) 01389 Threshold *= 2; // Favors back edge copies. 01390 01391 // If the virtual register live interval is long but it has low use desity, 01392 // do not join them, instead mark the physical register as its allocation 01393 // preference. 01394 unsigned Length = li_->getApproximateInstructionCount(JoinVInt); 01395 if (Length > Threshold && 01396 (((float)std::distance(mri_->use_begin(JoinVReg), mri_->use_end()) 01397 / Length) < (1.0 / Threshold))) { 01398 JoinVInt.preference = JoinPReg; 01399 ++numAborts; 01400 DOUT << "\tMay tie down a physical register, abort!\n"; 01401 Again = true; // May be possible to coalesce later. 01402 return false; 01403 } 01404 } 01405 } 01406 01407 // Okay, attempt to join these two intervals. On failure, this returns false. 01408 // Otherwise, if one of the intervals being joined is a physreg, this method 01409 // always canonicalizes DstInt to be it. The output "SrcInt" will not have 01410 // been modified, so we can use this information below to update aliases. 01411 bool Swapped = false; 01412 // If SrcInt is implicitly defined, it's safe to coalesce. 01413 bool isEmpty = SrcInt.empty(); 01414 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) { 01415 // Only coalesce an empty interval (defined by implicit_def) with 01416 // another interval which has a valno defined by the CopyMI and the CopyMI 01417 // is a kill of the implicit def. 01418 DOUT << "Not profitable!\n"; 01419 return false; 01420 } 01421 01422 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) { 01423 // Coalescing failed. 01424 01425 // If definition of source is defined by trivial computation, try 01426 // rematerializing it. 01427 if (!isExtSubReg && !isInsSubReg && 01428 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI)) 01429 return true; 01430 01431 // If we can eliminate the copy without merging the live ranges, do so now. 01432 if (!isExtSubReg && !isInsSubReg && 01433 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) || 01434 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) { 01435 JoinedCopies.insert(CopyMI); 01436 return true; 01437 } 01438 01439 // Otherwise, we are unable to join the intervals. 01440 DOUT << "Interference!\n"; 01441 Again = true; // May be possible to coalesce later. 01442 return false; 01443 } 01444 01445 LiveInterval *ResSrcInt = &SrcInt; 01446 LiveInterval *ResDstInt = &DstInt; 01447 if (Swapped) { 01448 std::swap(SrcReg, DstReg); 01449 std::swap(ResSrcInt, ResDstInt); 01450 } 01451 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) && 01452 "LiveInterval::join didn't work right!"); 01453 01454 // If we're about to merge live ranges into a physical register live interval, 01455 // we have to update any aliased register's live ranges to indicate that they 01456 // have clobbered values for this range. 01457 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { 01458 // If this is a extract_subreg where dst is a physical register, e.g. 01459 // cl = EXTRACT_SUBREG reg1024, 1 01460 // then create and update the actual physical register allocated to RHS. 01461 if (RealDstReg || RealSrcReg) { 01462 LiveInterval &RealInt = 01463 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg); 01464 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(), 01465 E = SavedLI->vni_end(); I != E; ++I) { 01466 const VNInfo *ValNo = *I; 01467 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->copy, 01468 li_->getVNInfoAllocator()); 01469 NewValNo->hasPHIKill = ValNo->hasPHIKill; 01470 NewValNo->redefByEC = ValNo->redefByEC; 01471 RealInt.addKills(NewValNo, ValNo->kills); 01472 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo); 01473 } 01474 RealInt.weight += SavedLI->weight; 01475 DstReg = RealDstReg ? RealDstReg : RealSrcReg; 01476 } 01477 01478 // Update the liveintervals of sub-registers. 01479 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS) 01480 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt, 01481 li_->getVNInfoAllocator()); 01482 } 01483 01484 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the 01485 // larger super-register. 01486 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) { 01487 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) { 01488 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator()); 01489 std::swap(SrcReg, DstReg); 01490 std::swap(ResSrcInt, ResDstInt); 01491 } 01492 } 01493 01494 // Coalescing to a virtual register that is of a sub-register class of the 01495 // other. Make sure the resulting register is set to the right register class. 01496 if (CrossRC) { 01497 ++numCrossRCs; 01498 if (NewRC) 01499 mri_->setRegClass(DstReg, NewRC); 01500 } 01501 01502 if (NewHeuristic) { 01503 // Add all copies that define val# in the source interval into the queue. 01504 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(), 01505 e = ResSrcInt->vni_end(); i != e; ++i) { 01506 const VNInfo *vni = *i; 01507 if (!vni->def || vni->def == ~1U || vni->def == ~0U) 01508 continue; 01509 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def); 01510 unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx; 01511 if (CopyMI && 01512 JoinedCopies.count(CopyMI) == 0 && 01513 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg, 01514 NewSrcSubIdx, NewDstSubIdx)) { 01515 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB); 01516 JoinQueue->push(CopyRec(CopyMI, LoopDepth, 01517 isBackEdgeCopy(CopyMI, DstReg))); 01518 } 01519 } 01520 } 01521 01522 // Remember to delete the copy instruction. 01523 JoinedCopies.insert(CopyMI); 01524 01525 // Some live range has been lengthened due to colaescing, eliminate the 01526 // unnecessary kills. 01527 RemoveUnnecessaryKills(SrcReg, *ResDstInt); 01528 if (TargetRegisterInfo::isVirtualRegister(DstReg)) 01529 RemoveUnnecessaryKills(DstReg, *ResDstInt); 01530 01531 if (isInsSubReg) 01532 // Avoid: 01533 // r1024 = op 01534 // r1024 = implicit_def 01535 // ... 01536 // = r1024 01537 RemoveDeadImpDef(DstReg, *ResDstInt); 01538 UpdateRegDefsUses(SrcReg, DstReg, SubIdx); 01539 01540 // SrcReg is guarateed to be the register whose live interval that is 01541 // being merged. 01542 li_->removeInterval(SrcReg); 01543 01544 // Manually deleted the live interval copy. 01545 if (SavedLI) { 01546 SavedLI->clear(); 01547 delete SavedLI; 01548 } 01549 01550 if (isEmpty) { 01551 // Now the copy is being coalesced away, the val# previously defined 01552 // by the copy is being defined by an IMPLICIT_DEF which defines a zero 01553 // length interval. Remove the val#. 01554 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI)); 01555 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx); 01556 VNInfo *ImpVal = LR->valno; 01557 assert(ImpVal->def == CopyIdx); 01558 unsigned NextDef = LR->end; 01559 RemoveCopiesFromValNo(*ResDstInt, ImpVal); 01560 ResDstInt->removeValNo(ImpVal); 01561 LR = ResDstInt->FindLiveRangeContaining(NextDef); 01562 if (LR != ResDstInt->end() && LR->valno->def == NextDef) { 01563 // Special case: vr1024 = implicit_def 01564 // vr1024 = insert_subreg vr1024, vr1025, c 01565 // The insert_subreg becomes a "copy" that defines a val# which can itself 01566 // be coalesced away. 01567 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef); 01568 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) 01569 LR->valno->copy = DefMI; 01570 } 01571 } 01572 01573 // If resulting interval has a preference that no longer fits because of subreg 01574 // coalescing, just clear the preference. 01575 if (ResDstInt->preference && (isExtSubReg || isInsSubReg) && 01576 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) { 01577 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg); 01578 if (!RC->contains(ResDstInt->preference)) 01579 ResDstInt->preference = 0; 01580 } 01581 01582 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_); 01583 DOUT << "\n"; 01584 01585 ++numJoins; 01586 return true; 01587 } 01588 01589 /// ComputeUltimateVN - Assuming we are going to join two live intervals, 01590 /// compute what the resultant value numbers for each value in the input two 01591 /// ranges will be. This is complicated by copies between the two which can 01592 /// and will commonly cause multiple value numbers to be merged into one. 01593 /// 01594 /// VN is the value number that we're trying to resolve. InstDefiningValue 01595 /// keeps track of the new InstDefiningValue assignment for the result 01596 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of 01597 /// whether a value in this or other is a copy from the opposite set. 01598 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have 01599 /// already been assigned. 01600 /// 01601 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this 01602 /// contains the value number the copy is from. 01603 /// 01604 static unsigned ComputeUltimateVN(VNInfo *VNI, 01605 SmallVector<VNInfo*, 16> &NewVNInfo, 01606 DenseMap<VNInfo*, VNInfo*> &ThisFromOther, 01607 DenseMap<VNInfo*, VNInfo*> &OtherFromThis, 01608 SmallVector<int, 16> &ThisValNoAssignments, 01609 SmallVector<int, 16> &OtherValNoAssignments) { 01610 unsigned VN = VNI->id; 01611 01612 // If the VN has already been computed, just return it. 01613 if (ThisValNoAssignments[VN] >= 0) 01614 return ThisValNoAssignments[VN]; 01615 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?"); 01616 01617 // If this val is not a copy from the other val, then it must be a new value 01618 // number in the destination. 01619 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI); 01620 if (I == ThisFromOther.end()) { 01621 NewVNInfo.push_back(VNI); 01622 return ThisValNoAssignments[VN] = NewVNInfo.size()-1; 01623 } 01624 VNInfo *OtherValNo = I->second; 01625 01626 // Otherwise, this *is* a copy from the RHS. If the other side has already 01627 // been computed, return it. 01628 if (OtherValNoAssignments[OtherValNo->id] >= 0) 01629 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id]; 01630 01631 // Mark this value number as currently being computed, then ask what the 01632 // ultimate value # of the other value is. 01633 ThisValNoAssignments[VN] = -2; 01634 unsigned UltimateVN = 01635 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther, 01636 OtherValNoAssignments, ThisValNoAssignments); 01637 return ThisValNoAssignments[VN] = UltimateVN; 01638 } 01639 01640 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) { 01641 return std::find(V.begin(), V.end(), Val) != V.end(); 01642 } 01643 01644 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of 01645 /// the specified live interval is defined by a copy from the specified 01646 /// register. 01647 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li, 01648 LiveRange *LR, 01649 unsigned Reg) { 01650 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno); 01651 if (SrcReg == Reg) 01652 return true; 01653 if (LR->valno->def == ~0U && 01654 TargetRegisterInfo::isPhysicalRegister(li.reg) && 01655 *tri_->getSuperRegisters(li.reg)) { 01656 // It's a sub-register live interval, we may not have precise information. 01657 // Re-compute it. 01658 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start); 01659 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 01660 if (DefMI && 01661 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) && 01662 DstReg == li.reg && SrcReg == Reg) { 01663 // Cache computed info. 01664 LR->valno->def = LR->start; 01665 LR->valno->copy = DefMI; 01666 return true; 01667 } 01668 } 01669 return false; 01670 } 01671 01672 /// SimpleJoin - Attempt to joint the specified interval into this one. The 01673 /// caller of this method must guarantee that the RHS only contains a single 01674 /// value number and that the RHS is not defined by a copy from this 01675 /// interval. This returns false if the intervals are not joinable, or it 01676 /// joins them and returns true. 01677 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ 01678 assert(RHS.containsOneValue()); 01679 01680 // Some number (potentially more than one) value numbers in the current 01681 // interval may be defined as copies from the RHS. Scan the overlapping 01682 // portions of the LHS and RHS, keeping track of this and looking for 01683 // overlapping live ranges that are NOT defined as copies. If these exist, we 01684 // cannot coalesce. 01685 01686 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end(); 01687 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end(); 01688 01689 if (LHSIt->start < RHSIt->start) { 01690 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start); 01691 if (LHSIt != LHS.begin()) --LHSIt; 01692 } else if (RHSIt->start < LHSIt->start) { 01693 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start); 01694 if (RHSIt != RHS.begin()) --RHSIt; 01695 } 01696 01697 SmallVector<VNInfo*, 8> EliminatedLHSVals; 01698 01699 while (1) { 01700 // Determine if these live intervals overlap. 01701 bool Overlaps = false; 01702 if (LHSIt->start <= RHSIt->start) 01703 Overlaps = LHSIt->end > RHSIt->start; 01704 else 01705 Overlaps = RHSIt->end > LHSIt->start; 01706 01707 // If the live intervals overlap, there are two interesting cases: if the 01708 // LHS interval is defined by a copy from the RHS, it's ok and we record 01709 // that the LHS value # is the same as the RHS. If it's not, then we cannot 01710 // coalesce these live ranges and we bail out. 01711 if (Overlaps) { 01712 // If we haven't already recorded that this value # is safe, check it. 01713 if (!InVector(LHSIt->valno, EliminatedLHSVals)) { 01714 // Copy from the RHS? 01715 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) 01716 return false; // Nope, bail out. 01717 01718 if (LHSIt->contains(RHSIt->valno->def)) 01719 // Here is an interesting situation: 01720 // BB1: 01721 // vr1025 = copy vr1024 01722 // .. 01723 // BB2: 01724 // vr1024 = op 01725 // = vr1025 01726 // Even though vr1025 is copied from vr1024, it's not safe to 01727 // coalesced them since live range of vr1025 intersects the 01728 // def of vr1024. This happens because vr1025 is assigned the 01729 // value of the previous iteration of vr1024. 01730 return false; 01731 EliminatedLHSVals.push_back(LHSIt->valno); 01732 } 01733 01734 // We know this entire LHS live range is okay, so skip it now. 01735 if (++LHSIt == LHSEnd) break; 01736 continue; 01737 } 01738 01739 if (LHSIt->end < RHSIt->end) { 01740 if (++LHSIt == LHSEnd) break; 01741 } else { 01742 // One interesting case to check here. It's possible that we have 01743 // something like "X3 = Y" which defines a new value number in the LHS, 01744 // and is the last use of this liverange of the RHS. In this case, we 01745 // want to notice this copy (so that it gets coalesced away) even though 01746 // the live ranges don't actually overlap. 01747 if (LHSIt->start == RHSIt->end) { 01748 if (InVector(LHSIt->valno, EliminatedLHSVals)) { 01749 // We already know that this value number is going to be merged in 01750 // if coalescing succeeds. Just skip the liverange. 01751 if (++LHSIt == LHSEnd) break; 01752 } else { 01753 // Otherwise, if this is a copy from the RHS, mark it as being merged 01754 // in. 01755 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) { 01756 if (LHSIt->contains(RHSIt->valno->def)) 01757 // Here is an interesting situation: 01758 // BB1: 01759 // vr1025 = copy vr1024 01760 // .. 01761 // BB2: 01762 // vr1024 = op 01763 // = vr1025 01764 // Even though vr1025 is copied from vr1024, it's not safe to 01765 // coalesced them since live range of vr1025 intersects the 01766 // def of vr1024. This happens because vr1025 is assigned the 01767 // value of the previous iteration of vr1024. 01768 return false; 01769 EliminatedLHSVals.push_back(LHSIt->valno); 01770 01771 // We know this entire LHS live range is okay, so skip it now. 01772 if (++LHSIt == LHSEnd) break; 01773 } 01774 } 01775 } 01776 01777 if (++RHSIt == RHSEnd) break; 01778 } 01779 } 01780 01781 // If we got here, we know that the coalescing will be successful and that 01782 // the value numbers in EliminatedLHSVals will all be merged together. Since 01783 // the most common case is that EliminatedLHSVals has a single number, we 01784 // optimize for it: if there is more than one value, we merge them all into 01785 // the lowest numbered one, then handle the interval as if we were merging 01786 // with one value number. 01787 VNInfo *LHSValNo = NULL; 01788 if (EliminatedLHSVals.size() > 1) { 01789 // Loop through all the equal value numbers merging them into the smallest 01790 // one. 01791 VNInfo *Smallest = EliminatedLHSVals[0]; 01792 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) { 01793 if (EliminatedLHSVals[i]->id < Smallest->id) { 01794 // Merge the current notion of the smallest into the smaller one. 01795 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]); 01796 Smallest = EliminatedLHSVals[i]; 01797 } else { 01798 // Merge into the smallest. 01799 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest); 01800 } 01801 } 01802 LHSValNo = Smallest; 01803 } else if (EliminatedLHSVals.empty()) { 01804 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) && 01805 *tri_->getSuperRegisters(LHS.reg)) 01806 // Imprecise sub-register information. Can't handle it. 01807 return false; 01808 assert(0 && "No copies from the RHS?"); 01809 } else { 01810 LHSValNo = EliminatedLHSVals[0]; 01811 } 01812 01813 // Okay, now that there is a single LHS value number that we're merging the 01814 // RHS into, update the value number info for the LHS to indicate that the 01815 // value number is defined where the RHS value number was. 01816 const VNInfo *VNI = RHS.getValNumInfo(0); 01817 LHSValNo->def = VNI->def; 01818 LHSValNo->copy = VNI->copy; 01819 01820 // Okay, the final step is to loop over the RHS live intervals, adding them to 01821 // the LHS. 01822 LHSValNo->hasPHIKill |= VNI->hasPHIKill; 01823 LHS.addKills(LHSValNo, VNI->kills); 01824 LHS.MergeRangesInAsValue(RHS, LHSValNo); 01825 LHS.weight += RHS.weight; 01826 if (RHS.preference && !LHS.preference) 01827 LHS.preference = RHS.preference; 01828 01829 return true; 01830 } 01831 01832 /// JoinIntervals - Attempt to join these two intervals. On failure, this 01833 /// returns false. Otherwise, if one of the intervals being joined is a 01834 /// physreg, this method always canonicalizes LHS to be it. The output 01835 /// "RHS" will not have been modified, so we can use this information 01836 /// below to update aliases. 01837 bool 01838 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, 01839 bool &Swapped) { 01840 // Compute the final value assignment, assuming that the live ranges can be 01841 // coalesced. 01842 SmallVector<int, 16> LHSValNoAssignments; 01843 SmallVector<int, 16> RHSValNoAssignments; 01844 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS; 01845 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS; 01846 SmallVector<VNInfo*, 16> NewVNInfo; 01847 01848 // If a live interval is a physical register, conservatively check if any 01849 // of its sub-registers is overlapping the live interval of the virtual 01850 // register. If so, do not coalesce. 01851 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) && 01852 *tri_->getSubRegisters(LHS.reg)) { 01853 // If it's coalescing a virtual register to a physical register, estimate 01854 // its live interval length. This is the *cost* of scanning an entire live 01855 // interval. If the cost is low, we'll do an exhaustive check instead. 01856 01857 // If this is something like this: 01858 // BB1: 01859 // v1024 = op 01860 // ... 01861 // BB2: 01862 // ... 01863 // RAX = v1024 01864 // 01865 // That is, the live interval of v1024 crosses a bb. Then we can't rely on 01866 // less conservative check. It's possible a sub-register is defined before 01867 // v1024 (or live in) and live out of BB1. 01868 if (RHS.containsOneValue() && 01869 li_->intervalIsInOneMBB(RHS) && 01870 li_->getApproximateInstructionCount(RHS) <= 10) { 01871 // Perform a more exhaustive check for some common cases. 01872 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies)) 01873 return false; 01874 } else { 01875 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR) 01876 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) { 01877 DOUT << "Interfere with sub-register "; 01878 DEBUG(li_->getInterval(*SR).print(DOUT, tri_)); 01879 return false; 01880 } 01881 } 01882 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) && 01883 *tri_->getSubRegisters(RHS.reg)) { 01884 if (LHS.containsOneValue() && 01885 li_->getApproximateInstructionCount(LHS) <= 10) { 01886 // Perform a more exhaustive check for some common cases. 01887 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies)) 01888 return false; 01889 } else { 01890 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR) 01891 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) { 01892 DOUT << "Interfere with sub-register "; 01893 DEBUG(li_->getInterval(*SR).print(DOUT, tri_)); 01894 return false; 01895 } 01896 } 01897 } 01898 01899 // Compute ultimate value numbers for the LHS and RHS values. 01900 if (RHS.containsOneValue()) { 01901 // Copies from a liveinterval with a single value are simple to handle and 01902 // very common, handle the special case here. This is important, because 01903 // often RHS is small and LHS is large (e.g. a physreg). 01904 01905 // Find out if the RHS is defined as a copy from some value in the LHS. 01906 int RHSVal0DefinedFromLHS = -1; 01907 int RHSValID = -1; 01908 VNInfo *RHSValNoInfo = NULL; 01909 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0); 01910 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0); 01911 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) { 01912 // If RHS is not defined as a copy from the LHS, we can use simpler and 01913 // faster checks to see if the live ranges are coalescable. This joiner 01914 // can't swap the LHS/RHS intervals though. 01915 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) { 01916 return SimpleJoin(LHS, RHS); 01917 } else { 01918 RHSValNoInfo = RHSValNoInfo0; 01919 } 01920 } else { 01921 // It was defined as a copy from the LHS, find out what value # it is. 01922 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno; 01923 RHSValID = RHSValNoInfo->id; 01924 RHSVal0DefinedFromLHS = RHSValID; 01925 } 01926 01927 LHSValNoAssignments.resize(LHS.getNumValNums(), -1); 01928 RHSValNoAssignments.resize(RHS.getNumValNums(), -1); 01929 NewVNInfo.resize(LHS.getNumValNums(), NULL); 01930 01931 // Okay, *all* of the values in LHS that are defined as a copy from RHS 01932 // should now get updated. 01933 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end(); 01934 i != e; ++i) { 01935 VNInfo *VNI = *i; 01936 unsigned VN = VNI->id; 01937 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) { 01938 if (LHSSrcReg != RHS.reg) { 01939 // If this is not a copy from the RHS, its value number will be 01940 // unmodified by the coalescing. 01941 NewVNInfo[VN] = VNI; 01942 LHSValNoAssignments[VN] = VN; 01943 } else if (RHSValID == -1) { 01944 // Otherwise, it is a copy from the RHS, and we don't already have a 01945 // value# for it. Keep the current value number, but remember it. 01946 LHSValNoAssignments[VN] = RHSValID = VN; 01947 NewVNInfo[VN] = RHSValNoInfo; 01948 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0; 01949 } else { 01950 // Otherwise, use the specified value #. 01951 LHSValNoAssignments[VN] = RHSValID; 01952 if (VN == (unsigned)RHSValID) { // Else this val# is dead. 01953 NewVNInfo[VN] = RHSValNoInfo; 01954 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0; 01955 } 01956 } 01957 } else { 01958 NewVNInfo[VN] = VNI; 01959 LHSValNoAssignments[VN] = VN; 01960 } 01961 } 01962 01963 assert(RHSValID != -1 && "Didn't find value #?"); 01964 RHSValNoAssignments[0] = RHSValID; 01965 if (RHSVal0DefinedFromLHS != -1) { 01966 // This path doesn't go through ComputeUltimateVN so just set 01967 // it to anything. 01968 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1; 01969 } 01970 } else { 01971 // Loop over the value numbers of the LHS, seeing if any are defined from 01972 // the RHS. 01973 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end(); 01974 i != e; ++i) { 01975 VNInfo *VNI = *i; 01976 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy? 01977 continue; 01978 01979 // DstReg is known to be a register in the LHS interval. If the src is 01980 // from the RHS interval, we can use its value #. 01981 if (li_->getVNInfoSourceReg(VNI) != RHS.reg) 01982 continue; 01983 01984 // Figure out the value # from the RHS. 01985 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno; 01986 } 01987 01988 // Loop over the value numbers of the RHS, seeing if any are defined from 01989 // the LHS. 01990 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end(); 01991 i != e; ++i) { 01992 VNInfo *VNI = *i; 01993 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy? 01994 continue; 01995 01996 // DstReg is known to be a register in the RHS interval. If the src is 01997 // from the LHS interval, we can use its value #. 01998 if (li_->getVNInfoSourceReg(VNI) != LHS.reg) 01999 continue; 02000 02001 // Figure out the value # from the LHS. 02002 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno; 02003 } 02004 02005 LHSValNoAssignments.resize(LHS.getNumValNums(), -1); 02006 RHSValNoAssignments.resize(RHS.getNumValNums(), -1); 02007 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums()); 02008 02009 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end(); 02010 i != e; ++i) { 02011 VNInfo *VNI = *i; 02012 unsigned VN = VNI->id; 02013 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 02014 continue; 02015 ComputeUltimateVN(VNI, NewVNInfo, 02016 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS, 02017 LHSValNoAssignments, RHSValNoAssignments); 02018 } 02019 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end(); 02020 i != e; ++i) { 02021 VNInfo *VNI = *i; 02022 unsigned VN = VNI->id; 02023 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 02024 continue; 02025 // If this value number isn't a copy from the LHS, it's a new number. 02026 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) { 02027 NewVNInfo.push_back(VNI); 02028 RHSValNoAssignments[VN] = NewVNInfo.size()-1; 02029 continue; 02030 } 02031 02032 ComputeUltimateVN(VNI, NewVNInfo, 02033 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS, 02034 RHSValNoAssignments, LHSValNoAssignments); 02035 } 02036 } 02037 02038 // Armed with the mappings of LHS/RHS values to ultimate values, walk the 02039 // interval lists to see if these intervals are coalescable. 02040 LiveInterval::const_iterator I = LHS.begin(); 02041 LiveInterval::const_iterator IE = LHS.end(); 02042 LiveInterval::const_iterator J = RHS.begin(); 02043 LiveInterval::const_iterator JE = RHS.end(); 02044 02045 // Skip ahead until the first place of potential sharing. 02046 if (I->start < J->start) { 02047 I = std::upper_bound(I, IE, J->start); 02048 if (I != LHS.begin()) --I; 02049 } else if (J->start < I->start) { 02050 J = std::upper_bound(J, JE, I->start); 02051 if (J != RHS.begin()) --J; 02052 } 02053 02054 while (1) { 02055 // Determine if these two live ranges overlap. 02056 bool Overlaps; 02057 if (I->start < J->start) { 02058 Overlaps = I->end > J->start; 02059 } else { 02060 Overlaps = J->end > I->start; 02061 } 02062 02063 // If so, check value # info to determine if they are really different. 02064 if (Overlaps) { 02065 // If the live range overlap will map to the same value number in the 02066 // result liverange, we can still coalesce them. If not, we can't. 02067 if (LHSValNoAssignments[I->valno->id] != 02068 RHSValNoAssignments[J->valno->id]) 02069 return false; 02070 } 02071 02072 if (I->end < J->end) { 02073 ++I; 02074 if (I == IE) break; 02075 } else { 02076 ++J; 02077 if (J == JE) break; 02078 } 02079 } 02080 02081 // Update kill info. Some live ranges are extended due to copy coalescing. 02082 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(), 02083 E = LHSValsDefinedFromRHS.end(); I != E; ++I) { 02084 VNInfo *VNI = I->first; 02085 unsigned LHSValID = LHSValNoAssignments[VNI->id]; 02086 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def); 02087 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill; 02088 RHS.addKills(NewVNInfo[LHSValID], VNI->kills); 02089 } 02090 02091 // Update kill info. Some live ranges are extended due to copy coalescing. 02092 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(), 02093 E = RHSValsDefinedFromLHS.end(); I != E; ++I) { 02094 VNInfo *VNI = I->first; 02095 unsigned RHSValID = RHSValNoAssignments[VNI->id]; 02096 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def); 02097 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill; 02098 LHS.addKills(NewVNInfo[RHSValID], VNI->kills); 02099 } 02100 02101 // If we get here, we know that we can coalesce the live ranges. Ask the 02102 // intervals to coalesce themselves now. 02103 if ((RHS.ranges.size() > LHS.ranges.size() && 02104 TargetRegisterInfo::isVirtualRegister(LHS.reg)) || 02105 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) { 02106 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo); 02107 Swapped = true; 02108 } else { 02109 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo); 02110 Swapped = false; 02111 } 02112 return true; 02113 } 02114 02115 namespace { 02116 // DepthMBBCompare - Comparison predicate that sort first based on the loop 02117 // depth of the basic block (the unsigned), and then on the MBB number. 02118 struct DepthMBBCompare { 02119 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair; 02120 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const { 02121 if (LHS.first > RHS.first) return true; // Deeper loops first 02122 return LHS.first == RHS.first && 02123 LHS.second->getNumber() < RHS.second->getNumber(); 02124 } 02125 }; 02126 } 02127 02128 /// getRepIntervalSize - Returns the size of the interval that represents the 02129 /// specified register. 02130 template<class SF> 02131 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) { 02132 return Rc->getRepIntervalSize(Reg); 02133 } 02134 02135 /// CopyRecSort::operator - Join priority queue sorting function. 02136 /// 02137 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const { 02138 // Inner loops first. 02139 if (left.LoopDepth > right.LoopDepth) 02140 return false; 02141 else if (left.LoopDepth == right.LoopDepth) 02142 if (left.isBackEdge && !right.isBackEdge) 02143 return false; 02144 return true; 02145 } 02146 02147 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB, 02148 std::vector<CopyRec> &TryAgain) { 02149 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n"; 02150 02151 std::vector<CopyRec> VirtCopies; 02152 std::vector<CopyRec> PhysCopies; 02153 std::vector<CopyRec> ImpDefCopies; 02154 unsigned LoopDepth = loopInfo->getLoopDepth(MBB); 02155 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); 02156 MII != E;) { 02157 MachineInstr *Inst = MII++; 02158 02159 // If this isn't a copy nor a extract_subreg, we can't join intervals. 02160 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 02161 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) { 02162 DstReg = Inst->getOperand(0).getReg(); 02163 SrcReg = Inst->getOperand(1).getReg(); 02164 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) { 02165 DstReg = Inst->getOperand(0).getReg(); 02166 SrcReg = Inst->getOperand(2).getReg(); 02167 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) 02168 continue; 02169 02170 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg); 02171 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 02172 if (NewHeuristic) { 02173 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg))); 02174 } else { 02175 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()) 02176 ImpDefCopies.push_back(CopyRec(Inst, 0, false)); 02177 else if (SrcIsPhys || DstIsPhys) 02178 PhysCopies.push_back(CopyRec(Inst, 0, false)); 02179 else 02180 VirtCopies.push_back(CopyRec(Inst, 0, false)); 02181 } 02182 } 02183 02184 if (NewHeuristic) 02185 return; 02186 02187 // Try coalescing implicit copies first, followed by copies to / from 02188 // physical registers, then finally copies from virtual registers to 02189 // virtual registers. 02190 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) { 02191 CopyRec &TheCopy = ImpDefCopies[i]; 02192 bool Again = false; 02193 if (!JoinCopy(TheCopy, Again)) 02194 if (Again) 02195 TryAgain.push_back(TheCopy); 02196 } 02197 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) { 02198 CopyRec &TheCopy = PhysCopies[i]; 02199 bool Again = false; 02200 if (!JoinCopy(TheCopy, Again)) 02201 if (Again) 02202 TryAgain.push_back(TheCopy); 02203 } 02204 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) { 02205 CopyRec &TheCopy = VirtCopies[i]; 02206 bool Again = false; 02207 if (!JoinCopy(TheCopy, Again)) 02208 if (Again) 02209 TryAgain.push_back(TheCopy); 02210 } 02211 } 02212 02213 void SimpleRegisterCoalescing::joinIntervals() { 02214 DOUT << "********** JOINING INTERVALS ***********\n"; 02215 02216 if (NewHeuristic) 02217 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this); 02218 02219 std::vector<CopyRec> TryAgainList; 02220 if (loopInfo->empty()) { 02221 // If there are no loops in the function, join intervals in function order. 02222 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); 02223 I != E; ++I) 02224 CopyCoalesceInMBB(I, TryAgainList); 02225 } else { 02226 // Otherwise, join intervals in inner loops before other intervals. 02227 // Unfortunately we can't just iterate over loop hierarchy here because 02228 // there may be more MBB's than BB's. Collect MBB's for sorting. 02229 02230 // Join intervals in the function prolog first. We want to join physical 02231 // registers with virtual registers before the intervals got too long. 02232 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs; 02233 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){ 02234 MachineBasicBlock *MBB = I; 02235 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I)); 02236 } 02237 02238 // Sort by loop depth. 02239 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare()); 02240 02241 // Finally, join intervals in loop nest order. 02242 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) 02243 CopyCoalesceInMBB(MBBs[i].second, TryAgainList); 02244 } 02245 02246 // Joining intervals can allow other intervals to be joined. Iteratively join 02247 // until we make no progress. 02248 if (NewHeuristic) { 02249 SmallVector<CopyRec, 16> TryAgain; 02250 bool ProgressMade = true; 02251 while (ProgressMade) { 02252 ProgressMade = false; 02253 while (!JoinQueue->empty()) { 02254 CopyRec R = JoinQueue->pop(); 02255 bool Again = false; 02256 bool Success = JoinCopy(R, Again); 02257 if (Success) 02258 ProgressMade = true; 02259 else if (Again) 02260 TryAgain.push_back(R); 02261 } 02262 02263 if (ProgressMade) { 02264 while (!TryAgain.empty()) { 02265 JoinQueue->push(TryAgain.back()); 02266 TryAgain.pop_back(); 02267 } 02268 } 02269 } 02270 } else { 02271 bool ProgressMade = true; 02272 while (ProgressMade) { 02273 ProgressMade = false; 02274 02275 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) { 02276 CopyRec &TheCopy = TryAgainList[i]; 02277 if (TheCopy.MI) { 02278 bool Again = false; 02279 bool Success = JoinCopy(TheCopy, Again); 02280 if (Success || !Again) { 02281 TheCopy.MI = 0; // Mark this one as done. 02282 ProgressMade = true; 02283 } 02284 } 02285 } 02286 } 02287 } 02288 02289 if (NewHeuristic) 02290 delete JoinQueue; 02291 } 02292 02293 /// Return true if the two specified registers belong to different register 02294 /// classes. The registers may be either phys or virt regs. 02295 bool 02296 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, 02297 unsigned RegB) const { 02298 // Get the register classes for the first reg. 02299 if (TargetRegisterInfo::isPhysicalRegister(RegA)) { 02300 assert(TargetRegisterInfo::isVirtualRegister(RegB) && 02301 "Shouldn't consider two physregs!"); 02302 return !mri_->getRegClass(RegB)->contains(RegA); 02303 } 02304 02305 // Compare against the regclass for the second reg. 02306 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA); 02307 if (TargetRegisterInfo::isVirtualRegister(RegB)) { 02308 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB); 02309 return RegClassA != RegClassB; 02310 } 02311 return !RegClassA->contains(RegB); 02312 } 02313 02314 /// lastRegisterUse - Returns the last use of the specific register between 02315 /// cycles Start and End or NULL if there are no uses. 02316 MachineOperand * 02317 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, 02318 unsigned Reg, unsigned &UseIdx) const{ 02319 UseIdx = 0; 02320 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 02321 MachineOperand *LastUse = NULL; 02322 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg), 02323 E = mri_->use_end(); I != E; ++I) { 02324 MachineOperand &Use = I.getOperand(); 02325 MachineInstr *UseMI = Use.getParent(); 02326 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 02327 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) && 02328 SrcReg == DstReg) 02329 // Ignore identity copies. 02330 continue; 02331 unsigned Idx = li_->getInstructionIndex(UseMI); 02332 if (Idx >= Start && Idx < End && Idx >= UseIdx) { 02333 LastUse = &Use; 02334 UseIdx = Idx; 02335 } 02336 } 02337 return LastUse; 02338 } 02339 02340 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM; 02341 int s = Start; 02342 while (e >= s) { 02343 // Skip deleted instructions 02344 MachineInstr *MI = li_->getInstructionFromIndex(e); 02345 while ((e - InstrSlots::NUM) >= s && !MI) { 02346 e -= InstrSlots::NUM; 02347 MI = li_->getInstructionFromIndex(e); 02348 } 02349 if (e < s || MI == NULL) 02350 return NULL; 02351 02352 // Ignore identity copies. 02353 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 02354 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) && 02355 SrcReg == DstReg)) 02356 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) { 02357 MachineOperand &Use = MI->getOperand(i); 02358 if (Use.isReg() && Use.isUse() && Use.getReg() && 02359 tri_->regsOverlap(Use.getReg(), Reg)) { 02360 UseIdx = e; 02361 return &Use; 02362 } 02363 } 02364 02365 e -= InstrSlots::NUM; 02366 } 02367 02368 return NULL; 02369 } 02370 02371 02372 void SimpleRegisterCoalescing::printRegName(unsigned reg) const { 02373 if (TargetRegisterInfo::isPhysicalRegister(reg)) 02374 cerr << tri_->getName(reg); 02375 else 02376 cerr << "%reg" << reg; 02377 } 02378 02379 void SimpleRegisterCoalescing::releaseMemory() { 02380 JoinedCopies.clear(); 02381 ReMatCopies.clear(); 02382 ReMatDefs.clear(); 02383 } 02384 02385 static bool isZeroLengthInterval(LiveInterval *li) { 02386 for (LiveInterval::Ranges::const_iterator 02387 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i) 02388 if (i->end - i->start > LiveIntervals::InstrSlots::NUM) 02389 return false; 02390 return true; 02391 } 02392 02393 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def, 02394 /// turn the copy into an implicit def. 02395 bool 02396 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I, 02397 MachineBasicBlock *MBB, 02398 unsigned DstReg, unsigned SrcReg) { 02399 MachineInstr *CopyMI = &*I; 02400 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI)); 02401 if (!li_->hasInterval(SrcReg)) 02402 return false; 02403 LiveInterval &SrcInt = li_->getInterval(SrcReg); 02404 if (!SrcInt.empty()) 02405 return false; 02406 if (!li_->hasInterval(DstReg)) 02407 return false; 02408 LiveInterval &DstInt = li_->getInterval(DstReg); 02409 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx); 02410 DstInt.removeValNo(DstLR->valno); 02411 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF)); 02412 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i) 02413 CopyMI->RemoveOperand(i); 02414 bool NoUse = mri_->use_empty(SrcReg); 02415 if (NoUse) { 02416 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg), 02417 E = mri_->reg_end(); I != E; ) { 02418 assert(I.getOperand().isDef()); 02419 MachineInstr *DefMI = &*I; 02420 ++I; 02421 // The implicit_def source has no other uses, delete it. 02422 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF); 02423 li_->RemoveMachineInstrFromMaps(DefMI); 02424 DefMI->eraseFromParent(); 02425 } 02426 } 02427 ++I; 02428 return true; 02429 } 02430 02431 02432 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) { 02433 mf_ = &fn; 02434 mri_ = &fn.getRegInfo(); 02435 tm_ = &fn.getTarget(); 02436 tri_ = tm_->getRegisterInfo(); 02437 tii_ = tm_->getInstrInfo(); 02438 li_ = &getAnalysis<LiveIntervals>(); 02439 loopInfo = &getAnalysis<MachineLoopInfo>(); 02440 02441 DOUT << "********** SIMPLE REGISTER COALESCING **********\n" 02442 << "********** Function: " 02443 << ((Value*)mf_->getFunction())->getName() << '\n'; 02444 02445 allocatableRegs_ = tri_->getAllocatableSet(fn); 02446 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(), 02447 E = tri_->regclass_end(); I != E; ++I) 02448 allocatableRCRegs_.insert(std::make_pair(*I, 02449 tri_->getAllocatableSet(fn, *I))); 02450 02451 // Join (coalesce) intervals if requested. 02452 if (EnableJoining) { 02453 joinIntervals(); 02454 DEBUG({ 02455 DOUT << "********** INTERVALS POST JOINING **********\n"; 02456 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){ 02457 I->second->print(DOUT, tri_); 02458 DOUT << "\n"; 02459 } 02460 }); 02461 } 02462 02463 // Perform a final pass over the instructions and compute spill weights 02464 // and remove identity moves. 02465 SmallVector<unsigned, 4> DeadDefs; 02466 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end(); 02467 mbbi != mbbe; ++mbbi) { 02468 MachineBasicBlock* mbb = mbbi; 02469 unsigned loopDepth = loopInfo->getLoopDepth(mbb); 02470 02471 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end(); 02472 mii != mie; ) { 02473 MachineInstr *MI = mii; 02474 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 02475 if (JoinedCopies.count(MI)) { 02476 // Delete all coalesced copies. 02477 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) { 02478 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG || 02479 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) && 02480 "Unrecognized copy instruction"); 02481 DstReg = MI->getOperand(0).getReg(); 02482 } 02483 if (MI->registerDefIsDead(DstReg)) { 02484 LiveInterval &li = li_->getInterval(DstReg); 02485 if (!ShortenDeadCopySrcLiveRange(li, MI)) 02486 ShortenDeadCopyLiveRange(li, MI); 02487 } 02488 li_->RemoveMachineInstrFromMaps(MI); 02489 mii = mbbi->erase(mii); 02490 ++numPeep; 02491 continue; 02492 } 02493 02494 // Now check if this is a remat'ed def instruction which is now dead. 02495 if (ReMatDefs.count(MI)) { 02496 bool isDead = true; 02497 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 02498 const MachineOperand &MO = MI->getOperand(i); 02499 if (!MO.isReg()) 02500 continue; 02501 unsigned Reg = MO.getReg(); 02502 if (!Reg) 02503 continue; 02504 if (TargetRegisterInfo::isVirtualRegister(Reg)) 02505 DeadDefs.push_back(Reg); 02506 if (MO.isDead()) 02507 continue; 02508 if (TargetRegisterInfo::isPhysicalRegister(Reg) || 02509 !mri_->use_empty(Reg)) { 02510 isDead = false; 02511 break; 02512 } 02513 } 02514 if (isDead) { 02515 while (!DeadDefs.empty()) { 02516 unsigned DeadDef = DeadDefs.back(); 02517 DeadDefs.pop_back(); 02518 RemoveDeadDef(li_->getInterval(DeadDef), MI); 02519 } 02520 li_->RemoveMachineInstrFromMaps(mii); 02521 mii = mbbi->erase(mii); 02522 continue; 02523 } else 02524 DeadDefs.clear(); 02525 } 02526 02527 // If the move will be an identity move delete it 02528 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx); 02529 if (isMove && SrcReg == DstReg) { 02530 if (li_->hasInterval(SrcReg)) { 02531 LiveInterval &RegInt = li_->getInterval(SrcReg); 02532 // If def of this move instruction is dead, remove its live range 02533 // from the dstination register's live interval. 02534 if (MI->registerDefIsDead(DstReg)) { 02535 if (!ShortenDeadCopySrcLiveRange(RegInt, MI)) 02536 ShortenDeadCopyLiveRange(RegInt, MI); 02537 } 02538 } 02539 li_->RemoveMachineInstrFromMaps(MI); 02540 mii = mbbi->erase(mii); 02541 ++numPeep; 02542 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) { 02543 SmallSet<unsigned, 4> UniqueUses; 02544 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 02545 const MachineOperand &mop = MI->getOperand(i); 02546 if (mop.isReg() && mop.getReg() && 02547 TargetRegisterInfo::isVirtualRegister(mop.getReg())) { 02548 unsigned reg = mop.getReg(); 02549 // Multiple uses of reg by the same instruction. It should not 02550 // contribute to spill weight again. 02551 if (UniqueUses.count(reg) != 0) 02552 continue; 02553 LiveInterval &RegInt = li_->getInterval(reg); 02554 RegInt.weight += 02555 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth); 02556 UniqueUses.insert(reg); 02557 } 02558 } 02559 ++mii; 02560 } 02561 } 02562 } 02563 02564 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) { 02565 LiveInterval &LI = *I->second; 02566 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) { 02567 // If the live interval length is essentially zero, i.e. in every live 02568 // range the use follows def immediately, it doesn't make sense to spill 02569 // it and hope it will be easier to allocate for this li. 02570 if (isZeroLengthInterval(&LI)) 02571 LI.weight = HUGE_VALF; 02572 else { 02573 bool isLoad = false; 02574 SmallVector<LiveInterval*, 4> SpillIs; 02575 if (li_->isReMaterializable(LI, SpillIs, isLoad)) { 02576 // If all of the definitions of the interval are re-materializable, 02577 // it is a preferred candidate for spilling. If non of the defs are 02578 // loads, then it's potentially very cheap to re-materialize. 02579 // FIXME: this gets much more complicated once we support non-trivial 02580 // re-materialization. 02581 if (isLoad) 02582 LI.weight *= 0.9F; 02583 else 02584 LI.weight *= 0.5F; 02585 } 02586 } 02587 02588 // Slightly prefer live interval that has been assigned a preferred reg. 02589 if (LI.preference) 02590 LI.weight *= 1.01F; 02591 02592 // Divide the weight of the interval by its size. This encourages 02593 // spilling of intervals that are large and have few uses, and 02594 // discourages spilling of small intervals with many uses. 02595 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM; 02596 } 02597 } 02598 02599 DEBUG(dump()); 02600 return true; 02601 } 02602 02603 /// print - Implement the dump method. 02604 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const { 02605 li_->print(O, m); 02606 } 02607 02608 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() { 02609 return new SimpleRegisterCoalescing(); 02610 } 02611 02612 // Make sure that anything that uses RegisterCoalescer pulls in this file... 02613 DEFINING_FILE_FOR(SimpleRegisterCoalescing)