1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the generic RegisterCoalescer interface which 11 // is used as the common interface used by all clients and 12 // implementations of register coalescing. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #define DEBUG_TYPE "regcoalescing" 17 #include "RegisterCoalescer.h" 18 #include "LiveDebugVariables.h" 19 #include "RegisterClassInfo.h" 20 #include "VirtRegMap.h" 21 22 #include "llvm/Pass.h" 23 #include "llvm/Value.h" 24 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 25 #include "llvm/CodeGen/MachineInstr.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/Target/TargetInstrInfo.h" 28 #include "llvm/Target/TargetRegisterInfo.h" 29 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 30 #include "llvm/Analysis/AliasAnalysis.h" 31 #include "llvm/CodeGen/MachineFrameInfo.h" 32 #include "llvm/CodeGen/MachineInstr.h" 33 #include "llvm/CodeGen/MachineLoopInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/Passes.h" 36 #include "llvm/Target/TargetInstrInfo.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Target/TargetOptions.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/ADT/OwningPtr.h" 44 #include "llvm/ADT/SmallSet.h" 45 #include "llvm/ADT/Statistic.h" 46 #include "llvm/ADT/STLExtras.h" 47 #include <algorithm> 48 #include <cmath> 49 using namespace llvm; 50 51 STATISTIC(numJoins , "Number of interval joins performed"); 52 STATISTIC(numCrossRCs , "Number of cross class joins performed"); 53 STATISTIC(numCommutes , "Number of instruction commuting performed"); 54 STATISTIC(numExtends , "Number of copies extended"); 55 STATISTIC(NumReMats , "Number of instructions re-materialized"); 56 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing"); 57 STATISTIC(numAborts , "Number of times interval joining aborted"); 58 STATISTIC(NumInflated , "Number of register classes inflated"); 59 60 static cl::opt<bool> 61 EnableJoining("join-liveintervals", 62 cl::desc("Coalesce copies (default=true)"), 63 cl::init(true)); 64 65 static cl::opt<bool> 66 DisableCrossClassJoin("disable-cross-class-join", 67 cl::desc("Avoid coalescing cross register class copies"), 68 cl::init(false), cl::Hidden); 69 70 static cl::opt<bool> 71 EnablePhysicalJoin("join-physregs", 72 cl::desc("Join physical register copies"), 73 cl::init(false), cl::Hidden); 74 75 static cl::opt<bool> 76 VerifyCoalescing("verify-coalescing", 77 cl::desc("Verify machine instrs before and after register coalescing"), 78 cl::Hidden); 79 80 namespace { 81 class RegisterCoalescer : public MachineFunctionPass { 82 MachineFunction* MF; 83 MachineRegisterInfo* MRI; 84 const TargetMachine* TM; 85 const TargetRegisterInfo* TRI; 86 const TargetInstrInfo* TII; 87 LiveIntervals *LIS; 88 LiveDebugVariables *LDV; 89 const MachineLoopInfo* Loops; 90 AliasAnalysis *AA; 91 RegisterClassInfo RegClassInfo; 92 93 /// JoinedCopies - Keep track of copies eliminated due to coalescing. 94 /// 95 SmallPtrSet<MachineInstr*, 32> JoinedCopies; 96 97 /// ReMatCopies - Keep track of copies eliminated due to remat. 98 /// 99 SmallPtrSet<MachineInstr*, 32> ReMatCopies; 100 101 /// ReMatDefs - Keep track of definition instructions which have 102 /// been remat'ed. 103 SmallPtrSet<MachineInstr*, 8> ReMatDefs; 104 105 /// joinIntervals - join compatible live intervals 106 void joinIntervals(); 107 108 /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting 109 /// copies that cannot yet be coalesced into the "TryAgain" list. 110 void CopyCoalesceInMBB(MachineBasicBlock *MBB, 111 std::vector<MachineInstr*> &TryAgain); 112 113 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg, 114 /// which are the src/dst of the copy instruction CopyMI. This returns 115 /// true if the copy was successfully coalesced away. If it is not 116 /// currently possible to coalesce this interval, but it may be possible if 117 /// other things get coalesced, then it returns true by reference in 118 /// 'Again'. 119 bool JoinCopy(MachineInstr *TheCopy, bool &Again); 120 121 /// JoinIntervals - Attempt to join these two intervals. On failure, this 122 /// returns false. The output "SrcInt" will not have been modified, so we 123 /// can use this information below to update aliases. 124 bool JoinIntervals(CoalescerPair &CP); 125 126 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If 127 /// the source value number is defined by a copy from the destination reg 128 /// see if we can merge these two destination reg valno# into a single 129 /// value number, eliminating a copy. 130 bool AdjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI); 131 132 /// HasOtherReachingDefs - Return true if there are definitions of IntB 133 /// other than BValNo val# that can reach uses of AValno val# of IntA. 134 bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB, 135 VNInfo *AValNo, VNInfo *BValNo); 136 137 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy. 138 /// If the source value number is defined by a commutable instruction and 139 /// its other operand is coalesced to the copy dest register, see if we 140 /// can transform the copy into a noop by commuting the definition. 141 bool RemoveCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI); 142 143 /// ReMaterializeTrivialDef - If the source of a copy is defined by a 144 /// trivial computation, replace the copy by rematerialize the definition. 145 /// If PreserveSrcInt is true, make sure SrcInt is valid after the call. 146 bool ReMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt, 147 unsigned DstReg, MachineInstr *CopyMI); 148 149 /// shouldJoinPhys - Return true if a physreg copy should be joined. 150 bool shouldJoinPhys(CoalescerPair &CP); 151 152 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and 153 /// update the subregister number if it is not zero. If DstReg is a 154 /// physical register and the existing subregister number of the def / use 155 /// being updated is not zero, make sure to set it to the correct physical 156 /// subregister. 157 void UpdateRegDefsUses(const CoalescerPair &CP); 158 159 /// RemoveDeadDef - If a def of a live interval is now determined dead, 160 /// remove the val# it defines. If the live interval becomes empty, remove 161 /// it as well. 162 bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI); 163 164 /// RemoveCopyFlag - If DstReg is no longer defined by CopyMI, clear the 165 /// VNInfo copy flag for DstReg and all aliases. 166 void RemoveCopyFlag(unsigned DstReg, const MachineInstr *CopyMI); 167 168 /// markAsJoined - Remember that CopyMI has already been joined. 169 void markAsJoined(MachineInstr *CopyMI); 170 171 /// eliminateUndefCopy - Handle copies of undef values. 172 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP); 173 174 public: 175 static char ID; // Class identification, replacement for typeinfo 176 RegisterCoalescer() : MachineFunctionPass(ID) { 177 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); 178 } 179 180 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 181 182 virtual void releaseMemory(); 183 184 /// runOnMachineFunction - pass entry point 185 virtual bool runOnMachineFunction(MachineFunction&); 186 187 /// print - Implement the dump method. 188 virtual void print(raw_ostream &O, const Module* = 0) const; 189 }; 190 } /// end anonymous namespace 191 192 char &llvm::RegisterCoalescerPassID = RegisterCoalescer::ID; 193 194 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing", 195 "Simple Register Coalescing", false, false) 196 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 197 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables) 198 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 199 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 200 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination) 201 INITIALIZE_PASS_DEPENDENCY(PHIElimination) 202 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass) 203 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 204 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing", 205 "Simple Register Coalescing", false, false) 206 207 char RegisterCoalescer::ID = 0; 208 209 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) { 210 if (!a) return b; 211 if (!b) return a; 212 return tri.composeSubRegIndices(a, b); 213 } 214 215 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, 216 unsigned &Src, unsigned &Dst, 217 unsigned &SrcSub, unsigned &DstSub) { 218 if (MI->isCopy()) { 219 Dst = MI->getOperand(0).getReg(); 220 DstSub = MI->getOperand(0).getSubReg(); 221 Src = MI->getOperand(1).getReg(); 222 SrcSub = MI->getOperand(1).getSubReg(); 223 } else if (MI->isSubregToReg()) { 224 Dst = MI->getOperand(0).getReg(); 225 DstSub = compose(tri, MI->getOperand(0).getSubReg(), 226 MI->getOperand(3).getImm()); 227 Src = MI->getOperand(2).getReg(); 228 SrcSub = MI->getOperand(2).getSubReg(); 229 } else 230 return false; 231 return true; 232 } 233 234 bool CoalescerPair::setRegisters(const MachineInstr *MI) { 235 SrcReg = DstReg = SubIdx = 0; 236 NewRC = 0; 237 Flipped = CrossClass = false; 238 239 unsigned Src, Dst, SrcSub, DstSub; 240 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 241 return false; 242 Partial = SrcSub || DstSub; 243 244 // If one register is a physreg, it must be Dst. 245 if (TargetRegisterInfo::isPhysicalRegister(Src)) { 246 if (TargetRegisterInfo::isPhysicalRegister(Dst)) 247 return false; 248 std::swap(Src, Dst); 249 std::swap(SrcSub, DstSub); 250 Flipped = true; 251 } 252 253 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); 254 255 if (TargetRegisterInfo::isPhysicalRegister(Dst)) { 256 // Eliminate DstSub on a physreg. 257 if (DstSub) { 258 Dst = TRI.getSubReg(Dst, DstSub); 259 if (!Dst) return false; 260 DstSub = 0; 261 } 262 263 // Eliminate SrcSub by picking a corresponding Dst superregister. 264 if (SrcSub) { 265 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src)); 266 if (!Dst) return false; 267 SrcSub = 0; 268 } else if (!MRI.getRegClass(Src)->contains(Dst)) { 269 return false; 270 } 271 } else { 272 // Both registers are virtual. 273 274 // Both registers have subreg indices. 275 if (SrcSub && DstSub) { 276 // For now we only handle the case of identical indices in commensurate 277 // registers: Dreg:ssub_1 + Dreg:ssub_1 -> Dreg 278 // FIXME: Handle Qreg:ssub_3 + Dreg:ssub_1 as QReg:dsub_1 + Dreg. 279 if (SrcSub != DstSub) 280 return false; 281 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src); 282 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst); 283 if (!TRI.getCommonSubClass(DstRC, SrcRC)) 284 return false; 285 SrcSub = DstSub = 0; 286 } 287 288 // There can be no SrcSub. 289 if (SrcSub) { 290 std::swap(Src, Dst); 291 DstSub = SrcSub; 292 SrcSub = 0; 293 assert(!Flipped && "Unexpected flip"); 294 Flipped = true; 295 } 296 297 // Find the new register class. 298 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src); 299 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst); 300 if (DstSub) 301 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub); 302 else 303 NewRC = TRI.getCommonSubClass(DstRC, SrcRC); 304 if (!NewRC) 305 return false; 306 CrossClass = NewRC != DstRC || NewRC != SrcRC; 307 } 308 // Check our invariants 309 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual"); 310 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) && 311 "Cannot have a physical SubIdx"); 312 SrcReg = Src; 313 DstReg = Dst; 314 SubIdx = DstSub; 315 return true; 316 } 317 318 bool CoalescerPair::flip() { 319 if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg)) 320 return false; 321 std::swap(SrcReg, DstReg); 322 Flipped = !Flipped; 323 return true; 324 } 325 326 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const { 327 if (!MI) 328 return false; 329 unsigned Src, Dst, SrcSub, DstSub; 330 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 331 return false; 332 333 // Find the virtual register that is SrcReg. 334 if (Dst == SrcReg) { 335 std::swap(Src, Dst); 336 std::swap(SrcSub, DstSub); 337 } else if (Src != SrcReg) { 338 return false; 339 } 340 341 // Now check that Dst matches DstReg. 342 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { 343 if (!TargetRegisterInfo::isPhysicalRegister(Dst)) 344 return false; 345 assert(!SubIdx && "Inconsistent CoalescerPair state."); 346 // DstSub could be set for a physreg from INSERT_SUBREG. 347 if (DstSub) 348 Dst = TRI.getSubReg(Dst, DstSub); 349 // Full copy of Src. 350 if (!SrcSub) 351 return DstReg == Dst; 352 // This is a partial register copy. Check that the parts match. 353 return TRI.getSubReg(DstReg, SrcSub) == Dst; 354 } else { 355 // DstReg is virtual. 356 if (DstReg != Dst) 357 return false; 358 // Registers match, do the subregisters line up? 359 return compose(TRI, SubIdx, SrcSub) == DstSub; 360 } 361 } 362 363 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const { 364 AU.setPreservesCFG(); 365 AU.addRequired<AliasAnalysis>(); 366 AU.addRequired<LiveIntervals>(); 367 AU.addPreserved<LiveIntervals>(); 368 AU.addRequired<LiveDebugVariables>(); 369 AU.addPreserved<LiveDebugVariables>(); 370 AU.addPreserved<SlotIndexes>(); 371 AU.addRequired<MachineLoopInfo>(); 372 AU.addPreserved<MachineLoopInfo>(); 373 AU.addPreservedID(MachineDominatorsID); 374 AU.addPreservedID(StrongPHIEliminationID); 375 AU.addPreservedID(PHIEliminationID); 376 AU.addPreservedID(TwoAddressInstructionPassID); 377 MachineFunctionPass::getAnalysisUsage(AU); 378 } 379 380 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) { 381 /// Joined copies are not deleted immediately, but kept in JoinedCopies. 382 JoinedCopies.insert(CopyMI); 383 384 /// Mark all register operands of CopyMI as <undef> so they won't affect dead 385 /// code elimination. 386 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(), 387 E = CopyMI->operands_end(); I != E; ++I) 388 if (I->isReg()) 389 I->setIsUndef(true); 390 } 391 392 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA 393 /// being the source and IntB being the dest, thus this defines a value number 394 /// in IntB. If the source value number (in IntA) is defined by a copy from B, 395 /// see if we can merge these two pieces of B into a single value number, 396 /// eliminating a copy. For example: 397 /// 398 /// A3 = B0 399 /// ... 400 /// B1 = A3 <- this copy 401 /// 402 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1 403 /// value number to be replaced with B0 (which simplifies the B liveinterval). 404 /// 405 /// This returns true if an interval was modified. 406 /// 407 bool RegisterCoalescer::AdjustCopiesBackFrom(const CoalescerPair &CP, 408 MachineInstr *CopyMI) { 409 // Bail if there is no dst interval - can happen when merging physical subreg 410 // operations. 411 if (!LIS->hasInterval(CP.getDstReg())) 412 return false; 413 414 LiveInterval &IntA = 415 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 416 LiveInterval &IntB = 417 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 418 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(); 419 420 // BValNo is a value number in B that is defined by a copy from A. 'B3' in 421 // the example above. 422 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx); 423 if (BLR == IntB.end()) return false; 424 VNInfo *BValNo = BLR->valno; 425 426 // Get the location that B is defined at. Two options: either this value has 427 // an unknown definition point or it is defined at CopyIdx. If unknown, we 428 // can't process it. 429 if (!BValNo->isDefByCopy()) return false; 430 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?"); 431 432 // AValNo is the value number in A that defines the copy, A3 in the example. 433 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true); 434 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx); 435 // The live range might not exist after fun with physreg coalescing. 436 if (ALR == IntA.end()) return false; 437 VNInfo *AValNo = ALR->valno; 438 // If it's re-defined by an early clobber somewhere in the live range, then 439 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround. 440 // See PR3149: 441 // 172 %ECX<def> = MOV32rr %reg1039<kill> 442 // 180 INLINEASM <es:subl $5,$1 443 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, 444 // %EAX<kill>, 445 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0 446 // 188 %EAX<def> = MOV32rr %EAX<kill> 447 // 196 %ECX<def> = MOV32rr %ECX<kill> 448 // 204 %ECX<def> = MOV32rr %ECX<kill> 449 // 212 %EAX<def> = MOV32rr %EAX<kill> 450 // 220 %EAX<def> = MOV32rr %EAX 451 // 228 %reg1039<def> = MOV32rr %ECX<kill> 452 // The early clobber operand ties ECX input to the ECX def. 453 // 454 // The live interval of ECX is represented as this: 455 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47) 456 // The coalescer has no idea there was a def in the middle of [174,230]. 457 if (AValNo->hasRedefByEC()) 458 return false; 459 460 // If AValNo is defined as a copy from IntB, we can potentially process this. 461 // Get the instruction that defines this value number. 462 if (!CP.isCoalescable(AValNo->getCopy())) 463 return false; 464 465 // Get the LiveRange in IntB that this value number starts with. 466 LiveInterval::iterator ValLR = 467 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot()); 468 if (ValLR == IntB.end()) 469 return false; 470 471 // Make sure that the end of the live range is inside the same block as 472 // CopyMI. 473 MachineInstr *ValLREndInst = 474 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot()); 475 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent()) 476 return false; 477 478 // Okay, we now know that ValLR ends in the same block that the CopyMI 479 // live-range starts. If there are no intervening live ranges between them in 480 // IntB, we can merge them. 481 if (ValLR+1 != BLR) return false; 482 483 // If a live interval is a physical register, conservatively check if any 484 // of its aliases is overlapping the live interval of the virtual register. 485 // If so, do not coalesce. 486 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) { 487 for (const unsigned *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS) 488 if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) { 489 DEBUG({ 490 dbgs() << "\t\tInterfere with alias "; 491 LIS->getInterval(*AS).print(dbgs(), TRI); 492 }); 493 return false; 494 } 495 } 496 497 DEBUG({ 498 dbgs() << "Extending: "; 499 IntB.print(dbgs(), TRI); 500 }); 501 502 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start; 503 // We are about to delete CopyMI, so need to remove it as the 'instruction 504 // that defines this value #'. Update the valnum with the new defining 505 // instruction #. 506 BValNo->def = FillerStart; 507 BValNo->setCopy(0); 508 509 // Okay, we can merge them. We need to insert a new liverange: 510 // [ValLR.end, BLR.begin) of either value number, then we merge the 511 // two value numbers. 512 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo)); 513 514 // If the IntB live range is assigned to a physical register, and if that 515 // physreg has sub-registers, update their live intervals as well. 516 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) { 517 for (const unsigned *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) { 518 if (!LIS->hasInterval(*SR)) 519 continue; 520 LiveInterval &SRLI = LIS->getInterval(*SR); 521 SRLI.addRange(LiveRange(FillerStart, FillerEnd, 522 SRLI.getNextValue(FillerStart, 0, 523 LIS->getVNInfoAllocator()))); 524 } 525 } 526 527 // Okay, merge "B1" into the same value number as "B0". 528 if (BValNo != ValLR->valno) { 529 // If B1 is killed by a PHI, then the merged live range must also be killed 530 // by the same PHI, as B0 and B1 can not overlap. 531 bool HasPHIKill = BValNo->hasPHIKill(); 532 IntB.MergeValueNumberInto(BValNo, ValLR->valno); 533 if (HasPHIKill) 534 ValLR->valno->setHasPHIKill(true); 535 } 536 DEBUG({ 537 dbgs() << " result = "; 538 IntB.print(dbgs(), TRI); 539 dbgs() << "\n"; 540 }); 541 542 // If the source instruction was killing the source register before the 543 // merge, unset the isKill marker given the live range has been extended. 544 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true); 545 if (UIdx != -1) { 546 ValLREndInst->getOperand(UIdx).setIsKill(false); 547 } 548 549 // If the copy instruction was killing the destination register before the 550 // merge, find the last use and trim the live range. That will also add the 551 // isKill marker. 552 if (ALR->end == CopyIdx) 553 LIS->shrinkToUses(&IntA); 554 555 ++numExtends; 556 return true; 557 } 558 559 /// HasOtherReachingDefs - Return true if there are definitions of IntB 560 /// other than BValNo val# that can reach uses of AValno val# of IntA. 561 bool RegisterCoalescer::HasOtherReachingDefs(LiveInterval &IntA, 562 LiveInterval &IntB, 563 VNInfo *AValNo, 564 VNInfo *BValNo) { 565 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end(); 566 AI != AE; ++AI) { 567 if (AI->valno != AValNo) continue; 568 LiveInterval::Ranges::iterator BI = 569 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start); 570 if (BI != IntB.ranges.begin()) 571 --BI; 572 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) { 573 if (BI->valno == BValNo) 574 continue; 575 if (BI->start <= AI->start && BI->end > AI->start) 576 return true; 577 if (BI->start > AI->start && BI->start < AI->end) 578 return true; 579 } 580 } 581 return false; 582 } 583 584 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with 585 /// IntA being the source and IntB being the dest, thus this defines a value 586 /// number in IntB. If the source value number (in IntA) is defined by a 587 /// commutable instruction and its other operand is coalesced to the copy dest 588 /// register, see if we can transform the copy into a noop by commuting the 589 /// definition. For example, 590 /// 591 /// A3 = op A2 B0<kill> 592 /// ... 593 /// B1 = A3 <- this copy 594 /// ... 595 /// = op A3 <- more uses 596 /// 597 /// ==> 598 /// 599 /// B2 = op B0 A2<kill> 600 /// ... 601 /// B1 = B2 <- now an identify copy 602 /// ... 603 /// = op B2 <- more uses 604 /// 605 /// This returns true if an interval was modified. 606 /// 607 bool RegisterCoalescer::RemoveCopyByCommutingDef(const CoalescerPair &CP, 608 MachineInstr *CopyMI) { 609 // FIXME: For now, only eliminate the copy by commuting its def when the 610 // source register is a virtual register. We want to guard against cases 611 // where the copy is a back edge copy and commuting the def lengthen the 612 // live interval of the source register to the entire loop. 613 if (CP.isPhys() && CP.isFlipped()) 614 return false; 615 616 // Bail if there is no dst interval. 617 if (!LIS->hasInterval(CP.getDstReg())) 618 return false; 619 620 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(); 621 622 LiveInterval &IntA = 623 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 624 LiveInterval &IntB = 625 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 626 627 // BValNo is a value number in B that is defined by a copy from A. 'B3' in 628 // the example above. 629 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx); 630 if (!BValNo || !BValNo->isDefByCopy()) 631 return false; 632 633 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?"); 634 635 // AValNo is the value number in A that defines the copy, A3 in the example. 636 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true)); 637 assert(AValNo && "COPY source not live"); 638 639 // If other defs can reach uses of this def, then it's not safe to perform 640 // the optimization. 641 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill()) 642 return false; 643 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def); 644 if (!DefMI) 645 return false; 646 if (!DefMI->isCommutable()) 647 return false; 648 // If DefMI is a two-address instruction then commuting it will change the 649 // destination register. 650 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg); 651 assert(DefIdx != -1); 652 unsigned UseOpIdx; 653 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx)) 654 return false; 655 unsigned Op1, Op2, NewDstIdx; 656 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2)) 657 return false; 658 if (Op1 == UseOpIdx) 659 NewDstIdx = Op2; 660 else if (Op2 == UseOpIdx) 661 NewDstIdx = Op1; 662 else 663 return false; 664 665 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx); 666 unsigned NewReg = NewDstMO.getReg(); 667 if (NewReg != IntB.reg || !NewDstMO.isKill()) 668 return false; 669 670 // Make sure there are no other definitions of IntB that would reach the 671 // uses which the new definition can reach. 672 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo)) 673 return false; 674 675 // Abort if the aliases of IntB.reg have values that are not simply the 676 // clobbers from the superreg. 677 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) 678 for (const unsigned *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS) 679 if (LIS->hasInterval(*AS) && 680 HasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0)) 681 return false; 682 683 // If some of the uses of IntA.reg is already coalesced away, return false. 684 // It's not possible to determine whether it's safe to perform the coalescing. 685 for (MachineRegisterInfo::use_nodbg_iterator UI = 686 MRI->use_nodbg_begin(IntA.reg), 687 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 688 MachineInstr *UseMI = &*UI; 689 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI); 690 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx); 691 if (ULR == IntA.end()) 692 continue; 693 if (ULR->valno == AValNo && JoinedCopies.count(UseMI)) 694 return false; 695 } 696 697 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t' 698 << *DefMI); 699 700 // At this point we have decided that it is legal to do this 701 // transformation. Start by commuting the instruction. 702 MachineBasicBlock *MBB = DefMI->getParent(); 703 MachineInstr *NewMI = TII->commuteInstruction(DefMI); 704 if (!NewMI) 705 return false; 706 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) && 707 TargetRegisterInfo::isVirtualRegister(IntB.reg) && 708 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg))) 709 return false; 710 if (NewMI != DefMI) { 711 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI); 712 MachineBasicBlock::iterator Pos = DefMI; 713 MBB->insert(Pos, NewMI); 714 MBB->erase(DefMI); 715 } 716 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false); 717 NewMI->getOperand(OpIdx).setIsKill(); 718 719 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g. 720 // A = or A, B 721 // ... 722 // B = A 723 // ... 724 // C = A<kill> 725 // ... 726 // = B 727 728 // Update uses of IntA of the specific Val# with IntB. 729 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg), 730 UE = MRI->use_end(); UI != UE;) { 731 MachineOperand &UseMO = UI.getOperand(); 732 MachineInstr *UseMI = &*UI; 733 ++UI; 734 if (JoinedCopies.count(UseMI)) 735 continue; 736 if (UseMI->isDebugValue()) { 737 // FIXME These don't have an instruction index. Not clear we have enough 738 // info to decide whether to do this replacement or not. For now do it. 739 UseMO.setReg(NewReg); 740 continue; 741 } 742 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true); 743 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx); 744 if (ULR == IntA.end() || ULR->valno != AValNo) 745 continue; 746 if (TargetRegisterInfo::isPhysicalRegister(NewReg)) 747 UseMO.substPhysReg(NewReg, *TRI); 748 else 749 UseMO.setReg(NewReg); 750 if (UseMI == CopyMI) 751 continue; 752 if (!UseMI->isCopy()) 753 continue; 754 if (UseMI->getOperand(0).getReg() != IntB.reg || 755 UseMI->getOperand(0).getSubReg()) 756 continue; 757 758 // This copy will become a noop. If it's defining a new val#, merge it into 759 // BValNo. 760 SlotIndex DefIdx = UseIdx.getRegSlot(); 761 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx); 762 if (!DVNI) 763 continue; 764 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI); 765 assert(DVNI->def == DefIdx); 766 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI); 767 markAsJoined(UseMI); 768 } 769 770 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition 771 // is updated. 772 VNInfo *ValNo = BValNo; 773 ValNo->def = AValNo->def; 774 ValNo->setCopy(0); 775 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end(); 776 AI != AE; ++AI) { 777 if (AI->valno != AValNo) continue; 778 IntB.addRange(LiveRange(AI->start, AI->end, ValNo)); 779 } 780 DEBUG(dbgs() << "\t\textended: " << IntB << '\n'); 781 782 IntA.removeValNo(AValNo); 783 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n'); 784 ++numCommutes; 785 return true; 786 } 787 788 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial 789 /// computation, replace the copy by rematerialize the definition. 790 bool RegisterCoalescer::ReMaterializeTrivialDef(LiveInterval &SrcInt, 791 bool preserveSrcInt, 792 unsigned DstReg, 793 MachineInstr *CopyMI) { 794 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true); 795 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx); 796 assert(SrcLR != SrcInt.end() && "Live range not found!"); 797 VNInfo *ValNo = SrcLR->valno; 798 if (ValNo->isPHIDef() || ValNo->isUnused()) 799 return false; 800 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def); 801 if (!DefMI) 802 return false; 803 assert(DefMI && "Defining instruction disappeared"); 804 if (!DefMI->isAsCheapAsAMove()) 805 return false; 806 if (!TII->isTriviallyReMaterializable(DefMI, AA)) 807 return false; 808 bool SawStore = false; 809 if (!DefMI->isSafeToMove(TII, AA, SawStore)) 810 return false; 811 const MCInstrDesc &MCID = DefMI->getDesc(); 812 if (MCID.getNumDefs() != 1) 813 return false; 814 if (!DefMI->isImplicitDef()) { 815 // Make sure the copy destination register class fits the instruction 816 // definition register class. The mismatch can happen as a result of earlier 817 // extract_subreg, insert_subreg, subreg_to_reg coalescing. 818 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI); 819 if (TargetRegisterInfo::isVirtualRegister(DstReg)) { 820 if (MRI->getRegClass(DstReg) != RC) 821 return false; 822 } else if (!RC->contains(DstReg)) 823 return false; 824 } 825 826 RemoveCopyFlag(DstReg, CopyMI); 827 828 MachineBasicBlock *MBB = CopyMI->getParent(); 829 MachineBasicBlock::iterator MII = 830 llvm::next(MachineBasicBlock::iterator(CopyMI)); 831 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI); 832 MachineInstr *NewMI = prior(MII); 833 834 // CopyMI may have implicit operands, transfer them over to the newly 835 // rematerialized instruction. And update implicit def interval valnos. 836 for (unsigned i = CopyMI->getDesc().getNumOperands(), 837 e = CopyMI->getNumOperands(); i != e; ++i) { 838 MachineOperand &MO = CopyMI->getOperand(i); 839 if (MO.isReg() && MO.isImplicit()) 840 NewMI->addOperand(MO); 841 if (MO.isDef()) 842 RemoveCopyFlag(MO.getReg(), CopyMI); 843 } 844 845 NewMI->copyImplicitOps(CopyMI); 846 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI); 847 CopyMI->eraseFromParent(); 848 ReMatCopies.insert(CopyMI); 849 ReMatDefs.insert(DefMI); 850 DEBUG(dbgs() << "Remat: " << *NewMI); 851 ++NumReMats; 852 853 // The source interval can become smaller because we removed a use. 854 if (preserveSrcInt) 855 LIS->shrinkToUses(&SrcInt); 856 857 return true; 858 } 859 860 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef> 861 /// values, it only removes local variables. When we have a copy like: 862 /// 863 /// %vreg1 = COPY %vreg2<undef> 864 /// 865 /// We delete the copy and remove the corresponding value number from %vreg1. 866 /// Any uses of that value number are marked as <undef>. 867 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI, 868 const CoalescerPair &CP) { 869 SlotIndex Idx = LIS->getInstructionIndex(CopyMI); 870 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg()); 871 if (SrcInt->liveAt(Idx)) 872 return false; 873 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg()); 874 if (DstInt->liveAt(Idx)) 875 return false; 876 877 // No intervals are live-in to CopyMI - it is undef. 878 if (CP.isFlipped()) 879 DstInt = SrcInt; 880 SrcInt = 0; 881 882 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot()); 883 assert(DeadVNI && "No value defined in DstInt"); 884 DstInt->removeValNo(DeadVNI); 885 886 // Find new undef uses. 887 for (MachineRegisterInfo::reg_nodbg_iterator 888 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end(); 889 I != E; ++I) { 890 MachineOperand &MO = I.getOperand(); 891 if (MO.isDef() || MO.isUndef()) 892 continue; 893 MachineInstr *MI = MO.getParent(); 894 SlotIndex Idx = LIS->getInstructionIndex(MI); 895 if (DstInt->liveAt(Idx)) 896 continue; 897 MO.setIsUndef(true); 898 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI); 899 } 900 return true; 901 } 902 903 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and 904 /// update the subregister number if it is not zero. If DstReg is a 905 /// physical register and the existing subregister number of the def / use 906 /// being updated is not zero, make sure to set it to the correct physical 907 /// subregister. 908 void 909 RegisterCoalescer::UpdateRegDefsUses(const CoalescerPair &CP) { 910 bool DstIsPhys = CP.isPhys(); 911 unsigned SrcReg = CP.getSrcReg(); 912 unsigned DstReg = CP.getDstReg(); 913 unsigned SubIdx = CP.getSubIdx(); 914 915 // Update LiveDebugVariables. 916 LDV->renameRegister(SrcReg, DstReg, SubIdx); 917 918 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg); 919 MachineInstr *UseMI = I.skipInstruction();) { 920 // A PhysReg copy that won't be coalesced can perhaps be rematerialized 921 // instead. 922 if (DstIsPhys) { 923 if (UseMI->isFullCopy() && 924 UseMI->getOperand(1).getReg() == SrcReg && 925 UseMI->getOperand(0).getReg() != SrcReg && 926 UseMI->getOperand(0).getReg() != DstReg && 927 !JoinedCopies.count(UseMI) && 928 ReMaterializeTrivialDef(LIS->getInterval(SrcReg), false, 929 UseMI->getOperand(0).getReg(), UseMI)) 930 continue; 931 } 932 933 SmallVector<unsigned,8> Ops; 934 bool Reads, Writes; 935 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops); 936 bool Kills = false, Deads = false; 937 938 // Replace SrcReg with DstReg in all UseMI operands. 939 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 940 MachineOperand &MO = UseMI->getOperand(Ops[i]); 941 Kills |= MO.isKill(); 942 Deads |= MO.isDead(); 943 944 // Make sure we don't create read-modify-write defs accidentally. We 945 // assume here that a SrcReg def cannot be joined into a live DstReg. If 946 // RegisterCoalescer starts tracking partially live registers, we will 947 // need to check the actual LiveInterval to determine if DstReg is live 948 // here. 949 if (SubIdx && !Reads) 950 MO.setIsUndef(); 951 952 if (DstIsPhys) 953 MO.substPhysReg(DstReg, *TRI); 954 else 955 MO.substVirtReg(DstReg, SubIdx, *TRI); 956 } 957 958 // This instruction is a copy that will be removed. 959 if (JoinedCopies.count(UseMI)) 960 continue; 961 962 if (SubIdx) { 963 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a 964 // read-modify-write of DstReg. 965 if (Deads) 966 UseMI->addRegisterDead(DstReg, TRI); 967 else if (!Reads && Writes) 968 UseMI->addRegisterDefined(DstReg, TRI); 969 970 // Kill flags apply to the whole physical register. 971 if (DstIsPhys && Kills) 972 UseMI->addRegisterKilled(DstReg, TRI); 973 } 974 975 DEBUG({ 976 dbgs() << "\t\tupdated: "; 977 if (!UseMI->isDebugValue()) 978 dbgs() << LIS->getInstructionIndex(UseMI) << "\t"; 979 dbgs() << *UseMI; 980 }); 981 } 982 } 983 984 /// removeIntervalIfEmpty - Check if the live interval of a physical register 985 /// is empty, if so remove it and also remove the empty intervals of its 986 /// sub-registers. Return true if live interval is removed. 987 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS, 988 const TargetRegisterInfo *TRI) { 989 if (li.empty()) { 990 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) 991 for (const unsigned* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) { 992 if (!LIS->hasInterval(*SR)) 993 continue; 994 LiveInterval &sli = LIS->getInterval(*SR); 995 if (sli.empty()) 996 LIS->removeInterval(*SR); 997 } 998 LIS->removeInterval(li.reg); 999 return true; 1000 } 1001 return false; 1002 } 1003 1004 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove 1005 /// the val# it defines. If the live interval becomes empty, remove it as well. 1006 bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li, 1007 MachineInstr *DefMI) { 1008 SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot(); 1009 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx); 1010 if (DefIdx != MLR->valno->def) 1011 return false; 1012 li.removeValNo(MLR->valno); 1013 return removeIntervalIfEmpty(li, LIS, TRI); 1014 } 1015 1016 void RegisterCoalescer::RemoveCopyFlag(unsigned DstReg, 1017 const MachineInstr *CopyMI) { 1018 SlotIndex DefIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(); 1019 if (LIS->hasInterval(DstReg)) { 1020 LiveInterval &LI = LIS->getInterval(DstReg); 1021 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx)) 1022 if (LR->valno->def == DefIdx) 1023 LR->valno->setCopy(0); 1024 } 1025 if (!TargetRegisterInfo::isPhysicalRegister(DstReg)) 1026 return; 1027 for (const unsigned* AS = TRI->getAliasSet(DstReg); *AS; ++AS) { 1028 if (!LIS->hasInterval(*AS)) 1029 continue; 1030 LiveInterval &LI = LIS->getInterval(*AS); 1031 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx)) 1032 if (LR->valno->def == DefIdx) 1033 LR->valno->setCopy(0); 1034 } 1035 } 1036 1037 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined. 1038 /// We need to be careful about coalescing a source physical register with a 1039 /// virtual register. Once the coalescing is done, it cannot be broken and these 1040 /// are not spillable! If the destination interval uses are far away, think 1041 /// twice about coalescing them! 1042 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) { 1043 bool Allocatable = LIS->isAllocatable(CP.getDstReg()); 1044 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg()); 1045 1046 /// Always join simple intervals that are defined by a single copy from a 1047 /// reserved register. This doesn't increase register pressure, so it is 1048 /// always beneficial. 1049 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue()) 1050 return true; 1051 1052 if (!EnablePhysicalJoin) { 1053 DEBUG(dbgs() << "\tPhysreg joins disabled.\n"); 1054 return false; 1055 } 1056 1057 // Only coalesce to allocatable physreg, we don't want to risk modifying 1058 // reserved registers. 1059 if (!Allocatable) { 1060 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n"); 1061 return false; // Not coalescable. 1062 } 1063 1064 // Don't join with physregs that have a ridiculous number of live 1065 // ranges. The data structure performance is really bad when that 1066 // happens. 1067 if (LIS->hasInterval(CP.getDstReg()) && 1068 LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) { 1069 ++numAborts; 1070 DEBUG(dbgs() 1071 << "\tPhysical register live interval too complicated, abort!\n"); 1072 return false; 1073 } 1074 1075 // FIXME: Why are we skipping this test for partial copies? 1076 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it. 1077 if (!CP.isPartial()) { 1078 const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg()); 1079 unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2; 1080 unsigned Length = LIS->getApproximateInstructionCount(JoinVInt); 1081 if (Length > Threshold) { 1082 ++numAborts; 1083 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n"); 1084 return false; 1085 } 1086 } 1087 return true; 1088 } 1089 1090 1091 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg, 1092 /// which are the src/dst of the copy instruction CopyMI. This returns true 1093 /// if the copy was successfully coalesced away. If it is not currently 1094 /// possible to coalesce this interval, but it may be possible if other 1095 /// things get coalesced, then it returns true by reference in 'Again'. 1096 bool RegisterCoalescer::JoinCopy(MachineInstr *CopyMI, bool &Again) { 1097 1098 Again = false; 1099 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI)) 1100 return false; // Already done. 1101 1102 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI); 1103 1104 CoalescerPair CP(*TII, *TRI); 1105 if (!CP.setRegisters(CopyMI)) { 1106 DEBUG(dbgs() << "\tNot coalescable.\n"); 1107 return false; 1108 } 1109 1110 // If they are already joined we continue. 1111 if (CP.getSrcReg() == CP.getDstReg()) { 1112 markAsJoined(CopyMI); 1113 DEBUG(dbgs() << "\tCopy already coalesced.\n"); 1114 return false; // Not coalescable. 1115 } 1116 1117 // Eliminate undefs. 1118 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) { 1119 markAsJoined(CopyMI); 1120 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n"); 1121 return false; // Not coalescable. 1122 } 1123 1124 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI) 1125 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx()) 1126 << "\n"); 1127 1128 // Enforce policies. 1129 if (CP.isPhys()) { 1130 if (!shouldJoinPhys(CP)) { 1131 // Before giving up coalescing, if definition of source is defined by 1132 // trivial computation, try rematerializing it. 1133 if (!CP.isFlipped() && 1134 ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true, 1135 CP.getDstReg(), CopyMI)) 1136 return true; 1137 return false; 1138 } 1139 } else { 1140 // Avoid constraining virtual register regclass too much. 1141 if (CP.isCrossClass()) { 1142 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n"); 1143 if (DisableCrossClassJoin) { 1144 DEBUG(dbgs() << "\tCross-class joins disabled.\n"); 1145 return false; 1146 } 1147 } 1148 1149 // When possible, let DstReg be the larger interval. 1150 if (!CP.getSubIdx() && LIS->getInterval(CP.getSrcReg()).ranges.size() > 1151 LIS->getInterval(CP.getDstReg()).ranges.size()) 1152 CP.flip(); 1153 } 1154 1155 // Okay, attempt to join these two intervals. On failure, this returns false. 1156 // Otherwise, if one of the intervals being joined is a physreg, this method 1157 // always canonicalizes DstInt to be it. The output "SrcInt" will not have 1158 // been modified, so we can use this information below to update aliases. 1159 if (!JoinIntervals(CP)) { 1160 // Coalescing failed. 1161 1162 // If definition of source is defined by trivial computation, try 1163 // rematerializing it. 1164 if (!CP.isFlipped() && 1165 ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true, 1166 CP.getDstReg(), CopyMI)) 1167 return true; 1168 1169 // If we can eliminate the copy without merging the live ranges, do so now. 1170 if (!CP.isPartial()) { 1171 if (AdjustCopiesBackFrom(CP, CopyMI) || 1172 RemoveCopyByCommutingDef(CP, CopyMI)) { 1173 markAsJoined(CopyMI); 1174 DEBUG(dbgs() << "\tTrivial!\n"); 1175 return true; 1176 } 1177 } 1178 1179 // Otherwise, we are unable to join the intervals. 1180 DEBUG(dbgs() << "\tInterference!\n"); 1181 Again = true; // May be possible to coalesce later. 1182 return false; 1183 } 1184 1185 // Coalescing to a virtual register that is of a sub-register class of the 1186 // other. Make sure the resulting register is set to the right register class. 1187 if (CP.isCrossClass()) { 1188 ++numCrossRCs; 1189 MRI->setRegClass(CP.getDstReg(), CP.getNewRC()); 1190 } 1191 1192 // Remember to delete the copy instruction. 1193 markAsJoined(CopyMI); 1194 1195 UpdateRegDefsUses(CP); 1196 1197 // If we have extended the live range of a physical register, make sure we 1198 // update live-in lists as well. 1199 if (CP.isPhys()) { 1200 SmallVector<MachineBasicBlock*, 16> BlockSeq; 1201 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the 1202 // ranges for this, and they are preserved. 1203 LiveInterval &SrcInt = LIS->getInterval(CP.getSrcReg()); 1204 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end(); 1205 I != E; ++I ) { 1206 LIS->findLiveInMBBs(I->start, I->end, BlockSeq); 1207 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) { 1208 MachineBasicBlock &block = *BlockSeq[idx]; 1209 if (!block.isLiveIn(CP.getDstReg())) 1210 block.addLiveIn(CP.getDstReg()); 1211 } 1212 BlockSeq.clear(); 1213 } 1214 } 1215 1216 // SrcReg is guarateed to be the register whose live interval that is 1217 // being merged. 1218 LIS->removeInterval(CP.getSrcReg()); 1219 1220 // Update regalloc hint. 1221 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF); 1222 1223 DEBUG({ 1224 LiveInterval &DstInt = LIS->getInterval(CP.getDstReg()); 1225 dbgs() << "\tJoined. Result = "; 1226 DstInt.print(dbgs(), TRI); 1227 dbgs() << "\n"; 1228 }); 1229 1230 ++numJoins; 1231 return true; 1232 } 1233 1234 /// ComputeUltimateVN - Assuming we are going to join two live intervals, 1235 /// compute what the resultant value numbers for each value in the input two 1236 /// ranges will be. This is complicated by copies between the two which can 1237 /// and will commonly cause multiple value numbers to be merged into one. 1238 /// 1239 /// VN is the value number that we're trying to resolve. InstDefiningValue 1240 /// keeps track of the new InstDefiningValue assignment for the result 1241 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of 1242 /// whether a value in this or other is a copy from the opposite set. 1243 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have 1244 /// already been assigned. 1245 /// 1246 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this 1247 /// contains the value number the copy is from. 1248 /// 1249 static unsigned ComputeUltimateVN(VNInfo *VNI, 1250 SmallVector<VNInfo*, 16> &NewVNInfo, 1251 DenseMap<VNInfo*, VNInfo*> &ThisFromOther, 1252 DenseMap<VNInfo*, VNInfo*> &OtherFromThis, 1253 SmallVector<int, 16> &ThisValNoAssignments, 1254 SmallVector<int, 16> &OtherValNoAssignments) { 1255 unsigned VN = VNI->id; 1256 1257 // If the VN has already been computed, just return it. 1258 if (ThisValNoAssignments[VN] >= 0) 1259 return ThisValNoAssignments[VN]; 1260 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers"); 1261 1262 // If this val is not a copy from the other val, then it must be a new value 1263 // number in the destination. 1264 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI); 1265 if (I == ThisFromOther.end()) { 1266 NewVNInfo.push_back(VNI); 1267 return ThisValNoAssignments[VN] = NewVNInfo.size()-1; 1268 } 1269 VNInfo *OtherValNo = I->second; 1270 1271 // Otherwise, this *is* a copy from the RHS. If the other side has already 1272 // been computed, return it. 1273 if (OtherValNoAssignments[OtherValNo->id] >= 0) 1274 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id]; 1275 1276 // Mark this value number as currently being computed, then ask what the 1277 // ultimate value # of the other value is. 1278 ThisValNoAssignments[VN] = -2; 1279 unsigned UltimateVN = 1280 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther, 1281 OtherValNoAssignments, ThisValNoAssignments); 1282 return ThisValNoAssignments[VN] = UltimateVN; 1283 } 1284 1285 1286 // Find out if we have something like 1287 // A = X 1288 // B = X 1289 // if so, we can pretend this is actually 1290 // A = X 1291 // B = A 1292 // which allows us to coalesce A and B. 1293 // VNI is the definition of B. LR is the life range of A that includes 1294 // the slot just before B. If we return true, we add "B = X" to DupCopies. 1295 // This implies that A dominates B. 1296 static bool RegistersDefinedFromSameValue(LiveIntervals &li, 1297 const TargetRegisterInfo &tri, 1298 CoalescerPair &CP, 1299 VNInfo *VNI, 1300 LiveRange *LR, 1301 SmallVector<MachineInstr*, 8> &DupCopies) { 1302 // FIXME: This is very conservative. For example, we don't handle 1303 // physical registers. 1304 1305 MachineInstr *MI = VNI->getCopy(); 1306 1307 if (!MI->isFullCopy() || CP.isPartial() || CP.isPhys()) 1308 return false; 1309 1310 unsigned Dst = MI->getOperand(0).getReg(); 1311 unsigned Src = MI->getOperand(1).getReg(); 1312 1313 if (!TargetRegisterInfo::isVirtualRegister(Src) || 1314 !TargetRegisterInfo::isVirtualRegister(Dst)) 1315 return false; 1316 1317 unsigned A = CP.getDstReg(); 1318 unsigned B = CP.getSrcReg(); 1319 1320 if (B == Dst) 1321 std::swap(A, B); 1322 assert(Dst == A); 1323 1324 VNInfo *Other = LR->valno; 1325 if (!Other->isDefByCopy()) 1326 return false; 1327 const MachineInstr *OtherMI = Other->getCopy(); 1328 1329 if (!OtherMI->isFullCopy()) 1330 return false; 1331 1332 unsigned OtherDst = OtherMI->getOperand(0).getReg(); 1333 unsigned OtherSrc = OtherMI->getOperand(1).getReg(); 1334 1335 if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) || 1336 !TargetRegisterInfo::isVirtualRegister(OtherDst)) 1337 return false; 1338 1339 assert(OtherDst == B); 1340 1341 if (Src != OtherSrc) 1342 return false; 1343 1344 // If the copies use two different value numbers of X, we cannot merge 1345 // A and B. 1346 LiveInterval &SrcInt = li.getInterval(Src); 1347 // getVNInfoBefore returns NULL for undef copies. In this case, the 1348 // optimization is still safe. 1349 if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def)) 1350 return false; 1351 1352 DupCopies.push_back(MI); 1353 1354 return true; 1355 } 1356 1357 /// JoinIntervals - Attempt to join these two intervals. On failure, this 1358 /// returns false. 1359 bool RegisterCoalescer::JoinIntervals(CoalescerPair &CP) { 1360 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg()); 1361 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; }); 1362 1363 // If a live interval is a physical register, check for interference with any 1364 // aliases. The interference check implemented here is a bit more conservative 1365 // than the full interfeence check below. We allow overlapping live ranges 1366 // only when one is a copy of the other. 1367 if (CP.isPhys()) { 1368 for (const unsigned *AS = TRI->getAliasSet(CP.getDstReg()); *AS; ++AS){ 1369 if (!LIS->hasInterval(*AS)) 1370 continue; 1371 const LiveInterval &LHS = LIS->getInterval(*AS); 1372 LiveInterval::const_iterator LI = LHS.begin(); 1373 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end(); 1374 RI != RE; ++RI) { 1375 LI = std::lower_bound(LI, LHS.end(), RI->start); 1376 // Does LHS have an overlapping live range starting before RI? 1377 if ((LI != LHS.begin() && LI[-1].end > RI->start) && 1378 (RI->start != RI->valno->def || 1379 !CP.isCoalescable(LIS->getInstructionFromIndex(RI->start)))) { 1380 DEBUG({ 1381 dbgs() << "\t\tInterference from alias: "; 1382 LHS.print(dbgs(), TRI); 1383 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n"; 1384 }); 1385 return false; 1386 } 1387 1388 // Check that LHS ranges beginning in this range are copies. 1389 for (; LI != LHS.end() && LI->start < RI->end; ++LI) { 1390 if (LI->start != LI->valno->def || 1391 !CP.isCoalescable(LIS->getInstructionFromIndex(LI->start))) { 1392 DEBUG({ 1393 dbgs() << "\t\tInterference from alias: "; 1394 LHS.print(dbgs(), TRI); 1395 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n"; 1396 }); 1397 return false; 1398 } 1399 } 1400 } 1401 } 1402 } 1403 1404 // Compute the final value assignment, assuming that the live ranges can be 1405 // coalesced. 1406 SmallVector<int, 16> LHSValNoAssignments; 1407 SmallVector<int, 16> RHSValNoAssignments; 1408 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS; 1409 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS; 1410 SmallVector<VNInfo*, 16> NewVNInfo; 1411 1412 SmallVector<MachineInstr*, 8> DupCopies; 1413 1414 LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg()); 1415 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; }); 1416 1417 // Loop over the value numbers of the LHS, seeing if any are defined from 1418 // the RHS. 1419 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end(); 1420 i != e; ++i) { 1421 VNInfo *VNI = *i; 1422 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy? 1423 continue; 1424 1425 // Never join with a register that has EarlyClobber redefs. 1426 if (VNI->hasRedefByEC()) 1427 return false; 1428 1429 // Figure out the value # from the RHS. 1430 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot()); 1431 // The copy could be to an aliased physreg. 1432 if (!lr) continue; 1433 1434 // DstReg is known to be a register in the LHS interval. If the src is 1435 // from the RHS interval, we can use its value #. 1436 MachineInstr *MI = VNI->getCopy(); 1437 if (!CP.isCoalescable(MI) && 1438 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies)) 1439 continue; 1440 1441 LHSValsDefinedFromRHS[VNI] = lr->valno; 1442 } 1443 1444 // Loop over the value numbers of the RHS, seeing if any are defined from 1445 // the LHS. 1446 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end(); 1447 i != e; ++i) { 1448 VNInfo *VNI = *i; 1449 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy? 1450 continue; 1451 1452 // Never join with a register that has EarlyClobber redefs. 1453 if (VNI->hasRedefByEC()) 1454 return false; 1455 1456 // Figure out the value # from the LHS. 1457 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot()); 1458 // The copy could be to an aliased physreg. 1459 if (!lr) continue; 1460 1461 // DstReg is known to be a register in the RHS interval. If the src is 1462 // from the LHS interval, we can use its value #. 1463 MachineInstr *MI = VNI->getCopy(); 1464 if (!CP.isCoalescable(MI) && 1465 !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies)) 1466 continue; 1467 1468 RHSValsDefinedFromLHS[VNI] = lr->valno; 1469 } 1470 1471 LHSValNoAssignments.resize(LHS.getNumValNums(), -1); 1472 RHSValNoAssignments.resize(RHS.getNumValNums(), -1); 1473 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums()); 1474 1475 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end(); 1476 i != e; ++i) { 1477 VNInfo *VNI = *i; 1478 unsigned VN = VNI->id; 1479 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused()) 1480 continue; 1481 ComputeUltimateVN(VNI, NewVNInfo, 1482 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS, 1483 LHSValNoAssignments, RHSValNoAssignments); 1484 } 1485 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end(); 1486 i != e; ++i) { 1487 VNInfo *VNI = *i; 1488 unsigned VN = VNI->id; 1489 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused()) 1490 continue; 1491 // If this value number isn't a copy from the LHS, it's a new number. 1492 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) { 1493 NewVNInfo.push_back(VNI); 1494 RHSValNoAssignments[VN] = NewVNInfo.size()-1; 1495 continue; 1496 } 1497 1498 ComputeUltimateVN(VNI, NewVNInfo, 1499 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS, 1500 RHSValNoAssignments, LHSValNoAssignments); 1501 } 1502 1503 // Armed with the mappings of LHS/RHS values to ultimate values, walk the 1504 // interval lists to see if these intervals are coalescable. 1505 LiveInterval::const_iterator I = LHS.begin(); 1506 LiveInterval::const_iterator IE = LHS.end(); 1507 LiveInterval::const_iterator J = RHS.begin(); 1508 LiveInterval::const_iterator JE = RHS.end(); 1509 1510 // Skip ahead until the first place of potential sharing. 1511 if (I != IE && J != JE) { 1512 if (I->start < J->start) { 1513 I = std::upper_bound(I, IE, J->start); 1514 if (I != LHS.begin()) --I; 1515 } else if (J->start < I->start) { 1516 J = std::upper_bound(J, JE, I->start); 1517 if (J != RHS.begin()) --J; 1518 } 1519 } 1520 1521 while (I != IE && J != JE) { 1522 // Determine if these two live ranges overlap. 1523 bool Overlaps; 1524 if (I->start < J->start) { 1525 Overlaps = I->end > J->start; 1526 } else { 1527 Overlaps = J->end > I->start; 1528 } 1529 1530 // If so, check value # info to determine if they are really different. 1531 if (Overlaps) { 1532 // If the live range overlap will map to the same value number in the 1533 // result liverange, we can still coalesce them. If not, we can't. 1534 if (LHSValNoAssignments[I->valno->id] != 1535 RHSValNoAssignments[J->valno->id]) 1536 return false; 1537 // If it's re-defined by an early clobber somewhere in the live range, 1538 // then conservatively abort coalescing. 1539 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC()) 1540 return false; 1541 } 1542 1543 if (I->end < J->end) 1544 ++I; 1545 else 1546 ++J; 1547 } 1548 1549 // Update kill info. Some live ranges are extended due to copy coalescing. 1550 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(), 1551 E = LHSValsDefinedFromRHS.end(); I != E; ++I) { 1552 VNInfo *VNI = I->first; 1553 unsigned LHSValID = LHSValNoAssignments[VNI->id]; 1554 if (VNI->hasPHIKill()) 1555 NewVNInfo[LHSValID]->setHasPHIKill(true); 1556 } 1557 1558 // Update kill info. Some live ranges are extended due to copy coalescing. 1559 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(), 1560 E = RHSValsDefinedFromLHS.end(); I != E; ++I) { 1561 VNInfo *VNI = I->first; 1562 unsigned RHSValID = RHSValNoAssignments[VNI->id]; 1563 if (VNI->hasPHIKill()) 1564 NewVNInfo[RHSValID]->setHasPHIKill(true); 1565 } 1566 1567 if (LHSValNoAssignments.empty()) 1568 LHSValNoAssignments.push_back(-1); 1569 if (RHSValNoAssignments.empty()) 1570 RHSValNoAssignments.push_back(-1); 1571 1572 SmallVector<unsigned, 8> SourceRegisters; 1573 for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(), 1574 E = DupCopies.end(); I != E; ++I) { 1575 MachineInstr *MI = *I; 1576 1577 // We have pretended that the assignment to B in 1578 // A = X 1579 // B = X 1580 // was actually a copy from A. Now that we decided to coalesce A and B, 1581 // transform the code into 1582 // A = X 1583 // X = X 1584 // and mark the X as coalesced to keep the illusion. 1585 unsigned Src = MI->getOperand(1).getReg(); 1586 SourceRegisters.push_back(Src); 1587 MI->getOperand(0).substVirtReg(Src, 0, *TRI); 1588 1589 markAsJoined(MI); 1590 } 1591 1592 // If B = X was the last use of X in a liverange, we have to shrink it now 1593 // that B = X is gone. 1594 for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(), 1595 E = SourceRegisters.end(); I != E; ++I) { 1596 LIS->shrinkToUses(&LIS->getInterval(*I)); 1597 } 1598 1599 // If we get here, we know that we can coalesce the live ranges. Ask the 1600 // intervals to coalesce themselves now. 1601 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo, 1602 MRI); 1603 return true; 1604 } 1605 1606 namespace { 1607 // DepthMBBCompare - Comparison predicate that sort first based on the loop 1608 // depth of the basic block (the unsigned), and then on the MBB number. 1609 struct DepthMBBCompare { 1610 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair; 1611 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const { 1612 // Deeper loops first 1613 if (LHS.first != RHS.first) 1614 return LHS.first > RHS.first; 1615 1616 // Prefer blocks that are more connected in the CFG. This takes care of 1617 // the most difficult copies first while intervals are short. 1618 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size(); 1619 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size(); 1620 if (cl != cr) 1621 return cl > cr; 1622 1623 // As a last resort, sort by block number. 1624 return LHS.second->getNumber() < RHS.second->getNumber(); 1625 } 1626 }; 1627 } 1628 1629 void RegisterCoalescer::CopyCoalesceInMBB(MachineBasicBlock *MBB, 1630 std::vector<MachineInstr*> &TryAgain) { 1631 DEBUG(dbgs() << MBB->getName() << ":\n"); 1632 1633 SmallVector<MachineInstr*, 8> VirtCopies; 1634 SmallVector<MachineInstr*, 8> PhysCopies; 1635 SmallVector<MachineInstr*, 8> ImpDefCopies; 1636 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); 1637 MII != E;) { 1638 MachineInstr *Inst = MII++; 1639 1640 // If this isn't a copy nor a extract_subreg, we can't join intervals. 1641 unsigned SrcReg, DstReg; 1642 if (Inst->isCopy()) { 1643 DstReg = Inst->getOperand(0).getReg(); 1644 SrcReg = Inst->getOperand(1).getReg(); 1645 } else if (Inst->isSubregToReg()) { 1646 DstReg = Inst->getOperand(0).getReg(); 1647 SrcReg = Inst->getOperand(2).getReg(); 1648 } else 1649 continue; 1650 1651 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg); 1652 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 1653 if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty()) 1654 ImpDefCopies.push_back(Inst); 1655 else if (SrcIsPhys || DstIsPhys) 1656 PhysCopies.push_back(Inst); 1657 else 1658 VirtCopies.push_back(Inst); 1659 } 1660 1661 // Try coalescing implicit copies and insert_subreg <undef> first, 1662 // followed by copies to / from physical registers, then finally copies 1663 // from virtual registers to virtual registers. 1664 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) { 1665 MachineInstr *TheCopy = ImpDefCopies[i]; 1666 bool Again = false; 1667 if (!JoinCopy(TheCopy, Again)) 1668 if (Again) 1669 TryAgain.push_back(TheCopy); 1670 } 1671 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) { 1672 MachineInstr *TheCopy = PhysCopies[i]; 1673 bool Again = false; 1674 if (!JoinCopy(TheCopy, Again)) 1675 if (Again) 1676 TryAgain.push_back(TheCopy); 1677 } 1678 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) { 1679 MachineInstr *TheCopy = VirtCopies[i]; 1680 bool Again = false; 1681 if (!JoinCopy(TheCopy, Again)) 1682 if (Again) 1683 TryAgain.push_back(TheCopy); 1684 } 1685 } 1686 1687 void RegisterCoalescer::joinIntervals() { 1688 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n"); 1689 1690 std::vector<MachineInstr*> TryAgainList; 1691 if (Loops->empty()) { 1692 // If there are no loops in the function, join intervals in function order. 1693 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); 1694 I != E; ++I) 1695 CopyCoalesceInMBB(I, TryAgainList); 1696 } else { 1697 // Otherwise, join intervals in inner loops before other intervals. 1698 // Unfortunately we can't just iterate over loop hierarchy here because 1699 // there may be more MBB's than BB's. Collect MBB's for sorting. 1700 1701 // Join intervals in the function prolog first. We want to join physical 1702 // registers with virtual registers before the intervals got too long. 1703 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs; 1704 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){ 1705 MachineBasicBlock *MBB = I; 1706 MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I)); 1707 } 1708 1709 // Sort by loop depth. 1710 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare()); 1711 1712 // Finally, join intervals in loop nest order. 1713 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) 1714 CopyCoalesceInMBB(MBBs[i].second, TryAgainList); 1715 } 1716 1717 // Joining intervals can allow other intervals to be joined. Iteratively join 1718 // until we make no progress. 1719 bool ProgressMade = true; 1720 while (ProgressMade) { 1721 ProgressMade = false; 1722 1723 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) { 1724 MachineInstr *&TheCopy = TryAgainList[i]; 1725 if (!TheCopy) 1726 continue; 1727 1728 bool Again = false; 1729 bool Success = JoinCopy(TheCopy, Again); 1730 if (Success || !Again) { 1731 TheCopy= 0; // Mark this one as done. 1732 ProgressMade = true; 1733 } 1734 } 1735 } 1736 } 1737 1738 void RegisterCoalescer::releaseMemory() { 1739 JoinedCopies.clear(); 1740 ReMatCopies.clear(); 1741 ReMatDefs.clear(); 1742 } 1743 1744 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) { 1745 MF = &fn; 1746 MRI = &fn.getRegInfo(); 1747 TM = &fn.getTarget(); 1748 TRI = TM->getRegisterInfo(); 1749 TII = TM->getInstrInfo(); 1750 LIS = &getAnalysis<LiveIntervals>(); 1751 LDV = &getAnalysis<LiveDebugVariables>(); 1752 AA = &getAnalysis<AliasAnalysis>(); 1753 Loops = &getAnalysis<MachineLoopInfo>(); 1754 1755 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n" 1756 << "********** Function: " 1757 << ((Value*)MF->getFunction())->getName() << '\n'); 1758 1759 if (VerifyCoalescing) 1760 MF->verify(this, "Before register coalescing"); 1761 1762 RegClassInfo.runOnMachineFunction(fn); 1763 1764 // Join (coalesce) intervals if requested. 1765 if (EnableJoining) { 1766 joinIntervals(); 1767 DEBUG({ 1768 dbgs() << "********** INTERVALS POST JOINING **********\n"; 1769 for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); 1770 I != E; ++I){ 1771 I->second->print(dbgs(), TRI); 1772 dbgs() << "\n"; 1773 } 1774 }); 1775 } 1776 1777 // Perform a final pass over the instructions and compute spill weights 1778 // and remove identity moves. 1779 SmallVector<unsigned, 4> DeadDefs, InflateRegs; 1780 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end(); 1781 mbbi != mbbe; ++mbbi) { 1782 MachineBasicBlock* mbb = mbbi; 1783 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end(); 1784 mii != mie; ) { 1785 MachineInstr *MI = mii; 1786 if (JoinedCopies.count(MI)) { 1787 // Delete all coalesced copies. 1788 bool DoDelete = true; 1789 assert(MI->isCopyLike() && "Unrecognized copy instruction"); 1790 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg(); 1791 unsigned DstReg = MI->getOperand(0).getReg(); 1792 1793 // Collect candidates for register class inflation. 1794 if (TargetRegisterInfo::isVirtualRegister(SrcReg) && 1795 RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg))) 1796 InflateRegs.push_back(SrcReg); 1797 if (TargetRegisterInfo::isVirtualRegister(DstReg) && 1798 RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg))) 1799 InflateRegs.push_back(DstReg); 1800 1801 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) && 1802 MI->getNumOperands() > 2) 1803 // Do not delete extract_subreg, insert_subreg of physical 1804 // registers unless the definition is dead. e.g. 1805 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1 1806 // or else the scavenger may complain. LowerSubregs will 1807 // delete them later. 1808 DoDelete = false; 1809 1810 if (MI->allDefsAreDead()) { 1811 if (TargetRegisterInfo::isVirtualRegister(SrcReg) && 1812 LIS->hasInterval(SrcReg)) 1813 LIS->shrinkToUses(&LIS->getInterval(SrcReg)); 1814 DoDelete = true; 1815 } 1816 if (!DoDelete) { 1817 // We need the instruction to adjust liveness, so make it a KILL. 1818 if (MI->isSubregToReg()) { 1819 MI->RemoveOperand(3); 1820 MI->RemoveOperand(1); 1821 } 1822 MI->setDesc(TII->get(TargetOpcode::KILL)); 1823 mii = llvm::next(mii); 1824 } else { 1825 LIS->RemoveMachineInstrFromMaps(MI); 1826 mii = mbbi->erase(mii); 1827 ++numPeep; 1828 } 1829 continue; 1830 } 1831 1832 // Now check if this is a remat'ed def instruction which is now dead. 1833 if (ReMatDefs.count(MI)) { 1834 bool isDead = true; 1835 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1836 const MachineOperand &MO = MI->getOperand(i); 1837 if (!MO.isReg()) 1838 continue; 1839 unsigned Reg = MO.getReg(); 1840 if (!Reg) 1841 continue; 1842 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1843 DeadDefs.push_back(Reg); 1844 // Remat may also enable register class inflation. 1845 if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg))) 1846 InflateRegs.push_back(Reg); 1847 } 1848 if (MO.isDead()) 1849 continue; 1850 if (TargetRegisterInfo::isPhysicalRegister(Reg) || 1851 !MRI->use_nodbg_empty(Reg)) { 1852 isDead = false; 1853 break; 1854 } 1855 } 1856 if (isDead) { 1857 while (!DeadDefs.empty()) { 1858 unsigned DeadDef = DeadDefs.back(); 1859 DeadDefs.pop_back(); 1860 RemoveDeadDef(LIS->getInterval(DeadDef), MI); 1861 } 1862 LIS->RemoveMachineInstrFromMaps(mii); 1863 mii = mbbi->erase(mii); 1864 continue; 1865 } else 1866 DeadDefs.clear(); 1867 } 1868 1869 ++mii; 1870 1871 // Check for now unnecessary kill flags. 1872 if (LIS->isNotInMIMap(MI)) continue; 1873 SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot(); 1874 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1875 MachineOperand &MO = MI->getOperand(i); 1876 if (!MO.isReg() || !MO.isKill()) continue; 1877 unsigned reg = MO.getReg(); 1878 if (!reg || !LIS->hasInterval(reg)) continue; 1879 if (!LIS->getInterval(reg).killedAt(DefIdx)) { 1880 MO.setIsKill(false); 1881 continue; 1882 } 1883 // When leaving a kill flag on a physreg, check if any subregs should 1884 // remain alive. 1885 if (!TargetRegisterInfo::isPhysicalRegister(reg)) 1886 continue; 1887 for (const unsigned *SR = TRI->getSubRegisters(reg); 1888 unsigned S = *SR; ++SR) 1889 if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx)) 1890 MI->addRegisterDefined(S, TRI); 1891 } 1892 } 1893 } 1894 1895 // After deleting a lot of copies, register classes may be less constrained. 1896 // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 -> 1897 // DPR inflation. 1898 array_pod_sort(InflateRegs.begin(), InflateRegs.end()); 1899 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()), 1900 InflateRegs.end()); 1901 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n"); 1902 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) { 1903 unsigned Reg = InflateRegs[i]; 1904 if (MRI->reg_nodbg_empty(Reg)) 1905 continue; 1906 if (MRI->recomputeRegClass(Reg, *TM)) { 1907 DEBUG(dbgs() << PrintReg(Reg) << " inflated to " 1908 << MRI->getRegClass(Reg)->getName() << '\n'); 1909 ++NumInflated; 1910 } 1911 } 1912 1913 DEBUG(dump()); 1914 DEBUG(LDV->dump()); 1915 if (VerifyCoalescing) 1916 MF->verify(this, "After register coalescing"); 1917 return true; 1918 } 1919 1920 /// print - Implement the dump method. 1921 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const { 1922 LIS->print(O, m); 1923 } 1924