1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===// 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 TwoAddress instruction pass which is used 11 // by most register allocators. Two-Address instructions are rewritten 12 // from: 13 // 14 // A = B op C 15 // 16 // to: 17 // 18 // A = B 19 // A op= C 20 // 21 // Note that if a register allocator chooses to use this pass, that it 22 // has to be capable of handling the non-SSA nature of these rewritten 23 // virtual registers. 24 // 25 // It is also worth noting that the duplicate operand of the two 26 // address instruction is removed. 27 // 28 //===----------------------------------------------------------------------===// 29 30 #include "llvm/CodeGen/Passes.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallSet.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/Analysis/AliasAnalysis.h" 37 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 38 #include "llvm/CodeGen/LiveVariables.h" 39 #include "llvm/CodeGen/MachineFunctionPass.h" 40 #include "llvm/CodeGen/MachineInstr.h" 41 #include "llvm/CodeGen/MachineInstrBuilder.h" 42 #include "llvm/CodeGen/MachineRegisterInfo.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/MC/MCInstrItineraries.h" 45 #include "llvm/Support/CommandLine.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/ErrorHandling.h" 48 #include "llvm/Target/TargetInstrInfo.h" 49 #include "llvm/Target/TargetMachine.h" 50 #include "llvm/Target/TargetRegisterInfo.h" 51 #include "llvm/Target/TargetSubtargetInfo.h" 52 using namespace llvm; 53 54 #define DEBUG_TYPE "twoaddrinstr" 55 56 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions"); 57 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce"); 58 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted"); 59 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address"); 60 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk"); 61 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up"); 62 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down"); 63 64 // Temporary flag to disable rescheduling. 65 static cl::opt<bool> 66 EnableRescheduling("twoaddr-reschedule", 67 cl::desc("Coalesce copies by rescheduling (default=true)"), 68 cl::init(true), cl::Hidden); 69 70 namespace { 71 class TwoAddressInstructionPass : public MachineFunctionPass { 72 MachineFunction *MF; 73 const TargetInstrInfo *TII; 74 const TargetRegisterInfo *TRI; 75 const InstrItineraryData *InstrItins; 76 MachineRegisterInfo *MRI; 77 LiveVariables *LV; 78 LiveIntervals *LIS; 79 AliasAnalysis *AA; 80 CodeGenOpt::Level OptLevel; 81 82 // The current basic block being processed. 83 MachineBasicBlock *MBB; 84 85 // DistanceMap - Keep track the distance of a MI from the start of the 86 // current basic block. 87 DenseMap<MachineInstr*, unsigned> DistanceMap; 88 89 // Set of already processed instructions in the current block. 90 SmallPtrSet<MachineInstr*, 8> Processed; 91 92 // SrcRegMap - A map from virtual registers to physical registers which are 93 // likely targets to be coalesced to due to copies from physical registers to 94 // virtual registers. e.g. v1024 = move r0. 95 DenseMap<unsigned, unsigned> SrcRegMap; 96 97 // DstRegMap - A map from virtual registers to physical registers which are 98 // likely targets to be coalesced to due to copies to physical registers from 99 // virtual registers. e.g. r1 = move v1024. 100 DenseMap<unsigned, unsigned> DstRegMap; 101 102 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg, 103 MachineBasicBlock::iterator OldPos); 104 105 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen); 106 107 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef); 108 109 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC, 110 MachineInstr *MI, unsigned Dist); 111 112 bool commuteInstruction(MachineBasicBlock::iterator &mi, 113 unsigned RegB, unsigned RegC, unsigned Dist); 114 115 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB); 116 117 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi, 118 MachineBasicBlock::iterator &nmi, 119 unsigned RegA, unsigned RegB, unsigned Dist); 120 121 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI); 122 123 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi, 124 MachineBasicBlock::iterator &nmi, 125 unsigned Reg); 126 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi, 127 MachineBasicBlock::iterator &nmi, 128 unsigned Reg); 129 130 bool tryInstructionTransform(MachineBasicBlock::iterator &mi, 131 MachineBasicBlock::iterator &nmi, 132 unsigned SrcIdx, unsigned DstIdx, 133 unsigned Dist, bool shouldOnlyCommute); 134 135 void scanUses(unsigned DstReg); 136 137 void processCopy(MachineInstr *MI); 138 139 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList; 140 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap; 141 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&); 142 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist); 143 void eliminateRegSequence(MachineBasicBlock::iterator&); 144 145 public: 146 static char ID; // Pass identification, replacement for typeid 147 TwoAddressInstructionPass() : MachineFunctionPass(ID) { 148 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry()); 149 } 150 151 void getAnalysisUsage(AnalysisUsage &AU) const override { 152 AU.setPreservesCFG(); 153 AU.addRequired<AliasAnalysis>(); 154 AU.addPreserved<LiveVariables>(); 155 AU.addPreserved<SlotIndexes>(); 156 AU.addPreserved<LiveIntervals>(); 157 AU.addPreservedID(MachineLoopInfoID); 158 AU.addPreservedID(MachineDominatorsID); 159 MachineFunctionPass::getAnalysisUsage(AU); 160 } 161 162 /// runOnMachineFunction - Pass entry point. 163 bool runOnMachineFunction(MachineFunction&) override; 164 }; 165 } // end anonymous namespace 166 167 char TwoAddressInstructionPass::ID = 0; 168 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction", 169 "Two-Address instruction pass", false, false) 170 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 171 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction", 172 "Two-Address instruction pass", false, false) 173 174 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID; 175 176 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS); 177 178 /// sink3AddrInstruction - A two-address instruction has been converted to a 179 /// three-address instruction to avoid clobbering a register. Try to sink it 180 /// past the instruction that would kill the above mentioned register to reduce 181 /// register pressure. 182 bool TwoAddressInstructionPass:: 183 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg, 184 MachineBasicBlock::iterator OldPos) { 185 // FIXME: Shouldn't we be trying to do this before we three-addressify the 186 // instruction? After this transformation is done, we no longer need 187 // the instruction to be in three-address form. 188 189 // Check if it's safe to move this instruction. 190 bool SeenStore = true; // Be conservative. 191 if (!MI->isSafeToMove(TII, AA, SeenStore)) 192 return false; 193 194 unsigned DefReg = 0; 195 SmallSet<unsigned, 4> UseRegs; 196 197 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 198 const MachineOperand &MO = MI->getOperand(i); 199 if (!MO.isReg()) 200 continue; 201 unsigned MOReg = MO.getReg(); 202 if (!MOReg) 203 continue; 204 if (MO.isUse() && MOReg != SavedReg) 205 UseRegs.insert(MO.getReg()); 206 if (!MO.isDef()) 207 continue; 208 if (MO.isImplicit()) 209 // Don't try to move it if it implicitly defines a register. 210 return false; 211 if (DefReg) 212 // For now, don't move any instructions that define multiple registers. 213 return false; 214 DefReg = MO.getReg(); 215 } 216 217 // Find the instruction that kills SavedReg. 218 MachineInstr *KillMI = nullptr; 219 if (LIS) { 220 LiveInterval &LI = LIS->getInterval(SavedReg); 221 assert(LI.end() != LI.begin() && 222 "Reg should not have empty live interval."); 223 224 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 225 LiveInterval::const_iterator I = LI.find(MBBEndIdx); 226 if (I != LI.end() && I->start < MBBEndIdx) 227 return false; 228 229 --I; 230 KillMI = LIS->getInstructionFromIndex(I->end); 231 } 232 if (!KillMI) { 233 for (MachineRegisterInfo::use_nodbg_iterator 234 UI = MRI->use_nodbg_begin(SavedReg), 235 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 236 MachineOperand &UseMO = *UI; 237 if (!UseMO.isKill()) 238 continue; 239 KillMI = UseMO.getParent(); 240 break; 241 } 242 } 243 244 // If we find the instruction that kills SavedReg, and it is in an 245 // appropriate location, we can try to sink the current instruction 246 // past it. 247 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI || 248 KillMI == OldPos || KillMI->isTerminator()) 249 return false; 250 251 // If any of the definitions are used by another instruction between the 252 // position and the kill use, then it's not safe to sink it. 253 // 254 // FIXME: This can be sped up if there is an easy way to query whether an 255 // instruction is before or after another instruction. Then we can use 256 // MachineRegisterInfo def / use instead. 257 MachineOperand *KillMO = nullptr; 258 MachineBasicBlock::iterator KillPos = KillMI; 259 ++KillPos; 260 261 unsigned NumVisited = 0; 262 for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) { 263 MachineInstr *OtherMI = I; 264 // DBG_VALUE cannot be counted against the limit. 265 if (OtherMI->isDebugValue()) 266 continue; 267 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost. 268 return false; 269 ++NumVisited; 270 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) { 271 MachineOperand &MO = OtherMI->getOperand(i); 272 if (!MO.isReg()) 273 continue; 274 unsigned MOReg = MO.getReg(); 275 if (!MOReg) 276 continue; 277 if (DefReg == MOReg) 278 return false; 279 280 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) { 281 if (OtherMI == KillMI && MOReg == SavedReg) 282 // Save the operand that kills the register. We want to unset the kill 283 // marker if we can sink MI past it. 284 KillMO = &MO; 285 else if (UseRegs.count(MOReg)) 286 // One of the uses is killed before the destination. 287 return false; 288 } 289 } 290 } 291 assert(KillMO && "Didn't find kill"); 292 293 if (!LIS) { 294 // Update kill and LV information. 295 KillMO->setIsKill(false); 296 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI); 297 KillMO->setIsKill(true); 298 299 if (LV) 300 LV->replaceKillInstruction(SavedReg, KillMI, MI); 301 } 302 303 // Move instruction to its destination. 304 MBB->remove(MI); 305 MBB->insert(KillPos, MI); 306 307 if (LIS) 308 LIS->handleMove(MI); 309 310 ++Num3AddrSunk; 311 return true; 312 } 313 314 /// getSingleDef -- return the MachineInstr* if it is the single def of the Reg 315 /// in current BB. 316 static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB, 317 const MachineRegisterInfo *MRI) { 318 MachineInstr *Ret = nullptr; 319 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) { 320 if (DefMI.getParent() != BB || DefMI.isDebugValue()) 321 continue; 322 if (!Ret) 323 Ret = &DefMI; 324 else if (Ret != &DefMI) 325 return nullptr; 326 } 327 return Ret; 328 } 329 330 /// Check if there is a reversed copy chain from FromReg to ToReg: 331 /// %Tmp1 = copy %Tmp2; 332 /// %FromReg = copy %Tmp1; 333 /// %ToReg = add %FromReg ... 334 /// %Tmp2 = copy %ToReg; 335 /// MaxLen specifies the maximum length of the copy chain the func 336 /// can walk through. 337 bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg, 338 int Maxlen) { 339 unsigned TmpReg = FromReg; 340 for (int i = 0; i < Maxlen; i++) { 341 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI); 342 if (!Def || !Def->isCopy()) 343 return false; 344 345 TmpReg = Def->getOperand(1).getReg(); 346 347 if (TmpReg == ToReg) 348 return true; 349 } 350 return false; 351 } 352 353 /// noUseAfterLastDef - Return true if there are no intervening uses between the 354 /// last instruction in the MBB that defines the specified register and the 355 /// two-address instruction which is being processed. It also returns the last 356 /// def location by reference 357 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist, 358 unsigned &LastDef) { 359 LastDef = 0; 360 unsigned LastUse = Dist; 361 for (MachineOperand &MO : MRI->reg_operands(Reg)) { 362 MachineInstr *MI = MO.getParent(); 363 if (MI->getParent() != MBB || MI->isDebugValue()) 364 continue; 365 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 366 if (DI == DistanceMap.end()) 367 continue; 368 if (MO.isUse() && DI->second < LastUse) 369 LastUse = DI->second; 370 if (MO.isDef() && DI->second > LastDef) 371 LastDef = DI->second; 372 } 373 374 return !(LastUse > LastDef && LastUse < Dist); 375 } 376 377 /// isCopyToReg - Return true if the specified MI is a copy instruction or 378 /// a extract_subreg instruction. It also returns the source and destination 379 /// registers and whether they are physical registers by reference. 380 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII, 381 unsigned &SrcReg, unsigned &DstReg, 382 bool &IsSrcPhys, bool &IsDstPhys) { 383 SrcReg = 0; 384 DstReg = 0; 385 if (MI.isCopy()) { 386 DstReg = MI.getOperand(0).getReg(); 387 SrcReg = MI.getOperand(1).getReg(); 388 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) { 389 DstReg = MI.getOperand(0).getReg(); 390 SrcReg = MI.getOperand(2).getReg(); 391 } else 392 return false; 393 394 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg); 395 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 396 return true; 397 } 398 399 /// isPLainlyKilled - Test if the given register value, which is used by the 400 // given instruction, is killed by the given instruction. 401 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, 402 LiveIntervals *LIS) { 403 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) && 404 !LIS->isNotInMIMap(MI)) { 405 // FIXME: Sometimes tryInstructionTransform() will add instructions and 406 // test whether they can be folded before keeping them. In this case it 407 // sets a kill before recursively calling tryInstructionTransform() again. 408 // If there is no interval available, we assume that this instruction is 409 // one of those. A kill flag is manually inserted on the operand so the 410 // check below will handle it. 411 LiveInterval &LI = LIS->getInterval(Reg); 412 // This is to match the kill flag version where undefs don't have kill 413 // flags. 414 if (!LI.hasAtLeastOneValue()) 415 return false; 416 417 SlotIndex useIdx = LIS->getInstructionIndex(MI); 418 LiveInterval::const_iterator I = LI.find(useIdx); 419 assert(I != LI.end() && "Reg must be live-in to use."); 420 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx); 421 } 422 423 return MI->killsRegister(Reg); 424 } 425 426 /// isKilled - Test if the given register value, which is used by the given 427 /// instruction, is killed by the given instruction. This looks through 428 /// coalescable copies to see if the original value is potentially not killed. 429 /// 430 /// For example, in this code: 431 /// 432 /// %reg1034 = copy %reg1024 433 /// %reg1035 = copy %reg1025<kill> 434 /// %reg1036 = add %reg1034<kill>, %reg1035<kill> 435 /// 436 /// %reg1034 is not considered to be killed, since it is copied from a 437 /// register which is not killed. Treating it as not killed lets the 438 /// normal heuristics commute the (two-address) add, which lets 439 /// coalescing eliminate the extra copy. 440 /// 441 /// If allowFalsePositives is true then likely kills are treated as kills even 442 /// if it can't be proven that they are kills. 443 static bool isKilled(MachineInstr &MI, unsigned Reg, 444 const MachineRegisterInfo *MRI, 445 const TargetInstrInfo *TII, 446 LiveIntervals *LIS, 447 bool allowFalsePositives) { 448 MachineInstr *DefMI = &MI; 449 for (;;) { 450 // All uses of physical registers are likely to be kills. 451 if (TargetRegisterInfo::isPhysicalRegister(Reg) && 452 (allowFalsePositives || MRI->hasOneUse(Reg))) 453 return true; 454 if (!isPlainlyKilled(DefMI, Reg, LIS)) 455 return false; 456 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 457 return true; 458 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg); 459 // If there are multiple defs, we can't do a simple analysis, so just 460 // go with what the kill flag says. 461 if (std::next(Begin) != MRI->def_end()) 462 return true; 463 DefMI = Begin->getParent(); 464 bool IsSrcPhys, IsDstPhys; 465 unsigned SrcReg, DstReg; 466 // If the def is something other than a copy, then it isn't going to 467 // be coalesced, so follow the kill flag. 468 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 469 return true; 470 Reg = SrcReg; 471 } 472 } 473 474 /// isTwoAddrUse - Return true if the specified MI uses the specified register 475 /// as a two-address use. If so, return the destination register by reference. 476 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) { 477 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) { 478 const MachineOperand &MO = MI.getOperand(i); 479 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg) 480 continue; 481 unsigned ti; 482 if (MI.isRegTiedToDefOperand(i, &ti)) { 483 DstReg = MI.getOperand(ti).getReg(); 484 return true; 485 } 486 } 487 return false; 488 } 489 490 /// findOnlyInterestingUse - Given a register, if has a single in-basic block 491 /// use, return the use instruction if it's a copy or a two-address use. 492 static 493 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB, 494 MachineRegisterInfo *MRI, 495 const TargetInstrInfo *TII, 496 bool &IsCopy, 497 unsigned &DstReg, bool &IsDstPhys) { 498 if (!MRI->hasOneNonDBGUse(Reg)) 499 // None or more than one use. 500 return nullptr; 501 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg); 502 if (UseMI.getParent() != MBB) 503 return nullptr; 504 unsigned SrcReg; 505 bool IsSrcPhys; 506 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) { 507 IsCopy = true; 508 return &UseMI; 509 } 510 IsDstPhys = false; 511 if (isTwoAddrUse(UseMI, Reg, DstReg)) { 512 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 513 return &UseMI; 514 } 515 return nullptr; 516 } 517 518 /// getMappedReg - Return the physical register the specified virtual register 519 /// might be mapped to. 520 static unsigned 521 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) { 522 while (TargetRegisterInfo::isVirtualRegister(Reg)) { 523 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg); 524 if (SI == RegMap.end()) 525 return 0; 526 Reg = SI->second; 527 } 528 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 529 return Reg; 530 return 0; 531 } 532 533 /// regsAreCompatible - Return true if the two registers are equal or aliased. 534 /// 535 static bool 536 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) { 537 if (RegA == RegB) 538 return true; 539 if (!RegA || !RegB) 540 return false; 541 return TRI->regsOverlap(RegA, RegB); 542 } 543 544 545 /// isProfitableToCommute - Return true if it's potentially profitable to commute 546 /// the two-address instruction that's being processed. 547 bool 548 TwoAddressInstructionPass:: 549 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC, 550 MachineInstr *MI, unsigned Dist) { 551 if (OptLevel == CodeGenOpt::None) 552 return false; 553 554 // Determine if it's profitable to commute this two address instruction. In 555 // general, we want no uses between this instruction and the definition of 556 // the two-address register. 557 // e.g. 558 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1 559 // %reg1029<def> = MOV8rr %reg1028 560 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead> 561 // insert => %reg1030<def> = MOV8rr %reg1028 562 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead> 563 // In this case, it might not be possible to coalesce the second MOV8rr 564 // instruction if the first one is coalesced. So it would be profitable to 565 // commute it: 566 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1 567 // %reg1029<def> = MOV8rr %reg1028 568 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead> 569 // insert => %reg1030<def> = MOV8rr %reg1029 570 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead> 571 572 if (!isPlainlyKilled(MI, regC, LIS)) 573 return false; 574 575 // Ok, we have something like: 576 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead> 577 // let's see if it's worth commuting it. 578 579 // Look for situations like this: 580 // %reg1024<def> = MOV r1 581 // %reg1025<def> = MOV r0 582 // %reg1026<def> = ADD %reg1024, %reg1025 583 // r0 = MOV %reg1026 584 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy. 585 unsigned ToRegA = getMappedReg(regA, DstRegMap); 586 if (ToRegA) { 587 unsigned FromRegB = getMappedReg(regB, SrcRegMap); 588 unsigned FromRegC = getMappedReg(regC, SrcRegMap); 589 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI); 590 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI); 591 592 // Compute if any of the following are true: 593 // -RegB is not tied to a register and RegC is compatible with RegA. 594 // -RegB is tied to the wrong physical register, but RegC is. 595 // -RegB is tied to the wrong physical register, and RegC isn't tied. 596 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC))) 597 return true; 598 // Don't compute if any of the following are true: 599 // -RegC is not tied to a register and RegB is compatible with RegA. 600 // -RegC is tied to the wrong physical register, but RegB is. 601 // -RegC is tied to the wrong physical register, and RegB isn't tied. 602 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB))) 603 return false; 604 } 605 606 // If there is a use of regC between its last def (could be livein) and this 607 // instruction, then bail. 608 unsigned LastDefC = 0; 609 if (!noUseAfterLastDef(regC, Dist, LastDefC)) 610 return false; 611 612 // If there is a use of regB between its last def (could be livein) and this 613 // instruction, then go ahead and make this transformation. 614 unsigned LastDefB = 0; 615 if (!noUseAfterLastDef(regB, Dist, LastDefB)) 616 return true; 617 618 // Look for situation like this: 619 // %reg101 = MOV %reg100 620 // %reg102 = ... 621 // %reg103 = ADD %reg102, %reg101 622 // ... = %reg103 ... 623 // %reg100 = MOV %reg103 624 // If there is a reversed copy chain from reg101 to reg103, commute the ADD 625 // to eliminate an otherwise unavoidable copy. 626 // FIXME: 627 // We can extend the logic further: If an pair of operands in an insn has 628 // been merged, the insn could be regarded as a virtual copy, and the virtual 629 // copy could also be used to construct a copy chain. 630 // To more generally minimize register copies, ideally the logic of two addr 631 // instruction pass should be integrated with register allocation pass where 632 // interference graph is available. 633 if (isRevCopyChain(regC, regA, 3)) 634 return true; 635 636 if (isRevCopyChain(regB, regA, 3)) 637 return false; 638 639 // Since there are no intervening uses for both registers, then commute 640 // if the def of regC is closer. Its live interval is shorter. 641 return LastDefB && LastDefC && LastDefC > LastDefB; 642 } 643 644 /// commuteInstruction - Commute a two-address instruction and update the basic 645 /// block, distance map, and live variables if needed. Return true if it is 646 /// successful. 647 bool TwoAddressInstructionPass:: 648 commuteInstruction(MachineBasicBlock::iterator &mi, 649 unsigned RegB, unsigned RegC, unsigned Dist) { 650 MachineInstr *MI = mi; 651 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI); 652 MachineInstr *NewMI = TII->commuteInstruction(MI); 653 654 if (NewMI == nullptr) { 655 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n"); 656 return false; 657 } 658 659 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI); 660 assert(NewMI == MI && 661 "TargetInstrInfo::commuteInstruction() should not return a new " 662 "instruction unless it was requested."); 663 664 // Update source register map. 665 unsigned FromRegC = getMappedReg(RegC, SrcRegMap); 666 if (FromRegC) { 667 unsigned RegA = MI->getOperand(0).getReg(); 668 SrcRegMap[RegA] = FromRegC; 669 } 670 671 return true; 672 } 673 674 /// isProfitableToConv3Addr - Return true if it is profitable to convert the 675 /// given 2-address instruction to a 3-address one. 676 bool 677 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){ 678 // Look for situations like this: 679 // %reg1024<def> = MOV r1 680 // %reg1025<def> = MOV r0 681 // %reg1026<def> = ADD %reg1024, %reg1025 682 // r2 = MOV %reg1026 683 // Turn ADD into a 3-address instruction to avoid a copy. 684 unsigned FromRegB = getMappedReg(RegB, SrcRegMap); 685 if (!FromRegB) 686 return false; 687 unsigned ToRegA = getMappedReg(RegA, DstRegMap); 688 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI)); 689 } 690 691 /// convertInstTo3Addr - Convert the specified two-address instruction into a 692 /// three address one. Return true if this transformation was successful. 693 bool 694 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi, 695 MachineBasicBlock::iterator &nmi, 696 unsigned RegA, unsigned RegB, 697 unsigned Dist) { 698 // FIXME: Why does convertToThreeAddress() need an iterator reference? 699 MachineFunction::iterator MFI = MBB; 700 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV); 701 assert(MBB == MFI && "convertToThreeAddress changed iterator reference"); 702 if (!NewMI) 703 return false; 704 705 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi); 706 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI); 707 bool Sunk = false; 708 709 if (LIS) 710 LIS->ReplaceMachineInstrInMaps(mi, NewMI); 711 712 if (NewMI->findRegisterUseOperand(RegB, false, TRI)) 713 // FIXME: Temporary workaround. If the new instruction doesn't 714 // uses RegB, convertToThreeAddress must have created more 715 // then one instruction. 716 Sunk = sink3AddrInstruction(NewMI, RegB, mi); 717 718 MBB->erase(mi); // Nuke the old inst. 719 720 if (!Sunk) { 721 DistanceMap.insert(std::make_pair(NewMI, Dist)); 722 mi = NewMI; 723 nmi = std::next(mi); 724 } 725 726 // Update source and destination register maps. 727 SrcRegMap.erase(RegA); 728 DstRegMap.erase(RegB); 729 return true; 730 } 731 732 /// scanUses - Scan forward recursively for only uses, update maps if the use 733 /// is a copy or a two-address instruction. 734 void 735 TwoAddressInstructionPass::scanUses(unsigned DstReg) { 736 SmallVector<unsigned, 4> VirtRegPairs; 737 bool IsDstPhys; 738 bool IsCopy = false; 739 unsigned NewReg = 0; 740 unsigned Reg = DstReg; 741 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy, 742 NewReg, IsDstPhys)) { 743 if (IsCopy && !Processed.insert(UseMI).second) 744 break; 745 746 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI); 747 if (DI != DistanceMap.end()) 748 // Earlier in the same MBB.Reached via a back edge. 749 break; 750 751 if (IsDstPhys) { 752 VirtRegPairs.push_back(NewReg); 753 break; 754 } 755 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second; 756 if (!isNew) 757 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!"); 758 VirtRegPairs.push_back(NewReg); 759 Reg = NewReg; 760 } 761 762 if (!VirtRegPairs.empty()) { 763 unsigned ToReg = VirtRegPairs.back(); 764 VirtRegPairs.pop_back(); 765 while (!VirtRegPairs.empty()) { 766 unsigned FromReg = VirtRegPairs.back(); 767 VirtRegPairs.pop_back(); 768 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second; 769 if (!isNew) 770 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!"); 771 ToReg = FromReg; 772 } 773 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second; 774 if (!isNew) 775 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!"); 776 } 777 } 778 779 /// processCopy - If the specified instruction is not yet processed, process it 780 /// if it's a copy. For a copy instruction, we find the physical registers the 781 /// source and destination registers might be mapped to. These are kept in 782 /// point-to maps used to determine future optimizations. e.g. 783 /// v1024 = mov r0 784 /// v1025 = mov r1 785 /// v1026 = add v1024, v1025 786 /// r1 = mov r1026 787 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially 788 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is 789 /// potentially joined with r1 on the output side. It's worthwhile to commute 790 /// 'add' to eliminate a copy. 791 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) { 792 if (Processed.count(MI)) 793 return; 794 795 bool IsSrcPhys, IsDstPhys; 796 unsigned SrcReg, DstReg; 797 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 798 return; 799 800 if (IsDstPhys && !IsSrcPhys) 801 DstRegMap.insert(std::make_pair(SrcReg, DstReg)); 802 else if (!IsDstPhys && IsSrcPhys) { 803 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second; 804 if (!isNew) 805 assert(SrcRegMap[DstReg] == SrcReg && 806 "Can't map to two src physical registers!"); 807 808 scanUses(DstReg); 809 } 810 811 Processed.insert(MI); 812 return; 813 } 814 815 /// rescheduleMIBelowKill - If there is one more local instruction that reads 816 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill 817 /// instruction in order to eliminate the need for the copy. 818 bool TwoAddressInstructionPass:: 819 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi, 820 MachineBasicBlock::iterator &nmi, 821 unsigned Reg) { 822 // Bail immediately if we don't have LV or LIS available. We use them to find 823 // kills efficiently. 824 if (!LV && !LIS) 825 return false; 826 827 MachineInstr *MI = &*mi; 828 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 829 if (DI == DistanceMap.end()) 830 // Must be created from unfolded load. Don't waste time trying this. 831 return false; 832 833 MachineInstr *KillMI = nullptr; 834 if (LIS) { 835 LiveInterval &LI = LIS->getInterval(Reg); 836 assert(LI.end() != LI.begin() && 837 "Reg should not have empty live interval."); 838 839 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 840 LiveInterval::const_iterator I = LI.find(MBBEndIdx); 841 if (I != LI.end() && I->start < MBBEndIdx) 842 return false; 843 844 --I; 845 KillMI = LIS->getInstructionFromIndex(I->end); 846 } else { 847 KillMI = LV->getVarInfo(Reg).findKill(MBB); 848 } 849 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 850 // Don't mess with copies, they may be coalesced later. 851 return false; 852 853 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() || 854 KillMI->isBranch() || KillMI->isTerminator()) 855 // Don't move pass calls, etc. 856 return false; 857 858 unsigned DstReg; 859 if (isTwoAddrUse(*KillMI, Reg, DstReg)) 860 return false; 861 862 bool SeenStore = true; 863 if (!MI->isSafeToMove(TII, AA, SeenStore)) 864 return false; 865 866 if (TII->getInstrLatency(InstrItins, MI) > 1) 867 // FIXME: Needs more sophisticated heuristics. 868 return false; 869 870 SmallSet<unsigned, 2> Uses; 871 SmallSet<unsigned, 2> Kills; 872 SmallSet<unsigned, 2> Defs; 873 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 874 const MachineOperand &MO = MI->getOperand(i); 875 if (!MO.isReg()) 876 continue; 877 unsigned MOReg = MO.getReg(); 878 if (!MOReg) 879 continue; 880 if (MO.isDef()) 881 Defs.insert(MOReg); 882 else { 883 Uses.insert(MOReg); 884 if (MOReg != Reg && (MO.isKill() || 885 (LIS && isPlainlyKilled(MI, MOReg, LIS)))) 886 Kills.insert(MOReg); 887 } 888 } 889 890 // Move the copies connected to MI down as well. 891 MachineBasicBlock::iterator Begin = MI; 892 MachineBasicBlock::iterator AfterMI = std::next(Begin); 893 894 MachineBasicBlock::iterator End = AfterMI; 895 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) { 896 Defs.insert(End->getOperand(0).getReg()); 897 ++End; 898 } 899 900 // Check if the reschedule will not break depedencies. 901 unsigned NumVisited = 0; 902 MachineBasicBlock::iterator KillPos = KillMI; 903 ++KillPos; 904 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) { 905 MachineInstr *OtherMI = I; 906 // DBG_VALUE cannot be counted against the limit. 907 if (OtherMI->isDebugValue()) 908 continue; 909 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 910 return false; 911 ++NumVisited; 912 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() || 913 OtherMI->isBranch() || OtherMI->isTerminator()) 914 // Don't move pass calls, etc. 915 return false; 916 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) { 917 const MachineOperand &MO = OtherMI->getOperand(i); 918 if (!MO.isReg()) 919 continue; 920 unsigned MOReg = MO.getReg(); 921 if (!MOReg) 922 continue; 923 if (MO.isDef()) { 924 if (Uses.count(MOReg)) 925 // Physical register use would be clobbered. 926 return false; 927 if (!MO.isDead() && Defs.count(MOReg)) 928 // May clobber a physical register def. 929 // FIXME: This may be too conservative. It's ok if the instruction 930 // is sunken completely below the use. 931 return false; 932 } else { 933 if (Defs.count(MOReg)) 934 return false; 935 bool isKill = MO.isKill() || 936 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS)); 937 if (MOReg != Reg && 938 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg))) 939 // Don't want to extend other live ranges and update kills. 940 return false; 941 if (MOReg == Reg && !isKill) 942 // We can't schedule across a use of the register in question. 943 return false; 944 // Ensure that if this is register in question, its the kill we expect. 945 assert((MOReg != Reg || OtherMI == KillMI) && 946 "Found multiple kills of a register in a basic block"); 947 } 948 } 949 } 950 951 // Move debug info as well. 952 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue()) 953 --Begin; 954 955 nmi = End; 956 MachineBasicBlock::iterator InsertPos = KillPos; 957 if (LIS) { 958 // We have to move the copies first so that the MBB is still well-formed 959 // when calling handleMove(). 960 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) { 961 MachineInstr *CopyMI = MBBI; 962 ++MBBI; 963 MBB->splice(InsertPos, MBB, CopyMI); 964 LIS->handleMove(CopyMI); 965 InsertPos = CopyMI; 966 } 967 End = std::next(MachineBasicBlock::iterator(MI)); 968 } 969 970 // Copies following MI may have been moved as well. 971 MBB->splice(InsertPos, MBB, Begin, End); 972 DistanceMap.erase(DI); 973 974 // Update live variables 975 if (LIS) { 976 LIS->handleMove(MI); 977 } else { 978 LV->removeVirtualRegisterKilled(Reg, KillMI); 979 LV->addVirtualRegisterKilled(Reg, MI); 980 } 981 982 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI); 983 return true; 984 } 985 986 /// isDefTooClose - Return true if the re-scheduling will put the given 987 /// instruction too close to the defs of its register dependencies. 988 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist, 989 MachineInstr *MI) { 990 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) { 991 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike()) 992 continue; 993 if (&DefMI == MI) 994 return true; // MI is defining something KillMI uses 995 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI); 996 if (DDI == DistanceMap.end()) 997 return true; // Below MI 998 unsigned DefDist = DDI->second; 999 assert(Dist > DefDist && "Visited def already?"); 1000 if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist)) 1001 return true; 1002 } 1003 return false; 1004 } 1005 1006 /// rescheduleKillAboveMI - If there is one more local instruction that reads 1007 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the 1008 /// current two-address instruction in order to eliminate the need for the 1009 /// copy. 1010 bool TwoAddressInstructionPass:: 1011 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi, 1012 MachineBasicBlock::iterator &nmi, 1013 unsigned Reg) { 1014 // Bail immediately if we don't have LV or LIS available. We use them to find 1015 // kills efficiently. 1016 if (!LV && !LIS) 1017 return false; 1018 1019 MachineInstr *MI = &*mi; 1020 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 1021 if (DI == DistanceMap.end()) 1022 // Must be created from unfolded load. Don't waste time trying this. 1023 return false; 1024 1025 MachineInstr *KillMI = nullptr; 1026 if (LIS) { 1027 LiveInterval &LI = LIS->getInterval(Reg); 1028 assert(LI.end() != LI.begin() && 1029 "Reg should not have empty live interval."); 1030 1031 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 1032 LiveInterval::const_iterator I = LI.find(MBBEndIdx); 1033 if (I != LI.end() && I->start < MBBEndIdx) 1034 return false; 1035 1036 --I; 1037 KillMI = LIS->getInstructionFromIndex(I->end); 1038 } else { 1039 KillMI = LV->getVarInfo(Reg).findKill(MBB); 1040 } 1041 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 1042 // Don't mess with copies, they may be coalesced later. 1043 return false; 1044 1045 unsigned DstReg; 1046 if (isTwoAddrUse(*KillMI, Reg, DstReg)) 1047 return false; 1048 1049 bool SeenStore = true; 1050 if (!KillMI->isSafeToMove(TII, AA, SeenStore)) 1051 return false; 1052 1053 SmallSet<unsigned, 2> Uses; 1054 SmallSet<unsigned, 2> Kills; 1055 SmallSet<unsigned, 2> Defs; 1056 SmallSet<unsigned, 2> LiveDefs; 1057 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) { 1058 const MachineOperand &MO = KillMI->getOperand(i); 1059 if (!MO.isReg()) 1060 continue; 1061 unsigned MOReg = MO.getReg(); 1062 if (MO.isUse()) { 1063 if (!MOReg) 1064 continue; 1065 if (isDefTooClose(MOReg, DI->second, MI)) 1066 return false; 1067 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS)); 1068 if (MOReg == Reg && !isKill) 1069 return false; 1070 Uses.insert(MOReg); 1071 if (isKill && MOReg != Reg) 1072 Kills.insert(MOReg); 1073 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) { 1074 Defs.insert(MOReg); 1075 if (!MO.isDead()) 1076 LiveDefs.insert(MOReg); 1077 } 1078 } 1079 1080 // Check if the reschedule will not break depedencies. 1081 unsigned NumVisited = 0; 1082 MachineBasicBlock::iterator KillPos = KillMI; 1083 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) { 1084 MachineInstr *OtherMI = I; 1085 // DBG_VALUE cannot be counted against the limit. 1086 if (OtherMI->isDebugValue()) 1087 continue; 1088 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 1089 return false; 1090 ++NumVisited; 1091 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() || 1092 OtherMI->isBranch() || OtherMI->isTerminator()) 1093 // Don't move pass calls, etc. 1094 return false; 1095 SmallVector<unsigned, 2> OtherDefs; 1096 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) { 1097 const MachineOperand &MO = OtherMI->getOperand(i); 1098 if (!MO.isReg()) 1099 continue; 1100 unsigned MOReg = MO.getReg(); 1101 if (!MOReg) 1102 continue; 1103 if (MO.isUse()) { 1104 if (Defs.count(MOReg)) 1105 // Moving KillMI can clobber the physical register if the def has 1106 // not been seen. 1107 return false; 1108 if (Kills.count(MOReg)) 1109 // Don't want to extend other live ranges and update kills. 1110 return false; 1111 if (OtherMI != MI && MOReg == Reg && 1112 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS)))) 1113 // We can't schedule across a use of the register in question. 1114 return false; 1115 } else { 1116 OtherDefs.push_back(MOReg); 1117 } 1118 } 1119 1120 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) { 1121 unsigned MOReg = OtherDefs[i]; 1122 if (Uses.count(MOReg)) 1123 return false; 1124 if (TargetRegisterInfo::isPhysicalRegister(MOReg) && 1125 LiveDefs.count(MOReg)) 1126 return false; 1127 // Physical register def is seen. 1128 Defs.erase(MOReg); 1129 } 1130 } 1131 1132 // Move the old kill above MI, don't forget to move debug info as well. 1133 MachineBasicBlock::iterator InsertPos = mi; 1134 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue()) 1135 --InsertPos; 1136 MachineBasicBlock::iterator From = KillMI; 1137 MachineBasicBlock::iterator To = std::next(From); 1138 while (std::prev(From)->isDebugValue()) 1139 --From; 1140 MBB->splice(InsertPos, MBB, From, To); 1141 1142 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr. 1143 DistanceMap.erase(DI); 1144 1145 // Update live variables 1146 if (LIS) { 1147 LIS->handleMove(KillMI); 1148 } else { 1149 LV->removeVirtualRegisterKilled(Reg, KillMI); 1150 LV->addVirtualRegisterKilled(Reg, MI); 1151 } 1152 1153 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI); 1154 return true; 1155 } 1156 1157 /// tryInstructionTransform - For the case where an instruction has a single 1158 /// pair of tied register operands, attempt some transformations that may 1159 /// either eliminate the tied operands or improve the opportunities for 1160 /// coalescing away the register copy. Returns true if no copy needs to be 1161 /// inserted to untie mi's operands (either because they were untied, or 1162 /// because mi was rescheduled, and will be visited again later). If the 1163 /// shouldOnlyCommute flag is true, only instruction commutation is attempted. 1164 bool TwoAddressInstructionPass:: 1165 tryInstructionTransform(MachineBasicBlock::iterator &mi, 1166 MachineBasicBlock::iterator &nmi, 1167 unsigned SrcIdx, unsigned DstIdx, 1168 unsigned Dist, bool shouldOnlyCommute) { 1169 if (OptLevel == CodeGenOpt::None) 1170 return false; 1171 1172 MachineInstr &MI = *mi; 1173 unsigned regA = MI.getOperand(DstIdx).getReg(); 1174 unsigned regB = MI.getOperand(SrcIdx).getReg(); 1175 1176 assert(TargetRegisterInfo::isVirtualRegister(regB) && 1177 "cannot make instruction into two-address form"); 1178 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true); 1179 1180 if (TargetRegisterInfo::isVirtualRegister(regA)) 1181 scanUses(regA); 1182 1183 // Check if it is profitable to commute the operands. 1184 unsigned SrcOp1, SrcOp2; 1185 unsigned regC = 0; 1186 unsigned regCIdx = ~0U; 1187 bool TryCommute = false; 1188 bool AggressiveCommute = false; 1189 if (MI.isCommutable() && MI.getNumOperands() >= 3 && 1190 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) { 1191 if (SrcIdx == SrcOp1) 1192 regCIdx = SrcOp2; 1193 else if (SrcIdx == SrcOp2) 1194 regCIdx = SrcOp1; 1195 1196 if (regCIdx != ~0U) { 1197 regC = MI.getOperand(regCIdx).getReg(); 1198 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false)) 1199 // If C dies but B does not, swap the B and C operands. 1200 // This makes the live ranges of A and C joinable. 1201 TryCommute = true; 1202 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) { 1203 TryCommute = true; 1204 AggressiveCommute = true; 1205 } 1206 } 1207 } 1208 1209 // If it's profitable to commute, try to do so. 1210 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) { 1211 ++NumCommuted; 1212 if (AggressiveCommute) 1213 ++NumAggrCommuted; 1214 return false; 1215 } 1216 1217 if (shouldOnlyCommute) 1218 return false; 1219 1220 // If there is one more use of regB later in the same MBB, consider 1221 // re-schedule this MI below it. 1222 if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) { 1223 ++NumReSchedDowns; 1224 return true; 1225 } 1226 1227 if (MI.isConvertibleTo3Addr()) { 1228 // This instruction is potentially convertible to a true 1229 // three-address instruction. Check if it is profitable. 1230 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) { 1231 // Try to convert it. 1232 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) { 1233 ++NumConvertedTo3Addr; 1234 return true; // Done with this instruction. 1235 } 1236 } 1237 } 1238 1239 // If there is one more use of regB later in the same MBB, consider 1240 // re-schedule it before this MI if it's legal. 1241 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) { 1242 ++NumReSchedUps; 1243 return true; 1244 } 1245 1246 // If this is an instruction with a load folded into it, try unfolding 1247 // the load, e.g. avoid this: 1248 // movq %rdx, %rcx 1249 // addq (%rax), %rcx 1250 // in favor of this: 1251 // movq (%rax), %rcx 1252 // addq %rdx, %rcx 1253 // because it's preferable to schedule a load than a register copy. 1254 if (MI.mayLoad() && !regBKilled) { 1255 // Determine if a load can be unfolded. 1256 unsigned LoadRegIndex; 1257 unsigned NewOpc = 1258 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), 1259 /*UnfoldLoad=*/true, 1260 /*UnfoldStore=*/false, 1261 &LoadRegIndex); 1262 if (NewOpc != 0) { 1263 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc); 1264 if (UnfoldMCID.getNumDefs() == 1) { 1265 // Unfold the load. 1266 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI); 1267 const TargetRegisterClass *RC = 1268 TRI->getAllocatableClass( 1269 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF)); 1270 unsigned Reg = MRI->createVirtualRegister(RC); 1271 SmallVector<MachineInstr *, 2> NewMIs; 1272 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg, 1273 /*UnfoldLoad=*/true,/*UnfoldStore=*/false, 1274 NewMIs)) { 1275 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 1276 return false; 1277 } 1278 assert(NewMIs.size() == 2 && 1279 "Unfolded a load into multiple instructions!"); 1280 // The load was previously folded, so this is the only use. 1281 NewMIs[1]->addRegisterKilled(Reg, TRI); 1282 1283 // Tentatively insert the instructions into the block so that they 1284 // look "normal" to the transformation logic. 1285 MBB->insert(mi, NewMIs[0]); 1286 MBB->insert(mi, NewMIs[1]); 1287 1288 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0] 1289 << "2addr: NEW INST: " << *NewMIs[1]); 1290 1291 // Transform the instruction, now that it no longer has a load. 1292 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA); 1293 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB); 1294 MachineBasicBlock::iterator NewMI = NewMIs[1]; 1295 bool TransformResult = 1296 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true); 1297 (void)TransformResult; 1298 assert(!TransformResult && 1299 "tryInstructionTransform() should return false."); 1300 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) { 1301 // Success, or at least we made an improvement. Keep the unfolded 1302 // instructions and discard the original. 1303 if (LV) { 1304 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1305 MachineOperand &MO = MI.getOperand(i); 1306 if (MO.isReg() && 1307 TargetRegisterInfo::isVirtualRegister(MO.getReg())) { 1308 if (MO.isUse()) { 1309 if (MO.isKill()) { 1310 if (NewMIs[0]->killsRegister(MO.getReg())) 1311 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]); 1312 else { 1313 assert(NewMIs[1]->killsRegister(MO.getReg()) && 1314 "Kill missing after load unfold!"); 1315 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]); 1316 } 1317 } 1318 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) { 1319 if (NewMIs[1]->registerDefIsDead(MO.getReg())) 1320 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]); 1321 else { 1322 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) && 1323 "Dead flag missing after load unfold!"); 1324 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]); 1325 } 1326 } 1327 } 1328 } 1329 LV->addVirtualRegisterKilled(Reg, NewMIs[1]); 1330 } 1331 1332 SmallVector<unsigned, 4> OrigRegs; 1333 if (LIS) { 1334 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(), 1335 MOE = MI.operands_end(); MOI != MOE; ++MOI) { 1336 if (MOI->isReg()) 1337 OrigRegs.push_back(MOI->getReg()); 1338 } 1339 } 1340 1341 MI.eraseFromParent(); 1342 1343 // Update LiveIntervals. 1344 if (LIS) { 1345 MachineBasicBlock::iterator Begin(NewMIs[0]); 1346 MachineBasicBlock::iterator End(NewMIs[1]); 1347 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs); 1348 } 1349 1350 mi = NewMIs[1]; 1351 } else { 1352 // Transforming didn't eliminate the tie and didn't lead to an 1353 // improvement. Clean up the unfolded instructions and keep the 1354 // original. 1355 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 1356 NewMIs[0]->eraseFromParent(); 1357 NewMIs[1]->eraseFromParent(); 1358 } 1359 } 1360 } 1361 } 1362 1363 return false; 1364 } 1365 1366 // Collect tied operands of MI that need to be handled. 1367 // Rewrite trivial cases immediately. 1368 // Return true if any tied operands where found, including the trivial ones. 1369 bool TwoAddressInstructionPass:: 1370 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) { 1371 const MCInstrDesc &MCID = MI->getDesc(); 1372 bool AnyOps = false; 1373 unsigned NumOps = MI->getNumOperands(); 1374 1375 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) { 1376 unsigned DstIdx = 0; 1377 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx)) 1378 continue; 1379 AnyOps = true; 1380 MachineOperand &SrcMO = MI->getOperand(SrcIdx); 1381 MachineOperand &DstMO = MI->getOperand(DstIdx); 1382 unsigned SrcReg = SrcMO.getReg(); 1383 unsigned DstReg = DstMO.getReg(); 1384 // Tied constraint already satisfied? 1385 if (SrcReg == DstReg) 1386 continue; 1387 1388 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid"); 1389 1390 // Deal with <undef> uses immediately - simply rewrite the src operand. 1391 if (SrcMO.isUndef() && !DstMO.getSubReg()) { 1392 // Constrain the DstReg register class if required. 1393 if (TargetRegisterInfo::isVirtualRegister(DstReg)) 1394 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx, 1395 TRI, *MF)) 1396 MRI->constrainRegClass(DstReg, RC); 1397 SrcMO.setReg(DstReg); 1398 SrcMO.setSubReg(0); 1399 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI); 1400 continue; 1401 } 1402 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx)); 1403 } 1404 return AnyOps; 1405 } 1406 1407 // Process a list of tied MI operands that all use the same source register. 1408 // The tied pairs are of the form (SrcIdx, DstIdx). 1409 void 1410 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI, 1411 TiedPairList &TiedPairs, 1412 unsigned &Dist) { 1413 bool IsEarlyClobber = false; 1414 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) { 1415 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second); 1416 IsEarlyClobber |= DstMO.isEarlyClobber(); 1417 } 1418 1419 bool RemovedKillFlag = false; 1420 bool AllUsesCopied = true; 1421 unsigned LastCopiedReg = 0; 1422 SlotIndex LastCopyIdx; 1423 unsigned RegB = 0; 1424 unsigned SubRegB = 0; 1425 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) { 1426 unsigned SrcIdx = TiedPairs[tpi].first; 1427 unsigned DstIdx = TiedPairs[tpi].second; 1428 1429 const MachineOperand &DstMO = MI->getOperand(DstIdx); 1430 unsigned RegA = DstMO.getReg(); 1431 1432 // Grab RegB from the instruction because it may have changed if the 1433 // instruction was commuted. 1434 RegB = MI->getOperand(SrcIdx).getReg(); 1435 SubRegB = MI->getOperand(SrcIdx).getSubReg(); 1436 1437 if (RegA == RegB) { 1438 // The register is tied to multiple destinations (or else we would 1439 // not have continued this far), but this use of the register 1440 // already matches the tied destination. Leave it. 1441 AllUsesCopied = false; 1442 continue; 1443 } 1444 LastCopiedReg = RegA; 1445 1446 assert(TargetRegisterInfo::isVirtualRegister(RegB) && 1447 "cannot make instruction into two-address form"); 1448 1449 #ifndef NDEBUG 1450 // First, verify that we don't have a use of "a" in the instruction 1451 // (a = b + a for example) because our transformation will not 1452 // work. This should never occur because we are in SSA form. 1453 for (unsigned i = 0; i != MI->getNumOperands(); ++i) 1454 assert(i == DstIdx || 1455 !MI->getOperand(i).isReg() || 1456 MI->getOperand(i).getReg() != RegA); 1457 #endif 1458 1459 // Emit a copy. 1460 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), 1461 TII->get(TargetOpcode::COPY), RegA); 1462 // If this operand is folding a truncation, the truncation now moves to the 1463 // copy so that the register classes remain valid for the operands. 1464 MIB.addReg(RegB, 0, SubRegB); 1465 const TargetRegisterClass *RC = MRI->getRegClass(RegB); 1466 if (SubRegB) { 1467 if (TargetRegisterInfo::isVirtualRegister(RegA)) { 1468 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA), 1469 SubRegB) && 1470 "tied subregister must be a truncation"); 1471 // The superreg class will not be used to constrain the subreg class. 1472 RC = nullptr; 1473 } 1474 else { 1475 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB)) 1476 && "tied subregister must be a truncation"); 1477 } 1478 } 1479 1480 // Update DistanceMap. 1481 MachineBasicBlock::iterator PrevMI = MI; 1482 --PrevMI; 1483 DistanceMap.insert(std::make_pair(PrevMI, Dist)); 1484 DistanceMap[MI] = ++Dist; 1485 1486 if (LIS) { 1487 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot(); 1488 1489 if (TargetRegisterInfo::isVirtualRegister(RegA)) { 1490 LiveInterval &LI = LIS->getInterval(RegA); 1491 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 1492 SlotIndex endIdx = 1493 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber); 1494 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI)); 1495 } 1496 } 1497 1498 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB); 1499 1500 MachineOperand &MO = MI->getOperand(SrcIdx); 1501 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() && 1502 "inconsistent operand info for 2-reg pass"); 1503 if (MO.isKill()) { 1504 MO.setIsKill(false); 1505 RemovedKillFlag = true; 1506 } 1507 1508 // Make sure regA is a legal regclass for the SrcIdx operand. 1509 if (TargetRegisterInfo::isVirtualRegister(RegA) && 1510 TargetRegisterInfo::isVirtualRegister(RegB)) 1511 MRI->constrainRegClass(RegA, RC); 1512 MO.setReg(RegA); 1513 // The getMatchingSuper asserts guarantee that the register class projected 1514 // by SubRegB is compatible with RegA with no subregister. So regardless of 1515 // whether the dest oper writes a subreg, the source oper should not. 1516 MO.setSubReg(0); 1517 1518 // Propagate SrcRegMap. 1519 SrcRegMap[RegA] = RegB; 1520 } 1521 1522 1523 if (AllUsesCopied) { 1524 if (!IsEarlyClobber) { 1525 // Replace other (un-tied) uses of regB with LastCopiedReg. 1526 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1527 MachineOperand &MO = MI->getOperand(i); 1528 if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB && 1529 MO.isUse()) { 1530 if (MO.isKill()) { 1531 MO.setIsKill(false); 1532 RemovedKillFlag = true; 1533 } 1534 MO.setReg(LastCopiedReg); 1535 MO.setSubReg(0); 1536 } 1537 } 1538 } 1539 1540 // Update live variables for regB. 1541 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) { 1542 MachineBasicBlock::iterator PrevMI = MI; 1543 --PrevMI; 1544 LV->addVirtualRegisterKilled(RegB, PrevMI); 1545 } 1546 1547 // Update LiveIntervals. 1548 if (LIS) { 1549 LiveInterval &LI = LIS->getInterval(RegB); 1550 SlotIndex MIIdx = LIS->getInstructionIndex(MI); 1551 LiveInterval::const_iterator I = LI.find(MIIdx); 1552 assert(I != LI.end() && "RegB must be live-in to use."); 1553 1554 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber); 1555 if (I->end == UseIdx) 1556 LI.removeSegment(LastCopyIdx, UseIdx); 1557 } 1558 1559 } else if (RemovedKillFlag) { 1560 // Some tied uses of regB matched their destination registers, so 1561 // regB is still used in this instruction, but a kill flag was 1562 // removed from a different tied use of regB, so now we need to add 1563 // a kill flag to one of the remaining uses of regB. 1564 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1565 MachineOperand &MO = MI->getOperand(i); 1566 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) { 1567 MO.setIsKill(true); 1568 break; 1569 } 1570 } 1571 } 1572 } 1573 1574 /// runOnMachineFunction - Reduce two-address instructions to two operands. 1575 /// 1576 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) { 1577 MF = &Func; 1578 const TargetMachine &TM = MF->getTarget(); 1579 MRI = &MF->getRegInfo(); 1580 TII = MF->getSubtarget().getInstrInfo(); 1581 TRI = MF->getSubtarget().getRegisterInfo(); 1582 InstrItins = MF->getSubtarget().getInstrItineraryData(); 1583 LV = getAnalysisIfAvailable<LiveVariables>(); 1584 LIS = getAnalysisIfAvailable<LiveIntervals>(); 1585 AA = &getAnalysis<AliasAnalysis>(); 1586 OptLevel = TM.getOptLevel(); 1587 1588 bool MadeChange = false; 1589 1590 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n"); 1591 DEBUG(dbgs() << "********** Function: " 1592 << MF->getName() << '\n'); 1593 1594 // This pass takes the function out of SSA form. 1595 MRI->leaveSSA(); 1596 1597 TiedOperandMap TiedOperands; 1598 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end(); 1599 MBBI != MBBE; ++MBBI) { 1600 MBB = MBBI; 1601 unsigned Dist = 0; 1602 DistanceMap.clear(); 1603 SrcRegMap.clear(); 1604 DstRegMap.clear(); 1605 Processed.clear(); 1606 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end(); 1607 mi != me; ) { 1608 MachineBasicBlock::iterator nmi = std::next(mi); 1609 if (mi->isDebugValue()) { 1610 mi = nmi; 1611 continue; 1612 } 1613 1614 // Expand REG_SEQUENCE instructions. This will position mi at the first 1615 // expanded instruction. 1616 if (mi->isRegSequence()) 1617 eliminateRegSequence(mi); 1618 1619 DistanceMap.insert(std::make_pair(mi, ++Dist)); 1620 1621 processCopy(&*mi); 1622 1623 // First scan through all the tied register uses in this instruction 1624 // and record a list of pairs of tied operands for each register. 1625 if (!collectTiedOperands(mi, TiedOperands)) { 1626 mi = nmi; 1627 continue; 1628 } 1629 1630 ++NumTwoAddressInstrs; 1631 MadeChange = true; 1632 DEBUG(dbgs() << '\t' << *mi); 1633 1634 // If the instruction has a single pair of tied operands, try some 1635 // transformations that may either eliminate the tied operands or 1636 // improve the opportunities for coalescing away the register copy. 1637 if (TiedOperands.size() == 1) { 1638 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs 1639 = TiedOperands.begin()->second; 1640 if (TiedPairs.size() == 1) { 1641 unsigned SrcIdx = TiedPairs[0].first; 1642 unsigned DstIdx = TiedPairs[0].second; 1643 unsigned SrcReg = mi->getOperand(SrcIdx).getReg(); 1644 unsigned DstReg = mi->getOperand(DstIdx).getReg(); 1645 if (SrcReg != DstReg && 1646 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) { 1647 // The tied operands have been eliminated or shifted further down the 1648 // block to ease elimination. Continue processing with 'nmi'. 1649 TiedOperands.clear(); 1650 mi = nmi; 1651 continue; 1652 } 1653 } 1654 } 1655 1656 // Now iterate over the information collected above. 1657 for (TiedOperandMap::iterator OI = TiedOperands.begin(), 1658 OE = TiedOperands.end(); OI != OE; ++OI) { 1659 processTiedPairs(mi, OI->second, Dist); 1660 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi); 1661 } 1662 1663 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form. 1664 if (mi->isInsertSubreg()) { 1665 // From %reg = INSERT_SUBREG %reg, %subreg, subidx 1666 // To %reg:subidx = COPY %subreg 1667 unsigned SubIdx = mi->getOperand(3).getImm(); 1668 mi->RemoveOperand(3); 1669 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx"); 1670 mi->getOperand(0).setSubReg(SubIdx); 1671 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef()); 1672 mi->RemoveOperand(1); 1673 mi->setDesc(TII->get(TargetOpcode::COPY)); 1674 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi); 1675 } 1676 1677 // Clear TiedOperands here instead of at the top of the loop 1678 // since most instructions do not have tied operands. 1679 TiedOperands.clear(); 1680 mi = nmi; 1681 } 1682 } 1683 1684 if (LIS) 1685 MF->verify(this, "After two-address instruction pass"); 1686 1687 return MadeChange; 1688 } 1689 1690 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process. 1691 /// 1692 /// The instruction is turned into a sequence of sub-register copies: 1693 /// 1694 /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1 1695 /// 1696 /// Becomes: 1697 /// 1698 /// %dst:ssub0<def,undef> = COPY %v1 1699 /// %dst:ssub1<def> = COPY %v2 1700 /// 1701 void TwoAddressInstructionPass:: 1702 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) { 1703 MachineInstr *MI = MBBI; 1704 unsigned DstReg = MI->getOperand(0).getReg(); 1705 if (MI->getOperand(0).getSubReg() || 1706 TargetRegisterInfo::isPhysicalRegister(DstReg) || 1707 !(MI->getNumOperands() & 1)) { 1708 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI); 1709 llvm_unreachable(nullptr); 1710 } 1711 1712 SmallVector<unsigned, 4> OrigRegs; 1713 if (LIS) { 1714 OrigRegs.push_back(MI->getOperand(0).getReg()); 1715 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) 1716 OrigRegs.push_back(MI->getOperand(i).getReg()); 1717 } 1718 1719 bool DefEmitted = false; 1720 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) { 1721 MachineOperand &UseMO = MI->getOperand(i); 1722 unsigned SrcReg = UseMO.getReg(); 1723 unsigned SubIdx = MI->getOperand(i+1).getImm(); 1724 // Nothing needs to be inserted for <undef> operands. 1725 if (UseMO.isUndef()) 1726 continue; 1727 1728 // Defer any kill flag to the last operand using SrcReg. Otherwise, we 1729 // might insert a COPY that uses SrcReg after is was killed. 1730 bool isKill = UseMO.isKill(); 1731 if (isKill) 1732 for (unsigned j = i + 2; j < e; j += 2) 1733 if (MI->getOperand(j).getReg() == SrcReg) { 1734 MI->getOperand(j).setIsKill(); 1735 UseMO.setIsKill(false); 1736 isKill = false; 1737 break; 1738 } 1739 1740 // Insert the sub-register copy. 1741 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), 1742 TII->get(TargetOpcode::COPY)) 1743 .addReg(DstReg, RegState::Define, SubIdx) 1744 .addOperand(UseMO); 1745 1746 // The first def needs an <undef> flag because there is no live register 1747 // before it. 1748 if (!DefEmitted) { 1749 CopyMI->getOperand(0).setIsUndef(true); 1750 // Return an iterator pointing to the first inserted instr. 1751 MBBI = CopyMI; 1752 } 1753 DefEmitted = true; 1754 1755 // Update LiveVariables' kill info. 1756 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg)) 1757 LV->replaceKillInstruction(SrcReg, MI, CopyMI); 1758 1759 DEBUG(dbgs() << "Inserted: " << *CopyMI); 1760 } 1761 1762 MachineBasicBlock::iterator EndMBBI = 1763 std::next(MachineBasicBlock::iterator(MI)); 1764 1765 if (!DefEmitted) { 1766 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF"); 1767 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF)); 1768 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j) 1769 MI->RemoveOperand(j); 1770 } else { 1771 DEBUG(dbgs() << "Eliminated: " << *MI); 1772 MI->eraseFromParent(); 1773 } 1774 1775 // Udpate LiveIntervals. 1776 if (LIS) 1777 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs); 1778 } 1779