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