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