TwoAddressInstructionPass.cpp revision 98ec91ea80e042907aac8d3cbd9614d29f6cba45
1//===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the TwoAddress instruction pass which is used 11// by most register allocators. Two-Address instructions are rewritten 12// from: 13// 14// A = B op C 15// 16// to: 17// 18// A = B 19// A op= C 20// 21// Note that if a register allocator chooses to use this pass, that it 22// has to be capable of handling the non-SSA nature of these rewritten 23// virtual registers. 24// 25// It is also worth noting that the duplicate operand of the two 26// address instruction is removed. 27// 28//===----------------------------------------------------------------------===// 29 30#define DEBUG_TYPE "twoaddrinstr" 31#include "llvm/CodeGen/Passes.h" 32#include "llvm/Function.h" 33#include "llvm/CodeGen/LiveVariables.h" 34#include "llvm/CodeGen/MachineFunctionPass.h" 35#include "llvm/CodeGen/MachineInstr.h" 36#include "llvm/CodeGen/MachineInstrBuilder.h" 37#include "llvm/CodeGen/MachineRegisterInfo.h" 38#include "llvm/Analysis/AliasAnalysis.h" 39#include "llvm/Target/TargetRegisterInfo.h" 40#include "llvm/Target/TargetInstrInfo.h" 41#include "llvm/Target/TargetMachine.h" 42#include "llvm/Target/TargetOptions.h" 43#include "llvm/Support/Debug.h" 44#include "llvm/Support/ErrorHandling.h" 45#include "llvm/ADT/BitVector.h" 46#include "llvm/ADT/DenseMap.h" 47#include "llvm/ADT/SmallSet.h" 48#include "llvm/ADT/Statistic.h" 49#include "llvm/ADT/STLExtras.h" 50using namespace llvm; 51 52STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions"); 53STATISTIC(NumCommuted , "Number of instructions commuted to coalesce"); 54STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted"); 55STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address"); 56STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk"); 57STATISTIC(NumReMats, "Number of instructions re-materialized"); 58STATISTIC(NumDeletes, "Number of dead instructions deleted"); 59 60namespace { 61 class TwoAddressInstructionPass : public MachineFunctionPass { 62 const TargetInstrInfo *TII; 63 const TargetRegisterInfo *TRI; 64 MachineRegisterInfo *MRI; 65 LiveVariables *LV; 66 AliasAnalysis *AA; 67 68 // DistanceMap - Keep track the distance of a MI from the start of the 69 // current basic block. 70 DenseMap<MachineInstr*, unsigned> DistanceMap; 71 72 // SrcRegMap - A map from virtual registers to physical registers which 73 // are likely targets to be coalesced to due to copies from physical 74 // registers to virtual registers. e.g. v1024 = move r0. 75 DenseMap<unsigned, unsigned> SrcRegMap; 76 77 // DstRegMap - A map from virtual registers to physical registers which 78 // are likely targets to be coalesced to due to copies to physical 79 // registers from virtual registers. e.g. r1 = move v1024. 80 DenseMap<unsigned, unsigned> DstRegMap; 81 82 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen 83 /// during the initial walk of the machine function. 84 SmallVector<MachineInstr*, 16> RegSequences; 85 86 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI, 87 unsigned Reg, 88 MachineBasicBlock::iterator OldPos); 89 90 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC, 91 MachineInstr *MI, MachineInstr *DefMI, 92 MachineBasicBlock *MBB, unsigned Loc); 93 94 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist, 95 unsigned &LastDef); 96 97 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB, 98 unsigned Dist); 99 100 bool isProfitableToCommute(unsigned regB, unsigned regC, 101 MachineInstr *MI, MachineBasicBlock *MBB, 102 unsigned Dist); 103 104 bool CommuteInstruction(MachineBasicBlock::iterator &mi, 105 MachineFunction::iterator &mbbi, 106 unsigned RegB, unsigned RegC, unsigned Dist); 107 108 bool isProfitableToConv3Addr(unsigned RegA); 109 110 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi, 111 MachineBasicBlock::iterator &nmi, 112 MachineFunction::iterator &mbbi, 113 unsigned RegB, unsigned Dist); 114 115 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill; 116 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills, 117 SmallVector<NewKill, 4> &NewKills, 118 MachineBasicBlock *MBB, unsigned Dist); 119 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi, 120 MachineBasicBlock::iterator &nmi, 121 MachineFunction::iterator &mbbi, unsigned Dist); 122 123 bool TryInstructionTransform(MachineBasicBlock::iterator &mi, 124 MachineBasicBlock::iterator &nmi, 125 MachineFunction::iterator &mbbi, 126 unsigned SrcIdx, unsigned DstIdx, 127 unsigned Dist); 128 129 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB, 130 SmallPtrSet<MachineInstr*, 8> &Processed); 131 132 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg); 133 134 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part 135 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as 136 /// sub-register references of the register defined by REG_SEQUENCE. 137 bool EliminateRegSequences(); 138 139 public: 140 static char ID; // Pass identification, replacement for typeid 141 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {} 142 143 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 144 AU.setPreservesCFG(); 145 AU.addRequired<AliasAnalysis>(); 146 AU.addPreserved<LiveVariables>(); 147 AU.addPreservedID(MachineLoopInfoID); 148 AU.addPreservedID(MachineDominatorsID); 149 if (StrongPHIElim) 150 AU.addPreservedID(StrongPHIEliminationID); 151 else 152 AU.addPreservedID(PHIEliminationID); 153 MachineFunctionPass::getAnalysisUsage(AU); 154 } 155 156 /// runOnMachineFunction - Pass entry point. 157 bool runOnMachineFunction(MachineFunction&); 158 }; 159} 160 161char TwoAddressInstructionPass::ID = 0; 162static RegisterPass<TwoAddressInstructionPass> 163X("twoaddressinstruction", "Two-Address instruction pass"); 164 165const PassInfo *const llvm::TwoAddressInstructionPassID = &X; 166 167/// Sink3AddrInstruction - A two-address instruction has been converted to a 168/// three-address instruction to avoid clobbering a register. Try to sink it 169/// past the instruction that would kill the above mentioned register to reduce 170/// register pressure. 171bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB, 172 MachineInstr *MI, unsigned SavedReg, 173 MachineBasicBlock::iterator OldPos) { 174 // Check if it's safe to move this instruction. 175 bool SeenStore = true; // Be conservative. 176 if (!MI->isSafeToMove(TII, AA, SeenStore)) 177 return false; 178 179 unsigned DefReg = 0; 180 SmallSet<unsigned, 4> UseRegs; 181 182 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 183 const MachineOperand &MO = MI->getOperand(i); 184 if (!MO.isReg()) 185 continue; 186 unsigned MOReg = MO.getReg(); 187 if (!MOReg) 188 continue; 189 if (MO.isUse() && MOReg != SavedReg) 190 UseRegs.insert(MO.getReg()); 191 if (!MO.isDef()) 192 continue; 193 if (MO.isImplicit()) 194 // Don't try to move it if it implicitly defines a register. 195 return false; 196 if (DefReg) 197 // For now, don't move any instructions that define multiple registers. 198 return false; 199 DefReg = MO.getReg(); 200 } 201 202 // Find the instruction that kills SavedReg. 203 MachineInstr *KillMI = NULL; 204 for (MachineRegisterInfo::use_nodbg_iterator 205 UI = MRI->use_nodbg_begin(SavedReg), 206 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 207 MachineOperand &UseMO = UI.getOperand(); 208 if (!UseMO.isKill()) 209 continue; 210 KillMI = UseMO.getParent(); 211 break; 212 } 213 214 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI) 215 return false; 216 217 // If any of the definitions are used by another instruction between the 218 // position and the kill use, then it's not safe to sink it. 219 // 220 // FIXME: This can be sped up if there is an easy way to query whether an 221 // instruction is before or after another instruction. Then we can use 222 // MachineRegisterInfo def / use instead. 223 MachineOperand *KillMO = NULL; 224 MachineBasicBlock::iterator KillPos = KillMI; 225 ++KillPos; 226 227 unsigned NumVisited = 0; 228 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) { 229 MachineInstr *OtherMI = I; 230 // DBG_VALUE cannot be counted against the limit. 231 if (OtherMI->isDebugValue()) 232 continue; 233 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost. 234 return false; 235 ++NumVisited; 236 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) { 237 MachineOperand &MO = OtherMI->getOperand(i); 238 if (!MO.isReg()) 239 continue; 240 unsigned MOReg = MO.getReg(); 241 if (!MOReg) 242 continue; 243 if (DefReg == MOReg) 244 return false; 245 246 if (MO.isKill()) { 247 if (OtherMI == KillMI && MOReg == SavedReg) 248 // Save the operand that kills the register. We want to unset the kill 249 // marker if we can sink MI past it. 250 KillMO = &MO; 251 else if (UseRegs.count(MOReg)) 252 // One of the uses is killed before the destination. 253 return false; 254 } 255 } 256 } 257 258 // Update kill and LV information. 259 KillMO->setIsKill(false); 260 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI); 261 KillMO->setIsKill(true); 262 263 if (LV) 264 LV->replaceKillInstruction(SavedReg, KillMI, MI); 265 266 // Move instruction to its destination. 267 MBB->remove(MI); 268 MBB->insert(KillPos, MI); 269 270 ++Num3AddrSunk; 271 return true; 272} 273 274/// isTwoAddrUse - Return true if the specified MI is using the specified 275/// register as a two-address operand. 276static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) { 277 const TargetInstrDesc &TID = UseMI->getDesc(); 278 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) { 279 MachineOperand &MO = UseMI->getOperand(i); 280 if (MO.isReg() && MO.getReg() == Reg && 281 (MO.isDef() || UseMI->isRegTiedToDefOperand(i))) 282 // Earlier use is a two-address one. 283 return true; 284 } 285 return false; 286} 287 288/// isProfitableToReMat - Return true if the heuristics determines it is likely 289/// to be profitable to re-materialize the definition of Reg rather than copy 290/// the register. 291bool 292TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg, 293 const TargetRegisterClass *RC, 294 MachineInstr *MI, MachineInstr *DefMI, 295 MachineBasicBlock *MBB, unsigned Loc) { 296 bool OtherUse = false; 297 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg), 298 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 299 MachineOperand &UseMO = UI.getOperand(); 300 MachineInstr *UseMI = UseMO.getParent(); 301 MachineBasicBlock *UseMBB = UseMI->getParent(); 302 if (UseMBB == MBB) { 303 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI); 304 if (DI != DistanceMap.end() && DI->second == Loc) 305 continue; // Current use. 306 OtherUse = true; 307 // There is at least one other use in the MBB that will clobber the 308 // register. 309 if (isTwoAddrUse(UseMI, Reg)) 310 return true; 311 } 312 } 313 314 // If other uses in MBB are not two-address uses, then don't remat. 315 if (OtherUse) 316 return false; 317 318 // No other uses in the same block, remat if it's defined in the same 319 // block so it does not unnecessarily extend the live range. 320 return MBB == DefMI->getParent(); 321} 322 323/// NoUseAfterLastDef - Return true if there are no intervening uses between the 324/// last instruction in the MBB that defines the specified register and the 325/// two-address instruction which is being processed. It also returns the last 326/// def location by reference 327bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg, 328 MachineBasicBlock *MBB, unsigned Dist, 329 unsigned &LastDef) { 330 LastDef = 0; 331 unsigned LastUse = Dist; 332 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg), 333 E = MRI->reg_end(); I != E; ++I) { 334 MachineOperand &MO = I.getOperand(); 335 MachineInstr *MI = MO.getParent(); 336 if (MI->getParent() != MBB || MI->isDebugValue()) 337 continue; 338 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 339 if (DI == DistanceMap.end()) 340 continue; 341 if (MO.isUse() && DI->second < LastUse) 342 LastUse = DI->second; 343 if (MO.isDef() && DI->second > LastDef) 344 LastDef = DI->second; 345 } 346 347 return !(LastUse > LastDef && LastUse < Dist); 348} 349 350MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg, 351 MachineBasicBlock *MBB, 352 unsigned Dist) { 353 unsigned LastUseDist = 0; 354 MachineInstr *LastUse = 0; 355 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg), 356 E = MRI->reg_end(); I != E; ++I) { 357 MachineOperand &MO = I.getOperand(); 358 MachineInstr *MI = MO.getParent(); 359 if (MI->getParent() != MBB || MI->isDebugValue()) 360 continue; 361 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 362 if (DI == DistanceMap.end()) 363 continue; 364 if (DI->second >= Dist) 365 continue; 366 367 if (MO.isUse() && DI->second > LastUseDist) { 368 LastUse = DI->first; 369 LastUseDist = DI->second; 370 } 371 } 372 return LastUse; 373} 374 375/// isCopyToReg - Return true if the specified MI is a copy instruction or 376/// a extract_subreg instruction. It also returns the source and destination 377/// registers and whether they are physical registers by reference. 378static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII, 379 unsigned &SrcReg, unsigned &DstReg, 380 bool &IsSrcPhys, bool &IsDstPhys) { 381 SrcReg = 0; 382 DstReg = 0; 383 unsigned SrcSubIdx, DstSubIdx; 384 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) { 385 if (MI.isExtractSubreg()) { 386 DstReg = MI.getOperand(0).getReg(); 387 SrcReg = MI.getOperand(1).getReg(); 388 } else if (MI.isInsertSubreg()) { 389 DstReg = MI.getOperand(0).getReg(); 390 SrcReg = MI.getOperand(2).getReg(); 391 } else if (MI.isSubregToReg()) { 392 DstReg = MI.getOperand(0).getReg(); 393 SrcReg = MI.getOperand(2).getReg(); 394 } 395 } 396 397 if (DstReg) { 398 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg); 399 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 400 return true; 401 } 402 return false; 403} 404 405/// isKilled - Test if the given register value, which is used by the given 406/// instruction, is killed by the given instruction. This looks through 407/// coalescable copies to see if the original value is potentially not killed. 408/// 409/// For example, in this code: 410/// 411/// %reg1034 = copy %reg1024 412/// %reg1035 = copy %reg1025<kill> 413/// %reg1036 = add %reg1034<kill>, %reg1035<kill> 414/// 415/// %reg1034 is not considered to be killed, since it is copied from a 416/// register which is not killed. Treating it as not killed lets the 417/// normal heuristics commute the (two-address) add, which lets 418/// coalescing eliminate the extra copy. 419/// 420static bool isKilled(MachineInstr &MI, unsigned Reg, 421 const MachineRegisterInfo *MRI, 422 const TargetInstrInfo *TII) { 423 MachineInstr *DefMI = &MI; 424 for (;;) { 425 if (!DefMI->killsRegister(Reg)) 426 return false; 427 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 428 return true; 429 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg); 430 // If there are multiple defs, we can't do a simple analysis, so just 431 // go with what the kill flag says. 432 if (llvm::next(Begin) != MRI->def_end()) 433 return true; 434 DefMI = &*Begin; 435 bool IsSrcPhys, IsDstPhys; 436 unsigned SrcReg, DstReg; 437 // If the def is something other than a copy, then it isn't going to 438 // be coalesced, so follow the kill flag. 439 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 440 return true; 441 Reg = SrcReg; 442 } 443} 444 445/// isTwoAddrUse - Return true if the specified MI uses the specified register 446/// as a two-address use. If so, return the destination register by reference. 447static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) { 448 const TargetInstrDesc &TID = MI.getDesc(); 449 unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands(); 450 for (unsigned i = 0; i != NumOps; ++i) { 451 const MachineOperand &MO = MI.getOperand(i); 452 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg) 453 continue; 454 unsigned ti; 455 if (MI.isRegTiedToDefOperand(i, &ti)) { 456 DstReg = MI.getOperand(ti).getReg(); 457 return true; 458 } 459 } 460 return false; 461} 462 463/// findOnlyInterestingUse - Given a register, if has a single in-basic block 464/// use, return the use instruction if it's a copy or a two-address use. 465static 466MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB, 467 MachineRegisterInfo *MRI, 468 const TargetInstrInfo *TII, 469 bool &IsCopy, 470 unsigned &DstReg, bool &IsDstPhys) { 471 if (!MRI->hasOneNonDBGUse(Reg)) 472 // None or more than one use. 473 return 0; 474 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg); 475 if (UseMI.getParent() != MBB) 476 return 0; 477 unsigned SrcReg; 478 bool IsSrcPhys; 479 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) { 480 IsCopy = true; 481 return &UseMI; 482 } 483 IsDstPhys = false; 484 if (isTwoAddrUse(UseMI, Reg, DstReg)) { 485 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); 486 return &UseMI; 487 } 488 return 0; 489} 490 491/// getMappedReg - Return the physical register the specified virtual register 492/// might be mapped to. 493static unsigned 494getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) { 495 while (TargetRegisterInfo::isVirtualRegister(Reg)) { 496 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg); 497 if (SI == RegMap.end()) 498 return 0; 499 Reg = SI->second; 500 } 501 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 502 return Reg; 503 return 0; 504} 505 506/// regsAreCompatible - Return true if the two registers are equal or aliased. 507/// 508static bool 509regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) { 510 if (RegA == RegB) 511 return true; 512 if (!RegA || !RegB) 513 return false; 514 return TRI->regsOverlap(RegA, RegB); 515} 516 517 518/// isProfitableToReMat - Return true if it's potentially profitable to commute 519/// the two-address instruction that's being processed. 520bool 521TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC, 522 MachineInstr *MI, MachineBasicBlock *MBB, 523 unsigned Dist) { 524 // Determine if it's profitable to commute this two address instruction. In 525 // general, we want no uses between this instruction and the definition of 526 // the two-address register. 527 // e.g. 528 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1 529 // %reg1029<def> = MOV8rr %reg1028 530 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead> 531 // insert => %reg1030<def> = MOV8rr %reg1028 532 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead> 533 // In this case, it might not be possible to coalesce the second MOV8rr 534 // instruction if the first one is coalesced. So it would be profitable to 535 // commute it: 536 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1 537 // %reg1029<def> = MOV8rr %reg1028 538 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead> 539 // insert => %reg1030<def> = MOV8rr %reg1029 540 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead> 541 542 if (!MI->killsRegister(regC)) 543 return false; 544 545 // Ok, we have something like: 546 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead> 547 // let's see if it's worth commuting it. 548 549 // Look for situations like this: 550 // %reg1024<def> = MOV r1 551 // %reg1025<def> = MOV r0 552 // %reg1026<def> = ADD %reg1024, %reg1025 553 // r0 = MOV %reg1026 554 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy. 555 unsigned FromRegB = getMappedReg(regB, SrcRegMap); 556 unsigned FromRegC = getMappedReg(regC, SrcRegMap); 557 unsigned ToRegB = getMappedReg(regB, DstRegMap); 558 unsigned ToRegC = getMappedReg(regC, DstRegMap); 559 if (!regsAreCompatible(FromRegB, ToRegB, TRI) && 560 (regsAreCompatible(FromRegB, ToRegC, TRI) || 561 regsAreCompatible(FromRegC, ToRegB, TRI))) 562 return true; 563 564 // If there is a use of regC between its last def (could be livein) and this 565 // instruction, then bail. 566 unsigned LastDefC = 0; 567 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC)) 568 return false; 569 570 // If there is a use of regB between its last def (could be livein) and this 571 // instruction, then go ahead and make this transformation. 572 unsigned LastDefB = 0; 573 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB)) 574 return true; 575 576 // Since there are no intervening uses for both registers, then commute 577 // if the def of regC is closer. Its live interval is shorter. 578 return LastDefB && LastDefC && LastDefC > LastDefB; 579} 580 581/// CommuteInstruction - Commute a two-address instruction and update the basic 582/// block, distance map, and live variables if needed. Return true if it is 583/// successful. 584bool 585TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi, 586 MachineFunction::iterator &mbbi, 587 unsigned RegB, unsigned RegC, unsigned Dist) { 588 MachineInstr *MI = mi; 589 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI); 590 MachineInstr *NewMI = TII->commuteInstruction(MI); 591 592 if (NewMI == 0) { 593 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n"); 594 return false; 595 } 596 597 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI); 598 // If the instruction changed to commute it, update livevar. 599 if (NewMI != MI) { 600 if (LV) 601 // Update live variables 602 LV->replaceKillInstruction(RegC, MI, NewMI); 603 604 mbbi->insert(mi, NewMI); // Insert the new inst 605 mbbi->erase(mi); // Nuke the old inst. 606 mi = NewMI; 607 DistanceMap.insert(std::make_pair(NewMI, Dist)); 608 } 609 610 // Update source register map. 611 unsigned FromRegC = getMappedReg(RegC, SrcRegMap); 612 if (FromRegC) { 613 unsigned RegA = MI->getOperand(0).getReg(); 614 SrcRegMap[RegA] = FromRegC; 615 } 616 617 return true; 618} 619 620/// isProfitableToConv3Addr - Return true if it is profitable to convert the 621/// given 2-address instruction to a 3-address one. 622bool 623TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) { 624 // Look for situations like this: 625 // %reg1024<def> = MOV r1 626 // %reg1025<def> = MOV r0 627 // %reg1026<def> = ADD %reg1024, %reg1025 628 // r2 = MOV %reg1026 629 // Turn ADD into a 3-address instruction to avoid a copy. 630 unsigned FromRegA = getMappedReg(RegA, SrcRegMap); 631 unsigned ToRegA = getMappedReg(RegA, DstRegMap); 632 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI)); 633} 634 635/// ConvertInstTo3Addr - Convert the specified two-address instruction into a 636/// three address one. Return true if this transformation was successful. 637bool 638TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi, 639 MachineBasicBlock::iterator &nmi, 640 MachineFunction::iterator &mbbi, 641 unsigned RegB, unsigned Dist) { 642 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV); 643 if (NewMI) { 644 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi); 645 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI); 646 bool Sunk = false; 647 648 if (NewMI->findRegisterUseOperand(RegB, false, TRI)) 649 // FIXME: Temporary workaround. If the new instruction doesn't 650 // uses RegB, convertToThreeAddress must have created more 651 // then one instruction. 652 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi); 653 654 mbbi->erase(mi); // Nuke the old inst. 655 656 if (!Sunk) { 657 DistanceMap.insert(std::make_pair(NewMI, Dist)); 658 mi = NewMI; 659 nmi = llvm::next(mi); 660 } 661 return true; 662 } 663 664 return false; 665} 666 667/// ProcessCopy - If the specified instruction is not yet processed, process it 668/// if it's a copy. For a copy instruction, we find the physical registers the 669/// source and destination registers might be mapped to. These are kept in 670/// point-to maps used to determine future optimizations. e.g. 671/// v1024 = mov r0 672/// v1025 = mov r1 673/// v1026 = add v1024, v1025 674/// r1 = mov r1026 675/// If 'add' is a two-address instruction, v1024, v1026 are both potentially 676/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is 677/// potentially joined with r1 on the output side. It's worthwhile to commute 678/// 'add' to eliminate a copy. 679void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI, 680 MachineBasicBlock *MBB, 681 SmallPtrSet<MachineInstr*, 8> &Processed) { 682 if (Processed.count(MI)) 683 return; 684 685 bool IsSrcPhys, IsDstPhys; 686 unsigned SrcReg, DstReg; 687 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 688 return; 689 690 if (IsDstPhys && !IsSrcPhys) 691 DstRegMap.insert(std::make_pair(SrcReg, DstReg)); 692 else if (!IsDstPhys && IsSrcPhys) { 693 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second; 694 if (!isNew) 695 assert(SrcRegMap[DstReg] == SrcReg && 696 "Can't map to two src physical registers!"); 697 698 SmallVector<unsigned, 4> VirtRegPairs; 699 bool IsCopy = false; 700 unsigned NewReg = 0; 701 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII, 702 IsCopy, NewReg, IsDstPhys)) { 703 if (IsCopy) { 704 if (!Processed.insert(UseMI)) 705 break; 706 } 707 708 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI); 709 if (DI != DistanceMap.end()) 710 // Earlier in the same MBB.Reached via a back edge. 711 break; 712 713 if (IsDstPhys) { 714 VirtRegPairs.push_back(NewReg); 715 break; 716 } 717 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second; 718 if (!isNew) 719 assert(SrcRegMap[NewReg] == DstReg && 720 "Can't map to two src physical registers!"); 721 VirtRegPairs.push_back(NewReg); 722 DstReg = NewReg; 723 } 724 725 if (!VirtRegPairs.empty()) { 726 unsigned ToReg = VirtRegPairs.back(); 727 VirtRegPairs.pop_back(); 728 while (!VirtRegPairs.empty()) { 729 unsigned FromReg = VirtRegPairs.back(); 730 VirtRegPairs.pop_back(); 731 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second; 732 if (!isNew) 733 assert(DstRegMap[FromReg] == ToReg && 734 "Can't map to two dst physical registers!"); 735 ToReg = FromReg; 736 } 737 } 738 } 739 740 Processed.insert(MI); 741} 742 743/// isSafeToDelete - If the specified instruction does not produce any side 744/// effects and all of its defs are dead, then it's safe to delete. 745static bool isSafeToDelete(MachineInstr *MI, 746 const TargetInstrInfo *TII, 747 SmallVector<unsigned, 4> &Kills) { 748 const TargetInstrDesc &TID = MI->getDesc(); 749 if (TID.mayStore() || TID.isCall()) 750 return false; 751 if (TID.isTerminator() || TID.hasUnmodeledSideEffects()) 752 return false; 753 754 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 755 MachineOperand &MO = MI->getOperand(i); 756 if (!MO.isReg()) 757 continue; 758 if (MO.isDef() && !MO.isDead()) 759 return false; 760 if (MO.isUse() && MO.isKill()) 761 Kills.push_back(MO.getReg()); 762 } 763 return true; 764} 765 766/// canUpdateDeletedKills - Check if all the registers listed in Kills are 767/// killed by instructions in MBB preceding the current instruction at 768/// position Dist. If so, return true and record information about the 769/// preceding kills in NewKills. 770bool TwoAddressInstructionPass:: 771canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills, 772 SmallVector<NewKill, 4> &NewKills, 773 MachineBasicBlock *MBB, unsigned Dist) { 774 while (!Kills.empty()) { 775 unsigned Kill = Kills.back(); 776 Kills.pop_back(); 777 if (TargetRegisterInfo::isPhysicalRegister(Kill)) 778 return false; 779 780 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist); 781 if (!LastKill) 782 return false; 783 784 bool isModRef = LastKill->definesRegister(Kill); 785 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef), 786 LastKill)); 787 } 788 return true; 789} 790 791/// DeleteUnusedInstr - If an instruction with a tied register operand can 792/// be safely deleted, just delete it. 793bool 794TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi, 795 MachineBasicBlock::iterator &nmi, 796 MachineFunction::iterator &mbbi, 797 unsigned Dist) { 798 // Check if the instruction has no side effects and if all its defs are dead. 799 SmallVector<unsigned, 4> Kills; 800 if (!isSafeToDelete(mi, TII, Kills)) 801 return false; 802 803 // If this instruction kills some virtual registers, we need to 804 // update the kill information. If it's not possible to do so, 805 // then bail out. 806 SmallVector<NewKill, 4> NewKills; 807 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist)) 808 return false; 809 810 if (LV) { 811 while (!NewKills.empty()) { 812 MachineInstr *NewKill = NewKills.back().second; 813 unsigned Kill = NewKills.back().first.first; 814 bool isDead = NewKills.back().first.second; 815 NewKills.pop_back(); 816 if (LV->removeVirtualRegisterKilled(Kill, mi)) { 817 if (isDead) 818 LV->addVirtualRegisterDead(Kill, NewKill); 819 else 820 LV->addVirtualRegisterKilled(Kill, NewKill); 821 } 822 } 823 } 824 825 mbbi->erase(mi); // Nuke the old inst. 826 mi = nmi; 827 return true; 828} 829 830/// TryInstructionTransform - For the case where an instruction has a single 831/// pair of tied register operands, attempt some transformations that may 832/// either eliminate the tied operands or improve the opportunities for 833/// coalescing away the register copy. Returns true if the tied operands 834/// are eliminated altogether. 835bool TwoAddressInstructionPass:: 836TryInstructionTransform(MachineBasicBlock::iterator &mi, 837 MachineBasicBlock::iterator &nmi, 838 MachineFunction::iterator &mbbi, 839 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) { 840 const TargetInstrDesc &TID = mi->getDesc(); 841 unsigned regA = mi->getOperand(DstIdx).getReg(); 842 unsigned regB = mi->getOperand(SrcIdx).getReg(); 843 844 assert(TargetRegisterInfo::isVirtualRegister(regB) && 845 "cannot make instruction into two-address form"); 846 847 // If regA is dead and the instruction can be deleted, just delete 848 // it so it doesn't clobber regB. 849 bool regBKilled = isKilled(*mi, regB, MRI, TII); 850 if (!regBKilled && mi->getOperand(DstIdx).isDead() && 851 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) { 852 ++NumDeletes; 853 return true; // Done with this instruction. 854 } 855 856 // Check if it is profitable to commute the operands. 857 unsigned SrcOp1, SrcOp2; 858 unsigned regC = 0; 859 unsigned regCIdx = ~0U; 860 bool TryCommute = false; 861 bool AggressiveCommute = false; 862 if (TID.isCommutable() && mi->getNumOperands() >= 3 && 863 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) { 864 if (SrcIdx == SrcOp1) 865 regCIdx = SrcOp2; 866 else if (SrcIdx == SrcOp2) 867 regCIdx = SrcOp1; 868 869 if (regCIdx != ~0U) { 870 regC = mi->getOperand(regCIdx).getReg(); 871 if (!regBKilled && isKilled(*mi, regC, MRI, TII)) 872 // If C dies but B does not, swap the B and C operands. 873 // This makes the live ranges of A and C joinable. 874 TryCommute = true; 875 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) { 876 TryCommute = true; 877 AggressiveCommute = true; 878 } 879 } 880 } 881 882 // If it's profitable to commute, try to do so. 883 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) { 884 ++NumCommuted; 885 if (AggressiveCommute) 886 ++NumAggrCommuted; 887 return false; 888 } 889 890 if (TID.isConvertibleTo3Addr()) { 891 // This instruction is potentially convertible to a true 892 // three-address instruction. Check if it is profitable. 893 if (!regBKilled || isProfitableToConv3Addr(regA)) { 894 // Try to convert it. 895 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) { 896 ++NumConvertedTo3Addr; 897 return true; // Done with this instruction. 898 } 899 } 900 } 901 902 // If this is an instruction with a load folded into it, try unfolding 903 // the load, e.g. avoid this: 904 // movq %rdx, %rcx 905 // addq (%rax), %rcx 906 // in favor of this: 907 // movq (%rax), %rcx 908 // addq %rdx, %rcx 909 // because it's preferable to schedule a load than a register copy. 910 if (TID.mayLoad() && !regBKilled) { 911 // Determine if a load can be unfolded. 912 unsigned LoadRegIndex; 913 unsigned NewOpc = 914 TII->getOpcodeAfterMemoryUnfold(mi->getOpcode(), 915 /*UnfoldLoad=*/true, 916 /*UnfoldStore=*/false, 917 &LoadRegIndex); 918 if (NewOpc != 0) { 919 const TargetInstrDesc &UnfoldTID = TII->get(NewOpc); 920 if (UnfoldTID.getNumDefs() == 1) { 921 MachineFunction &MF = *mbbi->getParent(); 922 923 // Unfold the load. 924 DEBUG(dbgs() << "2addr: UNFOLDING: " << *mi); 925 const TargetRegisterClass *RC = 926 UnfoldTID.OpInfo[LoadRegIndex].getRegClass(TRI); 927 unsigned Reg = MRI->createVirtualRegister(RC); 928 SmallVector<MachineInstr *, 2> NewMIs; 929 if (!TII->unfoldMemoryOperand(MF, mi, Reg, 930 /*UnfoldLoad=*/true,/*UnfoldStore=*/false, 931 NewMIs)) { 932 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 933 return false; 934 } 935 assert(NewMIs.size() == 2 && 936 "Unfolded a load into multiple instructions!"); 937 // The load was previously folded, so this is the only use. 938 NewMIs[1]->addRegisterKilled(Reg, TRI); 939 940 // Tentatively insert the instructions into the block so that they 941 // look "normal" to the transformation logic. 942 mbbi->insert(mi, NewMIs[0]); 943 mbbi->insert(mi, NewMIs[1]); 944 945 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0] 946 << "2addr: NEW INST: " << *NewMIs[1]); 947 948 // Transform the instruction, now that it no longer has a load. 949 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA); 950 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB); 951 MachineBasicBlock::iterator NewMI = NewMIs[1]; 952 bool TransformSuccess = 953 TryInstructionTransform(NewMI, mi, mbbi, 954 NewSrcIdx, NewDstIdx, Dist); 955 if (TransformSuccess || 956 NewMIs[1]->getOperand(NewSrcIdx).isKill()) { 957 // Success, or at least we made an improvement. Keep the unfolded 958 // instructions and discard the original. 959 if (LV) { 960 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) { 961 MachineOperand &MO = mi->getOperand(i); 962 if (MO.isReg() && MO.getReg() != 0 && 963 TargetRegisterInfo::isVirtualRegister(MO.getReg())) { 964 if (MO.isUse()) { 965 if (MO.isKill()) { 966 if (NewMIs[0]->killsRegister(MO.getReg())) 967 LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[0]); 968 else { 969 assert(NewMIs[1]->killsRegister(MO.getReg()) && 970 "Kill missing after load unfold!"); 971 LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[1]); 972 } 973 } 974 } else if (LV->removeVirtualRegisterDead(MO.getReg(), mi)) { 975 if (NewMIs[1]->registerDefIsDead(MO.getReg())) 976 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]); 977 else { 978 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) && 979 "Dead flag missing after load unfold!"); 980 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]); 981 } 982 } 983 } 984 } 985 LV->addVirtualRegisterKilled(Reg, NewMIs[1]); 986 } 987 mi->eraseFromParent(); 988 mi = NewMIs[1]; 989 if (TransformSuccess) 990 return true; 991 } else { 992 // Transforming didn't eliminate the tie and didn't lead to an 993 // improvement. Clean up the unfolded instructions and keep the 994 // original. 995 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 996 NewMIs[0]->eraseFromParent(); 997 NewMIs[1]->eraseFromParent(); 998 } 999 } 1000 } 1001 } 1002 1003 return false; 1004} 1005 1006/// runOnMachineFunction - Reduce two-address instructions to two operands. 1007/// 1008bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) { 1009 DEBUG(dbgs() << "Machine Function\n"); 1010 const TargetMachine &TM = MF.getTarget(); 1011 MRI = &MF.getRegInfo(); 1012 TII = TM.getInstrInfo(); 1013 TRI = TM.getRegisterInfo(); 1014 LV = getAnalysisIfAvailable<LiveVariables>(); 1015 AA = &getAnalysis<AliasAnalysis>(); 1016 1017 bool MadeChange = false; 1018 1019 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n"); 1020 DEBUG(dbgs() << "********** Function: " 1021 << MF.getFunction()->getName() << '\n'); 1022 1023 // ReMatRegs - Keep track of the registers whose def's are remat'ed. 1024 BitVector ReMatRegs; 1025 ReMatRegs.resize(MRI->getLastVirtReg()+1); 1026 1027 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> > 1028 TiedOperandMap; 1029 TiedOperandMap TiedOperands(4); 1030 1031 SmallPtrSet<MachineInstr*, 8> Processed; 1032 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end(); 1033 mbbi != mbbe; ++mbbi) { 1034 unsigned Dist = 0; 1035 DistanceMap.clear(); 1036 SrcRegMap.clear(); 1037 DstRegMap.clear(); 1038 Processed.clear(); 1039 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end(); 1040 mi != me; ) { 1041 MachineBasicBlock::iterator nmi = llvm::next(mi); 1042 if (mi->isDebugValue()) { 1043 mi = nmi; 1044 continue; 1045 } 1046 1047 // Remember REG_SEQUENCE instructions, we'll deal with them later. 1048 if (mi->isRegSequence()) 1049 RegSequences.push_back(&*mi); 1050 1051 const TargetInstrDesc &TID = mi->getDesc(); 1052 bool FirstTied = true; 1053 1054 DistanceMap.insert(std::make_pair(mi, ++Dist)); 1055 1056 ProcessCopy(&*mi, &*mbbi, Processed); 1057 1058 // First scan through all the tied register uses in this instruction 1059 // and record a list of pairs of tied operands for each register. 1060 unsigned NumOps = mi->isInlineAsm() 1061 ? mi->getNumOperands() : TID.getNumOperands(); 1062 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) { 1063 unsigned DstIdx = 0; 1064 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx)) 1065 continue; 1066 1067 if (FirstTied) { 1068 FirstTied = false; 1069 ++NumTwoAddressInstrs; 1070 DEBUG(dbgs() << '\t' << *mi); 1071 } 1072 1073 assert(mi->getOperand(SrcIdx).isReg() && 1074 mi->getOperand(SrcIdx).getReg() && 1075 mi->getOperand(SrcIdx).isUse() && 1076 "two address instruction invalid"); 1077 1078 unsigned regB = mi->getOperand(SrcIdx).getReg(); 1079 TiedOperandMap::iterator OI = TiedOperands.find(regB); 1080 if (OI == TiedOperands.end()) { 1081 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair; 1082 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first; 1083 } 1084 OI->second.push_back(std::make_pair(SrcIdx, DstIdx)); 1085 } 1086 1087 // Now iterate over the information collected above. 1088 for (TiedOperandMap::iterator OI = TiedOperands.begin(), 1089 OE = TiedOperands.end(); OI != OE; ++OI) { 1090 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second; 1091 1092 // If the instruction has a single pair of tied operands, try some 1093 // transformations that may either eliminate the tied operands or 1094 // improve the opportunities for coalescing away the register copy. 1095 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) { 1096 unsigned SrcIdx = TiedPairs[0].first; 1097 unsigned DstIdx = TiedPairs[0].second; 1098 1099 // If the registers are already equal, nothing needs to be done. 1100 if (mi->getOperand(SrcIdx).getReg() == 1101 mi->getOperand(DstIdx).getReg()) 1102 break; // Done with this instruction. 1103 1104 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist)) 1105 break; // The tied operands have been eliminated. 1106 } 1107 1108 bool RemovedKillFlag = false; 1109 bool AllUsesCopied = true; 1110 unsigned LastCopiedReg = 0; 1111 unsigned regB = OI->first; 1112 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) { 1113 unsigned SrcIdx = TiedPairs[tpi].first; 1114 unsigned DstIdx = TiedPairs[tpi].second; 1115 unsigned regA = mi->getOperand(DstIdx).getReg(); 1116 // Grab regB from the instruction because it may have changed if the 1117 // instruction was commuted. 1118 regB = mi->getOperand(SrcIdx).getReg(); 1119 1120 if (regA == regB) { 1121 // The register is tied to multiple destinations (or else we would 1122 // not have continued this far), but this use of the register 1123 // already matches the tied destination. Leave it. 1124 AllUsesCopied = false; 1125 continue; 1126 } 1127 LastCopiedReg = regA; 1128 1129 assert(TargetRegisterInfo::isVirtualRegister(regB) && 1130 "cannot make instruction into two-address form"); 1131 1132#ifndef NDEBUG 1133 // First, verify that we don't have a use of "a" in the instruction 1134 // (a = b + a for example) because our transformation will not 1135 // work. This should never occur because we are in SSA form. 1136 for (unsigned i = 0; i != mi->getNumOperands(); ++i) 1137 assert(i == DstIdx || 1138 !mi->getOperand(i).isReg() || 1139 mi->getOperand(i).getReg() != regA); 1140#endif 1141 1142 // Emit a copy or rematerialize the definition. 1143 const TargetRegisterClass *rc = MRI->getRegClass(regB); 1144 MachineInstr *DefMI = MRI->getVRegDef(regB); 1145 // If it's safe and profitable, remat the definition instead of 1146 // copying it. 1147 if (DefMI && 1148 DefMI->getDesc().isAsCheapAsAMove() && 1149 DefMI->isSafeToReMat(TII, AA, regB) && 1150 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){ 1151 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n"); 1152 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg(); 1153 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI); 1154 ReMatRegs.set(regB); 1155 ++NumReMats; 1156 } else { 1157 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc, 1158 mi->getDebugLoc()); 1159 (void)Emitted; 1160 assert(Emitted && "Unable to issue a copy instruction!\n"); 1161 } 1162 1163 MachineBasicBlock::iterator prevMI = prior(mi); 1164 // Update DistanceMap. 1165 DistanceMap.insert(std::make_pair(prevMI, Dist)); 1166 DistanceMap[mi] = ++Dist; 1167 1168 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI); 1169 1170 MachineOperand &MO = mi->getOperand(SrcIdx); 1171 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() && 1172 "inconsistent operand info for 2-reg pass"); 1173 if (MO.isKill()) { 1174 MO.setIsKill(false); 1175 RemovedKillFlag = true; 1176 } 1177 MO.setReg(regA); 1178 } 1179 1180 if (AllUsesCopied) { 1181 // Replace other (un-tied) uses of regB with LastCopiedReg. 1182 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) { 1183 MachineOperand &MO = mi->getOperand(i); 1184 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) { 1185 if (MO.isKill()) { 1186 MO.setIsKill(false); 1187 RemovedKillFlag = true; 1188 } 1189 MO.setReg(LastCopiedReg); 1190 } 1191 } 1192 1193 // Update live variables for regB. 1194 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi)) 1195 LV->addVirtualRegisterKilled(regB, prior(mi)); 1196 1197 } else if (RemovedKillFlag) { 1198 // Some tied uses of regB matched their destination registers, so 1199 // regB is still used in this instruction, but a kill flag was 1200 // removed from a different tied use of regB, so now we need to add 1201 // a kill flag to one of the remaining uses of regB. 1202 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) { 1203 MachineOperand &MO = mi->getOperand(i); 1204 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) { 1205 MO.setIsKill(true); 1206 break; 1207 } 1208 } 1209 } 1210 1211 // Schedule the source copy / remat inserted to form two-address 1212 // instruction. FIXME: Does it matter the distance map may not be 1213 // accurate after it's scheduled? 1214 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI); 1215 1216 MadeChange = true; 1217 1218 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi); 1219 } 1220 1221 // Clear TiedOperands here instead of at the top of the loop 1222 // since most instructions do not have tied operands. 1223 TiedOperands.clear(); 1224 mi = nmi; 1225 } 1226 } 1227 1228 // Some remat'ed instructions are dead. 1229 int VReg = ReMatRegs.find_first(); 1230 while (VReg != -1) { 1231 if (MRI->use_nodbg_empty(VReg)) { 1232 MachineInstr *DefMI = MRI->getVRegDef(VReg); 1233 DefMI->eraseFromParent(); 1234 } 1235 VReg = ReMatRegs.find_next(VReg); 1236 } 1237 1238 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve 1239 // SSA form. It's now safe to de-SSA. 1240 MadeChange |= EliminateRegSequences(); 1241 1242 return MadeChange; 1243} 1244 1245static void UpdateRegSequenceSrcs(unsigned SrcReg, 1246 unsigned DstReg, unsigned SubIdx, 1247 MachineRegisterInfo *MRI, 1248 const TargetRegisterInfo &TRI) { 1249 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg), 1250 RE = MRI->reg_end(); RI != RE; ) { 1251 MachineOperand &MO = RI.getOperand(); 1252 ++RI; 1253 MO.substVirtReg(DstReg, SubIdx, TRI); 1254 } 1255} 1256 1257/// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are 1258/// EXTRACT_SUBREG from the same register and to the same virtual register 1259/// with different sub-register indices, attempt to combine the 1260/// EXTRACT_SUBREGs and pre-coalesce them. e.g. 1261/// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0 1262/// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6 1263/// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5 1264/// Since D subregs 5, 6 can combine to a Q register, we can coalesce 1265/// reg1026 to reg1029. 1266void 1267TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, 1268 unsigned DstReg) { 1269 SmallSet<unsigned, 4> Seen; 1270 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) { 1271 unsigned SrcReg = Srcs[i]; 1272 if (!Seen.insert(SrcReg)) 1273 continue; 1274 1275 // Check that the instructions are all in the same basic block. 1276 MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg); 1277 MachineInstr *DstDefMI = MRI->getVRegDef(DstReg); 1278 if (SrcDefMI->getParent() != DstDefMI->getParent()) 1279 continue; 1280 1281 // If there are no other uses than extract_subreg which feed into 1282 // the reg_sequence, then we might be able to coalesce them. 1283 bool CanCoalesce = true; 1284 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices; 1285 for (MachineRegisterInfo::use_nodbg_iterator 1286 UI = MRI->use_nodbg_begin(SrcReg), 1287 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 1288 MachineInstr *UseMI = &*UI; 1289 if (!UseMI->isExtractSubreg() || 1290 UseMI->getOperand(0).getReg() != DstReg || 1291 UseMI->getOperand(1).getSubReg() != 0) { 1292 CanCoalesce = false; 1293 break; 1294 } 1295 SrcSubIndices.push_back(UseMI->getOperand(2).getImm()); 1296 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg()); 1297 } 1298 1299 if (!CanCoalesce || SrcSubIndices.size() < 2) 1300 continue; 1301 1302 // Check that the source subregisters can be combined. 1303 std::sort(SrcSubIndices.begin(), SrcSubIndices.end()); 1304 unsigned NewSrcSubIdx = 0; 1305 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices, 1306 NewSrcSubIdx)) 1307 continue; 1308 1309 // Check that the destination subregisters can also be combined. 1310 std::sort(DstSubIndices.begin(), DstSubIndices.end()); 1311 unsigned NewDstSubIdx = 0; 1312 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices, 1313 NewDstSubIdx)) 1314 continue; 1315 1316 // If neither source nor destination can be combined to the full register, 1317 // just give up. This could be improved if it ever matters. 1318 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0) 1319 continue; 1320 1321 // Now that we know that all the uses are extract_subregs and that those 1322 // subregs can somehow be combined, scan all the extract_subregs again to 1323 // make sure the subregs are in the right order and can be composed. 1324 MachineInstr *SomeMI = 0; 1325 CanCoalesce = true; 1326 for (MachineRegisterInfo::use_nodbg_iterator 1327 UI = MRI->use_nodbg_begin(SrcReg), 1328 UE = MRI->use_nodbg_end(); UI != UE; ++UI) { 1329 MachineInstr *UseMI = &*UI; 1330 assert(UseMI->isExtractSubreg()); 1331 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg(); 1332 unsigned SrcSubIdx = UseMI->getOperand(2).getImm(); 1333 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination"); 1334 if ((NewDstSubIdx == 0 && 1335 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) || 1336 (NewSrcSubIdx == 0 && 1337 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) { 1338 CanCoalesce = false; 1339 break; 1340 } 1341 // Keep track of one of the uses. 1342 SomeMI = UseMI; 1343 } 1344 if (!CanCoalesce) 1345 continue; 1346 1347 // Insert a copy or an extract to replace the original extracts. 1348 MachineBasicBlock::iterator InsertLoc = SomeMI; 1349 if (NewSrcSubIdx) { 1350 // Insert an extract subreg. 1351 BuildMI(*SomeMI->getParent(), InsertLoc, SomeMI->getDebugLoc(), 1352 TII->get(TargetOpcode::EXTRACT_SUBREG), DstReg) 1353 .addReg(SrcReg).addImm(NewSrcSubIdx); 1354 } else if (NewDstSubIdx) { 1355 // Do a subreg insertion. 1356 BuildMI(*SomeMI->getParent(), InsertLoc, SomeMI->getDebugLoc(), 1357 TII->get(TargetOpcode::INSERT_SUBREG), DstReg) 1358 .addReg(DstReg).addReg(SrcReg).addImm(NewDstSubIdx); 1359 } else { 1360 // Insert a copy. 1361 bool Emitted = 1362 TII->copyRegToReg(*SomeMI->getParent(), InsertLoc, DstReg, SrcReg, 1363 MRI->getRegClass(DstReg), MRI->getRegClass(SrcReg), 1364 SomeMI->getDebugLoc()); 1365 (void)Emitted; 1366 } 1367 MachineBasicBlock::iterator CopyMI = prior(InsertLoc); 1368 1369 // Remove all the old extract instructions. 1370 for (MachineRegisterInfo::use_nodbg_iterator 1371 UI = MRI->use_nodbg_begin(SrcReg), 1372 UE = MRI->use_nodbg_end(); UI != UE; ) { 1373 MachineInstr *UseMI = &*UI; 1374 ++UI; 1375 if (UseMI == CopyMI) 1376 continue; 1377 assert(UseMI->isExtractSubreg()); 1378 // Move any kills to the new copy or extract instruction. 1379 if (UseMI->getOperand(1).isKill()) { 1380 MachineOperand *KillMO = CopyMI->findRegisterUseOperand(SrcReg); 1381 KillMO->setIsKill(); 1382 if (LV) 1383 // Update live variables 1384 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI); 1385 } 1386 UseMI->eraseFromParent(); 1387 } 1388 } 1389} 1390 1391static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq, 1392 MachineRegisterInfo *MRI) { 1393 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg), 1394 UE = MRI->use_end(); UI != UE; ++UI) { 1395 MachineInstr *UseMI = &*UI; 1396 if (UseMI != RegSeq && UseMI->isRegSequence()) 1397 return true; 1398 } 1399 return false; 1400} 1401 1402/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part 1403/// of the de-ssa process. This replaces sources of REG_SEQUENCE as 1404/// sub-register references of the register defined by REG_SEQUENCE. e.g. 1405/// 1406/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ... 1407/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6 1408/// => 1409/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ... 1410bool TwoAddressInstructionPass::EliminateRegSequences() { 1411 if (RegSequences.empty()) 1412 return false; 1413 1414 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) { 1415 MachineInstr *MI = RegSequences[i]; 1416 unsigned DstReg = MI->getOperand(0).getReg(); 1417 if (MI->getOperand(0).getSubReg() || 1418 TargetRegisterInfo::isPhysicalRegister(DstReg) || 1419 !(MI->getNumOperands() & 1)) { 1420 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI); 1421 llvm_unreachable(0); 1422 } 1423 1424 bool IsImpDef = true; 1425 SmallVector<unsigned, 4> RealSrcs; 1426 SmallSet<unsigned, 4> Seen; 1427 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) { 1428 unsigned SrcReg = MI->getOperand(i).getReg(); 1429 if (MI->getOperand(i).getSubReg() || 1430 TargetRegisterInfo::isPhysicalRegister(SrcReg)) { 1431 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI); 1432 llvm_unreachable(0); 1433 } 1434 1435 MachineInstr *DefMI = MRI->getVRegDef(SrcReg); 1436 if (DefMI->isImplicitDef()) { 1437 DefMI->eraseFromParent(); 1438 continue; 1439 } 1440 IsImpDef = false; 1441 1442 // Remember EXTRACT_SUBREG sources. These might be candidate for 1443 // coalescing. 1444 if (DefMI->isExtractSubreg()) 1445 RealSrcs.push_back(DefMI->getOperand(1).getReg()); 1446 1447 if (!Seen.insert(SrcReg) || 1448 MI->getParent() != DefMI->getParent() || 1449 !MI->getOperand(i).isKill() || 1450 HasOtherRegSequenceUses(SrcReg, MI, MRI)) { 1451 // REG_SEQUENCE cannot have duplicated operands, add a copy. 1452 // Also add an copy if the source is live-in the block. We don't want 1453 // to end up with a partial-redef of a livein, e.g. 1454 // BB0: 1455 // reg1051:10<def> = 1456 // ... 1457 // BB1: 1458 // ... = reg1051:10 1459 // BB2: 1460 // reg1051:9<def> = 1461 // LiveIntervalAnalysis won't like it. 1462 // 1463 // If the REG_SEQUENCE doesn't kill its source, keeping live variables 1464 // correctly up to date becomes very difficult. Insert a copy. 1465 // 1466 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 1467 unsigned NewReg = MRI->createVirtualRegister(RC); 1468 MachineBasicBlock::iterator InsertLoc = MI; 1469 bool Emitted = 1470 TII->copyRegToReg(*MI->getParent(), InsertLoc, NewReg, SrcReg, RC, RC, 1471 MI->getDebugLoc()); 1472 (void)Emitted; 1473 assert(Emitted && "Unable to issue a copy instruction!\n"); 1474 MI->getOperand(i).setReg(NewReg); 1475 if (MI->getOperand(i).isKill()) { 1476 MachineBasicBlock::iterator CopyMI = prior(InsertLoc); 1477 MachineOperand *KillMO = CopyMI->findRegisterUseOperand(SrcReg); 1478 KillMO->setIsKill(); 1479 if (LV) 1480 // Update live variables 1481 LV->replaceKillInstruction(SrcReg, MI, &*CopyMI); 1482 } 1483 } 1484 } 1485 1486 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) { 1487 unsigned SrcReg = MI->getOperand(i).getReg(); 1488 unsigned SubIdx = MI->getOperand(i+1).getImm(); 1489 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI); 1490 } 1491 1492 if (IsImpDef) { 1493 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF"); 1494 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF)); 1495 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j) 1496 MI->RemoveOperand(j); 1497 } else { 1498 DEBUG(dbgs() << "Eliminated: " << *MI); 1499 MI->eraseFromParent(); 1500 } 1501 1502 // Try coalescing some EXTRACT_SUBREG instructions. This can create 1503 // INSERT_SUBREG instructions that must have <undef> flags added by 1504 // LiveIntervalAnalysis, so only run it when LiveVariables is available. 1505 if (LV) 1506 CoalesceExtSubRegs(RealSrcs, DstReg); 1507 } 1508 1509 RegSequences.clear(); 1510 return true; 1511} 1512