LLVM API Documentation
00001 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the TwoAddress instruction pass which is used 00011 // by most register allocators. Two-Address instructions are rewritten 00012 // from: 00013 // 00014 // A = B op C 00015 // 00016 // to: 00017 // 00018 // A = B 00019 // A op= C 00020 // 00021 // Note that if a register allocator chooses to use this pass, that it 00022 // has to be capable of handling the non-SSA nature of these rewritten 00023 // virtual registers. 00024 // 00025 // It is also worth noting that the duplicate operand of the two 00026 // address instruction is removed. 00027 // 00028 //===----------------------------------------------------------------------===// 00029 00030 #define DEBUG_TYPE "twoaddrinstr" 00031 #include "llvm/CodeGen/Passes.h" 00032 #include "llvm/ADT/BitVector.h" 00033 #include "llvm/ADT/DenseMap.h" 00034 #include "llvm/ADT/STLExtras.h" 00035 #include "llvm/ADT/SmallSet.h" 00036 #include "llvm/ADT/Statistic.h" 00037 #include "llvm/Analysis/AliasAnalysis.h" 00038 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 00039 #include "llvm/CodeGen/LiveVariables.h" 00040 #include "llvm/CodeGen/MachineFunctionPass.h" 00041 #include "llvm/CodeGen/MachineInstr.h" 00042 #include "llvm/CodeGen/MachineInstrBuilder.h" 00043 #include "llvm/CodeGen/MachineRegisterInfo.h" 00044 #include "llvm/IR/Function.h" 00045 #include "llvm/MC/MCInstrItineraries.h" 00046 #include "llvm/Support/CommandLine.h" 00047 #include "llvm/Support/Debug.h" 00048 #include "llvm/Support/ErrorHandling.h" 00049 #include "llvm/Target/TargetInstrInfo.h" 00050 #include "llvm/Target/TargetMachine.h" 00051 #include "llvm/Target/TargetRegisterInfo.h" 00052 using namespace llvm; 00053 00054 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions"); 00055 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce"); 00056 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted"); 00057 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address"); 00058 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk"); 00059 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up"); 00060 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down"); 00061 00062 // Temporary flag to disable rescheduling. 00063 static cl::opt<bool> 00064 EnableRescheduling("twoaddr-reschedule", 00065 cl::desc("Coalesce copies by rescheduling (default=true)"), 00066 cl::init(true), cl::Hidden); 00067 00068 namespace { 00069 class TwoAddressInstructionPass : public MachineFunctionPass { 00070 MachineFunction *MF; 00071 const TargetInstrInfo *TII; 00072 const TargetRegisterInfo *TRI; 00073 const InstrItineraryData *InstrItins; 00074 MachineRegisterInfo *MRI; 00075 LiveVariables *LV; 00076 LiveIntervals *LIS; 00077 AliasAnalysis *AA; 00078 CodeGenOpt::Level OptLevel; 00079 00080 // The current basic block being processed. 00081 MachineBasicBlock *MBB; 00082 00083 // DistanceMap - Keep track the distance of a MI from the start of the 00084 // current basic block. 00085 DenseMap<MachineInstr*, unsigned> DistanceMap; 00086 00087 // Set of already processed instructions in the current block. 00088 SmallPtrSet<MachineInstr*, 8> Processed; 00089 00090 // SrcRegMap - A map from virtual registers to physical registers which are 00091 // likely targets to be coalesced to due to copies from physical registers to 00092 // virtual registers. e.g. v1024 = move r0. 00093 DenseMap<unsigned, unsigned> SrcRegMap; 00094 00095 // DstRegMap - A map from virtual registers to physical registers which are 00096 // likely targets to be coalesced to due to copies to physical registers from 00097 // virtual registers. e.g. r1 = move v1024. 00098 DenseMap<unsigned, unsigned> DstRegMap; 00099 00100 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg, 00101 MachineBasicBlock::iterator OldPos); 00102 00103 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef); 00104 00105 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC, 00106 MachineInstr *MI, unsigned Dist); 00107 00108 bool commuteInstruction(MachineBasicBlock::iterator &mi, 00109 unsigned RegB, unsigned RegC, unsigned Dist); 00110 00111 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB); 00112 00113 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi, 00114 MachineBasicBlock::iterator &nmi, 00115 unsigned RegA, unsigned RegB, unsigned Dist); 00116 00117 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI); 00118 00119 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi, 00120 MachineBasicBlock::iterator &nmi, 00121 unsigned Reg); 00122 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi, 00123 MachineBasicBlock::iterator &nmi, 00124 unsigned Reg); 00125 00126 bool tryInstructionTransform(MachineBasicBlock::iterator &mi, 00127 MachineBasicBlock::iterator &nmi, 00128 unsigned SrcIdx, unsigned DstIdx, 00129 unsigned Dist, bool shouldOnlyCommute); 00130 00131 void scanUses(unsigned DstReg); 00132 00133 void processCopy(MachineInstr *MI); 00134 00135 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList; 00136 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap; 00137 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&); 00138 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist); 00139 void eliminateRegSequence(MachineBasicBlock::iterator&); 00140 00141 public: 00142 static char ID; // Pass identification, replacement for typeid 00143 TwoAddressInstructionPass() : MachineFunctionPass(ID) { 00144 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry()); 00145 } 00146 00147 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00148 AU.setPreservesCFG(); 00149 AU.addRequired<AliasAnalysis>(); 00150 AU.addPreserved<LiveVariables>(); 00151 AU.addPreserved<SlotIndexes>(); 00152 AU.addPreserved<LiveIntervals>(); 00153 AU.addPreservedID(MachineLoopInfoID); 00154 AU.addPreservedID(MachineDominatorsID); 00155 MachineFunctionPass::getAnalysisUsage(AU); 00156 } 00157 00158 /// runOnMachineFunction - Pass entry point. 00159 bool runOnMachineFunction(MachineFunction&); 00160 }; 00161 } // end anonymous namespace 00162 00163 char TwoAddressInstructionPass::ID = 0; 00164 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction", 00165 "Two-Address instruction pass", false, false) 00166 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 00167 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction", 00168 "Two-Address instruction pass", false, false) 00169 00170 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID; 00171 00172 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS); 00173 00174 /// sink3AddrInstruction - A two-address instruction has been converted to a 00175 /// three-address instruction to avoid clobbering a register. Try to sink it 00176 /// past the instruction that would kill the above mentioned register to reduce 00177 /// register pressure. 00178 bool TwoAddressInstructionPass:: 00179 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg, 00180 MachineBasicBlock::iterator OldPos) { 00181 // FIXME: Shouldn't we be trying to do this before we three-addressify the 00182 // instruction? After this transformation is done, we no longer need 00183 // the instruction to be in three-address form. 00184 00185 // Check if it's safe to move this instruction. 00186 bool SeenStore = true; // Be conservative. 00187 if (!MI->isSafeToMove(TII, AA, SeenStore)) 00188 return false; 00189 00190 unsigned DefReg = 0; 00191 SmallSet<unsigned, 4> UseRegs; 00192 00193 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 00194 const MachineOperand &MO = MI->getOperand(i); 00195 if (!MO.isReg()) 00196 continue; 00197 unsigned MOReg = MO.getReg(); 00198 if (!MOReg) 00199 continue; 00200 if (MO.isUse() && MOReg != SavedReg) 00201 UseRegs.insert(MO.getReg()); 00202 if (!MO.isDef()) 00203 continue; 00204 if (MO.isImplicit()) 00205 // Don't try to move it if it implicitly defines a register. 00206 return false; 00207 if (DefReg) 00208 // For now, don't move any instructions that define multiple registers. 00209 return false; 00210 DefReg = MO.getReg(); 00211 } 00212 00213 // Find the instruction that kills SavedReg. 00214 MachineInstr *KillMI = NULL; 00215 if (LIS) { 00216 LiveInterval &LI = LIS->getInterval(SavedReg); 00217 assert(LI.end() != LI.begin() && 00218 "Reg should not have empty live interval."); 00219 00220 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 00221 LiveInterval::const_iterator I = LI.find(MBBEndIdx); 00222 if (I != LI.end() && I->start < MBBEndIdx) 00223 return false; 00224 00225 --I; 00226 KillMI = LIS->getInstructionFromIndex(I->end); 00227 } 00228 if (!KillMI) { 00229 for (MachineRegisterInfo::use_nodbg_iterator 00230 UI = MRI->use_nodbg_begin(SavedReg), 00231 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 00232 MachineOperand &UseMO = UI.getOperand(); 00233 if (!UseMO.isKill()) 00234 continue; 00235 KillMI = UseMO.getParent(); 00236 break; 00237 } 00238 } 00239 00240 // If we find the instruction that kills SavedReg, and it is in an 00241 // appropriate location, we can try to sink the current instruction 00242 // past it. 00243 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI || 00244 KillMI == OldPos || KillMI->isTerminator()) 00245 return false; 00246 00247 // If any of the definitions are used by another instruction between the 00248 // position and the kill use, then it's not safe to sink it. 00249 // 00250 // FIXME: This can be sped up if there is an easy way to query whether an 00251 // instruction is before or after another instruction. Then we can use 00252 // MachineRegisterInfo def / use instead. 00253 MachineOperand *KillMO = NULL; 00254 MachineBasicBlock::iterator KillPos = KillMI; 00255 ++KillPos; 00256 00257 unsigned NumVisited = 0; 00258 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) { 00259 MachineInstr *OtherMI = I; 00260 // DBG_VALUE cannot be counted against the limit. 00261 if (OtherMI->isDebugValue()) 00262 continue; 00263 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost. 00264 return false; 00265 ++NumVisited; 00266 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) { 00267 MachineOperand &MO = OtherMI->getOperand(i); 00268 if (!MO.isReg()) 00269 continue; 00270 unsigned MOReg = MO.getReg(); 00271 if (!MOReg) 00272 continue; 00273 if (DefReg == MOReg) 00274 return false; 00275 00276 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) { 00277 if (OtherMI == KillMI && MOReg == SavedReg) 00278 // Save the operand that kills the register. We want to unset the kill 00279 // marker if we can sink MI past it. 00280 KillMO = &MO; 00281 else if (UseRegs.count(MOReg)) 00282 // One of the uses is killed before the destination. 00283 return false; 00284 } 00285 } 00286 } 00287 assert(KillMO && "Didn't find kill"); 00288 00289 if (!LIS) { 00290 // Update kill and LV information. 00291 KillMO->setIsKill(false); 00292 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI); 00293 KillMO->setIsKill(true); 00294 00295 if (LV) 00296 LV->replaceKillInstruction(SavedReg, KillMI, MI); 00297 } 00298 00299 // Move instruction to its destination. 00300 MBB->remove(MI); 00301 MBB->insert(KillPos, MI); 00302 00303 if (LIS) 00304 LIS->handleMove(MI); 00305 00306 ++Num3AddrSunk; 00307 return true; 00308 } 00309 00310 /// noUseAfterLastDef - Return true if there are no intervening uses between the 00311 /// last instruction in the MBB that defines the specified register and the 00312 /// two-address instruction which is being processed. It also returns the last 00313 /// def location by reference 00314 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist, 00315 unsigned &LastDef) { 00316 LastDef = 0; 00317 unsigned LastUse = Dist; 00318 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg), 00319 E = MRI->reg_end(); I != E; ++I) { 00320 MachineOperand &MO = I.getOperand(); 00321 MachineInstr *MI = MO.getParent(); 00322 if (MI->getParent() != MBB || MI->isDebugValue()) 00323 continue; 00324 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 00325 if (DI == DistanceMap.end()) 00326 continue; 00327 if (MO.isUse() && DI->second < LastUse) 00328 LastUse = DI->second; 00329 if (MO.isDef() && DI->second > LastDef) 00330 LastDef = DI->second; 00331 } 00332 00333 return !(LastUse > LastDef && LastUse < Dist); 00334 } 00335 00336 /// isCopyToReg - Return true if the specified MI is a copy instruction or 00337 /// a extract_subreg instruction. It also returns the source and destination 00338 /// registers and whether they are physical registers by reference. 00339 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII, 00340 unsigned &SrcReg, unsigned &DstReg, 00341 bool &IsSrcPhys, bool &IsDstPhys) { 00342 SrcReg = 0; 00343 DstReg = 0; 00344 if (MI.isCopy()) { 00345 DstReg = MI.getOperand(0).getReg(); 00346 SrcReg = MI.getOperand(1).getReg(); 00347 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) { 00348 DstReg = MI.getOperand(0).getReg(); 00349 SrcReg = MI.getOperand(2).getReg(); 00350 } else 00351 return false; 00352 00353 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg); 00354 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 00355 return true; 00356 } 00357 00358 /// isPLainlyKilled - Test if the given register value, which is used by the 00359 // given instruction, is killed by the given instruction. 00360 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, 00361 LiveIntervals *LIS) { 00362 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) && 00363 !LIS->isNotInMIMap(MI)) { 00364 // FIXME: Sometimes tryInstructionTransform() will add instructions and 00365 // test whether they can be folded before keeping them. In this case it 00366 // sets a kill before recursively calling tryInstructionTransform() again. 00367 // If there is no interval available, we assume that this instruction is 00368 // one of those. A kill flag is manually inserted on the operand so the 00369 // check below will handle it. 00370 LiveInterval &LI = LIS->getInterval(Reg); 00371 // This is to match the kill flag version where undefs don't have kill 00372 // flags. 00373 if (!LI.hasAtLeastOneValue()) 00374 return false; 00375 00376 SlotIndex useIdx = LIS->getInstructionIndex(MI); 00377 LiveInterval::const_iterator I = LI.find(useIdx); 00378 assert(I != LI.end() && "Reg must be live-in to use."); 00379 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx); 00380 } 00381 00382 return MI->killsRegister(Reg); 00383 } 00384 00385 /// isKilled - Test if the given register value, which is used by the given 00386 /// instruction, is killed by the given instruction. This looks through 00387 /// coalescable copies to see if the original value is potentially not killed. 00388 /// 00389 /// For example, in this code: 00390 /// 00391 /// %reg1034 = copy %reg1024 00392 /// %reg1035 = copy %reg1025<kill> 00393 /// %reg1036 = add %reg1034<kill>, %reg1035<kill> 00394 /// 00395 /// %reg1034 is not considered to be killed, since it is copied from a 00396 /// register which is not killed. Treating it as not killed lets the 00397 /// normal heuristics commute the (two-address) add, which lets 00398 /// coalescing eliminate the extra copy. 00399 /// 00400 /// If allowFalsePositives is true then likely kills are treated as kills even 00401 /// if it can't be proven that they are kills. 00402 static bool isKilled(MachineInstr &MI, unsigned Reg, 00403 const MachineRegisterInfo *MRI, 00404 const TargetInstrInfo *TII, 00405 LiveIntervals *LIS, 00406 bool allowFalsePositives) { 00407 MachineInstr *DefMI = &MI; 00408 for (;;) { 00409 // All uses of physical registers are likely to be kills. 00410 if (TargetRegisterInfo::isPhysicalRegister(Reg) && 00411 (allowFalsePositives || MRI->hasOneUse(Reg))) 00412 return true; 00413 if (!isPlainlyKilled(DefMI, Reg, LIS)) 00414 return false; 00415 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 00416 return true; 00417 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg); 00418 // If there are multiple defs, we can't do a simple analysis, so just 00419 // go with what the kill flag says. 00420 if (llvm::next(Begin) != MRI->def_end()) 00421 return true; 00422 DefMI = &*Begin; 00423 bool IsSrcPhys, IsDstPhys; 00424 unsigned SrcReg, DstReg; 00425 // If the def is something other than a copy, then it isn't going to 00426 // be coalesced, so follow the kill flag. 00427 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 00428 return true; 00429 Reg = SrcReg; 00430 } 00431 } 00432 00433 /// isTwoAddrUse - Return true if the specified MI uses the specified register 00434 /// as a two-address use. If so, return the destination register by reference. 00435 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) { 00436 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) { 00437 const MachineOperand &MO = MI.getOperand(i); 00438 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg) 00439 continue; 00440 unsigned ti; 00441 if (MI.isRegTiedToDefOperand(i, &ti)) { 00442 DstReg = MI.getOperand(ti).getReg(); 00443 return true; 00444 } 00445 } 00446 return false; 00447 } 00448 00449 /// findOnlyInterestingUse - Given a register, if has a single in-basic block 00450 /// use, return the use instruction if it's a copy or a two-address use. 00451 static 00452 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB, 00453 MachineRegisterInfo *MRI, 00454 const TargetInstrInfo *TII, 00455 bool &IsCopy, 00456 unsigned &DstReg, bool &IsDstPhys) { 00457 if (!MRI->hasOneNonDBGUse(Reg)) 00458 // None or more than one use. 00459 return 0; 00460 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg); 00461 if (UseMI.getParent() != MBB) 00462 return 0; 00463 unsigned SrcReg; 00464 bool IsSrcPhys; 00465 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) { 00466 IsCopy = true; 00467 return &UseMI; 00468 } 00469 IsDstPhys = false; 00470 if (isTwoAddrUse(UseMI, Reg, DstReg)) { 00471 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 00472 return &UseMI; 00473 } 00474 return 0; 00475 } 00476 00477 /// getMappedReg - Return the physical register the specified virtual register 00478 /// might be mapped to. 00479 static unsigned 00480 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) { 00481 while (TargetRegisterInfo::isVirtualRegister(Reg)) { 00482 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg); 00483 if (SI == RegMap.end()) 00484 return 0; 00485 Reg = SI->second; 00486 } 00487 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 00488 return Reg; 00489 return 0; 00490 } 00491 00492 /// regsAreCompatible - Return true if the two registers are equal or aliased. 00493 /// 00494 static bool 00495 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) { 00496 if (RegA == RegB) 00497 return true; 00498 if (!RegA || !RegB) 00499 return false; 00500 return TRI->regsOverlap(RegA, RegB); 00501 } 00502 00503 00504 /// isProfitableToCommute - Return true if it's potentially profitable to commute 00505 /// the two-address instruction that's being processed. 00506 bool 00507 TwoAddressInstructionPass:: 00508 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC, 00509 MachineInstr *MI, unsigned Dist) { 00510 if (OptLevel == CodeGenOpt::None) 00511 return false; 00512 00513 // Determine if it's profitable to commute this two address instruction. In 00514 // general, we want no uses between this instruction and the definition of 00515 // the two-address register. 00516 // e.g. 00517 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1 00518 // %reg1029<def> = MOV8rr %reg1028 00519 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead> 00520 // insert => %reg1030<def> = MOV8rr %reg1028 00521 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead> 00522 // In this case, it might not be possible to coalesce the second MOV8rr 00523 // instruction if the first one is coalesced. So it would be profitable to 00524 // commute it: 00525 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1 00526 // %reg1029<def> = MOV8rr %reg1028 00527 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead> 00528 // insert => %reg1030<def> = MOV8rr %reg1029 00529 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead> 00530 00531 if (!isPlainlyKilled(MI, regC, LIS)) 00532 return false; 00533 00534 // Ok, we have something like: 00535 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead> 00536 // let's see if it's worth commuting it. 00537 00538 // Look for situations like this: 00539 // %reg1024<def> = MOV r1 00540 // %reg1025<def> = MOV r0 00541 // %reg1026<def> = ADD %reg1024, %reg1025 00542 // r0 = MOV %reg1026 00543 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy. 00544 unsigned ToRegA = getMappedReg(regA, DstRegMap); 00545 if (ToRegA) { 00546 unsigned FromRegB = getMappedReg(regB, SrcRegMap); 00547 unsigned FromRegC = getMappedReg(regC, SrcRegMap); 00548 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI); 00549 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI); 00550 if (BComp != CComp) 00551 return !BComp && CComp; 00552 } 00553 00554 // If there is a use of regC between its last def (could be livein) and this 00555 // instruction, then bail. 00556 unsigned LastDefC = 0; 00557 if (!noUseAfterLastDef(regC, Dist, LastDefC)) 00558 return false; 00559 00560 // If there is a use of regB between its last def (could be livein) and this 00561 // instruction, then go ahead and make this transformation. 00562 unsigned LastDefB = 0; 00563 if (!noUseAfterLastDef(regB, Dist, LastDefB)) 00564 return true; 00565 00566 // Since there are no intervening uses for both registers, then commute 00567 // if the def of regC is closer. Its live interval is shorter. 00568 return LastDefB && LastDefC && LastDefC > LastDefB; 00569 } 00570 00571 /// commuteInstruction - Commute a two-address instruction and update the basic 00572 /// block, distance map, and live variables if needed. Return true if it is 00573 /// successful. 00574 bool TwoAddressInstructionPass:: 00575 commuteInstruction(MachineBasicBlock::iterator &mi, 00576 unsigned RegB, unsigned RegC, unsigned Dist) { 00577 MachineInstr *MI = mi; 00578 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI); 00579 MachineInstr *NewMI = TII->commuteInstruction(MI); 00580 00581 if (NewMI == 0) { 00582 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n"); 00583 return false; 00584 } 00585 00586 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI); 00587 assert(NewMI == MI && 00588 "TargetInstrInfo::commuteInstruction() should not return a new " 00589 "instruction unless it was requested."); 00590 00591 // Update source register map. 00592 unsigned FromRegC = getMappedReg(RegC, SrcRegMap); 00593 if (FromRegC) { 00594 unsigned RegA = MI->getOperand(0).getReg(); 00595 SrcRegMap[RegA] = FromRegC; 00596 } 00597 00598 return true; 00599 } 00600 00601 /// isProfitableToConv3Addr - Return true if it is profitable to convert the 00602 /// given 2-address instruction to a 3-address one. 00603 bool 00604 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){ 00605 // Look for situations like this: 00606 // %reg1024<def> = MOV r1 00607 // %reg1025<def> = MOV r0 00608 // %reg1026<def> = ADD %reg1024, %reg1025 00609 // r2 = MOV %reg1026 00610 // Turn ADD into a 3-address instruction to avoid a copy. 00611 unsigned FromRegB = getMappedReg(RegB, SrcRegMap); 00612 if (!FromRegB) 00613 return false; 00614 unsigned ToRegA = getMappedReg(RegA, DstRegMap); 00615 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI)); 00616 } 00617 00618 /// convertInstTo3Addr - Convert the specified two-address instruction into a 00619 /// three address one. Return true if this transformation was successful. 00620 bool 00621 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi, 00622 MachineBasicBlock::iterator &nmi, 00623 unsigned RegA, unsigned RegB, 00624 unsigned Dist) { 00625 // FIXME: Why does convertToThreeAddress() need an iterator reference? 00626 MachineFunction::iterator MFI = MBB; 00627 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV); 00628 assert(MBB == MFI && "convertToThreeAddress changed iterator reference"); 00629 if (!NewMI) 00630 return false; 00631 00632 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi); 00633 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI); 00634 bool Sunk = false; 00635 00636 if (LIS) 00637 LIS->ReplaceMachineInstrInMaps(mi, NewMI); 00638 00639 if (NewMI->findRegisterUseOperand(RegB, false, TRI)) 00640 // FIXME: Temporary workaround. If the new instruction doesn't 00641 // uses RegB, convertToThreeAddress must have created more 00642 // then one instruction. 00643 Sunk = sink3AddrInstruction(NewMI, RegB, mi); 00644 00645 MBB->erase(mi); // Nuke the old inst. 00646 00647 if (!Sunk) { 00648 DistanceMap.insert(std::make_pair(NewMI, Dist)); 00649 mi = NewMI; 00650 nmi = llvm::next(mi); 00651 } 00652 00653 // Update source and destination register maps. 00654 SrcRegMap.erase(RegA); 00655 DstRegMap.erase(RegB); 00656 return true; 00657 } 00658 00659 /// scanUses - Scan forward recursively for only uses, update maps if the use 00660 /// is a copy or a two-address instruction. 00661 void 00662 TwoAddressInstructionPass::scanUses(unsigned DstReg) { 00663 SmallVector<unsigned, 4> VirtRegPairs; 00664 bool IsDstPhys; 00665 bool IsCopy = false; 00666 unsigned NewReg = 0; 00667 unsigned Reg = DstReg; 00668 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy, 00669 NewReg, IsDstPhys)) { 00670 if (IsCopy && !Processed.insert(UseMI)) 00671 break; 00672 00673 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI); 00674 if (DI != DistanceMap.end()) 00675 // Earlier in the same MBB.Reached via a back edge. 00676 break; 00677 00678 if (IsDstPhys) { 00679 VirtRegPairs.push_back(NewReg); 00680 break; 00681 } 00682 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second; 00683 if (!isNew) 00684 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!"); 00685 VirtRegPairs.push_back(NewReg); 00686 Reg = NewReg; 00687 } 00688 00689 if (!VirtRegPairs.empty()) { 00690 unsigned ToReg = VirtRegPairs.back(); 00691 VirtRegPairs.pop_back(); 00692 while (!VirtRegPairs.empty()) { 00693 unsigned FromReg = VirtRegPairs.back(); 00694 VirtRegPairs.pop_back(); 00695 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second; 00696 if (!isNew) 00697 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!"); 00698 ToReg = FromReg; 00699 } 00700 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second; 00701 if (!isNew) 00702 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!"); 00703 } 00704 } 00705 00706 /// processCopy - If the specified instruction is not yet processed, process it 00707 /// if it's a copy. For a copy instruction, we find the physical registers the 00708 /// source and destination registers might be mapped to. These are kept in 00709 /// point-to maps used to determine future optimizations. e.g. 00710 /// v1024 = mov r0 00711 /// v1025 = mov r1 00712 /// v1026 = add v1024, v1025 00713 /// r1 = mov r1026 00714 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially 00715 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is 00716 /// potentially joined with r1 on the output side. It's worthwhile to commute 00717 /// 'add' to eliminate a copy. 00718 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) { 00719 if (Processed.count(MI)) 00720 return; 00721 00722 bool IsSrcPhys, IsDstPhys; 00723 unsigned SrcReg, DstReg; 00724 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 00725 return; 00726 00727 if (IsDstPhys && !IsSrcPhys) 00728 DstRegMap.insert(std::make_pair(SrcReg, DstReg)); 00729 else if (!IsDstPhys && IsSrcPhys) { 00730 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second; 00731 if (!isNew) 00732 assert(SrcRegMap[DstReg] == SrcReg && 00733 "Can't map to two src physical registers!"); 00734 00735 scanUses(DstReg); 00736 } 00737 00738 Processed.insert(MI); 00739 return; 00740 } 00741 00742 /// rescheduleMIBelowKill - If there is one more local instruction that reads 00743 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill 00744 /// instruction in order to eliminate the need for the copy. 00745 bool TwoAddressInstructionPass:: 00746 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi, 00747 MachineBasicBlock::iterator &nmi, 00748 unsigned Reg) { 00749 // Bail immediately if we don't have LV or LIS available. We use them to find 00750 // kills efficiently. 00751 if (!LV && !LIS) 00752 return false; 00753 00754 MachineInstr *MI = &*mi; 00755 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 00756 if (DI == DistanceMap.end()) 00757 // Must be created from unfolded load. Don't waste time trying this. 00758 return false; 00759 00760 MachineInstr *KillMI = 0; 00761 if (LIS) { 00762 LiveInterval &LI = LIS->getInterval(Reg); 00763 assert(LI.end() != LI.begin() && 00764 "Reg should not have empty live interval."); 00765 00766 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 00767 LiveInterval::const_iterator I = LI.find(MBBEndIdx); 00768 if (I != LI.end() && I->start < MBBEndIdx) 00769 return false; 00770 00771 --I; 00772 KillMI = LIS->getInstructionFromIndex(I->end); 00773 } else { 00774 KillMI = LV->getVarInfo(Reg).findKill(MBB); 00775 } 00776 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 00777 // Don't mess with copies, they may be coalesced later. 00778 return false; 00779 00780 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() || 00781 KillMI->isBranch() || KillMI->isTerminator()) 00782 // Don't move pass calls, etc. 00783 return false; 00784 00785 unsigned DstReg; 00786 if (isTwoAddrUse(*KillMI, Reg, DstReg)) 00787 return false; 00788 00789 bool SeenStore = true; 00790 if (!MI->isSafeToMove(TII, AA, SeenStore)) 00791 return false; 00792 00793 if (TII->getInstrLatency(InstrItins, MI) > 1) 00794 // FIXME: Needs more sophisticated heuristics. 00795 return false; 00796 00797 SmallSet<unsigned, 2> Uses; 00798 SmallSet<unsigned, 2> Kills; 00799 SmallSet<unsigned, 2> Defs; 00800 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 00801 const MachineOperand &MO = MI->getOperand(i); 00802 if (!MO.isReg()) 00803 continue; 00804 unsigned MOReg = MO.getReg(); 00805 if (!MOReg) 00806 continue; 00807 if (MO.isDef()) 00808 Defs.insert(MOReg); 00809 else { 00810 Uses.insert(MOReg); 00811 if (MOReg != Reg && (MO.isKill() || 00812 (LIS && isPlainlyKilled(MI, MOReg, LIS)))) 00813 Kills.insert(MOReg); 00814 } 00815 } 00816 00817 // Move the copies connected to MI down as well. 00818 MachineBasicBlock::iterator Begin = MI; 00819 MachineBasicBlock::iterator AfterMI = llvm::next(Begin); 00820 00821 MachineBasicBlock::iterator End = AfterMI; 00822 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) { 00823 Defs.insert(End->getOperand(0).getReg()); 00824 ++End; 00825 } 00826 00827 // Check if the reschedule will not break depedencies. 00828 unsigned NumVisited = 0; 00829 MachineBasicBlock::iterator KillPos = KillMI; 00830 ++KillPos; 00831 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) { 00832 MachineInstr *OtherMI = I; 00833 // DBG_VALUE cannot be counted against the limit. 00834 if (OtherMI->isDebugValue()) 00835 continue; 00836 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 00837 return false; 00838 ++NumVisited; 00839 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() || 00840 OtherMI->isBranch() || OtherMI->isTerminator()) 00841 // Don't move pass calls, etc. 00842 return false; 00843 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) { 00844 const MachineOperand &MO = OtherMI->getOperand(i); 00845 if (!MO.isReg()) 00846 continue; 00847 unsigned MOReg = MO.getReg(); 00848 if (!MOReg) 00849 continue; 00850 if (MO.isDef()) { 00851 if (Uses.count(MOReg)) 00852 // Physical register use would be clobbered. 00853 return false; 00854 if (!MO.isDead() && Defs.count(MOReg)) 00855 // May clobber a physical register def. 00856 // FIXME: This may be too conservative. It's ok if the instruction 00857 // is sunken completely below the use. 00858 return false; 00859 } else { 00860 if (Defs.count(MOReg)) 00861 return false; 00862 bool isKill = MO.isKill() || 00863 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS)); 00864 if (MOReg != Reg && 00865 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg))) 00866 // Don't want to extend other live ranges and update kills. 00867 return false; 00868 if (MOReg == Reg && !isKill) 00869 // We can't schedule across a use of the register in question. 00870 return false; 00871 // Ensure that if this is register in question, its the kill we expect. 00872 assert((MOReg != Reg || OtherMI == KillMI) && 00873 "Found multiple kills of a register in a basic block"); 00874 } 00875 } 00876 } 00877 00878 // Move debug info as well. 00879 while (Begin != MBB->begin() && llvm::prior(Begin)->isDebugValue()) 00880 --Begin; 00881 00882 nmi = End; 00883 MachineBasicBlock::iterator InsertPos = KillPos; 00884 if (LIS) { 00885 // We have to move the copies first so that the MBB is still well-formed 00886 // when calling handleMove(). 00887 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) { 00888 MachineInstr *CopyMI = MBBI; 00889 ++MBBI; 00890 MBB->splice(InsertPos, MBB, CopyMI); 00891 LIS->handleMove(CopyMI); 00892 InsertPos = CopyMI; 00893 } 00894 End = llvm::next(MachineBasicBlock::iterator(MI)); 00895 } 00896 00897 // Copies following MI may have been moved as well. 00898 MBB->splice(InsertPos, MBB, Begin, End); 00899 DistanceMap.erase(DI); 00900 00901 // Update live variables 00902 if (LIS) { 00903 LIS->handleMove(MI); 00904 } else { 00905 LV->removeVirtualRegisterKilled(Reg, KillMI); 00906 LV->addVirtualRegisterKilled(Reg, MI); 00907 } 00908 00909 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI); 00910 return true; 00911 } 00912 00913 /// isDefTooClose - Return true if the re-scheduling will put the given 00914 /// instruction too close to the defs of its register dependencies. 00915 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist, 00916 MachineInstr *MI) { 00917 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg), 00918 DE = MRI->def_end(); DI != DE; ++DI) { 00919 MachineInstr *DefMI = &*DI; 00920 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike()) 00921 continue; 00922 if (DefMI == MI) 00923 return true; // MI is defining something KillMI uses 00924 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI); 00925 if (DDI == DistanceMap.end()) 00926 return true; // Below MI 00927 unsigned DefDist = DDI->second; 00928 assert(Dist > DefDist && "Visited def already?"); 00929 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist)) 00930 return true; 00931 } 00932 return false; 00933 } 00934 00935 /// rescheduleKillAboveMI - If there is one more local instruction that reads 00936 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the 00937 /// current two-address instruction in order to eliminate the need for the 00938 /// copy. 00939 bool TwoAddressInstructionPass:: 00940 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi, 00941 MachineBasicBlock::iterator &nmi, 00942 unsigned Reg) { 00943 // Bail immediately if we don't have LV or LIS available. We use them to find 00944 // kills efficiently. 00945 if (!LV && !LIS) 00946 return false; 00947 00948 MachineInstr *MI = &*mi; 00949 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 00950 if (DI == DistanceMap.end()) 00951 // Must be created from unfolded load. Don't waste time trying this. 00952 return false; 00953 00954 MachineInstr *KillMI = 0; 00955 if (LIS) { 00956 LiveInterval &LI = LIS->getInterval(Reg); 00957 assert(LI.end() != LI.begin() && 00958 "Reg should not have empty live interval."); 00959 00960 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 00961 LiveInterval::const_iterator I = LI.find(MBBEndIdx); 00962 if (I != LI.end() && I->start < MBBEndIdx) 00963 return false; 00964 00965 --I; 00966 KillMI = LIS->getInstructionFromIndex(I->end); 00967 } else { 00968 KillMI = LV->getVarInfo(Reg).findKill(MBB); 00969 } 00970 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 00971 // Don't mess with copies, they may be coalesced later. 00972 return false; 00973 00974 unsigned DstReg; 00975 if (isTwoAddrUse(*KillMI, Reg, DstReg)) 00976 return false; 00977 00978 bool SeenStore = true; 00979 if (!KillMI->isSafeToMove(TII, AA, SeenStore)) 00980 return false; 00981 00982 SmallSet<unsigned, 2> Uses; 00983 SmallSet<unsigned, 2> Kills; 00984 SmallSet<unsigned, 2> Defs; 00985 SmallSet<unsigned, 2> LiveDefs; 00986 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) { 00987 const MachineOperand &MO = KillMI->getOperand(i); 00988 if (!MO.isReg()) 00989 continue; 00990 unsigned MOReg = MO.getReg(); 00991 if (MO.isUse()) { 00992 if (!MOReg) 00993 continue; 00994 if (isDefTooClose(MOReg, DI->second, MI)) 00995 return false; 00996 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS)); 00997 if (MOReg == Reg && !isKill) 00998 return false; 00999 Uses.insert(MOReg); 01000 if (isKill && MOReg != Reg) 01001 Kills.insert(MOReg); 01002 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) { 01003 Defs.insert(MOReg); 01004 if (!MO.isDead()) 01005 LiveDefs.insert(MOReg); 01006 } 01007 } 01008 01009 // Check if the reschedule will not break depedencies. 01010 unsigned NumVisited = 0; 01011 MachineBasicBlock::iterator KillPos = KillMI; 01012 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) { 01013 MachineInstr *OtherMI = I; 01014 // DBG_VALUE cannot be counted against the limit. 01015 if (OtherMI->isDebugValue()) 01016 continue; 01017 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 01018 return false; 01019 ++NumVisited; 01020 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() || 01021 OtherMI->isBranch() || OtherMI->isTerminator()) 01022 // Don't move pass calls, etc. 01023 return false; 01024 SmallVector<unsigned, 2> OtherDefs; 01025 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) { 01026 const MachineOperand &MO = OtherMI->getOperand(i); 01027 if (!MO.isReg()) 01028 continue; 01029 unsigned MOReg = MO.getReg(); 01030 if (!MOReg) 01031 continue; 01032 if (MO.isUse()) { 01033 if (Defs.count(MOReg)) 01034 // Moving KillMI can clobber the physical register if the def has 01035 // not been seen. 01036 return false; 01037 if (Kills.count(MOReg)) 01038 // Don't want to extend other live ranges and update kills. 01039 return false; 01040 if (OtherMI != MI && MOReg == Reg && 01041 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS)))) 01042 // We can't schedule across a use of the register in question. 01043 return false; 01044 } else { 01045 OtherDefs.push_back(MOReg); 01046 } 01047 } 01048 01049 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) { 01050 unsigned MOReg = OtherDefs[i]; 01051 if (Uses.count(MOReg)) 01052 return false; 01053 if (TargetRegisterInfo::isPhysicalRegister(MOReg) && 01054 LiveDefs.count(MOReg)) 01055 return false; 01056 // Physical register def is seen. 01057 Defs.erase(MOReg); 01058 } 01059 } 01060 01061 // Move the old kill above MI, don't forget to move debug info as well. 01062 MachineBasicBlock::iterator InsertPos = mi; 01063 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue()) 01064 --InsertPos; 01065 MachineBasicBlock::iterator From = KillMI; 01066 MachineBasicBlock::iterator To = llvm::next(From); 01067 while (llvm::prior(From)->isDebugValue()) 01068 --From; 01069 MBB->splice(InsertPos, MBB, From, To); 01070 01071 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr. 01072 DistanceMap.erase(DI); 01073 01074 // Update live variables 01075 if (LIS) { 01076 LIS->handleMove(KillMI); 01077 } else { 01078 LV->removeVirtualRegisterKilled(Reg, KillMI); 01079 LV->addVirtualRegisterKilled(Reg, MI); 01080 } 01081 01082 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI); 01083 return true; 01084 } 01085 01086 /// tryInstructionTransform - For the case where an instruction has a single 01087 /// pair of tied register operands, attempt some transformations that may 01088 /// either eliminate the tied operands or improve the opportunities for 01089 /// coalescing away the register copy. Returns true if no copy needs to be 01090 /// inserted to untie mi's operands (either because they were untied, or 01091 /// because mi was rescheduled, and will be visited again later). If the 01092 /// shouldOnlyCommute flag is true, only instruction commutation is attempted. 01093 bool TwoAddressInstructionPass:: 01094 tryInstructionTransform(MachineBasicBlock::iterator &mi, 01095 MachineBasicBlock::iterator &nmi, 01096 unsigned SrcIdx, unsigned DstIdx, 01097 unsigned Dist, bool shouldOnlyCommute) { 01098 if (OptLevel == CodeGenOpt::None) 01099 return false; 01100 01101 MachineInstr &MI = *mi; 01102 unsigned regA = MI.getOperand(DstIdx).getReg(); 01103 unsigned regB = MI.getOperand(SrcIdx).getReg(); 01104 01105 assert(TargetRegisterInfo::isVirtualRegister(regB) && 01106 "cannot make instruction into two-address form"); 01107 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true); 01108 01109 if (TargetRegisterInfo::isVirtualRegister(regA)) 01110 scanUses(regA); 01111 01112 // Check if it is profitable to commute the operands. 01113 unsigned SrcOp1, SrcOp2; 01114 unsigned regC = 0; 01115 unsigned regCIdx = ~0U; 01116 bool TryCommute = false; 01117 bool AggressiveCommute = false; 01118 if (MI.isCommutable() && MI.getNumOperands() >= 3 && 01119 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) { 01120 if (SrcIdx == SrcOp1) 01121 regCIdx = SrcOp2; 01122 else if (SrcIdx == SrcOp2) 01123 regCIdx = SrcOp1; 01124 01125 if (regCIdx != ~0U) { 01126 regC = MI.getOperand(regCIdx).getReg(); 01127 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false)) 01128 // If C dies but B does not, swap the B and C operands. 01129 // This makes the live ranges of A and C joinable. 01130 TryCommute = true; 01131 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) { 01132 TryCommute = true; 01133 AggressiveCommute = true; 01134 } 01135 } 01136 } 01137 01138 // If it's profitable to commute, try to do so. 01139 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) { 01140 ++NumCommuted; 01141 if (AggressiveCommute) 01142 ++NumAggrCommuted; 01143 return false; 01144 } 01145 01146 if (shouldOnlyCommute) 01147 return false; 01148 01149 // If there is one more use of regB later in the same MBB, consider 01150 // re-schedule this MI below it. 01151 if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) { 01152 ++NumReSchedDowns; 01153 return true; 01154 } 01155 01156 if (MI.isConvertibleTo3Addr()) { 01157 // This instruction is potentially convertible to a true 01158 // three-address instruction. Check if it is profitable. 01159 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) { 01160 // Try to convert it. 01161 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) { 01162 ++NumConvertedTo3Addr; 01163 return true; // Done with this instruction. 01164 } 01165 } 01166 } 01167 01168 // If there is one more use of regB later in the same MBB, consider 01169 // re-schedule it before this MI if it's legal. 01170 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) { 01171 ++NumReSchedUps; 01172 return true; 01173 } 01174 01175 // If this is an instruction with a load folded into it, try unfolding 01176 // the load, e.g. avoid this: 01177 // movq %rdx, %rcx 01178 // addq (%rax), %rcx 01179 // in favor of this: 01180 // movq (%rax), %rcx 01181 // addq %rdx, %rcx 01182 // because it's preferable to schedule a load than a register copy. 01183 if (MI.mayLoad() && !regBKilled) { 01184 // Determine if a load can be unfolded. 01185 unsigned LoadRegIndex; 01186 unsigned NewOpc = 01187 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), 01188 /*UnfoldLoad=*/true, 01189 /*UnfoldStore=*/false, 01190 &LoadRegIndex); 01191 if (NewOpc != 0) { 01192 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc); 01193 if (UnfoldMCID.getNumDefs() == 1) { 01194 // Unfold the load. 01195 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI); 01196 const TargetRegisterClass *RC = 01197 TRI->getAllocatableClass( 01198 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF)); 01199 unsigned Reg = MRI->createVirtualRegister(RC); 01200 SmallVector<MachineInstr *, 2> NewMIs; 01201 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg, 01202 /*UnfoldLoad=*/true,/*UnfoldStore=*/false, 01203 NewMIs)) { 01204 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 01205 return false; 01206 } 01207 assert(NewMIs.size() == 2 && 01208 "Unfolded a load into multiple instructions!"); 01209 // The load was previously folded, so this is the only use. 01210 NewMIs[1]->addRegisterKilled(Reg, TRI); 01211 01212 // Tentatively insert the instructions into the block so that they 01213 // look "normal" to the transformation logic. 01214 MBB->insert(mi, NewMIs[0]); 01215 MBB->insert(mi, NewMIs[1]); 01216 01217 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0] 01218 << "2addr: NEW INST: " << *NewMIs[1]); 01219 01220 // Transform the instruction, now that it no longer has a load. 01221 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA); 01222 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB); 01223 MachineBasicBlock::iterator NewMI = NewMIs[1]; 01224 bool TransformResult = 01225 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true); 01226 (void)TransformResult; 01227 assert(!TransformResult && 01228 "tryInstructionTransform() should return false."); 01229 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) { 01230 // Success, or at least we made an improvement. Keep the unfolded 01231 // instructions and discard the original. 01232 if (LV) { 01233 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 01234 MachineOperand &MO = MI.getOperand(i); 01235 if (MO.isReg() && 01236 TargetRegisterInfo::isVirtualRegister(MO.getReg())) { 01237 if (MO.isUse()) { 01238 if (MO.isKill()) { 01239 if (NewMIs[0]->killsRegister(MO.getReg())) 01240 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]); 01241 else { 01242 assert(NewMIs[1]->killsRegister(MO.getReg()) && 01243 "Kill missing after load unfold!"); 01244 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]); 01245 } 01246 } 01247 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) { 01248 if (NewMIs[1]->registerDefIsDead(MO.getReg())) 01249 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]); 01250 else { 01251 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) && 01252 "Dead flag missing after load unfold!"); 01253 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]); 01254 } 01255 } 01256 } 01257 } 01258 LV->addVirtualRegisterKilled(Reg, NewMIs[1]); 01259 } 01260 01261 SmallVector<unsigned, 4> OrigRegs; 01262 if (LIS) { 01263 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(), 01264 MOE = MI.operands_end(); MOI != MOE; ++MOI) { 01265 if (MOI->isReg()) 01266 OrigRegs.push_back(MOI->getReg()); 01267 } 01268 } 01269 01270 MI.eraseFromParent(); 01271 01272 // Update LiveIntervals. 01273 if (LIS) { 01274 MachineBasicBlock::iterator Begin(NewMIs[0]); 01275 MachineBasicBlock::iterator End(NewMIs[1]); 01276 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs); 01277 } 01278 01279 mi = NewMIs[1]; 01280 } else { 01281 // Transforming didn't eliminate the tie and didn't lead to an 01282 // improvement. Clean up the unfolded instructions and keep the 01283 // original. 01284 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 01285 NewMIs[0]->eraseFromParent(); 01286 NewMIs[1]->eraseFromParent(); 01287 } 01288 } 01289 } 01290 } 01291 01292 return false; 01293 } 01294 01295 // Collect tied operands of MI that need to be handled. 01296 // Rewrite trivial cases immediately. 01297 // Return true if any tied operands where found, including the trivial ones. 01298 bool TwoAddressInstructionPass:: 01299 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) { 01300 const MCInstrDesc &MCID = MI->getDesc(); 01301 bool AnyOps = false; 01302 unsigned NumOps = MI->getNumOperands(); 01303 01304 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) { 01305 unsigned DstIdx = 0; 01306 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx)) 01307 continue; 01308 AnyOps = true; 01309 MachineOperand &SrcMO = MI->getOperand(SrcIdx); 01310 MachineOperand &DstMO = MI->getOperand(DstIdx); 01311 unsigned SrcReg = SrcMO.getReg(); 01312 unsigned DstReg = DstMO.getReg(); 01313 // Tied constraint already satisfied? 01314 if (SrcReg == DstReg) 01315 continue; 01316 01317 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid"); 01318 01319 // Deal with <undef> uses immediately - simply rewrite the src operand. 01320 if (SrcMO.isUndef()) { 01321 // Constrain the DstReg register class if required. 01322 if (TargetRegisterInfo::isVirtualRegister(DstReg)) 01323 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx, 01324 TRI, *MF)) 01325 MRI->constrainRegClass(DstReg, RC); 01326 SrcMO.setReg(DstReg); 01327 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI); 01328 continue; 01329 } 01330 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx)); 01331 } 01332 return AnyOps; 01333 } 01334 01335 // Process a list of tied MI operands that all use the same source register. 01336 // The tied pairs are of the form (SrcIdx, DstIdx). 01337 void 01338 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI, 01339 TiedPairList &TiedPairs, 01340 unsigned &Dist) { 01341 bool IsEarlyClobber = false; 01342 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) { 01343 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second); 01344 IsEarlyClobber |= DstMO.isEarlyClobber(); 01345 } 01346 01347 bool RemovedKillFlag = false; 01348 bool AllUsesCopied = true; 01349 unsigned LastCopiedReg = 0; 01350 SlotIndex LastCopyIdx; 01351 unsigned RegB = 0; 01352 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) { 01353 unsigned SrcIdx = TiedPairs[tpi].first; 01354 unsigned DstIdx = TiedPairs[tpi].second; 01355 01356 const MachineOperand &DstMO = MI->getOperand(DstIdx); 01357 unsigned RegA = DstMO.getReg(); 01358 01359 // Grab RegB from the instruction because it may have changed if the 01360 // instruction was commuted. 01361 RegB = MI->getOperand(SrcIdx).getReg(); 01362 01363 if (RegA == RegB) { 01364 // The register is tied to multiple destinations (or else we would 01365 // not have continued this far), but this use of the register 01366 // already matches the tied destination. Leave it. 01367 AllUsesCopied = false; 01368 continue; 01369 } 01370 LastCopiedReg = RegA; 01371 01372 assert(TargetRegisterInfo::isVirtualRegister(RegB) && 01373 "cannot make instruction into two-address form"); 01374 01375 #ifndef NDEBUG 01376 // First, verify that we don't have a use of "a" in the instruction 01377 // (a = b + a for example) because our transformation will not 01378 // work. This should never occur because we are in SSA form. 01379 for (unsigned i = 0; i != MI->getNumOperands(); ++i) 01380 assert(i == DstIdx || 01381 !MI->getOperand(i).isReg() || 01382 MI->getOperand(i).getReg() != RegA); 01383 #endif 01384 01385 // Emit a copy. 01386 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), 01387 TII->get(TargetOpcode::COPY), RegA).addReg(RegB); 01388 01389 // Update DistanceMap. 01390 MachineBasicBlock::iterator PrevMI = MI; 01391 --PrevMI; 01392 DistanceMap.insert(std::make_pair(PrevMI, Dist)); 01393 DistanceMap[MI] = ++Dist; 01394 01395 if (LIS) { 01396 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot(); 01397 01398 if (TargetRegisterInfo::isVirtualRegister(RegA)) { 01399 LiveInterval &LI = LIS->getInterval(RegA); 01400 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 01401 SlotIndex endIdx = 01402 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber); 01403 LI.addRange(LiveRange(LastCopyIdx, endIdx, VNI)); 01404 } 01405 } 01406 01407 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI); 01408 01409 MachineOperand &MO = MI->getOperand(SrcIdx); 01410 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() && 01411 "inconsistent operand info for 2-reg pass"); 01412 if (MO.isKill()) { 01413 MO.setIsKill(false); 01414 RemovedKillFlag = true; 01415 } 01416 01417 // Make sure regA is a legal regclass for the SrcIdx operand. 01418 if (TargetRegisterInfo::isVirtualRegister(RegA) && 01419 TargetRegisterInfo::isVirtualRegister(RegB)) 01420 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB)); 01421 01422 MO.setReg(RegA); 01423 01424 // Propagate SrcRegMap. 01425 SrcRegMap[RegA] = RegB; 01426 } 01427 01428 01429 if (AllUsesCopied) { 01430 if (!IsEarlyClobber) { 01431 // Replace other (un-tied) uses of regB with LastCopiedReg. 01432 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 01433 MachineOperand &MO = MI->getOperand(i); 01434 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) { 01435 if (MO.isKill()) { 01436 MO.setIsKill(false); 01437 RemovedKillFlag = true; 01438 } 01439 MO.setReg(LastCopiedReg); 01440 } 01441 } 01442 } 01443 01444 // Update live variables for regB. 01445 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) { 01446 MachineBasicBlock::iterator PrevMI = MI; 01447 --PrevMI; 01448 LV->addVirtualRegisterKilled(RegB, PrevMI); 01449 } 01450 01451 // Update LiveIntervals. 01452 if (LIS) { 01453 LiveInterval &LI = LIS->getInterval(RegB); 01454 SlotIndex MIIdx = LIS->getInstructionIndex(MI); 01455 LiveInterval::const_iterator I = LI.find(MIIdx); 01456 assert(I != LI.end() && "RegB must be live-in to use."); 01457 01458 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber); 01459 if (I->end == UseIdx) 01460 LI.removeRange(LastCopyIdx, UseIdx); 01461 } 01462 01463 } else if (RemovedKillFlag) { 01464 // Some tied uses of regB matched their destination registers, so 01465 // regB is still used in this instruction, but a kill flag was 01466 // removed from a different tied use of regB, so now we need to add 01467 // a kill flag to one of the remaining uses of regB. 01468 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 01469 MachineOperand &MO = MI->getOperand(i); 01470 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) { 01471 MO.setIsKill(true); 01472 break; 01473 } 01474 } 01475 } 01476 } 01477 01478 /// runOnMachineFunction - Reduce two-address instructions to two operands. 01479 /// 01480 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) { 01481 MF = &Func; 01482 const TargetMachine &TM = MF->getTarget(); 01483 MRI = &MF->getRegInfo(); 01484 TII = TM.getInstrInfo(); 01485 TRI = TM.getRegisterInfo(); 01486 InstrItins = TM.getInstrItineraryData(); 01487 LV = getAnalysisIfAvailable<LiveVariables>(); 01488 LIS = getAnalysisIfAvailable<LiveIntervals>(); 01489 AA = &getAnalysis<AliasAnalysis>(); 01490 OptLevel = TM.getOptLevel(); 01491 01492 bool MadeChange = false; 01493 01494 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n"); 01495 DEBUG(dbgs() << "********** Function: " 01496 << MF->getName() << '\n'); 01497 01498 // This pass takes the function out of SSA form. 01499 MRI->leaveSSA(); 01500 01501 TiedOperandMap TiedOperands; 01502 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end(); 01503 MBBI != MBBE; ++MBBI) { 01504 MBB = MBBI; 01505 unsigned Dist = 0; 01506 DistanceMap.clear(); 01507 SrcRegMap.clear(); 01508 DstRegMap.clear(); 01509 Processed.clear(); 01510 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end(); 01511 mi != me; ) { 01512 MachineBasicBlock::iterator nmi = llvm::next(mi); 01513 if (mi->isDebugValue()) { 01514 mi = nmi; 01515 continue; 01516 } 01517 01518 // Expand REG_SEQUENCE instructions. This will position mi at the first 01519 // expanded instruction. 01520 if (mi->isRegSequence()) 01521 eliminateRegSequence(mi); 01522 01523 DistanceMap.insert(std::make_pair(mi, ++Dist)); 01524 01525 processCopy(&*mi); 01526 01527 // First scan through all the tied register uses in this instruction 01528 // and record a list of pairs of tied operands for each register. 01529 if (!collectTiedOperands(mi, TiedOperands)) { 01530 mi = nmi; 01531 continue; 01532 } 01533 01534 ++NumTwoAddressInstrs; 01535 MadeChange = true; 01536 DEBUG(dbgs() << '\t' << *mi); 01537 01538 // If the instruction has a single pair of tied operands, try some 01539 // transformations that may either eliminate the tied operands or 01540 // improve the opportunities for coalescing away the register copy. 01541 if (TiedOperands.size() == 1) { 01542 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs 01543 = TiedOperands.begin()->second; 01544 if (TiedPairs.size() == 1) { 01545 unsigned SrcIdx = TiedPairs[0].first; 01546 unsigned DstIdx = TiedPairs[0].second; 01547 unsigned SrcReg = mi->getOperand(SrcIdx).getReg(); 01548 unsigned DstReg = mi->getOperand(DstIdx).getReg(); 01549 if (SrcReg != DstReg && 01550 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) { 01551 // The tied operands have been eliminated or shifted further down the 01552 // block to ease elimination. Continue processing with 'nmi'. 01553 TiedOperands.clear(); 01554 mi = nmi; 01555 continue; 01556 } 01557 } 01558 } 01559 01560 // Now iterate over the information collected above. 01561 for (TiedOperandMap::iterator OI = TiedOperands.begin(), 01562 OE = TiedOperands.end(); OI != OE; ++OI) { 01563 processTiedPairs(mi, OI->second, Dist); 01564 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi); 01565 } 01566 01567 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form. 01568 if (mi->isInsertSubreg()) { 01569 // From %reg = INSERT_SUBREG %reg, %subreg, subidx 01570 // To %reg:subidx = COPY %subreg 01571 unsigned SubIdx = mi->getOperand(3).getImm(); 01572 mi->RemoveOperand(3); 01573 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx"); 01574 mi->getOperand(0).setSubReg(SubIdx); 01575 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef()); 01576 mi->RemoveOperand(1); 01577 mi->setDesc(TII->get(TargetOpcode::COPY)); 01578 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi); 01579 } 01580 01581 // Clear TiedOperands here instead of at the top of the loop 01582 // since most instructions do not have tied operands. 01583 TiedOperands.clear(); 01584 mi = nmi; 01585 } 01586 } 01587 01588 if (LIS) 01589 MF->verify(this, "After two-address instruction pass"); 01590 01591 return MadeChange; 01592 } 01593 01594 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process. 01595 /// 01596 /// The instruction is turned into a sequence of sub-register copies: 01597 /// 01598 /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1 01599 /// 01600 /// Becomes: 01601 /// 01602 /// %dst:ssub0<def,undef> = COPY %v1 01603 /// %dst:ssub1<def> = COPY %v2 01604 /// 01605 void TwoAddressInstructionPass:: 01606 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) { 01607 MachineInstr *MI = MBBI; 01608 unsigned DstReg = MI->getOperand(0).getReg(); 01609 if (MI->getOperand(0).getSubReg() || 01610 TargetRegisterInfo::isPhysicalRegister(DstReg) || 01611 !(MI->getNumOperands() & 1)) { 01612 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI); 01613 llvm_unreachable(0); 01614 } 01615 01616 SmallVector<unsigned, 4> OrigRegs; 01617 if (LIS) { 01618 OrigRegs.push_back(MI->getOperand(0).getReg()); 01619 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) 01620 OrigRegs.push_back(MI->getOperand(i).getReg()); 01621 } 01622 01623 bool DefEmitted = false; 01624 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) { 01625 MachineOperand &UseMO = MI->getOperand(i); 01626 unsigned SrcReg = UseMO.getReg(); 01627 unsigned SubIdx = MI->getOperand(i+1).getImm(); 01628 // Nothing needs to be inserted for <undef> operands. 01629 if (UseMO.isUndef()) 01630 continue; 01631 01632 // Defer any kill flag to the last operand using SrcReg. Otherwise, we 01633 // might insert a COPY that uses SrcReg after is was killed. 01634 bool isKill = UseMO.isKill(); 01635 if (isKill) 01636 for (unsigned j = i + 2; j < e; j += 2) 01637 if (MI->getOperand(j).getReg() == SrcReg) { 01638 MI->getOperand(j).setIsKill(); 01639 UseMO.setIsKill(false); 01640 isKill = false; 01641 break; 01642 } 01643 01644 // Insert the sub-register copy. 01645 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), 01646 TII->get(TargetOpcode::COPY)) 01647 .addReg(DstReg, RegState::Define, SubIdx) 01648 .addOperand(UseMO); 01649 01650 // The first def needs an <undef> flag because there is no live register 01651 // before it. 01652 if (!DefEmitted) { 01653 CopyMI->getOperand(0).setIsUndef(true); 01654 // Return an iterator pointing to the first inserted instr. 01655 MBBI = CopyMI; 01656 } 01657 DefEmitted = true; 01658 01659 // Update LiveVariables' kill info. 01660 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg)) 01661 LV->replaceKillInstruction(SrcReg, MI, CopyMI); 01662 01663 DEBUG(dbgs() << "Inserted: " << *CopyMI); 01664 } 01665 01666 MachineBasicBlock::iterator EndMBBI = 01667 llvm::next(MachineBasicBlock::iterator(MI)); 01668 01669 if (!DefEmitted) { 01670 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF"); 01671 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF)); 01672 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j) 01673 MI->RemoveOperand(j); 01674 } else { 01675 DEBUG(dbgs() << "Eliminated: " << *MI); 01676 MI->eraseFromParent(); 01677 } 01678 01679 // Udpate LiveIntervals. 01680 if (LIS) 01681 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs); 01682 }