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