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 "regalloc" 17 #include "RegisterCoalescer.h" 18 #include "llvm/ADT/OwningPtr.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 24 #include "llvm/CodeGen/LiveRangeEdit.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineInstr.h" 27 #include "llvm/CodeGen/MachineLoopInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/Passes.h" 30 #include "llvm/CodeGen/RegisterClassInfo.h" 31 #include "llvm/CodeGen/VirtRegMap.h" 32 #include "llvm/IR/Value.h" 33 #include "llvm/Pass.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Target/TargetInstrInfo.h" 39 #include "llvm/Target/TargetMachine.h" 40 #include "llvm/Target/TargetRegisterInfo.h" 41 #include "llvm/Target/TargetSubtargetInfo.h" 42 #include <algorithm> 43 #include <cmath> 44 using namespace llvm; 45 46 STATISTIC(numJoins , "Number of interval joins performed"); 47 STATISTIC(numCrossRCs , "Number of cross class joins performed"); 48 STATISTIC(numCommutes , "Number of instruction commuting performed"); 49 STATISTIC(numExtends , "Number of copies extended"); 50 STATISTIC(NumReMats , "Number of instructions re-materialized"); 51 STATISTIC(NumInflated , "Number of register classes inflated"); 52 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested"); 53 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved"); 54 55 static cl::opt<bool> 56 EnableJoining("join-liveintervals", 57 cl::desc("Coalesce copies (default=true)"), 58 cl::init(true)); 59 60 // Temporary flag to test critical edge unsplitting. 61 static cl::opt<bool> 62 EnableJoinSplits("join-splitedges", 63 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden); 64 65 // Temporary flag to test global copy optimization. 66 static cl::opt<cl::boolOrDefault> 67 EnableGlobalCopies("join-globalcopies", 68 cl::desc("Coalesce copies that span blocks (default=subtarget)"), 69 cl::init(cl::BOU_UNSET), cl::Hidden); 70 71 static cl::opt<bool> 72 VerifyCoalescing("verify-coalescing", 73 cl::desc("Verify machine instrs before and after register coalescing"), 74 cl::Hidden); 75 76 namespace { 77 class RegisterCoalescer : public MachineFunctionPass, 78 private LiveRangeEdit::Delegate { 79 MachineFunction* MF; 80 MachineRegisterInfo* MRI; 81 const TargetMachine* TM; 82 const TargetRegisterInfo* TRI; 83 const TargetInstrInfo* TII; 84 LiveIntervals *LIS; 85 const MachineLoopInfo* Loops; 86 AliasAnalysis *AA; 87 RegisterClassInfo RegClassInfo; 88 89 /// \brief True if the coalescer should aggressively coalesce global copies 90 /// in favor of keeping local copies. 91 bool JoinGlobalCopies; 92 93 /// \brief True if the coalescer should aggressively coalesce fall-thru 94 /// blocks exclusively containing copies. 95 bool JoinSplitEdges; 96 97 /// WorkList - Copy instructions yet to be coalesced. 98 SmallVector<MachineInstr*, 8> WorkList; 99 SmallVector<MachineInstr*, 8> LocalWorkList; 100 101 /// ErasedInstrs - Set of instruction pointers that have been erased, and 102 /// that may be present in WorkList. 103 SmallPtrSet<MachineInstr*, 8> ErasedInstrs; 104 105 /// Dead instructions that are about to be deleted. 106 SmallVector<MachineInstr*, 8> DeadDefs; 107 108 /// Virtual registers to be considered for register class inflation. 109 SmallVector<unsigned, 8> InflateRegs; 110 111 /// Recursively eliminate dead defs in DeadDefs. 112 void eliminateDeadDefs(); 113 114 /// LiveRangeEdit callback. 115 void LRE_WillEraseInstruction(MachineInstr *MI); 116 117 /// coalesceLocals - coalesce the LocalWorkList. 118 void coalesceLocals(); 119 120 /// joinAllIntervals - join compatible live intervals 121 void joinAllIntervals(); 122 123 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting 124 /// copies that cannot yet be coalesced into WorkList. 125 void copyCoalesceInMBB(MachineBasicBlock *MBB); 126 127 /// copyCoalesceWorkList - Try to coalesce all copies in CurrList. Return 128 /// true if any progress was made. 129 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList); 130 131 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg, 132 /// which are the src/dst of the copy instruction CopyMI. This returns 133 /// true if the copy was successfully coalesced away. If it is not 134 /// currently possible to coalesce this interval, but it may be possible if 135 /// other things get coalesced, then it returns true by reference in 136 /// 'Again'. 137 bool joinCopy(MachineInstr *TheCopy, bool &Again); 138 139 /// joinIntervals - Attempt to join these two intervals. On failure, this 140 /// returns false. The output "SrcInt" will not have been modified, so we 141 /// can use this information below to update aliases. 142 bool joinIntervals(CoalescerPair &CP); 143 144 /// Attempt joining two virtual registers. Return true on success. 145 bool joinVirtRegs(CoalescerPair &CP); 146 147 /// Attempt joining with a reserved physreg. 148 bool joinReservedPhysReg(CoalescerPair &CP); 149 150 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If 151 /// the source value number is defined by a copy from the destination reg 152 /// see if we can merge these two destination reg valno# into a single 153 /// value number, eliminating a copy. 154 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI); 155 156 /// hasOtherReachingDefs - Return true if there are definitions of IntB 157 /// other than BValNo val# that can reach uses of AValno val# of IntA. 158 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB, 159 VNInfo *AValNo, VNInfo *BValNo); 160 161 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy. 162 /// If the source value number is defined by a commutable instruction and 163 /// its other operand is coalesced to the copy dest register, see if we 164 /// can transform the copy into a noop by commuting the definition. 165 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI); 166 167 /// reMaterializeTrivialDef - If the source of a copy is defined by a 168 /// trivial computation, replace the copy by rematerialize the definition. 169 bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI, 170 bool &IsDefCopy); 171 172 /// canJoinPhys - Return true if a physreg copy should be joined. 173 bool canJoinPhys(const CoalescerPair &CP); 174 175 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and 176 /// update the subregister number if it is not zero. If DstReg is a 177 /// physical register and the existing subregister number of the def / use 178 /// being updated is not zero, make sure to set it to the correct physical 179 /// subregister. 180 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx); 181 182 /// eliminateUndefCopy - Handle copies of undef values. 183 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP); 184 185 public: 186 static char ID; // Class identification, replacement for typeinfo 187 RegisterCoalescer() : MachineFunctionPass(ID) { 188 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); 189 } 190 191 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 192 193 virtual void releaseMemory(); 194 195 /// runOnMachineFunction - pass entry point 196 virtual bool runOnMachineFunction(MachineFunction&); 197 198 /// print - Implement the dump method. 199 virtual void print(raw_ostream &O, const Module* = 0) const; 200 }; 201 } /// end anonymous namespace 202 203 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID; 204 205 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing", 206 "Simple Register Coalescing", false, false) 207 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 208 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 209 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 210 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 211 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing", 212 "Simple Register Coalescing", false, false) 213 214 char RegisterCoalescer::ID = 0; 215 216 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, 217 unsigned &Src, unsigned &Dst, 218 unsigned &SrcSub, unsigned &DstSub) { 219 if (MI->isCopy()) { 220 Dst = MI->getOperand(0).getReg(); 221 DstSub = MI->getOperand(0).getSubReg(); 222 Src = MI->getOperand(1).getReg(); 223 SrcSub = MI->getOperand(1).getSubReg(); 224 } else if (MI->isSubregToReg()) { 225 Dst = MI->getOperand(0).getReg(); 226 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(), 227 MI->getOperand(3).getImm()); 228 Src = MI->getOperand(2).getReg(); 229 SrcSub = MI->getOperand(2).getSubReg(); 230 } else 231 return false; 232 return true; 233 } 234 235 // Return true if this block should be vacated by the coalescer to eliminate 236 // branches. The important cases to handle in the coalescer are critical edges 237 // split during phi elimination which contain only copies. Simple blocks that 238 // contain non-branches should also be vacated, but this can be handled by an 239 // earlier pass similar to early if-conversion. 240 static bool isSplitEdge(const MachineBasicBlock *MBB) { 241 if (MBB->pred_size() != 1 || MBB->succ_size() != 1) 242 return false; 243 244 for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end(); 245 MII != E; ++MII) { 246 if (!MII->isCopyLike() && !MII->isUnconditionalBranch()) 247 return false; 248 } 249 return true; 250 } 251 252 bool CoalescerPair::setRegisters(const MachineInstr *MI) { 253 SrcReg = DstReg = 0; 254 SrcIdx = DstIdx = 0; 255 NewRC = 0; 256 Flipped = CrossClass = false; 257 258 unsigned Src, Dst, SrcSub, DstSub; 259 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 260 return false; 261 Partial = SrcSub || DstSub; 262 263 // If one register is a physreg, it must be Dst. 264 if (TargetRegisterInfo::isPhysicalRegister(Src)) { 265 if (TargetRegisterInfo::isPhysicalRegister(Dst)) 266 return false; 267 std::swap(Src, Dst); 268 std::swap(SrcSub, DstSub); 269 Flipped = true; 270 } 271 272 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); 273 274 if (TargetRegisterInfo::isPhysicalRegister(Dst)) { 275 // Eliminate DstSub on a physreg. 276 if (DstSub) { 277 Dst = TRI.getSubReg(Dst, DstSub); 278 if (!Dst) return false; 279 DstSub = 0; 280 } 281 282 // Eliminate SrcSub by picking a corresponding Dst superregister. 283 if (SrcSub) { 284 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src)); 285 if (!Dst) return false; 286 SrcSub = 0; 287 } else if (!MRI.getRegClass(Src)->contains(Dst)) { 288 return false; 289 } 290 } else { 291 // Both registers are virtual. 292 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src); 293 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst); 294 295 // Both registers have subreg indices. 296 if (SrcSub && DstSub) { 297 // Copies between different sub-registers are never coalescable. 298 if (Src == Dst && SrcSub != DstSub) 299 return false; 300 301 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub, 302 SrcIdx, DstIdx); 303 if (!NewRC) 304 return false; 305 } else if (DstSub) { 306 // SrcReg will be merged with a sub-register of DstReg. 307 SrcIdx = DstSub; 308 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub); 309 } else if (SrcSub) { 310 // DstReg will be merged with a sub-register of SrcReg. 311 DstIdx = SrcSub; 312 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub); 313 } else { 314 // This is a straight copy without sub-registers. 315 NewRC = TRI.getCommonSubClass(DstRC, SrcRC); 316 } 317 318 // The combined constraint may be impossible to satisfy. 319 if (!NewRC) 320 return false; 321 322 // Prefer SrcReg to be a sub-register of DstReg. 323 // FIXME: Coalescer should support subregs symmetrically. 324 if (DstIdx && !SrcIdx) { 325 std::swap(Src, Dst); 326 std::swap(SrcIdx, DstIdx); 327 Flipped = !Flipped; 328 } 329 330 CrossClass = NewRC != DstRC || NewRC != SrcRC; 331 } 332 // Check our invariants 333 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual"); 334 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) && 335 "Cannot have a physical SubIdx"); 336 SrcReg = Src; 337 DstReg = Dst; 338 return true; 339 } 340 341 bool CoalescerPair::flip() { 342 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) 343 return false; 344 std::swap(SrcReg, DstReg); 345 std::swap(SrcIdx, DstIdx); 346 Flipped = !Flipped; 347 return true; 348 } 349 350 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const { 351 if (!MI) 352 return false; 353 unsigned Src, Dst, SrcSub, DstSub; 354 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub)) 355 return false; 356 357 // Find the virtual register that is SrcReg. 358 if (Dst == SrcReg) { 359 std::swap(Src, Dst); 360 std::swap(SrcSub, DstSub); 361 } else if (Src != SrcReg) { 362 return false; 363 } 364 365 // Now check that Dst matches DstReg. 366 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { 367 if (!TargetRegisterInfo::isPhysicalRegister(Dst)) 368 return false; 369 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state."); 370 // DstSub could be set for a physreg from INSERT_SUBREG. 371 if (DstSub) 372 Dst = TRI.getSubReg(Dst, DstSub); 373 // Full copy of Src. 374 if (!SrcSub) 375 return DstReg == Dst; 376 // This is a partial register copy. Check that the parts match. 377 return TRI.getSubReg(DstReg, SrcSub) == Dst; 378 } else { 379 // DstReg is virtual. 380 if (DstReg != Dst) 381 return false; 382 // Registers match, do the subregisters line up? 383 return TRI.composeSubRegIndices(SrcIdx, SrcSub) == 384 TRI.composeSubRegIndices(DstIdx, DstSub); 385 } 386 } 387 388 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const { 389 AU.setPreservesCFG(); 390 AU.addRequired<AliasAnalysis>(); 391 AU.addRequired<LiveIntervals>(); 392 AU.addPreserved<LiveIntervals>(); 393 AU.addPreserved<SlotIndexes>(); 394 AU.addRequired<MachineLoopInfo>(); 395 AU.addPreserved<MachineLoopInfo>(); 396 AU.addPreservedID(MachineDominatorsID); 397 MachineFunctionPass::getAnalysisUsage(AU); 398 } 399 400 void RegisterCoalescer::eliminateDeadDefs() { 401 SmallVector<LiveInterval*, 8> NewRegs; 402 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs); 403 } 404 405 // Callback from eliminateDeadDefs(). 406 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) { 407 // MI may be in WorkList. Make sure we don't visit it. 408 ErasedInstrs.insert(MI); 409 } 410 411 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA 412 /// being the source and IntB being the dest, thus this defines a value number 413 /// in IntB. If the source value number (in IntA) is defined by a copy from B, 414 /// see if we can merge these two pieces of B into a single value number, 415 /// eliminating a copy. For example: 416 /// 417 /// A3 = B0 418 /// ... 419 /// B1 = A3 <- this copy 420 /// 421 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1 422 /// value number to be replaced with B0 (which simplifies the B liveinterval). 423 /// 424 /// This returns true if an interval was modified. 425 /// 426 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP, 427 MachineInstr *CopyMI) { 428 assert(!CP.isPartial() && "This doesn't work for partial copies."); 429 assert(!CP.isPhys() && "This doesn't work for physreg copies."); 430 431 LiveInterval &IntA = 432 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 433 LiveInterval &IntB = 434 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 435 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(); 436 437 // BValNo is a value number in B that is defined by a copy from A. 'B3' in 438 // the example above. 439 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx); 440 if (BLR == IntB.end()) return false; 441 VNInfo *BValNo = BLR->valno; 442 443 // Get the location that B is defined at. Two options: either this value has 444 // an unknown definition point or it is defined at CopyIdx. If unknown, we 445 // can't process it. 446 if (BValNo->def != CopyIdx) return false; 447 448 // AValNo is the value number in A that defines the copy, A3 in the example. 449 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true); 450 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx); 451 // The live range might not exist after fun with physreg coalescing. 452 if (ALR == IntA.end()) return false; 453 VNInfo *AValNo = ALR->valno; 454 455 // If AValNo is defined as a copy from IntB, we can potentially process this. 456 // Get the instruction that defines this value number. 457 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def); 458 // Don't allow any partial copies, even if isCoalescable() allows them. 459 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy()) 460 return false; 461 462 // Get the LiveRange in IntB that this value number starts with. 463 LiveInterval::iterator ValLR = 464 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot()); 465 if (ValLR == IntB.end()) 466 return false; 467 468 // Make sure that the end of the live range is inside the same block as 469 // CopyMI. 470 MachineInstr *ValLREndInst = 471 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot()); 472 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent()) 473 return false; 474 475 // Okay, we now know that ValLR ends in the same block that the CopyMI 476 // live-range starts. If there are no intervening live ranges between them in 477 // IntB, we can merge them. 478 if (ValLR+1 != BLR) return false; 479 480 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI)); 481 482 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start; 483 // We are about to delete CopyMI, so need to remove it as the 'instruction 484 // that defines this value #'. Update the valnum with the new defining 485 // instruction #. 486 BValNo->def = FillerStart; 487 488 // Okay, we can merge them. We need to insert a new liverange: 489 // [ValLR.end, BLR.begin) of either value number, then we merge the 490 // two value numbers. 491 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo)); 492 493 // Okay, merge "B1" into the same value number as "B0". 494 if (BValNo != ValLR->valno) 495 IntB.MergeValueNumberInto(BValNo, ValLR->valno); 496 DEBUG(dbgs() << " result = " << IntB << '\n'); 497 498 // If the source instruction was killing the source register before the 499 // merge, unset the isKill marker given the live range has been extended. 500 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true); 501 if (UIdx != -1) { 502 ValLREndInst->getOperand(UIdx).setIsKill(false); 503 } 504 505 // Rewrite the copy. If the copy instruction was killing the destination 506 // register before the merge, find the last use and trim the live range. That 507 // will also add the isKill marker. 508 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI); 509 if (ALR->end == CopyIdx) 510 LIS->shrinkToUses(&IntA); 511 512 ++numExtends; 513 return true; 514 } 515 516 /// hasOtherReachingDefs - Return true if there are definitions of IntB 517 /// other than BValNo val# that can reach uses of AValno val# of IntA. 518 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA, 519 LiveInterval &IntB, 520 VNInfo *AValNo, 521 VNInfo *BValNo) { 522 // If AValNo has PHI kills, conservatively assume that IntB defs can reach 523 // the PHI values. 524 if (LIS->hasPHIKill(IntA, AValNo)) 525 return true; 526 527 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end(); 528 AI != AE; ++AI) { 529 if (AI->valno != AValNo) continue; 530 LiveInterval::Ranges::iterator BI = 531 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start); 532 if (BI != IntB.ranges.begin()) 533 --BI; 534 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) { 535 if (BI->valno == BValNo) 536 continue; 537 if (BI->start <= AI->start && BI->end > AI->start) 538 return true; 539 if (BI->start > AI->start && BI->start < AI->end) 540 return true; 541 } 542 } 543 return false; 544 } 545 546 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with 547 /// IntA being the source and IntB being the dest, thus this defines a value 548 /// number in IntB. If the source value number (in IntA) is defined by a 549 /// commutable instruction and its other operand is coalesced to the copy dest 550 /// register, see if we can transform the copy into a noop by commuting the 551 /// definition. For example, 552 /// 553 /// A3 = op A2 B0<kill> 554 /// ... 555 /// B1 = A3 <- this copy 556 /// ... 557 /// = op A3 <- more uses 558 /// 559 /// ==> 560 /// 561 /// B2 = op B0 A2<kill> 562 /// ... 563 /// B1 = B2 <- now an identify copy 564 /// ... 565 /// = op B2 <- more uses 566 /// 567 /// This returns true if an interval was modified. 568 /// 569 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP, 570 MachineInstr *CopyMI) { 571 assert (!CP.isPhys()); 572 573 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(); 574 575 LiveInterval &IntA = 576 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg()); 577 LiveInterval &IntB = 578 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg()); 579 580 // BValNo is a value number in B that is defined by a copy from A. 'B3' in 581 // the example above. 582 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx); 583 if (!BValNo || BValNo->def != CopyIdx) 584 return false; 585 586 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?"); 587 588 // AValNo is the value number in A that defines the copy, A3 in the example. 589 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true)); 590 assert(AValNo && "COPY source not live"); 591 if (AValNo->isPHIDef() || AValNo->isUnused()) 592 return false; 593 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def); 594 if (!DefMI) 595 return false; 596 if (!DefMI->isCommutable()) 597 return false; 598 // If DefMI is a two-address instruction then commuting it will change the 599 // destination register. 600 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg); 601 assert(DefIdx != -1); 602 unsigned UseOpIdx; 603 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx)) 604 return false; 605 unsigned Op1, Op2, NewDstIdx; 606 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2)) 607 return false; 608 if (Op1 == UseOpIdx) 609 NewDstIdx = Op2; 610 else if (Op2 == UseOpIdx) 611 NewDstIdx = Op1; 612 else 613 return false; 614 615 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx); 616 unsigned NewReg = NewDstMO.getReg(); 617 if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill()) 618 return false; 619 620 // Make sure there are no other definitions of IntB that would reach the 621 // uses which the new definition can reach. 622 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo)) 623 return false; 624 625 // If some of the uses of IntA.reg is already coalesced away, return false. 626 // It's not possible to determine whether it's safe to perform the coalescing. 627 for (MachineRegisterInfo::use_nodbg_iterator UI = 628 MRI->use_nodbg_begin(IntA.reg), 629 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 630 MachineInstr *UseMI = &*UI; 631 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI); 632 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx); 633 if (ULR == IntA.end() || ULR->valno != AValNo) 634 continue; 635 // If this use is tied to a def, we can't rewrite the register. 636 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo())) 637 return false; 638 } 639 640 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t' 641 << *DefMI); 642 643 // At this point we have decided that it is legal to do this 644 // transformation. Start by commuting the instruction. 645 MachineBasicBlock *MBB = DefMI->getParent(); 646 MachineInstr *NewMI = TII->commuteInstruction(DefMI); 647 if (!NewMI) 648 return false; 649 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) && 650 TargetRegisterInfo::isVirtualRegister(IntB.reg) && 651 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg))) 652 return false; 653 if (NewMI != DefMI) { 654 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI); 655 MachineBasicBlock::iterator Pos = DefMI; 656 MBB->insert(Pos, NewMI); 657 MBB->erase(DefMI); 658 } 659 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false); 660 NewMI->getOperand(OpIdx).setIsKill(); 661 662 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g. 663 // A = or A, B 664 // ... 665 // B = A 666 // ... 667 // C = A<kill> 668 // ... 669 // = B 670 671 // Update uses of IntA of the specific Val# with IntB. 672 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg), 673 UE = MRI->use_end(); UI != UE;) { 674 MachineOperand &UseMO = UI.getOperand(); 675 MachineInstr *UseMI = &*UI; 676 ++UI; 677 if (UseMI->isDebugValue()) { 678 // FIXME These don't have an instruction index. Not clear we have enough 679 // info to decide whether to do this replacement or not. For now do it. 680 UseMO.setReg(NewReg); 681 continue; 682 } 683 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true); 684 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx); 685 if (ULR == IntA.end() || ULR->valno != AValNo) 686 continue; 687 // Kill flags are no longer accurate. They are recomputed after RA. 688 UseMO.setIsKill(false); 689 if (TargetRegisterInfo::isPhysicalRegister(NewReg)) 690 UseMO.substPhysReg(NewReg, *TRI); 691 else 692 UseMO.setReg(NewReg); 693 if (UseMI == CopyMI) 694 continue; 695 if (!UseMI->isCopy()) 696 continue; 697 if (UseMI->getOperand(0).getReg() != IntB.reg || 698 UseMI->getOperand(0).getSubReg()) 699 continue; 700 701 // This copy will become a noop. If it's defining a new val#, merge it into 702 // BValNo. 703 SlotIndex DefIdx = UseIdx.getRegSlot(); 704 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx); 705 if (!DVNI) 706 continue; 707 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI); 708 assert(DVNI->def == DefIdx); 709 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI); 710 ErasedInstrs.insert(UseMI); 711 LIS->RemoveMachineInstrFromMaps(UseMI); 712 UseMI->eraseFromParent(); 713 } 714 715 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition 716 // is updated. 717 VNInfo *ValNo = BValNo; 718 ValNo->def = AValNo->def; 719 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end(); 720 AI != AE; ++AI) { 721 if (AI->valno != AValNo) continue; 722 IntB.addRange(LiveRange(AI->start, AI->end, ValNo)); 723 } 724 DEBUG(dbgs() << "\t\textended: " << IntB << '\n'); 725 726 IntA.removeValNo(AValNo); 727 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n'); 728 ++numCommutes; 729 return true; 730 } 731 732 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial 733 /// computation, replace the copy by rematerialize the definition. 734 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP, 735 MachineInstr *CopyMI, 736 bool &IsDefCopy) { 737 IsDefCopy = false; 738 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg(); 739 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx(); 740 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg(); 741 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx(); 742 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)) 743 return false; 744 745 LiveInterval &SrcInt = LIS->getInterval(SrcReg); 746 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true); 747 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx); 748 assert(SrcLR != SrcInt.end() && "Live range not found!"); 749 VNInfo *ValNo = SrcLR->valno; 750 if (ValNo->isPHIDef() || ValNo->isUnused()) 751 return false; 752 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def); 753 if (!DefMI) 754 return false; 755 assert(DefMI && "Defining instruction disappeared"); 756 if (DefMI->isCopyLike()) { 757 IsDefCopy = true; 758 return false; 759 } 760 if (!DefMI->isAsCheapAsAMove()) 761 return false; 762 if (!TII->isTriviallyReMaterializable(DefMI, AA)) 763 return false; 764 bool SawStore = false; 765 if (!DefMI->isSafeToMove(TII, AA, SawStore)) 766 return false; 767 const MCInstrDesc &MCID = DefMI->getDesc(); 768 if (MCID.getNumDefs() != 1) 769 return false; 770 // Only support subregister destinations when the def is read-undef. 771 MachineOperand &DstOperand = CopyMI->getOperand(0); 772 unsigned CopyDstReg = DstOperand.getReg(); 773 if (DstOperand.getSubReg() && !DstOperand.isUndef()) 774 return false; 775 776 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF); 777 if (!DefMI->isImplicitDef()) { 778 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) { 779 unsigned NewDstReg = DstReg; 780 781 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(), 782 DefMI->getOperand(0).getSubReg()); 783 if (NewDstIdx) 784 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx); 785 786 // Finally, make sure that the physical subregister that will be 787 // constructed later is permitted for the instruction. 788 if (!DefRC->contains(NewDstReg)) 789 return false; 790 } else { 791 // Theoretically, some stack frame reference could exist. Just make sure 792 // it hasn't actually happened. 793 assert(TargetRegisterInfo::isVirtualRegister(DstReg) && 794 "Only expect to deal with virtual or physical registers"); 795 } 796 } 797 798 MachineBasicBlock *MBB = CopyMI->getParent(); 799 MachineBasicBlock::iterator MII = 800 llvm::next(MachineBasicBlock::iterator(CopyMI)); 801 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI); 802 MachineInstr *NewMI = prior(MII); 803 804 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI); 805 CopyMI->eraseFromParent(); 806 ErasedInstrs.insert(CopyMI); 807 808 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86). 809 // We need to remember these so we can add intervals once we insert 810 // NewMI into SlotIndexes. 811 SmallVector<unsigned, 4> NewMIImplDefs; 812 for (unsigned i = NewMI->getDesc().getNumOperands(), 813 e = NewMI->getNumOperands(); i != e; ++i) { 814 MachineOperand &MO = NewMI->getOperand(i); 815 if (MO.isReg()) { 816 assert(MO.isDef() && MO.isImplicit() && MO.isDead() && 817 TargetRegisterInfo::isPhysicalRegister(MO.getReg())); 818 NewMIImplDefs.push_back(MO.getReg()); 819 } 820 } 821 822 if (TargetRegisterInfo::isVirtualRegister(DstReg)) { 823 unsigned NewIdx = NewMI->getOperand(0).getSubReg(); 824 const TargetRegisterClass *RCForInst; 825 if (NewIdx) 826 RCForInst = TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg), DefRC, 827 NewIdx); 828 829 if (MRI->constrainRegClass(DstReg, DefRC)) { 830 // The materialized instruction is quite capable of setting DstReg 831 // directly, but it may still have a now-trivial subregister index which 832 // we should clear. 833 NewMI->getOperand(0).setSubReg(0); 834 } else if (NewIdx && RCForInst) { 835 // The subreg index on NewMI is essential; we still have to make sure 836 // DstReg:idx is in a class that NewMI can use. 837 MRI->constrainRegClass(DstReg, RCForInst); 838 } else { 839 // DstReg is actually incompatible with NewMI, we have to move to a 840 // super-reg's class. This could come from a sequence like: 841 // GR32 = MOV32r0 842 // GR8 = COPY GR32:sub_8 843 MRI->setRegClass(DstReg, CP.getNewRC()); 844 updateRegDefsUses(DstReg, DstReg, DstIdx); 845 NewMI->getOperand(0).setSubReg( 846 TRI->composeSubRegIndices(SrcIdx, DefMI->getOperand(0).getSubReg())); 847 } 848 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) { 849 // The New instruction may be defining a sub-register of what's actually 850 // been asked for. If so it must implicitly define the whole thing. 851 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) && 852 "Only expect virtual or physical registers in remat"); 853 NewMI->getOperand(0).setIsDead(true); 854 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg, 855 true /*IsDef*/, 856 true /*IsImp*/, 857 false /*IsKill*/)); 858 } 859 860 if (NewMI->getOperand(0).getSubReg()) 861 NewMI->getOperand(0).setIsUndef(); 862 863 // CopyMI may have implicit operands, transfer them over to the newly 864 // rematerialized instruction. And update implicit def interval valnos. 865 for (unsigned i = CopyMI->getDesc().getNumOperands(), 866 e = CopyMI->getNumOperands(); i != e; ++i) { 867 MachineOperand &MO = CopyMI->getOperand(i); 868 if (MO.isReg()) { 869 assert(MO.isImplicit() && "No explicit operands after implict operands."); 870 // Discard VReg implicit defs. 871 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) { 872 NewMI->addOperand(MO); 873 } 874 } 875 } 876 877 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI); 878 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) { 879 unsigned Reg = NewMIImplDefs[i]; 880 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 881 if (LiveInterval *LI = LIS->getCachedRegUnit(*Units)) 882 LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator()); 883 } 884 885 DEBUG(dbgs() << "Remat: " << *NewMI); 886 ++NumReMats; 887 888 // The source interval can become smaller because we removed a use. 889 LIS->shrinkToUses(&SrcInt, &DeadDefs); 890 if (!DeadDefs.empty()) 891 eliminateDeadDefs(); 892 893 return true; 894 } 895 896 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef> 897 /// values, it only removes local variables. When we have a copy like: 898 /// 899 /// %vreg1 = COPY %vreg2<undef> 900 /// 901 /// We delete the copy and remove the corresponding value number from %vreg1. 902 /// Any uses of that value number are marked as <undef>. 903 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI, 904 const CoalescerPair &CP) { 905 SlotIndex Idx = LIS->getInstructionIndex(CopyMI); 906 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg()); 907 if (SrcInt->liveAt(Idx)) 908 return false; 909 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg()); 910 if (DstInt->liveAt(Idx)) 911 return false; 912 913 // No intervals are live-in to CopyMI - it is undef. 914 if (CP.isFlipped()) 915 DstInt = SrcInt; 916 SrcInt = 0; 917 918 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot()); 919 assert(DeadVNI && "No value defined in DstInt"); 920 DstInt->removeValNo(DeadVNI); 921 922 // Find new undef uses. 923 for (MachineRegisterInfo::reg_nodbg_iterator 924 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end(); 925 I != E; ++I) { 926 MachineOperand &MO = I.getOperand(); 927 if (MO.isDef() || MO.isUndef()) 928 continue; 929 MachineInstr *MI = MO.getParent(); 930 SlotIndex Idx = LIS->getInstructionIndex(MI); 931 if (DstInt->liveAt(Idx)) 932 continue; 933 MO.setIsUndef(true); 934 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI); 935 } 936 return true; 937 } 938 939 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and 940 /// update the subregister number if it is not zero. If DstReg is a 941 /// physical register and the existing subregister number of the def / use 942 /// being updated is not zero, make sure to set it to the correct physical 943 /// subregister. 944 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg, 945 unsigned DstReg, 946 unsigned SubIdx) { 947 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 948 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg); 949 950 SmallPtrSet<MachineInstr*, 8> Visited; 951 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg); 952 MachineInstr *UseMI = I.skipInstruction();) { 953 // Each instruction can only be rewritten once because sub-register 954 // composition is not always idempotent. When SrcReg != DstReg, rewriting 955 // the UseMI operands removes them from the SrcReg use-def chain, but when 956 // SrcReg is DstReg we could encounter UseMI twice if it has multiple 957 // operands mentioning the virtual register. 958 if (SrcReg == DstReg && !Visited.insert(UseMI)) 959 continue; 960 961 SmallVector<unsigned,8> Ops; 962 bool Reads, Writes; 963 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops); 964 965 // If SrcReg wasn't read, it may still be the case that DstReg is live-in 966 // because SrcReg is a sub-register. 967 if (DstInt && !Reads && SubIdx) 968 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI)); 969 970 // Replace SrcReg with DstReg in all UseMI operands. 971 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 972 MachineOperand &MO = UseMI->getOperand(Ops[i]); 973 974 // Adjust <undef> flags in case of sub-register joins. We don't want to 975 // turn a full def into a read-modify-write sub-register def and vice 976 // versa. 977 if (SubIdx && MO.isDef()) 978 MO.setIsUndef(!Reads); 979 980 if (DstIsPhys) 981 MO.substPhysReg(DstReg, *TRI); 982 else 983 MO.substVirtReg(DstReg, SubIdx, *TRI); 984 } 985 986 DEBUG({ 987 dbgs() << "\t\tupdated: "; 988 if (!UseMI->isDebugValue()) 989 dbgs() << LIS->getInstructionIndex(UseMI) << "\t"; 990 dbgs() << *UseMI; 991 }); 992 } 993 } 994 995 /// canJoinPhys - Return true if a copy involving a physreg should be joined. 996 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) { 997 /// Always join simple intervals that are defined by a single copy from a 998 /// reserved register. This doesn't increase register pressure, so it is 999 /// always beneficial. 1000 if (!MRI->isReserved(CP.getDstReg())) { 1001 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n"); 1002 return false; 1003 } 1004 1005 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg()); 1006 if (CP.isFlipped() && JoinVInt.containsOneValue()) 1007 return true; 1008 1009 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n"); 1010 return false; 1011 } 1012 1013 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg, 1014 /// which are the src/dst of the copy instruction CopyMI. This returns true 1015 /// if the copy was successfully coalesced away. If it is not currently 1016 /// possible to coalesce this interval, but it may be possible if other 1017 /// things get coalesced, then it returns true by reference in 'Again'. 1018 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) { 1019 1020 Again = false; 1021 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI); 1022 1023 CoalescerPair CP(*TRI); 1024 if (!CP.setRegisters(CopyMI)) { 1025 DEBUG(dbgs() << "\tNot coalescable.\n"); 1026 return false; 1027 } 1028 1029 // Dead code elimination. This really should be handled by MachineDCE, but 1030 // sometimes dead copies slip through, and we can't generate invalid live 1031 // ranges. 1032 if (!CP.isPhys() && CopyMI->allDefsAreDead()) { 1033 DEBUG(dbgs() << "\tCopy is dead.\n"); 1034 DeadDefs.push_back(CopyMI); 1035 eliminateDeadDefs(); 1036 return true; 1037 } 1038 1039 // Eliminate undefs. 1040 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) { 1041 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n"); 1042 LIS->RemoveMachineInstrFromMaps(CopyMI); 1043 CopyMI->eraseFromParent(); 1044 return false; // Not coalescable. 1045 } 1046 1047 // Coalesced copies are normally removed immediately, but transformations 1048 // like removeCopyByCommutingDef() can inadvertently create identity copies. 1049 // When that happens, just join the values and remove the copy. 1050 if (CP.getSrcReg() == CP.getDstReg()) { 1051 LiveInterval &LI = LIS->getInterval(CP.getSrcReg()); 1052 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n'); 1053 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI)); 1054 if (VNInfo *DefVNI = LRQ.valueDefined()) { 1055 VNInfo *ReadVNI = LRQ.valueIn(); 1056 assert(ReadVNI && "No value before copy and no <undef> flag."); 1057 assert(ReadVNI != DefVNI && "Cannot read and define the same value."); 1058 LI.MergeValueNumberInto(DefVNI, ReadVNI); 1059 DEBUG(dbgs() << "\tMerged values: " << LI << '\n'); 1060 } 1061 LIS->RemoveMachineInstrFromMaps(CopyMI); 1062 CopyMI->eraseFromParent(); 1063 return true; 1064 } 1065 1066 // Enforce policies. 1067 if (CP.isPhys()) { 1068 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI) 1069 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) 1070 << '\n'); 1071 if (!canJoinPhys(CP)) { 1072 // Before giving up coalescing, if definition of source is defined by 1073 // trivial computation, try rematerializing it. 1074 bool IsDefCopy; 1075 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) 1076 return true; 1077 if (IsDefCopy) 1078 Again = true; // May be possible to coalesce later. 1079 return false; 1080 } 1081 } else { 1082 DEBUG({ 1083 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName() 1084 << " with "; 1085 if (CP.getDstIdx() && CP.getSrcIdx()) 1086 dbgs() << PrintReg(CP.getDstReg()) << " in " 1087 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and " 1088 << PrintReg(CP.getSrcReg()) << " in " 1089 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n'; 1090 else 1091 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in " 1092 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n'; 1093 }); 1094 1095 // When possible, let DstReg be the larger interval. 1096 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() > 1097 LIS->getInterval(CP.getDstReg()).ranges.size()) 1098 CP.flip(); 1099 } 1100 1101 // Okay, attempt to join these two intervals. On failure, this returns false. 1102 // Otherwise, if one of the intervals being joined is a physreg, this method 1103 // always canonicalizes DstInt to be it. The output "SrcInt" will not have 1104 // been modified, so we can use this information below to update aliases. 1105 if (!joinIntervals(CP)) { 1106 // Coalescing failed. 1107 1108 // If definition of source is defined by trivial computation, try 1109 // rematerializing it. 1110 bool IsDefCopy; 1111 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy)) 1112 return true; 1113 1114 // If we can eliminate the copy without merging the live ranges, do so now. 1115 if (!CP.isPartial() && !CP.isPhys()) { 1116 if (adjustCopiesBackFrom(CP, CopyMI) || 1117 removeCopyByCommutingDef(CP, CopyMI)) { 1118 LIS->RemoveMachineInstrFromMaps(CopyMI); 1119 CopyMI->eraseFromParent(); 1120 DEBUG(dbgs() << "\tTrivial!\n"); 1121 return true; 1122 } 1123 } 1124 1125 // Otherwise, we are unable to join the intervals. 1126 DEBUG(dbgs() << "\tInterference!\n"); 1127 Again = true; // May be possible to coalesce later. 1128 return false; 1129 } 1130 1131 // Coalescing to a virtual register that is of a sub-register class of the 1132 // other. Make sure the resulting register is set to the right register class. 1133 if (CP.isCrossClass()) { 1134 ++numCrossRCs; 1135 MRI->setRegClass(CP.getDstReg(), CP.getNewRC()); 1136 } 1137 1138 // Removing sub-register copies can ease the register class constraints. 1139 // Make sure we attempt to inflate the register class of DstReg. 1140 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC())) 1141 InflateRegs.push_back(CP.getDstReg()); 1142 1143 // CopyMI has been erased by joinIntervals at this point. Remove it from 1144 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back 1145 // to the work list. This keeps ErasedInstrs from growing needlessly. 1146 ErasedInstrs.erase(CopyMI); 1147 1148 // Rewrite all SrcReg operands to DstReg. 1149 // Also update DstReg operands to include DstIdx if it is set. 1150 if (CP.getDstIdx()) 1151 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx()); 1152 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx()); 1153 1154 // SrcReg is guaranteed to be the register whose live interval that is 1155 // being merged. 1156 LIS->removeInterval(CP.getSrcReg()); 1157 1158 // Update regalloc hint. 1159 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF); 1160 1161 DEBUG({ 1162 dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI); 1163 if (!CP.isPhys()) 1164 dbgs() << LIS->getInterval(CP.getDstReg()); 1165 dbgs() << '\n'; 1166 }); 1167 1168 ++numJoins; 1169 return true; 1170 } 1171 1172 /// Attempt joining with a reserved physreg. 1173 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) { 1174 assert(CP.isPhys() && "Must be a physreg copy"); 1175 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register"); 1176 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg()); 1177 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS 1178 << '\n'); 1179 1180 assert(CP.isFlipped() && RHS.containsOneValue() && 1181 "Invalid join with reserved register"); 1182 1183 // Optimization for reserved registers like ESP. We can only merge with a 1184 // reserved physreg if RHS has a single value that is a copy of CP.DstReg(). 1185 // The live range of the reserved register will look like a set of dead defs 1186 // - we don't properly track the live range of reserved registers. 1187 1188 // Deny any overlapping intervals. This depends on all the reserved 1189 // register live ranges to look like dead defs. 1190 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI) 1191 if (RHS.overlaps(LIS->getRegUnit(*UI))) { 1192 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n'); 1193 return false; 1194 } 1195 1196 // Skip any value computations, we are not adding new values to the 1197 // reserved register. Also skip merging the live ranges, the reserved 1198 // register live range doesn't need to be accurate as long as all the 1199 // defs are there. 1200 1201 // Delete the identity copy. 1202 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg); 1203 LIS->RemoveMachineInstrFromMaps(CopyMI); 1204 CopyMI->eraseFromParent(); 1205 1206 // We don't track kills for reserved registers. 1207 MRI->clearKillFlags(CP.getSrcReg()); 1208 1209 return true; 1210 } 1211 1212 //===----------------------------------------------------------------------===// 1213 // Interference checking and interval joining 1214 //===----------------------------------------------------------------------===// 1215 // 1216 // In the easiest case, the two live ranges being joined are disjoint, and 1217 // there is no interference to consider. It is quite common, though, to have 1218 // overlapping live ranges, and we need to check if the interference can be 1219 // resolved. 1220 // 1221 // The live range of a single SSA value forms a sub-tree of the dominator tree. 1222 // This means that two SSA values overlap if and only if the def of one value 1223 // is contained in the live range of the other value. As a special case, the 1224 // overlapping values can be defined at the same index. 1225 // 1226 // The interference from an overlapping def can be resolved in these cases: 1227 // 1228 // 1. Coalescable copies. The value is defined by a copy that would become an 1229 // identity copy after joining SrcReg and DstReg. The copy instruction will 1230 // be removed, and the value will be merged with the source value. 1231 // 1232 // There can be several copies back and forth, causing many values to be 1233 // merged into one. We compute a list of ultimate values in the joined live 1234 // range as well as a mappings from the old value numbers. 1235 // 1236 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI 1237 // predecessors have a live out value. It doesn't cause real interference, 1238 // and can be merged into the value it overlaps. Like a coalescable copy, it 1239 // can be erased after joining. 1240 // 1241 // 3. Copy of external value. The overlapping def may be a copy of a value that 1242 // is already in the other register. This is like a coalescable copy, but 1243 // the live range of the source register must be trimmed after erasing the 1244 // copy instruction: 1245 // 1246 // %src = COPY %ext 1247 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext. 1248 // 1249 // 4. Clobbering undefined lanes. Vector registers are sometimes built by 1250 // defining one lane at a time: 1251 // 1252 // %dst:ssub0<def,read-undef> = FOO 1253 // %src = BAR 1254 // %dst:ssub1<def> = COPY %src 1255 // 1256 // The live range of %src overlaps the %dst value defined by FOO, but 1257 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane 1258 // which was undef anyway. 1259 // 1260 // The value mapping is more complicated in this case. The final live range 1261 // will have different value numbers for both FOO and BAR, but there is no 1262 // simple mapping from old to new values. It may even be necessary to add 1263 // new PHI values. 1264 // 1265 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that 1266 // is live, but never read. This can happen because we don't compute 1267 // individual live ranges per lane. 1268 // 1269 // %dst<def> = FOO 1270 // %src = BAR 1271 // %dst:ssub1<def> = COPY %src 1272 // 1273 // This kind of interference is only resolved locally. If the clobbered 1274 // lane value escapes the block, the join is aborted. 1275 1276 namespace { 1277 /// Track information about values in a single virtual register about to be 1278 /// joined. Objects of this class are always created in pairs - one for each 1279 /// side of the CoalescerPair. 1280 class JoinVals { 1281 LiveInterval &LI; 1282 1283 // Location of this register in the final joined register. 1284 // Either CP.DstIdx or CP.SrcIdx. 1285 unsigned SubIdx; 1286 1287 // Values that will be present in the final live range. 1288 SmallVectorImpl<VNInfo*> &NewVNInfo; 1289 1290 const CoalescerPair &CP; 1291 LiveIntervals *LIS; 1292 SlotIndexes *Indexes; 1293 const TargetRegisterInfo *TRI; 1294 1295 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo. 1296 // This is suitable for passing to LiveInterval::join(). 1297 SmallVector<int, 8> Assignments; 1298 1299 // Conflict resolution for overlapping values. 1300 enum ConflictResolution { 1301 // No overlap, simply keep this value. 1302 CR_Keep, 1303 1304 // Merge this value into OtherVNI and erase the defining instruction. 1305 // Used for IMPLICIT_DEF, coalescable copies, and copies from external 1306 // values. 1307 CR_Erase, 1308 1309 // Merge this value into OtherVNI but keep the defining instruction. 1310 // This is for the special case where OtherVNI is defined by the same 1311 // instruction. 1312 CR_Merge, 1313 1314 // Keep this value, and have it replace OtherVNI where possible. This 1315 // complicates value mapping since OtherVNI maps to two different values 1316 // before and after this def. 1317 // Used when clobbering undefined or dead lanes. 1318 CR_Replace, 1319 1320 // Unresolved conflict. Visit later when all values have been mapped. 1321 CR_Unresolved, 1322 1323 // Unresolvable conflict. Abort the join. 1324 CR_Impossible 1325 }; 1326 1327 // Per-value info for LI. The lane bit masks are all relative to the final 1328 // joined register, so they can be compared directly between SrcReg and 1329 // DstReg. 1330 struct Val { 1331 ConflictResolution Resolution; 1332 1333 // Lanes written by this def, 0 for unanalyzed values. 1334 unsigned WriteLanes; 1335 1336 // Lanes with defined values in this register. Other lanes are undef and 1337 // safe to clobber. 1338 unsigned ValidLanes; 1339 1340 // Value in LI being redefined by this def. 1341 VNInfo *RedefVNI; 1342 1343 // Value in the other live range that overlaps this def, if any. 1344 VNInfo *OtherVNI; 1345 1346 // Is this value an IMPLICIT_DEF that can be erased? 1347 // 1348 // IMPLICIT_DEF values should only exist at the end of a basic block that 1349 // is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be 1350 // safely erased if they are overlapping a live value in the other live 1351 // interval. 1352 // 1353 // Weird control flow graphs and incomplete PHI handling in 1354 // ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with 1355 // longer live ranges. Such IMPLICIT_DEF values should be treated like 1356 // normal values. 1357 bool ErasableImplicitDef; 1358 1359 // True when the live range of this value will be pruned because of an 1360 // overlapping CR_Replace value in the other live range. 1361 bool Pruned; 1362 1363 // True once Pruned above has been computed. 1364 bool PrunedComputed; 1365 1366 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0), 1367 RedefVNI(0), OtherVNI(0), ErasableImplicitDef(false), 1368 Pruned(false), PrunedComputed(false) {} 1369 1370 bool isAnalyzed() const { return WriteLanes != 0; } 1371 }; 1372 1373 // One entry per value number in LI. 1374 SmallVector<Val, 8> Vals; 1375 1376 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef); 1377 VNInfo *stripCopies(VNInfo *VNI); 1378 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other); 1379 void computeAssignment(unsigned ValNo, JoinVals &Other); 1380 bool taintExtent(unsigned, unsigned, JoinVals&, 1381 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&); 1382 bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned); 1383 bool isPrunedValue(unsigned ValNo, JoinVals &Other); 1384 1385 public: 1386 JoinVals(LiveInterval &li, unsigned subIdx, 1387 SmallVectorImpl<VNInfo*> &newVNInfo, 1388 const CoalescerPair &cp, 1389 LiveIntervals *lis, 1390 const TargetRegisterInfo *tri) 1391 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis), 1392 Indexes(LIS->getSlotIndexes()), TRI(tri), 1393 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums()) 1394 {} 1395 1396 /// Analyze defs in LI and compute a value mapping in NewVNInfo. 1397 /// Returns false if any conflicts were impossible to resolve. 1398 bool mapValues(JoinVals &Other); 1399 1400 /// Try to resolve conflicts that require all values to be mapped. 1401 /// Returns false if any conflicts were impossible to resolve. 1402 bool resolveConflicts(JoinVals &Other); 1403 1404 /// Prune the live range of values in Other.LI where they would conflict with 1405 /// CR_Replace values in LI. Collect end points for restoring the live range 1406 /// after joining. 1407 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints); 1408 1409 /// Erase any machine instructions that have been coalesced away. 1410 /// Add erased instructions to ErasedInstrs. 1411 /// Add foreign virtual registers to ShrinkRegs if their live range ended at 1412 /// the erased instrs. 1413 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs, 1414 SmallVectorImpl<unsigned> &ShrinkRegs); 1415 1416 /// Get the value assignments suitable for passing to LiveInterval::join. 1417 const int *getAssignments() const { return Assignments.data(); } 1418 }; 1419 } // end anonymous namespace 1420 1421 /// Compute the bitmask of lanes actually written by DefMI. 1422 /// Set Redef if there are any partial register definitions that depend on the 1423 /// previous value of the register. 1424 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) { 1425 unsigned L = 0; 1426 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) { 1427 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef()) 1428 continue; 1429 L |= TRI->getSubRegIndexLaneMask( 1430 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())); 1431 if (MO->readsReg()) 1432 Redef = true; 1433 } 1434 return L; 1435 } 1436 1437 /// Find the ultimate value that VNI was copied from. 1438 VNInfo *JoinVals::stripCopies(VNInfo *VNI) { 1439 while (!VNI->isPHIDef()) { 1440 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def); 1441 assert(MI && "No defining instruction"); 1442 if (!MI->isFullCopy()) 1443 break; 1444 unsigned Reg = MI->getOperand(1).getReg(); 1445 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1446 break; 1447 LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def); 1448 if (!LRQ.valueIn()) 1449 break; 1450 VNI = LRQ.valueIn(); 1451 } 1452 return VNI; 1453 } 1454 1455 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo]. 1456 /// Return a conflict resolution when possible, but leave the hard cases as 1457 /// CR_Unresolved. 1458 /// Recursively calls computeAssignment() on this and Other, guaranteeing that 1459 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning. 1460 /// The recursion always goes upwards in the dominator tree, making loops 1461 /// impossible. 1462 JoinVals::ConflictResolution 1463 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) { 1464 Val &V = Vals[ValNo]; 1465 assert(!V.isAnalyzed() && "Value has already been analyzed!"); 1466 VNInfo *VNI = LI.getValNumInfo(ValNo); 1467 if (VNI->isUnused()) { 1468 V.WriteLanes = ~0u; 1469 return CR_Keep; 1470 } 1471 1472 // Get the instruction defining this value, compute the lanes written. 1473 const MachineInstr *DefMI = 0; 1474 if (VNI->isPHIDef()) { 1475 // Conservatively assume that all lanes in a PHI are valid. 1476 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx); 1477 } else { 1478 DefMI = Indexes->getInstructionFromIndex(VNI->def); 1479 bool Redef = false; 1480 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef); 1481 1482 // If this is a read-modify-write instruction, there may be more valid 1483 // lanes than the ones written by this instruction. 1484 // This only covers partial redef operands. DefMI may have normal use 1485 // operands reading the register. They don't contribute valid lanes. 1486 // 1487 // This adds ssub1 to the set of valid lanes in %src: 1488 // 1489 // %src:ssub1<def> = FOO 1490 // 1491 // This leaves only ssub1 valid, making any other lanes undef: 1492 // 1493 // %src:ssub1<def,read-undef> = FOO %src:ssub2 1494 // 1495 // The <read-undef> flag on the def operand means that old lane values are 1496 // not important. 1497 if (Redef) { 1498 V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn(); 1499 assert(V.RedefVNI && "Instruction is reading nonexistent value"); 1500 computeAssignment(V.RedefVNI->id, Other); 1501 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes; 1502 } 1503 1504 // An IMPLICIT_DEF writes undef values. 1505 if (DefMI->isImplicitDef()) { 1506 // We normally expect IMPLICIT_DEF values to be live only until the end 1507 // of their block. If the value is really live longer and gets pruned in 1508 // another block, this flag is cleared again. 1509 V.ErasableImplicitDef = true; 1510 V.ValidLanes &= ~V.WriteLanes; 1511 } 1512 } 1513 1514 // Find the value in Other that overlaps VNI->def, if any. 1515 LiveRangeQuery OtherLRQ(Other.LI, VNI->def); 1516 1517 // It is possible that both values are defined by the same instruction, or 1518 // the values are PHIs defined in the same block. When that happens, the two 1519 // values should be merged into one, but not into any preceding value. 1520 // The first value defined or visited gets CR_Keep, the other gets CR_Merge. 1521 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) { 1522 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ"); 1523 1524 // One value stays, the other is merged. Keep the earlier one, or the first 1525 // one we see. 1526 if (OtherVNI->def < VNI->def) 1527 Other.computeAssignment(OtherVNI->id, *this); 1528 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) { 1529 // This is an early-clobber def overlapping a live-in value in the other 1530 // register. Not mergeable. 1531 V.OtherVNI = OtherLRQ.valueIn(); 1532 return CR_Impossible; 1533 } 1534 V.OtherVNI = OtherVNI; 1535 Val &OtherV = Other.Vals[OtherVNI->id]; 1536 // Keep this value, check for conflicts when analyzing OtherVNI. 1537 if (!OtherV.isAnalyzed()) 1538 return CR_Keep; 1539 // Both sides have been analyzed now. 1540 // Allow overlapping PHI values. Any real interference would show up in a 1541 // predecessor, the PHI itself can't introduce any conflicts. 1542 if (VNI->isPHIDef()) 1543 return CR_Merge; 1544 if (V.ValidLanes & OtherV.ValidLanes) 1545 // Overlapping lanes can't be resolved. 1546 return CR_Impossible; 1547 else 1548 return CR_Merge; 1549 } 1550 1551 // No simultaneous def. Is Other live at the def? 1552 V.OtherVNI = OtherLRQ.valueIn(); 1553 if (!V.OtherVNI) 1554 // No overlap, no conflict. 1555 return CR_Keep; 1556 1557 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ"); 1558 1559 // We have overlapping values, or possibly a kill of Other. 1560 // Recursively compute assignments up the dominator tree. 1561 Other.computeAssignment(V.OtherVNI->id, *this); 1562 Val &OtherV = Other.Vals[V.OtherVNI->id]; 1563 1564 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block. 1565 // This shouldn't normally happen, but ProcessImplicitDefs can leave such 1566 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it 1567 // technically. 1568 // 1569 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try 1570 // to erase the IMPLICIT_DEF instruction. 1571 if (OtherV.ErasableImplicitDef && DefMI && 1572 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) { 1573 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def 1574 << " extends into BB#" << DefMI->getParent()->getNumber() 1575 << ", keeping it.\n"); 1576 OtherV.ErasableImplicitDef = false; 1577 } 1578 1579 // Allow overlapping PHI values. Any real interference would show up in a 1580 // predecessor, the PHI itself can't introduce any conflicts. 1581 if (VNI->isPHIDef()) 1582 return CR_Replace; 1583 1584 // Check for simple erasable conflicts. 1585 if (DefMI->isImplicitDef()) 1586 return CR_Erase; 1587 1588 // Include the non-conflict where DefMI is a coalescable copy that kills 1589 // OtherVNI. We still want the copy erased and value numbers merged. 1590 if (CP.isCoalescable(DefMI)) { 1591 // Some of the lanes copied from OtherVNI may be undef, making them undef 1592 // here too. 1593 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes; 1594 return CR_Erase; 1595 } 1596 1597 // This may not be a real conflict if DefMI simply kills Other and defines 1598 // VNI. 1599 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def) 1600 return CR_Keep; 1601 1602 // Handle the case where VNI and OtherVNI can be proven to be identical: 1603 // 1604 // %other = COPY %ext 1605 // %this = COPY %ext <-- Erase this copy 1606 // 1607 if (DefMI->isFullCopy() && !CP.isPartial() && 1608 stripCopies(VNI) == stripCopies(V.OtherVNI)) 1609 return CR_Erase; 1610 1611 // If the lanes written by this instruction were all undef in OtherVNI, it is 1612 // still safe to join the live ranges. This can't be done with a simple value 1613 // mapping, though - OtherVNI will map to multiple values: 1614 // 1615 // 1 %dst:ssub0 = FOO <-- OtherVNI 1616 // 2 %src = BAR <-- VNI 1617 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy. 1618 // 4 BAZ %dst<kill> 1619 // 5 QUUX %src<kill> 1620 // 1621 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace 1622 // handles this complex value mapping. 1623 if ((V.WriteLanes & OtherV.ValidLanes) == 0) 1624 return CR_Replace; 1625 1626 // If the other live range is killed by DefMI and the live ranges are still 1627 // overlapping, it must be because we're looking at an early clobber def: 1628 // 1629 // %dst<def,early-clobber> = ASM %src<kill> 1630 // 1631 // In this case, it is illegal to merge the two live ranges since the early 1632 // clobber def would clobber %src before it was read. 1633 if (OtherLRQ.isKill()) { 1634 // This case where the def doesn't overlap the kill is handled above. 1635 assert(VNI->def.isEarlyClobber() && 1636 "Only early clobber defs can overlap a kill"); 1637 return CR_Impossible; 1638 } 1639 1640 // VNI is clobbering live lanes in OtherVNI, but there is still the 1641 // possibility that no instructions actually read the clobbered lanes. 1642 // If we're clobbering all the lanes in OtherVNI, at least one must be read. 1643 // Otherwise Other.LI wouldn't be live here. 1644 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0) 1645 return CR_Impossible; 1646 1647 // We need to verify that no instructions are reading the clobbered lanes. To 1648 // save compile time, we'll only check that locally. Don't allow the tainted 1649 // value to escape the basic block. 1650 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 1651 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB)) 1652 return CR_Impossible; 1653 1654 // There are still some things that could go wrong besides clobbered lanes 1655 // being read, for example OtherVNI may be only partially redefined in MBB, 1656 // and some clobbered lanes could escape the block. Save this analysis for 1657 // resolveConflicts() when all values have been mapped. We need to know 1658 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute 1659 // that now - the recursive analyzeValue() calls must go upwards in the 1660 // dominator tree. 1661 return CR_Unresolved; 1662 } 1663 1664 /// Compute the value assignment for ValNo in LI. 1665 /// This may be called recursively by analyzeValue(), but never for a ValNo on 1666 /// the stack. 1667 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) { 1668 Val &V = Vals[ValNo]; 1669 if (V.isAnalyzed()) { 1670 // Recursion should always move up the dominator tree, so ValNo is not 1671 // supposed to reappear before it has been assigned. 1672 assert(Assignments[ValNo] != -1 && "Bad recursion?"); 1673 return; 1674 } 1675 switch ((V.Resolution = analyzeValue(ValNo, Other))) { 1676 case CR_Erase: 1677 case CR_Merge: 1678 // Merge this ValNo into OtherVNI. 1679 assert(V.OtherVNI && "OtherVNI not assigned, can't merge."); 1680 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion"); 1681 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id]; 1682 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@' 1683 << LI.getValNumInfo(ValNo)->def << " into " 1684 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@' 1685 << V.OtherVNI->def << " --> @" 1686 << NewVNInfo[Assignments[ValNo]]->def << '\n'); 1687 break; 1688 case CR_Replace: 1689 case CR_Unresolved: 1690 // The other value is going to be pruned if this join is successful. 1691 assert(V.OtherVNI && "OtherVNI not assigned, can't prune"); 1692 Other.Vals[V.OtherVNI->id].Pruned = true; 1693 // Fall through. 1694 default: 1695 // This value number needs to go in the final joined live range. 1696 Assignments[ValNo] = NewVNInfo.size(); 1697 NewVNInfo.push_back(LI.getValNumInfo(ValNo)); 1698 break; 1699 } 1700 } 1701 1702 bool JoinVals::mapValues(JoinVals &Other) { 1703 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) { 1704 computeAssignment(i, Other); 1705 if (Vals[i].Resolution == CR_Impossible) { 1706 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i 1707 << '@' << LI.getValNumInfo(i)->def << '\n'); 1708 return false; 1709 } 1710 } 1711 return true; 1712 } 1713 1714 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute 1715 /// the extent of the tainted lanes in the block. 1716 /// 1717 /// Multiple values in Other.LI can be affected since partial redefinitions can 1718 /// preserve previously tainted lanes. 1719 /// 1720 /// 1 %dst = VLOAD <-- Define all lanes in %dst 1721 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0 1722 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0 1723 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read 1724 /// 1725 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes) 1726 /// entry to TaintedVals. 1727 /// 1728 /// Returns false if the tainted lanes extend beyond the basic block. 1729 bool JoinVals:: 1730 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other, 1731 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) { 1732 VNInfo *VNI = LI.getValNumInfo(ValNo); 1733 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 1734 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB); 1735 1736 // Scan Other.LI from VNI.def to MBBEnd. 1737 LiveInterval::iterator OtherI = Other.LI.find(VNI->def); 1738 assert(OtherI != Other.LI.end() && "No conflict?"); 1739 do { 1740 // OtherI is pointing to a tainted value. Abort the join if the tainted 1741 // lanes escape the block. 1742 SlotIndex End = OtherI->end; 1743 if (End >= MBBEnd) { 1744 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':' 1745 << OtherI->valno->id << '@' << OtherI->start << '\n'); 1746 return false; 1747 } 1748 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':' 1749 << OtherI->valno->id << '@' << OtherI->start 1750 << " to " << End << '\n'); 1751 // A dead def is not a problem. 1752 if (End.isDead()) 1753 break; 1754 TaintExtent.push_back(std::make_pair(End, TaintedLanes)); 1755 1756 // Check for another def in the MBB. 1757 if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd) 1758 break; 1759 1760 // Lanes written by the new def are no longer tainted. 1761 const Val &OV = Other.Vals[OtherI->valno->id]; 1762 TaintedLanes &= ~OV.WriteLanes; 1763 if (!OV.RedefVNI) 1764 break; 1765 } while (TaintedLanes); 1766 return true; 1767 } 1768 1769 /// Return true if MI uses any of the given Lanes from Reg. 1770 /// This does not include partial redefinitions of Reg. 1771 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx, 1772 unsigned Lanes) { 1773 if (MI->isDebugValue()) 1774 return false; 1775 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) { 1776 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg) 1777 continue; 1778 if (!MO->readsReg()) 1779 continue; 1780 if (Lanes & TRI->getSubRegIndexLaneMask( 1781 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()))) 1782 return true; 1783 } 1784 return false; 1785 } 1786 1787 bool JoinVals::resolveConflicts(JoinVals &Other) { 1788 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) { 1789 Val &V = Vals[i]; 1790 assert (V.Resolution != CR_Impossible && "Unresolvable conflict"); 1791 if (V.Resolution != CR_Unresolved) 1792 continue; 1793 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i 1794 << '@' << LI.getValNumInfo(i)->def << '\n'); 1795 ++NumLaneConflicts; 1796 assert(V.OtherVNI && "Inconsistent conflict resolution."); 1797 VNInfo *VNI = LI.getValNumInfo(i); 1798 const Val &OtherV = Other.Vals[V.OtherVNI->id]; 1799 1800 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the 1801 // join, those lanes will be tainted with a wrong value. Get the extent of 1802 // the tainted lanes. 1803 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes; 1804 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent; 1805 if (!taintExtent(i, TaintedLanes, Other, TaintExtent)) 1806 // Tainted lanes would extend beyond the basic block. 1807 return false; 1808 1809 assert(!TaintExtent.empty() && "There should be at least one conflict."); 1810 1811 // Now look at the instructions from VNI->def to TaintExtent (inclusive). 1812 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def); 1813 MachineBasicBlock::iterator MI = MBB->begin(); 1814 if (!VNI->isPHIDef()) { 1815 MI = Indexes->getInstructionFromIndex(VNI->def); 1816 // No need to check the instruction defining VNI for reads. 1817 ++MI; 1818 } 1819 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) && 1820 "Interference ends on VNI->def. Should have been handled earlier"); 1821 MachineInstr *LastMI = 1822 Indexes->getInstructionFromIndex(TaintExtent.front().first); 1823 assert(LastMI && "Range must end at a proper instruction"); 1824 unsigned TaintNum = 0; 1825 for(;;) { 1826 assert(MI != MBB->end() && "Bad LastMI"); 1827 if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) { 1828 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI); 1829 return false; 1830 } 1831 // LastMI is the last instruction to use the current value. 1832 if (&*MI == LastMI) { 1833 if (++TaintNum == TaintExtent.size()) 1834 break; 1835 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first); 1836 assert(LastMI && "Range must end at a proper instruction"); 1837 TaintedLanes = TaintExtent[TaintNum].second; 1838 } 1839 ++MI; 1840 } 1841 1842 // The tainted lanes are unused. 1843 V.Resolution = CR_Replace; 1844 ++NumLaneResolves; 1845 } 1846 return true; 1847 } 1848 1849 // Determine if ValNo is a copy of a value number in LI or Other.LI that will 1850 // be pruned: 1851 // 1852 // %dst = COPY %src 1853 // %src = COPY %dst <-- This value to be pruned. 1854 // %dst = COPY %src <-- This value is a copy of a pruned value. 1855 // 1856 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) { 1857 Val &V = Vals[ValNo]; 1858 if (V.Pruned || V.PrunedComputed) 1859 return V.Pruned; 1860 1861 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge) 1862 return V.Pruned; 1863 1864 // Follow copies up the dominator tree and check if any intermediate value 1865 // has been pruned. 1866 V.PrunedComputed = true; 1867 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this); 1868 return V.Pruned; 1869 } 1870 1871 void JoinVals::pruneValues(JoinVals &Other, 1872 SmallVectorImpl<SlotIndex> &EndPoints) { 1873 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) { 1874 SlotIndex Def = LI.getValNumInfo(i)->def; 1875 switch (Vals[i].Resolution) { 1876 case CR_Keep: 1877 break; 1878 case CR_Replace: { 1879 // This value takes precedence over the value in Other.LI. 1880 LIS->pruneValue(&Other.LI, Def, &EndPoints); 1881 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF 1882 // instructions are only inserted to provide a live-out value for PHI 1883 // predecessors, so the instruction should simply go away once its value 1884 // has been replaced. 1885 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id]; 1886 bool EraseImpDef = OtherV.ErasableImplicitDef && 1887 OtherV.Resolution == CR_Keep; 1888 if (!Def.isBlock()) { 1889 // Remove <def,read-undef> flags. This def is now a partial redef. 1890 // Also remove <def,dead> flags since the joined live range will 1891 // continue past this instruction. 1892 for (MIOperands MO(Indexes->getInstructionFromIndex(Def)); 1893 MO.isValid(); ++MO) 1894 if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) { 1895 MO->setIsUndef(EraseImpDef); 1896 MO->setIsDead(false); 1897 } 1898 // This value will reach instructions below, but we need to make sure 1899 // the live range also reaches the instruction at Def. 1900 if (!EraseImpDef) 1901 EndPoints.push_back(Def); 1902 } 1903 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def 1904 << ": " << Other.LI << '\n'); 1905 break; 1906 } 1907 case CR_Erase: 1908 case CR_Merge: 1909 if (isPrunedValue(i, Other)) { 1910 // This value is ultimately a copy of a pruned value in LI or Other.LI. 1911 // We can no longer trust the value mapping computed by 1912 // computeAssignment(), the value that was originally copied could have 1913 // been replaced. 1914 LIS->pruneValue(&LI, Def, &EndPoints); 1915 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at " 1916 << Def << ": " << LI << '\n'); 1917 } 1918 break; 1919 case CR_Unresolved: 1920 case CR_Impossible: 1921 llvm_unreachable("Unresolved conflicts"); 1922 } 1923 } 1924 } 1925 1926 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs, 1927 SmallVectorImpl<unsigned> &ShrinkRegs) { 1928 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) { 1929 // Get the def location before markUnused() below invalidates it. 1930 SlotIndex Def = LI.getValNumInfo(i)->def; 1931 switch (Vals[i].Resolution) { 1932 case CR_Keep: 1933 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any 1934 // longer. The IMPLICIT_DEF instructions are only inserted by 1935 // PHIElimination to guarantee that all PHI predecessors have a value. 1936 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned) 1937 break; 1938 // Remove value number i from LI. Note that this VNInfo is still present 1939 // in NewVNInfo, so it will appear as an unused value number in the final 1940 // joined interval. 1941 LI.getValNumInfo(i)->markUnused(); 1942 LI.removeValNo(LI.getValNumInfo(i)); 1943 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n'); 1944 // FALL THROUGH. 1945 1946 case CR_Erase: { 1947 MachineInstr *MI = Indexes->getInstructionFromIndex(Def); 1948 assert(MI && "No instruction to erase"); 1949 if (MI->isCopy()) { 1950 unsigned Reg = MI->getOperand(1).getReg(); 1951 if (TargetRegisterInfo::isVirtualRegister(Reg) && 1952 Reg != CP.getSrcReg() && Reg != CP.getDstReg()) 1953 ShrinkRegs.push_back(Reg); 1954 } 1955 ErasedInstrs.insert(MI); 1956 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI); 1957 LIS->RemoveMachineInstrFromMaps(MI); 1958 MI->eraseFromParent(); 1959 break; 1960 } 1961 default: 1962 break; 1963 } 1964 } 1965 } 1966 1967 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) { 1968 SmallVector<VNInfo*, 16> NewVNInfo; 1969 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg()); 1970 LiveInterval &LHS = LIS->getInterval(CP.getDstReg()); 1971 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI); 1972 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI); 1973 1974 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS 1975 << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS 1976 << '\n'); 1977 1978 // First compute NewVNInfo and the simple value mappings. 1979 // Detect impossible conflicts early. 1980 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) 1981 return false; 1982 1983 // Some conflicts can only be resolved after all values have been mapped. 1984 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals)) 1985 return false; 1986 1987 // All clear, the live ranges can be merged. 1988 1989 // The merging algorithm in LiveInterval::join() can't handle conflicting 1990 // value mappings, so we need to remove any live ranges that overlap a 1991 // CR_Replace resolution. Collect a set of end points that can be used to 1992 // restore the live range after joining. 1993 SmallVector<SlotIndex, 8> EndPoints; 1994 LHSVals.pruneValues(RHSVals, EndPoints); 1995 RHSVals.pruneValues(LHSVals, EndPoints); 1996 1997 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external 1998 // registers to require trimming. 1999 SmallVector<unsigned, 8> ShrinkRegs; 2000 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs); 2001 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs); 2002 while (!ShrinkRegs.empty()) 2003 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val())); 2004 2005 // Join RHS into LHS. 2006 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo, 2007 MRI); 2008 2009 // Kill flags are going to be wrong if the live ranges were overlapping. 2010 // Eventually, we should simply clear all kill flags when computing live 2011 // ranges. They are reinserted after register allocation. 2012 MRI->clearKillFlags(LHS.reg); 2013 MRI->clearKillFlags(RHS.reg); 2014 2015 if (EndPoints.empty()) 2016 return true; 2017 2018 // Recompute the parts of the live range we had to remove because of 2019 // CR_Replace conflicts. 2020 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size() 2021 << " points: " << LHS << '\n'); 2022 LIS->extendToIndices(&LHS, EndPoints); 2023 return true; 2024 } 2025 2026 /// joinIntervals - Attempt to join these two intervals. On failure, this 2027 /// returns false. 2028 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) { 2029 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP); 2030 } 2031 2032 namespace { 2033 // Information concerning MBB coalescing priority. 2034 struct MBBPriorityInfo { 2035 MachineBasicBlock *MBB; 2036 unsigned Depth; 2037 bool IsSplit; 2038 2039 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit) 2040 : MBB(mbb), Depth(depth), IsSplit(issplit) {} 2041 }; 2042 } 2043 2044 // C-style comparator that sorts first based on the loop depth of the basic 2045 // block (the unsigned), and then on the MBB number. 2046 // 2047 // EnableGlobalCopies assumes that the primary sort key is loop depth. 2048 static int compareMBBPriority(const void *L, const void *R) { 2049 const MBBPriorityInfo *LHS = static_cast<const MBBPriorityInfo*>(L); 2050 const MBBPriorityInfo *RHS = static_cast<const MBBPriorityInfo*>(R); 2051 // Deeper loops first 2052 if (LHS->Depth != RHS->Depth) 2053 return LHS->Depth > RHS->Depth ? -1 : 1; 2054 2055 // Try to unsplit critical edges next. 2056 if (LHS->IsSplit != RHS->IsSplit) 2057 return LHS->IsSplit ? -1 : 1; 2058 2059 // Prefer blocks that are more connected in the CFG. This takes care of 2060 // the most difficult copies first while intervals are short. 2061 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size(); 2062 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size(); 2063 if (cl != cr) 2064 return cl > cr ? -1 : 1; 2065 2066 // As a last resort, sort by block number. 2067 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1; 2068 } 2069 2070 /// \returns true if the given copy uses or defines a local live range. 2071 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) { 2072 if (!Copy->isCopy()) 2073 return false; 2074 2075 if (Copy->getOperand(1).isUndef()) 2076 return false; 2077 2078 unsigned SrcReg = Copy->getOperand(1).getReg(); 2079 unsigned DstReg = Copy->getOperand(0).getReg(); 2080 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) 2081 || TargetRegisterInfo::isPhysicalRegister(DstReg)) 2082 return false; 2083 2084 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg)) 2085 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg)); 2086 } 2087 2088 // Try joining WorkList copies starting from index From. 2089 // Null out any successful joins. 2090 bool RegisterCoalescer:: 2091 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) { 2092 bool Progress = false; 2093 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) { 2094 if (!CurrList[i]) 2095 continue; 2096 // Skip instruction pointers that have already been erased, for example by 2097 // dead code elimination. 2098 if (ErasedInstrs.erase(CurrList[i])) { 2099 CurrList[i] = 0; 2100 continue; 2101 } 2102 bool Again = false; 2103 bool Success = joinCopy(CurrList[i], Again); 2104 Progress |= Success; 2105 if (Success || !Again) 2106 CurrList[i] = 0; 2107 } 2108 return Progress; 2109 } 2110 2111 void 2112 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) { 2113 DEBUG(dbgs() << MBB->getName() << ":\n"); 2114 2115 // Collect all copy-like instructions in MBB. Don't start coalescing anything 2116 // yet, it might invalidate the iterator. 2117 const unsigned PrevSize = WorkList.size(); 2118 if (JoinGlobalCopies) { 2119 // Coalesce copies bottom-up to coalesce local defs before local uses. They 2120 // are not inherently easier to resolve, but slightly preferable until we 2121 // have local live range splitting. In particular this is required by 2122 // cmp+jmp macro fusion. 2123 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); 2124 MII != E; ++MII) { 2125 if (!MII->isCopyLike()) 2126 continue; 2127 if (isLocalCopy(&(*MII), LIS)) 2128 LocalWorkList.push_back(&(*MII)); 2129 else 2130 WorkList.push_back(&(*MII)); 2131 } 2132 } 2133 else { 2134 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); 2135 MII != E; ++MII) 2136 if (MII->isCopyLike()) 2137 WorkList.push_back(MII); 2138 } 2139 // Try coalescing the collected copies immediately, and remove the nulls. 2140 // This prevents the WorkList from getting too large since most copies are 2141 // joinable on the first attempt. 2142 MutableArrayRef<MachineInstr*> 2143 CurrList(WorkList.begin() + PrevSize, WorkList.end()); 2144 if (copyCoalesceWorkList(CurrList)) 2145 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(), 2146 (MachineInstr*)0), WorkList.end()); 2147 } 2148 2149 void RegisterCoalescer::coalesceLocals() { 2150 copyCoalesceWorkList(LocalWorkList); 2151 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) { 2152 if (LocalWorkList[j]) 2153 WorkList.push_back(LocalWorkList[j]); 2154 } 2155 LocalWorkList.clear(); 2156 } 2157 2158 void RegisterCoalescer::joinAllIntervals() { 2159 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n"); 2160 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around."); 2161 2162 std::vector<MBBPriorityInfo> MBBs; 2163 MBBs.reserve(MF->size()); 2164 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){ 2165 MachineBasicBlock *MBB = I; 2166 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB), 2167 JoinSplitEdges && isSplitEdge(MBB))); 2168 } 2169 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority); 2170 2171 // Coalesce intervals in MBB priority order. 2172 unsigned CurrDepth = UINT_MAX; 2173 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) { 2174 // Try coalescing the collected local copies for deeper loops. 2175 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) { 2176 coalesceLocals(); 2177 CurrDepth = MBBs[i].Depth; 2178 } 2179 copyCoalesceInMBB(MBBs[i].MBB); 2180 } 2181 coalesceLocals(); 2182 2183 // Joining intervals can allow other intervals to be joined. Iteratively join 2184 // until we make no progress. 2185 while (copyCoalesceWorkList(WorkList)) 2186 /* empty */ ; 2187 } 2188 2189 void RegisterCoalescer::releaseMemory() { 2190 ErasedInstrs.clear(); 2191 WorkList.clear(); 2192 DeadDefs.clear(); 2193 InflateRegs.clear(); 2194 } 2195 2196 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) { 2197 MF = &fn; 2198 MRI = &fn.getRegInfo(); 2199 TM = &fn.getTarget(); 2200 TRI = TM->getRegisterInfo(); 2201 TII = TM->getInstrInfo(); 2202 LIS = &getAnalysis<LiveIntervals>(); 2203 AA = &getAnalysis<AliasAnalysis>(); 2204 Loops = &getAnalysis<MachineLoopInfo>(); 2205 2206 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>(); 2207 if (EnableGlobalCopies == cl::BOU_UNSET) 2208 JoinGlobalCopies = ST.enableMachineScheduler(); 2209 else 2210 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE); 2211 2212 // The MachineScheduler does not currently require JoinSplitEdges. This will 2213 // either be enabled unconditionally or replaced by a more general live range 2214 // splitting optimization. 2215 JoinSplitEdges = EnableJoinSplits; 2216 2217 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n" 2218 << "********** Function: " << MF->getName() << '\n'); 2219 2220 if (VerifyCoalescing) 2221 MF->verify(this, "Before register coalescing"); 2222 2223 RegClassInfo.runOnMachineFunction(fn); 2224 2225 // Join (coalesce) intervals if requested. 2226 if (EnableJoining) 2227 joinAllIntervals(); 2228 2229 // After deleting a lot of copies, register classes may be less constrained. 2230 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 -> 2231 // DPR inflation. 2232 array_pod_sort(InflateRegs.begin(), InflateRegs.end()); 2233 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()), 2234 InflateRegs.end()); 2235 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n"); 2236 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) { 2237 unsigned Reg = InflateRegs[i]; 2238 if (MRI->reg_nodbg_empty(Reg)) 2239 continue; 2240 if (MRI->recomputeRegClass(Reg, *TM)) { 2241 DEBUG(dbgs() << PrintReg(Reg) << " inflated to " 2242 << MRI->getRegClass(Reg)->getName() << '\n'); 2243 ++NumInflated; 2244 } 2245 } 2246 2247 DEBUG(dump()); 2248 if (VerifyCoalescing) 2249 MF->verify(this, "After register coalescing"); 2250 return true; 2251 } 2252 2253 /// print - Implement the dump method. 2254 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const { 2255 LIS->print(O, m); 2256 } 2257