1 //===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===// 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 // Perform peephole optimizations on the machine code: 11 // 12 // - Optimize Extensions 13 // 14 // Optimization of sign / zero extension instructions. It may be extended to 15 // handle other instructions with similar properties. 16 // 17 // On some targets, some instructions, e.g. X86 sign / zero extension, may 18 // leave the source value in the lower part of the result. This optimization 19 // will replace some uses of the pre-extension value with uses of the 20 // sub-register of the results. 21 // 22 // - Optimize Comparisons 23 // 24 // Optimization of comparison instructions. For instance, in this code: 25 // 26 // sub r1, 1 27 // cmp r1, 0 28 // bz L1 29 // 30 // If the "sub" instruction all ready sets (or could be modified to set) the 31 // same flag that the "cmp" instruction sets and that "bz" uses, then we can 32 // eliminate the "cmp" instruction. 33 // 34 // Another instance, in this code: 35 // 36 // sub r1, r3 | sub r1, imm 37 // cmp r3, r1 or cmp r1, r3 | cmp r1, imm 38 // bge L1 39 // 40 // If the branch instruction can use flag from "sub", then we can replace 41 // "sub" with "subs" and eliminate the "cmp" instruction. 42 // 43 // - Optimize Loads: 44 // 45 // Loads that can be folded into a later instruction. A load is foldable 46 // if it loads to virtual registers and the virtual register defined has 47 // a single use. 48 // 49 // - Optimize Copies and Bitcast (more generally, target specific copies): 50 // 51 // Rewrite copies and bitcasts to avoid cross register bank copies 52 // when possible. 53 // E.g., Consider the following example, where capital and lower 54 // letters denote different register file: 55 // b = copy A <-- cross-bank copy 56 // C = copy b <-- cross-bank copy 57 // => 58 // b = copy A <-- cross-bank copy 59 // C = copy A <-- same-bank copy 60 // 61 // E.g., for bitcast: 62 // b = bitcast A <-- cross-bank copy 63 // C = bitcast b <-- cross-bank copy 64 // => 65 // b = bitcast A <-- cross-bank copy 66 // C = copy A <-- same-bank copy 67 //===----------------------------------------------------------------------===// 68 69 #include "llvm/ADT/DenseMap.h" 70 #include "llvm/ADT/SmallPtrSet.h" 71 #include "llvm/ADT/SmallSet.h" 72 #include "llvm/ADT/SmallVector.h" 73 #include "llvm/ADT/Statistic.h" 74 #include "llvm/CodeGen/MachineBasicBlock.h" 75 #include "llvm/CodeGen/MachineDominators.h" 76 #include "llvm/CodeGen/MachineFunction.h" 77 #include "llvm/CodeGen/MachineInstr.h" 78 #include "llvm/CodeGen/MachineInstrBuilder.h" 79 #include "llvm/CodeGen/MachineLoopInfo.h" 80 #include "llvm/CodeGen/MachineOperand.h" 81 #include "llvm/CodeGen/MachineRegisterInfo.h" 82 #include "llvm/CodeGen/Passes.h" 83 #include "llvm/MC/MCInstrDesc.h" 84 #include "llvm/Support/CommandLine.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Target/TargetInstrInfo.h" 89 #include "llvm/Target/TargetRegisterInfo.h" 90 #include "llvm/Target/TargetSubtargetInfo.h" 91 #include <cassert> 92 #include <cstdint> 93 #include <memory> 94 #include <utility> 95 96 using namespace llvm; 97 98 #define DEBUG_TYPE "peephole-opt" 99 100 // Optimize Extensions 101 static cl::opt<bool> 102 Aggressive("aggressive-ext-opt", cl::Hidden, 103 cl::desc("Aggressive extension optimization")); 104 105 static cl::opt<bool> 106 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false), 107 cl::desc("Disable the peephole optimizer")); 108 109 static cl::opt<bool> 110 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false), 111 cl::desc("Disable advanced copy optimization")); 112 113 static cl::opt<bool> DisableNAPhysCopyOpt( 114 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false), 115 cl::desc("Disable non-allocatable physical register copy optimization")); 116 117 // Limit the number of PHI instructions to process 118 // in PeepholeOptimizer::getNextSource. 119 static cl::opt<unsigned> RewritePHILimit( 120 "rewrite-phi-limit", cl::Hidden, cl::init(10), 121 cl::desc("Limit the length of PHI chains to lookup")); 122 123 // Limit the length of recurrence chain when evaluating the benefit of 124 // commuting operands. 125 static cl::opt<unsigned> MaxRecurrenceChain( 126 "recurrence-chain-limit", cl::Hidden, cl::init(3), 127 cl::desc("Maximum length of recurrence chain when evaluating the benefit " 128 "of commuting operands")); 129 130 131 STATISTIC(NumReuse, "Number of extension results reused"); 132 STATISTIC(NumCmps, "Number of compares eliminated"); 133 STATISTIC(NumImmFold, "Number of move immediate folded"); 134 STATISTIC(NumLoadFold, "Number of loads folded"); 135 STATISTIC(NumSelects, "Number of selects optimized"); 136 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized"); 137 STATISTIC(NumRewrittenCopies, "Number of copies rewritten"); 138 STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed"); 139 140 namespace { 141 142 class ValueTrackerResult; 143 class RecurrenceInstr; 144 145 class PeepholeOptimizer : public MachineFunctionPass { 146 const TargetInstrInfo *TII; 147 const TargetRegisterInfo *TRI; 148 MachineRegisterInfo *MRI; 149 MachineDominatorTree *DT; // Machine dominator tree 150 MachineLoopInfo *MLI; 151 152 public: 153 static char ID; // Pass identification 154 155 PeepholeOptimizer() : MachineFunctionPass(ID) { 156 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry()); 157 } 158 159 bool runOnMachineFunction(MachineFunction &MF) override; 160 161 void getAnalysisUsage(AnalysisUsage &AU) const override { 162 AU.setPreservesCFG(); 163 MachineFunctionPass::getAnalysisUsage(AU); 164 AU.addRequired<MachineLoopInfo>(); 165 AU.addPreserved<MachineLoopInfo>(); 166 if (Aggressive) { 167 AU.addRequired<MachineDominatorTree>(); 168 AU.addPreserved<MachineDominatorTree>(); 169 } 170 } 171 172 /// \brief Track Def -> Use info used for rewriting copies. 173 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult> 174 RewriteMapTy; 175 176 /// \brief Sequence of instructions that formulate recurrence cycle. 177 typedef SmallVector<RecurrenceInstr, 4> RecurrenceCycle; 178 179 private: 180 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB); 181 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB, 182 SmallPtrSetImpl<MachineInstr*> &LocalMIs); 183 bool optimizeSelect(MachineInstr *MI, 184 SmallPtrSetImpl<MachineInstr *> &LocalMIs); 185 bool optimizeCondBranch(MachineInstr *MI); 186 bool optimizeCoalescableCopy(MachineInstr *MI); 187 bool optimizeUncoalescableCopy(MachineInstr *MI, 188 SmallPtrSetImpl<MachineInstr *> &LocalMIs); 189 bool optimizeRecurrence(MachineInstr &PHI); 190 bool findNextSource(unsigned Reg, unsigned SubReg, 191 RewriteMapTy &RewriteMap); 192 bool isMoveImmediate(MachineInstr *MI, 193 SmallSet<unsigned, 4> &ImmDefRegs, 194 DenseMap<unsigned, MachineInstr*> &ImmDefMIs); 195 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB, 196 SmallSet<unsigned, 4> &ImmDefRegs, 197 DenseMap<unsigned, MachineInstr*> &ImmDefMIs); 198 /// \brief Finds recurrence cycles, but only ones that formulated around 199 /// a def operand and a use operand that are tied. If there is a use 200 /// operand commutable with the tied use operand, find recurrence cycle 201 /// along that operand as well. 202 bool findTargetRecurrence(unsigned Reg, 203 const SmallSet<unsigned, 2> &TargetReg, 204 RecurrenceCycle &RC); 205 206 /// \brief If copy instruction \p MI is a virtual register copy, track it in 207 /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was 208 /// previously seen as a copy, replace the uses of this copy with the 209 /// previously seen copy's destination register. 210 bool foldRedundantCopy(MachineInstr *MI, 211 SmallSet<unsigned, 4> &CopySrcRegs, 212 DenseMap<unsigned, MachineInstr *> &CopyMIs); 213 214 /// \brief Is the register \p Reg a non-allocatable physical register? 215 bool isNAPhysCopy(unsigned Reg); 216 217 /// \brief If copy instruction \p MI is a non-allocatable virtual<->physical 218 /// register copy, track it in the \p NAPhysToVirtMIs map. If this 219 /// non-allocatable physical register was previously copied to a virtual 220 /// registered and hasn't been clobbered, the virt->phys copy can be 221 /// deleted. 222 bool foldRedundantNAPhysCopy( 223 MachineInstr *MI, 224 DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs); 225 226 bool isLoadFoldable(MachineInstr *MI, 227 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates); 228 229 /// \brief Check whether \p MI is understood by the register coalescer 230 /// but may require some rewriting. 231 bool isCoalescableCopy(const MachineInstr &MI) { 232 // SubregToRegs are not interesting, because they are already register 233 // coalescer friendly. 234 return MI.isCopy() || (!DisableAdvCopyOpt && 235 (MI.isRegSequence() || MI.isInsertSubreg() || 236 MI.isExtractSubreg())); 237 } 238 239 /// \brief Check whether \p MI is a copy like instruction that is 240 /// not recognized by the register coalescer. 241 bool isUncoalescableCopy(const MachineInstr &MI) { 242 return MI.isBitcast() || 243 (!DisableAdvCopyOpt && 244 (MI.isRegSequenceLike() || MI.isInsertSubregLike() || 245 MI.isExtractSubregLike())); 246 } 247 }; 248 249 /// \brief Helper class to hold instructions that are inside recurrence 250 /// cycles. The recurrence cycle is formulated around 1) a def operand and its 251 /// tied use operand, or 2) a def operand and a use operand that is commutable 252 /// with another use operand which is tied to the def operand. In the latter 253 /// case, index of the tied use operand and the commutable use operand are 254 /// maintained with CommutePair. 255 class RecurrenceInstr { 256 public: 257 typedef std::pair<unsigned, unsigned> IndexPair; 258 259 RecurrenceInstr(MachineInstr *MI) : MI(MI) {} 260 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2) 261 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {} 262 263 MachineInstr *getMI() const { return MI; } 264 Optional<IndexPair> getCommutePair() const { return CommutePair; } 265 266 private: 267 MachineInstr *MI; 268 Optional<IndexPair> CommutePair; 269 }; 270 271 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the 272 /// returned sources for a given search and the instructions where the sources 273 /// were tracked from. 274 class ValueTrackerResult { 275 private: 276 /// Track all sources found by one ValueTracker query. 277 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs; 278 279 /// Instruction using the sources in 'RegSrcs'. 280 const MachineInstr *Inst; 281 282 public: 283 ValueTrackerResult() : Inst(nullptr) {} 284 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) { 285 addSource(Reg, SubReg); 286 } 287 288 bool isValid() const { return getNumSources() > 0; } 289 290 void setInst(const MachineInstr *I) { Inst = I; } 291 const MachineInstr *getInst() const { return Inst; } 292 293 void clear() { 294 RegSrcs.clear(); 295 Inst = nullptr; 296 } 297 298 void addSource(unsigned SrcReg, unsigned SrcSubReg) { 299 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg)); 300 } 301 302 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) { 303 assert(Idx < getNumSources() && "Reg pair source out of index"); 304 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg); 305 } 306 307 int getNumSources() const { return RegSrcs.size(); } 308 309 unsigned getSrcReg(int Idx) const { 310 assert(Idx < getNumSources() && "Reg source out of index"); 311 return RegSrcs[Idx].Reg; 312 } 313 314 unsigned getSrcSubReg(int Idx) const { 315 assert(Idx < getNumSources() && "SubReg source out of index"); 316 return RegSrcs[Idx].SubReg; 317 } 318 319 bool operator==(const ValueTrackerResult &Other) { 320 if (Other.getInst() != getInst()) 321 return false; 322 323 if (Other.getNumSources() != getNumSources()) 324 return false; 325 326 for (int i = 0, e = Other.getNumSources(); i != e; ++i) 327 if (Other.getSrcReg(i) != getSrcReg(i) || 328 Other.getSrcSubReg(i) != getSrcSubReg(i)) 329 return false; 330 return true; 331 } 332 }; 333 334 /// \brief Helper class to track the possible sources of a value defined by 335 /// a (chain of) copy related instructions. 336 /// Given a definition (instruction and definition index), this class 337 /// follows the use-def chain to find successive suitable sources. 338 /// The given source can be used to rewrite the definition into 339 /// def = COPY src. 340 /// 341 /// For instance, let us consider the following snippet: 342 /// v0 = 343 /// v2 = INSERT_SUBREG v1, v0, sub0 344 /// def = COPY v2.sub0 345 /// 346 /// Using a ValueTracker for def = COPY v2.sub0 will give the following 347 /// suitable sources: 348 /// v2.sub0 and v0. 349 /// Then, def can be rewritten into def = COPY v0. 350 class ValueTracker { 351 private: 352 /// The current point into the use-def chain. 353 const MachineInstr *Def; 354 /// The index of the definition in Def. 355 unsigned DefIdx; 356 /// The sub register index of the definition. 357 unsigned DefSubReg; 358 /// The register where the value can be found. 359 unsigned Reg; 360 /// Specifiy whether or not the value tracking looks through 361 /// complex instructions. When this is false, the value tracker 362 /// bails on everything that is not a copy or a bitcast. 363 /// 364 /// Note: This could have been implemented as a specialized version of 365 /// the ValueTracker class but that would have complicated the code of 366 /// the users of this class. 367 bool UseAdvancedTracking; 368 /// MachineRegisterInfo used to perform tracking. 369 const MachineRegisterInfo &MRI; 370 /// Optional TargetInstrInfo used to perform some complex 371 /// tracking. 372 const TargetInstrInfo *TII; 373 374 /// \brief Dispatcher to the right underlying implementation of 375 /// getNextSource. 376 ValueTrackerResult getNextSourceImpl(); 377 /// \brief Specialized version of getNextSource for Copy instructions. 378 ValueTrackerResult getNextSourceFromCopy(); 379 /// \brief Specialized version of getNextSource for Bitcast instructions. 380 ValueTrackerResult getNextSourceFromBitcast(); 381 /// \brief Specialized version of getNextSource for RegSequence 382 /// instructions. 383 ValueTrackerResult getNextSourceFromRegSequence(); 384 /// \brief Specialized version of getNextSource for InsertSubreg 385 /// instructions. 386 ValueTrackerResult getNextSourceFromInsertSubreg(); 387 /// \brief Specialized version of getNextSource for ExtractSubreg 388 /// instructions. 389 ValueTrackerResult getNextSourceFromExtractSubreg(); 390 /// \brief Specialized version of getNextSource for SubregToReg 391 /// instructions. 392 ValueTrackerResult getNextSourceFromSubregToReg(); 393 /// \brief Specialized version of getNextSource for PHI instructions. 394 ValueTrackerResult getNextSourceFromPHI(); 395 396 public: 397 /// \brief Create a ValueTracker instance for the value defined by \p Reg. 398 /// \p DefSubReg represents the sub register index the value tracker will 399 /// track. It does not need to match the sub register index used in the 400 /// definition of \p Reg. 401 /// \p UseAdvancedTracking specifies whether or not the value tracker looks 402 /// through complex instructions. By default (false), it handles only copy 403 /// and bitcast instructions. 404 /// If \p Reg is a physical register, a value tracker constructed with 405 /// this constructor will not find any alternative source. 406 /// Indeed, when \p Reg is a physical register that constructor does not 407 /// know which definition of \p Reg it should track. 408 /// Use the next constructor to track a physical register. 409 ValueTracker(unsigned Reg, unsigned DefSubReg, 410 const MachineRegisterInfo &MRI, 411 bool UseAdvancedTracking = false, 412 const TargetInstrInfo *TII = nullptr) 413 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg), 414 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) { 415 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) { 416 Def = MRI.getVRegDef(Reg); 417 DefIdx = MRI.def_begin(Reg).getOperandNo(); 418 } 419 } 420 421 /// \brief Create a ValueTracker instance for the value defined by 422 /// the pair \p MI, \p DefIdx. 423 /// Unlike the other constructor, the value tracker produced by this one 424 /// may be able to find a new source when the definition is a physical 425 /// register. 426 /// This could be useful to rewrite target specific instructions into 427 /// generic copy instructions. 428 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg, 429 const MachineRegisterInfo &MRI, 430 bool UseAdvancedTracking = false, 431 const TargetInstrInfo *TII = nullptr) 432 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg), 433 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) { 434 assert(DefIdx < Def->getDesc().getNumDefs() && 435 Def->getOperand(DefIdx).isReg() && "Invalid definition"); 436 Reg = Def->getOperand(DefIdx).getReg(); 437 } 438 439 /// \brief Following the use-def chain, get the next available source 440 /// for the tracked value. 441 /// \return A ValueTrackerResult containing a set of registers 442 /// and sub registers with tracked values. A ValueTrackerResult with 443 /// an empty set of registers means no source was found. 444 ValueTrackerResult getNextSource(); 445 446 /// \brief Get the last register where the initial value can be found. 447 /// Initially this is the register of the definition. 448 /// Then, after each successful call to getNextSource, this is the 449 /// register of the last source. 450 unsigned getReg() const { return Reg; } 451 }; 452 453 } // end anonymous namespace 454 455 char PeepholeOptimizer::ID = 0; 456 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID; 457 458 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE, 459 "Peephole Optimizations", false, false) 460 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 461 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 462 INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE, 463 "Peephole Optimizations", false, false) 464 465 /// If instruction is a copy-like instruction, i.e. it reads a single register 466 /// and writes a single register and it does not modify the source, and if the 467 /// source value is preserved as a sub-register of the result, then replace all 468 /// reachable uses of the source with the subreg of the result. 469 /// 470 /// Do not generate an EXTRACT that is used only in a debug use, as this changes 471 /// the code. Since this code does not currently share EXTRACTs, just ignore all 472 /// debug uses. 473 bool PeepholeOptimizer:: 474 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB, 475 SmallPtrSetImpl<MachineInstr*> &LocalMIs) { 476 unsigned SrcReg, DstReg, SubIdx; 477 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx)) 478 return false; 479 480 if (TargetRegisterInfo::isPhysicalRegister(DstReg) || 481 TargetRegisterInfo::isPhysicalRegister(SrcReg)) 482 return false; 483 484 if (MRI->hasOneNonDBGUse(SrcReg)) 485 // No other uses. 486 return false; 487 488 // Ensure DstReg can get a register class that actually supports 489 // sub-registers. Don't change the class until we commit. 490 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg); 491 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx); 492 if (!DstRC) 493 return false; 494 495 // The ext instr may be operating on a sub-register of SrcReg as well. 496 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit 497 // register. 498 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of 499 // SrcReg:SubIdx should be replaced. 500 bool UseSrcSubIdx = 501 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr; 502 503 // The source has other uses. See if we can replace the other uses with use of 504 // the result of the extension. 505 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs; 506 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg)) 507 ReachedBBs.insert(UI.getParent()); 508 509 // Uses that are in the same BB of uses of the result of the instruction. 510 SmallVector<MachineOperand*, 8> Uses; 511 512 // Uses that the result of the instruction can reach. 513 SmallVector<MachineOperand*, 8> ExtendedUses; 514 515 bool ExtendLife = true; 516 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) { 517 MachineInstr *UseMI = UseMO.getParent(); 518 if (UseMI == MI) 519 continue; 520 521 if (UseMI->isPHI()) { 522 ExtendLife = false; 523 continue; 524 } 525 526 // Only accept uses of SrcReg:SubIdx. 527 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx) 528 continue; 529 530 // It's an error to translate this: 531 // 532 // %reg1025 = <sext> %reg1024 533 // ... 534 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4 535 // 536 // into this: 537 // 538 // %reg1025 = <sext> %reg1024 539 // ... 540 // %reg1027 = COPY %reg1025:4 541 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4 542 // 543 // The problem here is that SUBREG_TO_REG is there to assert that an 544 // implicit zext occurs. It doesn't insert a zext instruction. If we allow 545 // the COPY here, it will give us the value after the <sext>, not the 546 // original value of %reg1024 before <sext>. 547 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG) 548 continue; 549 550 MachineBasicBlock *UseMBB = UseMI->getParent(); 551 if (UseMBB == MBB) { 552 // Local uses that come after the extension. 553 if (!LocalMIs.count(UseMI)) 554 Uses.push_back(&UseMO); 555 } else if (ReachedBBs.count(UseMBB)) { 556 // Non-local uses where the result of the extension is used. Always 557 // replace these unless it's a PHI. 558 Uses.push_back(&UseMO); 559 } else if (Aggressive && DT->dominates(MBB, UseMBB)) { 560 // We may want to extend the live range of the extension result in order 561 // to replace these uses. 562 ExtendedUses.push_back(&UseMO); 563 } else { 564 // Both will be live out of the def MBB anyway. Don't extend live range of 565 // the extension result. 566 ExtendLife = false; 567 break; 568 } 569 } 570 571 if (ExtendLife && !ExtendedUses.empty()) 572 // Extend the liveness of the extension result. 573 Uses.append(ExtendedUses.begin(), ExtendedUses.end()); 574 575 // Now replace all uses. 576 bool Changed = false; 577 if (!Uses.empty()) { 578 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs; 579 580 // Look for PHI uses of the extended result, we don't want to extend the 581 // liveness of a PHI input. It breaks all kinds of assumptions down 582 // stream. A PHI use is expected to be the kill of its source values. 583 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg)) 584 if (UI.isPHI()) 585 PHIBBs.insert(UI.getParent()); 586 587 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 588 for (unsigned i = 0, e = Uses.size(); i != e; ++i) { 589 MachineOperand *UseMO = Uses[i]; 590 MachineInstr *UseMI = UseMO->getParent(); 591 MachineBasicBlock *UseMBB = UseMI->getParent(); 592 if (PHIBBs.count(UseMBB)) 593 continue; 594 595 // About to add uses of DstReg, clear DstReg's kill flags. 596 if (!Changed) { 597 MRI->clearKillFlags(DstReg); 598 MRI->constrainRegClass(DstReg, DstRC); 599 } 600 601 unsigned NewVR = MRI->createVirtualRegister(RC); 602 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(), 603 TII->get(TargetOpcode::COPY), NewVR) 604 .addReg(DstReg, 0, SubIdx); 605 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set. 606 if (UseSrcSubIdx) { 607 Copy->getOperand(0).setSubReg(SubIdx); 608 Copy->getOperand(0).setIsUndef(); 609 } 610 UseMO->setReg(NewVR); 611 ++NumReuse; 612 Changed = true; 613 } 614 } 615 616 return Changed; 617 } 618 619 /// If the instruction is a compare and the previous instruction it's comparing 620 /// against already sets (or could be modified to set) the same flag as the 621 /// compare, then we can remove the comparison and use the flag from the 622 /// previous instruction. 623 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI, 624 MachineBasicBlock *MBB) { 625 // If this instruction is a comparison against zero and isn't comparing a 626 // physical register, we can try to optimize it. 627 unsigned SrcReg, SrcReg2; 628 int CmpMask, CmpValue; 629 if (!TII->analyzeCompare(*MI, SrcReg, SrcReg2, CmpMask, CmpValue) || 630 TargetRegisterInfo::isPhysicalRegister(SrcReg) || 631 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2))) 632 return false; 633 634 // Attempt to optimize the comparison instruction. 635 if (TII->optimizeCompareInstr(*MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) { 636 ++NumCmps; 637 return true; 638 } 639 640 return false; 641 } 642 643 /// Optimize a select instruction. 644 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI, 645 SmallPtrSetImpl<MachineInstr *> &LocalMIs) { 646 unsigned TrueOp = 0; 647 unsigned FalseOp = 0; 648 bool Optimizable = false; 649 SmallVector<MachineOperand, 4> Cond; 650 if (TII->analyzeSelect(*MI, Cond, TrueOp, FalseOp, Optimizable)) 651 return false; 652 if (!Optimizable) 653 return false; 654 if (!TII->optimizeSelect(*MI, LocalMIs)) 655 return false; 656 MI->eraseFromParent(); 657 ++NumSelects; 658 return true; 659 } 660 661 /// \brief Check if a simpler conditional branch can be 662 // generated 663 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) { 664 return TII->optimizeCondBranch(*MI); 665 } 666 667 /// \brief Try to find the next source that share the same register file 668 /// for the value defined by \p Reg and \p SubReg. 669 /// When true is returned, the \p RewriteMap can be used by the client to 670 /// retrieve all Def -> Use along the way up to the next source. Any found 671 /// Use that is not itself a key for another entry, is the next source to 672 /// use. During the search for the next source, multiple sources can be found 673 /// given multiple incoming sources of a PHI instruction. In this case, we 674 /// look in each PHI source for the next source; all found next sources must 675 /// share the same register file as \p Reg and \p SubReg. The client should 676 /// then be capable to rewrite all intermediate PHIs to get the next source. 677 /// \return False if no alternative sources are available. True otherwise. 678 bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg, 679 RewriteMapTy &RewriteMap) { 680 // Do not try to find a new source for a physical register. 681 // So far we do not have any motivating example for doing that. 682 // Thus, instead of maintaining untested code, we will revisit that if 683 // that changes at some point. 684 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 685 return false; 686 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg); 687 688 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook; 689 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg); 690 SrcToLook.push_back(CurSrcPair); 691 692 unsigned PHICount = 0; 693 while (!SrcToLook.empty() && PHICount < RewritePHILimit) { 694 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val(); 695 // As explained above, do not handle physical registers 696 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg)) 697 return false; 698 699 CurSrcPair = Pair; 700 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, 701 !DisableAdvCopyOpt, TII); 702 ValueTrackerResult Res; 703 bool ShouldRewrite = false; 704 705 do { 706 // Follow the chain of copies until we reach the top of the use-def chain 707 // or find a more suitable source. 708 Res = ValTracker.getNextSource(); 709 if (!Res.isValid()) 710 break; 711 712 // Insert the Def -> Use entry for the recently found source. 713 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair); 714 if (CurSrcRes.isValid()) { 715 assert(CurSrcRes == Res && "ValueTrackerResult found must match"); 716 // An existent entry with multiple sources is a PHI cycle we must avoid. 717 // Otherwise it's an entry with a valid next source we already found. 718 if (CurSrcRes.getNumSources() > 1) { 719 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n"); 720 return false; 721 } 722 break; 723 } 724 RewriteMap.insert(std::make_pair(CurSrcPair, Res)); 725 726 // ValueTrackerResult usually have one source unless it's the result from 727 // a PHI instruction. Add the found PHI edges to be looked up further. 728 unsigned NumSrcs = Res.getNumSources(); 729 if (NumSrcs > 1) { 730 PHICount++; 731 for (unsigned i = 0; i < NumSrcs; ++i) 732 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair( 733 Res.getSrcReg(i), Res.getSrcSubReg(i))); 734 break; 735 } 736 737 CurSrcPair.Reg = Res.getSrcReg(0); 738 CurSrcPair.SubReg = Res.getSrcSubReg(0); 739 // Do not extend the live-ranges of physical registers as they add 740 // constraints to the register allocator. Moreover, if we want to extend 741 // the live-range of a physical register, unlike SSA virtual register, 742 // we will have to check that they aren't redefine before the related use. 743 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg)) 744 return false; 745 746 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg); 747 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC, 748 CurSrcPair.SubReg); 749 } while (!ShouldRewrite); 750 751 // Continue looking for new sources... 752 if (Res.isValid()) 753 continue; 754 755 // Do not continue searching for a new source if the there's at least 756 // one use-def which cannot be rewritten. 757 if (!ShouldRewrite) 758 return false; 759 } 760 761 if (PHICount >= RewritePHILimit) { 762 DEBUG(dbgs() << "findNextSource: PHI limit reached\n"); 763 return false; 764 } 765 766 // If we did not find a more suitable source, there is nothing to optimize. 767 return CurSrcPair.Reg != Reg; 768 } 769 770 /// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are 771 /// guaranteed to have the same register class. This is necessary whenever we 772 /// successfully traverse a PHI instruction and find suitable sources coming 773 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def 774 /// suitable to be used in a new COPY instruction. 775 static MachineInstr * 776 insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII, 777 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs, 778 MachineInstr *OrigPHI) { 779 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?"); 780 781 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg); 782 unsigned NewVR = MRI->createVirtualRegister(NewRC); 783 MachineBasicBlock *MBB = OrigPHI->getParent(); 784 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(), 785 TII->get(TargetOpcode::PHI), NewVR); 786 787 unsigned MBBOpIdx = 2; 788 for (auto RegPair : SrcRegs) { 789 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg); 790 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB()); 791 // Since we're extended the lifetime of RegPair.Reg, clear the 792 // kill flags to account for that and make RegPair.Reg reaches 793 // the new PHI. 794 MRI->clearKillFlags(RegPair.Reg); 795 MBBOpIdx += 2; 796 } 797 798 return MIB; 799 } 800 801 namespace { 802 803 /// \brief Helper class to rewrite the arguments of a copy-like instruction. 804 class CopyRewriter { 805 protected: 806 /// The copy-like instruction. 807 MachineInstr &CopyLike; 808 /// The index of the source being rewritten. 809 unsigned CurrentSrcIdx; 810 811 public: 812 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {} 813 814 virtual ~CopyRewriter() {} 815 816 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and 817 /// the related value that it affects (TrackReg, TrackSubReg). 818 /// A source is considered rewritable if its register class and the 819 /// register class of the related TrackReg may not be register 820 /// coalescer friendly. In other words, given a copy-like instruction 821 /// not all the arguments may be returned at rewritable source, since 822 /// some arguments are none to be register coalescer friendly. 823 /// 824 /// Each call of this method moves the current source to the next 825 /// rewritable source. 826 /// For instance, let CopyLike be the instruction to rewrite. 827 /// CopyLike has one definition and one source: 828 /// dst.dstSubIdx = CopyLike src.srcSubIdx. 829 /// 830 /// The first call will give the first rewritable source, i.e., 831 /// the only source this instruction has: 832 /// (SrcReg, SrcSubReg) = (src, srcSubIdx). 833 /// This source defines the whole definition, i.e., 834 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx). 835 /// 836 /// The second and subsequent calls will return false, as there is only one 837 /// rewritable source. 838 /// 839 /// \return True if a rewritable source has been found, false otherwise. 840 /// The output arguments are valid if and only if true is returned. 841 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg, 842 unsigned &TrackReg, 843 unsigned &TrackSubReg) { 844 // If CurrentSrcIdx == 1, this means this function has already been called 845 // once. CopyLike has one definition and one argument, thus, there is 846 // nothing else to rewrite. 847 if (!CopyLike.isCopy() || CurrentSrcIdx == 1) 848 return false; 849 // This is the first call to getNextRewritableSource. 850 // Move the CurrentSrcIdx to remember that we made that call. 851 CurrentSrcIdx = 1; 852 // The rewritable source is the argument. 853 const MachineOperand &MOSrc = CopyLike.getOperand(1); 854 SrcReg = MOSrc.getReg(); 855 SrcSubReg = MOSrc.getSubReg(); 856 // What we track are the alternative sources of the definition. 857 const MachineOperand &MODef = CopyLike.getOperand(0); 858 TrackReg = MODef.getReg(); 859 TrackSubReg = MODef.getSubReg(); 860 return true; 861 } 862 863 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg 864 /// if possible. 865 /// \return True if the rewriting was possible, false otherwise. 866 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) { 867 if (!CopyLike.isCopy() || CurrentSrcIdx != 1) 868 return false; 869 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx); 870 MOSrc.setReg(NewReg); 871 MOSrc.setSubReg(NewSubReg); 872 return true; 873 } 874 875 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find 876 /// the new source to use for rewrite. If \p HandleMultipleSources is true and 877 /// multiple sources for a given \p Def are found along the way, we found a 878 /// PHI instructions that needs to be rewritten. 879 /// TODO: HandleMultipleSources should be removed once we test PHI handling 880 /// with coalescable copies. 881 TargetInstrInfo::RegSubRegPair 882 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII, 883 TargetInstrInfo::RegSubRegPair Def, 884 PeepholeOptimizer::RewriteMapTy &RewriteMap, 885 bool HandleMultipleSources = true) { 886 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg); 887 do { 888 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc); 889 // If there are no entries on the map, LookupSrc is the new source. 890 if (!Res.isValid()) 891 return LookupSrc; 892 893 // There's only one source for this definition, keep searching... 894 unsigned NumSrcs = Res.getNumSources(); 895 if (NumSrcs == 1) { 896 LookupSrc.Reg = Res.getSrcReg(0); 897 LookupSrc.SubReg = Res.getSrcSubReg(0); 898 continue; 899 } 900 901 // TODO: Remove once multiple srcs w/ coalescable copies are supported. 902 if (!HandleMultipleSources) 903 break; 904 905 // Multiple sources, recurse into each source to find a new source 906 // for it. Then, rewrite the PHI accordingly to its new edges. 907 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs; 908 for (unsigned i = 0; i < NumSrcs; ++i) { 909 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i), 910 Res.getSrcSubReg(i)); 911 NewPHISrcs.push_back( 912 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources)); 913 } 914 915 // Build the new PHI node and return its def register as the new source. 916 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst()); 917 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI); 918 DEBUG(dbgs() << "-- getNewSource\n"); 919 DEBUG(dbgs() << " Replacing: " << *OrigPHI); 920 DEBUG(dbgs() << " With: " << *NewPHI); 921 const MachineOperand &MODef = NewPHI->getOperand(0); 922 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg()); 923 924 } while (true); 925 926 return TargetInstrInfo::RegSubRegPair(0, 0); 927 } 928 929 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap 930 /// and create a new COPY instruction. More info about RewriteMap in 931 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle 932 /// Uncoalescable copies, since they are copy like instructions that aren't 933 /// recognized by the register allocator. 934 virtual MachineInstr * 935 RewriteSource(TargetInstrInfo::RegSubRegPair Def, 936 PeepholeOptimizer::RewriteMapTy &RewriteMap) { 937 return nullptr; 938 } 939 }; 940 941 /// \brief Helper class to rewrite uncoalescable copy like instructions 942 /// into new COPY (coalescable friendly) instructions. 943 class UncoalescableRewriter : public CopyRewriter { 944 protected: 945 const TargetInstrInfo &TII; 946 MachineRegisterInfo &MRI; 947 /// The number of defs in the bitcast 948 unsigned NumDefs; 949 950 public: 951 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII, 952 MachineRegisterInfo &MRI) 953 : CopyRewriter(MI), TII(TII), MRI(MRI) { 954 NumDefs = MI.getDesc().getNumDefs(); 955 } 956 957 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg) 958 /// All such sources need to be considered rewritable in order to 959 /// rewrite a uncoalescable copy-like instruction. This method return 960 /// each definition that must be checked if rewritable. 961 /// 962 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg, 963 unsigned &TrackReg, 964 unsigned &TrackSubReg) override { 965 // Find the next non-dead definition and continue from there. 966 if (CurrentSrcIdx == NumDefs) 967 return false; 968 969 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) { 970 ++CurrentSrcIdx; 971 if (CurrentSrcIdx == NumDefs) 972 return false; 973 } 974 975 // What we track are the alternative sources of the definition. 976 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx); 977 TrackReg = MODef.getReg(); 978 TrackSubReg = MODef.getSubReg(); 979 980 CurrentSrcIdx++; 981 return true; 982 } 983 984 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap 985 /// and create a new COPY instruction. More info about RewriteMap in 986 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle 987 /// Uncoalescable copies, since they are copy like instructions that aren't 988 /// recognized by the register allocator. 989 MachineInstr * 990 RewriteSource(TargetInstrInfo::RegSubRegPair Def, 991 PeepholeOptimizer::RewriteMapTy &RewriteMap) override { 992 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) && 993 "We do not rewrite physical registers"); 994 995 // Find the new source to use in the COPY rewrite. 996 TargetInstrInfo::RegSubRegPair NewSrc = 997 getNewSource(&MRI, &TII, Def, RewriteMap); 998 999 // Insert the COPY. 1000 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg); 1001 unsigned NewVR = MRI.createVirtualRegister(DefRC); 1002 1003 MachineInstr *NewCopy = 1004 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(), 1005 TII.get(TargetOpcode::COPY), NewVR) 1006 .addReg(NewSrc.Reg, 0, NewSrc.SubReg); 1007 1008 NewCopy->getOperand(0).setSubReg(Def.SubReg); 1009 if (Def.SubReg) 1010 NewCopy->getOperand(0).setIsUndef(); 1011 1012 DEBUG(dbgs() << "-- RewriteSource\n"); 1013 DEBUG(dbgs() << " Replacing: " << CopyLike); 1014 DEBUG(dbgs() << " With: " << *NewCopy); 1015 MRI.replaceRegWith(Def.Reg, NewVR); 1016 MRI.clearKillFlags(NewVR); 1017 1018 // We extended the lifetime of NewSrc.Reg, clear the kill flags to 1019 // account for that. 1020 MRI.clearKillFlags(NewSrc.Reg); 1021 1022 return NewCopy; 1023 } 1024 }; 1025 1026 /// \brief Specialized rewriter for INSERT_SUBREG instruction. 1027 class InsertSubregRewriter : public CopyRewriter { 1028 public: 1029 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) { 1030 assert(MI.isInsertSubreg() && "Invalid instruction"); 1031 } 1032 1033 /// \brief See CopyRewriter::getNextRewritableSource. 1034 /// Here CopyLike has the following form: 1035 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx. 1036 /// Src1 has the same register class has dst, hence, there is 1037 /// nothing to rewrite. 1038 /// Src2.src2SubIdx, may not be register coalescer friendly. 1039 /// Therefore, the first call to this method returns: 1040 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx). 1041 /// (TrackReg, TrackSubReg) = (dst, subIdx). 1042 /// 1043 /// Subsequence calls will return false. 1044 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg, 1045 unsigned &TrackReg, 1046 unsigned &TrackSubReg) override { 1047 // If we already get the only source we can rewrite, return false. 1048 if (CurrentSrcIdx == 2) 1049 return false; 1050 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0. 1051 CurrentSrcIdx = 2; 1052 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2); 1053 SrcReg = MOInsertedReg.getReg(); 1054 SrcSubReg = MOInsertedReg.getSubReg(); 1055 const MachineOperand &MODef = CopyLike.getOperand(0); 1056 1057 // We want to track something that is compatible with the 1058 // partial definition. 1059 TrackReg = MODef.getReg(); 1060 if (MODef.getSubReg()) 1061 // Bail if we have to compose sub-register indices. 1062 return false; 1063 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm(); 1064 return true; 1065 } 1066 1067 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override { 1068 if (CurrentSrcIdx != 2) 1069 return false; 1070 // We are rewriting the inserted reg. 1071 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx); 1072 MO.setReg(NewReg); 1073 MO.setSubReg(NewSubReg); 1074 return true; 1075 } 1076 }; 1077 1078 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction. 1079 class ExtractSubregRewriter : public CopyRewriter { 1080 const TargetInstrInfo &TII; 1081 1082 public: 1083 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII) 1084 : CopyRewriter(MI), TII(TII) { 1085 assert(MI.isExtractSubreg() && "Invalid instruction"); 1086 } 1087 1088 /// \brief See CopyRewriter::getNextRewritableSource. 1089 /// Here CopyLike has the following form: 1090 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx. 1091 /// There is only one rewritable source: Src.subIdx, 1092 /// which defines dst.dstSubIdx. 1093 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg, 1094 unsigned &TrackReg, 1095 unsigned &TrackSubReg) override { 1096 // If we already get the only source we can rewrite, return false. 1097 if (CurrentSrcIdx == 1) 1098 return false; 1099 // We are looking at v1 = EXTRACT_SUBREG v0, sub0. 1100 CurrentSrcIdx = 1; 1101 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1); 1102 SrcReg = MOExtractedReg.getReg(); 1103 // If we have to compose sub-register indices, bail out. 1104 if (MOExtractedReg.getSubReg()) 1105 return false; 1106 1107 SrcSubReg = CopyLike.getOperand(2).getImm(); 1108 1109 // We want to track something that is compatible with the definition. 1110 const MachineOperand &MODef = CopyLike.getOperand(0); 1111 TrackReg = MODef.getReg(); 1112 TrackSubReg = MODef.getSubReg(); 1113 return true; 1114 } 1115 1116 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override { 1117 // The only source we can rewrite is the input register. 1118 if (CurrentSrcIdx != 1) 1119 return false; 1120 1121 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg); 1122 1123 // If we find a source that does not require to extract something, 1124 // rewrite the operation with a copy. 1125 if (!NewSubReg) { 1126 // Move the current index to an invalid position. 1127 // We do not want another call to this method to be able 1128 // to do any change. 1129 CurrentSrcIdx = -1; 1130 // Rewrite the operation as a COPY. 1131 // Get rid of the sub-register index. 1132 CopyLike.RemoveOperand(2); 1133 // Morph the operation into a COPY. 1134 CopyLike.setDesc(TII.get(TargetOpcode::COPY)); 1135 return true; 1136 } 1137 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg); 1138 return true; 1139 } 1140 }; 1141 1142 /// \brief Specialized rewriter for REG_SEQUENCE instruction. 1143 class RegSequenceRewriter : public CopyRewriter { 1144 public: 1145 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) { 1146 assert(MI.isRegSequence() && "Invalid instruction"); 1147 } 1148 1149 /// \brief See CopyRewriter::getNextRewritableSource. 1150 /// Here CopyLike has the following form: 1151 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2. 1152 /// Each call will return a different source, walking all the available 1153 /// source. 1154 /// 1155 /// The first call returns: 1156 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx). 1157 /// (TrackReg, TrackSubReg) = (dst, subIdx1). 1158 /// 1159 /// The second call returns: 1160 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx). 1161 /// (TrackReg, TrackSubReg) = (dst, subIdx2). 1162 /// 1163 /// And so on, until all the sources have been traversed, then 1164 /// it returns false. 1165 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg, 1166 unsigned &TrackReg, 1167 unsigned &TrackSubReg) override { 1168 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc. 1169 1170 // If this is the first call, move to the first argument. 1171 if (CurrentSrcIdx == 0) { 1172 CurrentSrcIdx = 1; 1173 } else { 1174 // Otherwise, move to the next argument and check that it is valid. 1175 CurrentSrcIdx += 2; 1176 if (CurrentSrcIdx >= CopyLike.getNumOperands()) 1177 return false; 1178 } 1179 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx); 1180 SrcReg = MOInsertedReg.getReg(); 1181 // If we have to compose sub-register indices, bail out. 1182 if ((SrcSubReg = MOInsertedReg.getSubReg())) 1183 return false; 1184 1185 // We want to track something that is compatible with the related 1186 // partial definition. 1187 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm(); 1188 1189 const MachineOperand &MODef = CopyLike.getOperand(0); 1190 TrackReg = MODef.getReg(); 1191 // If we have to compose sub-registers, bail. 1192 return MODef.getSubReg() == 0; 1193 } 1194 1195 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override { 1196 // We cannot rewrite out of bound operands. 1197 // Moreover, rewritable sources are at odd positions. 1198 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands()) 1199 return false; 1200 1201 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx); 1202 MO.setReg(NewReg); 1203 MO.setSubReg(NewSubReg); 1204 return true; 1205 } 1206 }; 1207 1208 } // end anonymous namespace 1209 1210 /// \brief Get the appropriated CopyRewriter for \p MI. 1211 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr 1212 /// if no rewriter works for \p MI. 1213 static CopyRewriter *getCopyRewriter(MachineInstr &MI, 1214 const TargetInstrInfo &TII, 1215 MachineRegisterInfo &MRI) { 1216 // Handle uncoalescable copy-like instructions. 1217 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() || 1218 MI.isExtractSubregLike())) 1219 return new UncoalescableRewriter(MI, TII, MRI); 1220 1221 switch (MI.getOpcode()) { 1222 default: 1223 return nullptr; 1224 case TargetOpcode::COPY: 1225 return new CopyRewriter(MI); 1226 case TargetOpcode::INSERT_SUBREG: 1227 return new InsertSubregRewriter(MI); 1228 case TargetOpcode::EXTRACT_SUBREG: 1229 return new ExtractSubregRewriter(MI, TII); 1230 case TargetOpcode::REG_SEQUENCE: 1231 return new RegSequenceRewriter(MI); 1232 } 1233 llvm_unreachable(nullptr); 1234 } 1235 1236 /// \brief Optimize generic copy instructions to avoid cross 1237 /// register bank copy. The optimization looks through a chain of 1238 /// copies and tries to find a source that has a compatible register 1239 /// class. 1240 /// Two register classes are considered to be compatible if they share 1241 /// the same register bank. 1242 /// New copies issued by this optimization are register allocator 1243 /// friendly. This optimization does not remove any copy as it may 1244 /// overconstrain the register allocator, but replaces some operands 1245 /// when possible. 1246 /// \pre isCoalescableCopy(*MI) is true. 1247 /// \return True, when \p MI has been rewritten. False otherwise. 1248 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) { 1249 assert(MI && isCoalescableCopy(*MI) && "Invalid argument"); 1250 assert(MI->getDesc().getNumDefs() == 1 && 1251 "Coalescer can understand multiple defs?!"); 1252 const MachineOperand &MODef = MI->getOperand(0); 1253 // Do not rewrite physical definitions. 1254 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg())) 1255 return false; 1256 1257 bool Changed = false; 1258 // Get the right rewriter for the current copy. 1259 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI)); 1260 // If none exists, bail out. 1261 if (!CpyRewriter) 1262 return false; 1263 // Rewrite each rewritable source. 1264 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg; 1265 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg, 1266 TrackSubReg)) { 1267 // Keep track of PHI nodes and its incoming edges when looking for sources. 1268 RewriteMapTy RewriteMap; 1269 // Try to find a more suitable source. If we failed to do so, or get the 1270 // actual source, move to the next source. 1271 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap)) 1272 continue; 1273 1274 // Get the new source to rewrite. TODO: Only enable handling of multiple 1275 // sources (PHIs) once we have a motivating example and testcases for it. 1276 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg); 1277 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource( 1278 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */); 1279 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0) 1280 continue; 1281 1282 // Rewrite source. 1283 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) { 1284 // We may have extended the live-range of NewSrc, account for that. 1285 MRI->clearKillFlags(NewSrc.Reg); 1286 Changed = true; 1287 } 1288 } 1289 // TODO: We could have a clean-up method to tidy the instruction. 1290 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0 1291 // => v0 = COPY v1 1292 // Currently we haven't seen motivating example for that and we 1293 // want to avoid untested code. 1294 NumRewrittenCopies += Changed; 1295 return Changed; 1296 } 1297 1298 /// \brief Optimize copy-like instructions to create 1299 /// register coalescer friendly instruction. 1300 /// The optimization tries to kill-off the \p MI by looking 1301 /// through a chain of copies to find a source that has a compatible 1302 /// register class. 1303 /// If such a source is found, it replace \p MI by a generic COPY 1304 /// operation. 1305 /// \pre isUncoalescableCopy(*MI) is true. 1306 /// \return True, when \p MI has been optimized. In that case, \p MI has 1307 /// been removed from its parent. 1308 /// All COPY instructions created, are inserted in \p LocalMIs. 1309 bool PeepholeOptimizer::optimizeUncoalescableCopy( 1310 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) { 1311 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument"); 1312 1313 // Check if we can rewrite all the values defined by this instruction. 1314 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs; 1315 // Get the right rewriter for the current copy. 1316 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI)); 1317 // If none exists, bail out. 1318 if (!CpyRewriter) 1319 return false; 1320 1321 // Rewrite each rewritable source by generating new COPYs. This works 1322 // differently from optimizeCoalescableCopy since it first makes sure that all 1323 // definitions can be rewritten. 1324 RewriteMapTy RewriteMap; 1325 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg; 1326 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg, 1327 CopyDefSubReg)) { 1328 // If a physical register is here, this is probably for a good reason. 1329 // Do not rewrite that. 1330 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg)) 1331 return false; 1332 1333 // If we do not know how to rewrite this definition, there is no point 1334 // in trying to kill this instruction. 1335 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg); 1336 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap)) 1337 return false; 1338 1339 RewritePairs.push_back(Def); 1340 } 1341 1342 // The change is possible for all defs, do it. 1343 for (const auto &Def : RewritePairs) { 1344 // Rewrite the "copy" in a way the register coalescer understands. 1345 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap); 1346 assert(NewCopy && "Should be able to always generate a new copy"); 1347 LocalMIs.insert(NewCopy); 1348 } 1349 1350 // MI is now dead. 1351 MI->eraseFromParent(); 1352 ++NumUncoalescableCopies; 1353 return true; 1354 } 1355 1356 /// Check whether MI is a candidate for folding into a later instruction. 1357 /// We only fold loads to virtual registers and the virtual register defined 1358 /// has a single use. 1359 bool PeepholeOptimizer::isLoadFoldable( 1360 MachineInstr *MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) { 1361 if (!MI->canFoldAsLoad() || !MI->mayLoad()) 1362 return false; 1363 const MCInstrDesc &MCID = MI->getDesc(); 1364 if (MCID.getNumDefs() != 1) 1365 return false; 1366 1367 unsigned Reg = MI->getOperand(0).getReg(); 1368 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting 1369 // loads. It should be checked when processing uses of the load, since 1370 // uses can be removed during peephole. 1371 if (!MI->getOperand(0).getSubReg() && 1372 TargetRegisterInfo::isVirtualRegister(Reg) && 1373 MRI->hasOneNonDBGUse(Reg)) { 1374 FoldAsLoadDefCandidates.insert(Reg); 1375 return true; 1376 } 1377 return false; 1378 } 1379 1380 bool PeepholeOptimizer::isMoveImmediate( 1381 MachineInstr *MI, SmallSet<unsigned, 4> &ImmDefRegs, 1382 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) { 1383 const MCInstrDesc &MCID = MI->getDesc(); 1384 if (!MI->isMoveImmediate()) 1385 return false; 1386 if (MCID.getNumDefs() != 1) 1387 return false; 1388 unsigned Reg = MI->getOperand(0).getReg(); 1389 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1390 ImmDefMIs.insert(std::make_pair(Reg, MI)); 1391 ImmDefRegs.insert(Reg); 1392 return true; 1393 } 1394 1395 return false; 1396 } 1397 1398 /// Try folding register operands that are defined by move immediate 1399 /// instructions, i.e. a trivial constant folding optimization, if 1400 /// and only if the def and use are in the same BB. 1401 bool PeepholeOptimizer::foldImmediate( 1402 MachineInstr *MI, MachineBasicBlock *MBB, SmallSet<unsigned, 4> &ImmDefRegs, 1403 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) { 1404 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) { 1405 MachineOperand &MO = MI->getOperand(i); 1406 if (!MO.isReg() || MO.isDef()) 1407 continue; 1408 // Ignore dead implicit defs. 1409 if (MO.isImplicit() && MO.isDead()) 1410 continue; 1411 unsigned Reg = MO.getReg(); 1412 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1413 continue; 1414 if (ImmDefRegs.count(Reg) == 0) 1415 continue; 1416 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg); 1417 assert(II != ImmDefMIs.end() && "couldn't find immediate definition"); 1418 if (TII->FoldImmediate(*MI, *II->second, Reg, MRI)) { 1419 ++NumImmFold; 1420 return true; 1421 } 1422 } 1423 return false; 1424 } 1425 1426 // FIXME: This is very simple and misses some cases which should be handled when 1427 // motivating examples are found. 1428 // 1429 // The copy rewriting logic should look at uses as well as defs and be able to 1430 // eliminate copies across blocks. 1431 // 1432 // Later copies that are subregister extracts will also not be eliminated since 1433 // only the first copy is considered. 1434 // 1435 // e.g. 1436 // %vreg1 = COPY %vreg0 1437 // %vreg2 = COPY %vreg0:sub1 1438 // 1439 // Should replace %vreg2 uses with %vreg1:sub1 1440 bool PeepholeOptimizer::foldRedundantCopy( 1441 MachineInstr *MI, SmallSet<unsigned, 4> &CopySrcRegs, 1442 DenseMap<unsigned, MachineInstr *> &CopyMIs) { 1443 assert(MI->isCopy() && "expected a COPY machine instruction"); 1444 1445 unsigned SrcReg = MI->getOperand(1).getReg(); 1446 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) 1447 return false; 1448 1449 unsigned DstReg = MI->getOperand(0).getReg(); 1450 if (!TargetRegisterInfo::isVirtualRegister(DstReg)) 1451 return false; 1452 1453 if (CopySrcRegs.insert(SrcReg).second) { 1454 // First copy of this reg seen. 1455 CopyMIs.insert(std::make_pair(SrcReg, MI)); 1456 return false; 1457 } 1458 1459 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second; 1460 1461 unsigned SrcSubReg = MI->getOperand(1).getSubReg(); 1462 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg(); 1463 1464 // Can't replace different subregister extracts. 1465 if (SrcSubReg != PrevSrcSubReg) 1466 return false; 1467 1468 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg(); 1469 1470 // Only replace if the copy register class is the same. 1471 // 1472 // TODO: If we have multiple copies to different register classes, we may want 1473 // to track multiple copies of the same source register. 1474 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg)) 1475 return false; 1476 1477 MRI->replaceRegWith(DstReg, PrevDstReg); 1478 1479 // Lifetime of the previous copy has been extended. 1480 MRI->clearKillFlags(PrevDstReg); 1481 return true; 1482 } 1483 1484 bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) { 1485 return TargetRegisterInfo::isPhysicalRegister(Reg) && 1486 !MRI->isAllocatable(Reg); 1487 } 1488 1489 bool PeepholeOptimizer::foldRedundantNAPhysCopy( 1490 MachineInstr *MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) { 1491 assert(MI->isCopy() && "expected a COPY machine instruction"); 1492 1493 if (DisableNAPhysCopyOpt) 1494 return false; 1495 1496 unsigned DstReg = MI->getOperand(0).getReg(); 1497 unsigned SrcReg = MI->getOperand(1).getReg(); 1498 if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) { 1499 // %vreg = COPY %PHYSREG 1500 // Avoid using a datastructure which can track multiple live non-allocatable 1501 // phys->virt copies since LLVM doesn't seem to do this. 1502 NAPhysToVirtMIs.insert({SrcReg, MI}); 1503 return false; 1504 } 1505 1506 if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg))) 1507 return false; 1508 1509 // %PHYSREG = COPY %vreg 1510 auto PrevCopy = NAPhysToVirtMIs.find(DstReg); 1511 if (PrevCopy == NAPhysToVirtMIs.end()) { 1512 // We can't remove the copy: there was an intervening clobber of the 1513 // non-allocatable physical register after the copy to virtual. 1514 DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " << *MI 1515 << '\n'); 1516 return false; 1517 } 1518 1519 unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg(); 1520 if (PrevDstReg == SrcReg) { 1521 // Remove the virt->phys copy: we saw the virtual register definition, and 1522 // the non-allocatable physical register's state hasn't changed since then. 1523 DEBUG(dbgs() << "NAPhysCopy: erasing " << *MI << '\n'); 1524 ++NumNAPhysCopies; 1525 return true; 1526 } 1527 1528 // Potential missed optimization opportunity: we saw a different virtual 1529 // register get a copy of the non-allocatable physical register, and we only 1530 // track one such copy. Avoid getting confused by this new non-allocatable 1531 // physical register definition, and remove it from the tracked copies. 1532 DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << *MI << '\n'); 1533 NAPhysToVirtMIs.erase(PrevCopy); 1534 return false; 1535 } 1536 1537 /// \bried Returns true if \p MO is a virtual register operand. 1538 static bool isVirtualRegisterOperand(MachineOperand &MO) { 1539 if (!MO.isReg()) 1540 return false; 1541 return TargetRegisterInfo::isVirtualRegister(MO.getReg()); 1542 } 1543 1544 bool PeepholeOptimizer::findTargetRecurrence( 1545 unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs, 1546 RecurrenceCycle &RC) { 1547 // Recurrence found if Reg is in TargetRegs. 1548 if (TargetRegs.count(Reg)) 1549 return true; 1550 1551 // TODO: Curerntly, we only allow the last instruction of the recurrence 1552 // cycle (the instruction that feeds the PHI instruction) to have more than 1553 // one uses to guarantee that commuting operands does not tie registers 1554 // with overlapping live range. Once we have actual live range info of 1555 // each register, this constraint can be relaxed. 1556 if (!MRI->hasOneNonDBGUse(Reg)) 1557 return false; 1558 1559 // Give up if the reccurrence chain length is longer than the limit. 1560 if (RC.size() >= MaxRecurrenceChain) 1561 return false; 1562 1563 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg)); 1564 unsigned Idx = MI.findRegisterUseOperandIdx(Reg); 1565 1566 // Only interested in recurrences whose instructions have only one def, which 1567 // is a virtual register. 1568 if (MI.getDesc().getNumDefs() != 1) 1569 return false; 1570 1571 MachineOperand &DefOp = MI.getOperand(0); 1572 if (!isVirtualRegisterOperand(DefOp)) 1573 return false; 1574 1575 // Check if def operand of MI is tied to any use operand. We are only 1576 // interested in the case that all the instructions in the recurrence chain 1577 // have there def operand tied with one of the use operand. 1578 unsigned TiedUseIdx; 1579 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx)) 1580 return false; 1581 1582 if (Idx == TiedUseIdx) { 1583 RC.push_back(RecurrenceInstr(&MI)); 1584 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC); 1585 } else { 1586 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx. 1587 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex; 1588 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) { 1589 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx)); 1590 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC); 1591 } 1592 } 1593 1594 return false; 1595 } 1596 1597 /// \brief Phi instructions will eventually be lowered to copy instructions. If 1598 /// phi is in a loop header, a recurrence may formulated around the source and 1599 /// destination of the phi. For such case commuting operands of the instructions 1600 /// in the recurrence may enable coalescing of the copy instruction generated 1601 /// from the phi. For example, if there is a recurrence of 1602 /// 1603 /// LoopHeader: 1604 /// %vreg1 = phi(%vreg0, %vreg100) 1605 /// LoopLatch: 1606 /// %vreg0<def, tied1> = ADD %vreg2<def, tied0>, %vreg1 1607 /// 1608 /// , the fact that vreg0 and vreg2 are in the same tied operands set makes 1609 /// the coalescing of copy instruction generated from the phi in 1610 /// LoopHeader(i.e. %vreg1 = COPY %vreg0) impossible, because %vreg1 and 1611 /// %vreg2 have overlapping live range. This introduces additional move 1612 /// instruction to the final assembly. However, if we commute %vreg2 and 1613 /// %vreg1 of ADD instruction, the redundant move instruction can be 1614 /// avoided. 1615 bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) { 1616 SmallSet<unsigned, 2> TargetRegs; 1617 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) { 1618 MachineOperand &MO = PHI.getOperand(Idx); 1619 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction"); 1620 TargetRegs.insert(MO.getReg()); 1621 } 1622 1623 bool Changed = false; 1624 RecurrenceCycle RC; 1625 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) { 1626 // Commutes operands of instructions in RC if necessary so that the copy to 1627 // be generated from PHI can be coalesced. 1628 DEBUG(dbgs() << "Optimize recurrence chain from " << PHI); 1629 for (auto &RI : RC) { 1630 DEBUG(dbgs() << "\tInst: " << *(RI.getMI())); 1631 auto CP = RI.getCommutePair(); 1632 if (CP) { 1633 Changed = true; 1634 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first, 1635 (*CP).second); 1636 DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI())); 1637 } 1638 } 1639 } 1640 1641 return Changed; 1642 } 1643 1644 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) { 1645 if (skipFunction(*MF.getFunction())) 1646 return false; 1647 1648 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n"); 1649 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n'); 1650 1651 if (DisablePeephole) 1652 return false; 1653 1654 TII = MF.getSubtarget().getInstrInfo(); 1655 TRI = MF.getSubtarget().getRegisterInfo(); 1656 MRI = &MF.getRegInfo(); 1657 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr; 1658 MLI = &getAnalysis<MachineLoopInfo>(); 1659 1660 bool Changed = false; 1661 1662 for (MachineBasicBlock &MBB : MF) { 1663 bool SeenMoveImm = false; 1664 1665 // During this forward scan, at some point it needs to answer the question 1666 // "given a pointer to an MI in the current BB, is it located before or 1667 // after the current instruction". 1668 // To perform this, the following set keeps track of the MIs already seen 1669 // during the scan, if a MI is not in the set, it is assumed to be located 1670 // after. Newly created MIs have to be inserted in the set as well. 1671 SmallPtrSet<MachineInstr*, 16> LocalMIs; 1672 SmallSet<unsigned, 4> ImmDefRegs; 1673 DenseMap<unsigned, MachineInstr*> ImmDefMIs; 1674 SmallSet<unsigned, 16> FoldAsLoadDefCandidates; 1675 1676 // Track when a non-allocatable physical register is copied to a virtual 1677 // register so that useless moves can be removed. 1678 // 1679 // %PHYSREG is the map index; MI is the last valid `%vreg = COPY %PHYSREG` 1680 // without any intervening re-definition of %PHYSREG. 1681 DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs; 1682 1683 // Set of virtual registers that are copied from. 1684 SmallSet<unsigned, 4> CopySrcRegs; 1685 DenseMap<unsigned, MachineInstr *> CopySrcMIs; 1686 1687 bool IsLoopHeader = MLI->isLoopHeader(&MBB); 1688 1689 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end(); 1690 MII != MIE; ) { 1691 MachineInstr *MI = &*MII; 1692 // We may be erasing MI below, increment MII now. 1693 ++MII; 1694 LocalMIs.insert(MI); 1695 1696 // Skip debug values. They should not affect this peephole optimization. 1697 if (MI->isDebugValue()) 1698 continue; 1699 1700 if (MI->isPosition()) 1701 continue; 1702 1703 if (IsLoopHeader && MI->isPHI()) { 1704 if (optimizeRecurrence(*MI)) { 1705 Changed = true; 1706 continue; 1707 } 1708 } 1709 1710 if (!MI->isCopy()) { 1711 for (const auto &Op : MI->operands()) { 1712 // Visit all operands: definitions can be implicit or explicit. 1713 if (Op.isReg()) { 1714 unsigned Reg = Op.getReg(); 1715 if (Op.isDef() && isNAPhysCopy(Reg)) { 1716 const auto &Def = NAPhysToVirtMIs.find(Reg); 1717 if (Def != NAPhysToVirtMIs.end()) { 1718 // A new definition of the non-allocatable physical register 1719 // invalidates previous copies. 1720 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI 1721 << '\n'); 1722 NAPhysToVirtMIs.erase(Def); 1723 } 1724 } 1725 } else if (Op.isRegMask()) { 1726 const uint32_t *RegMask = Op.getRegMask(); 1727 for (auto &RegMI : NAPhysToVirtMIs) { 1728 unsigned Def = RegMI.first; 1729 if (MachineOperand::clobbersPhysReg(RegMask, Def)) { 1730 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI 1731 << '\n'); 1732 NAPhysToVirtMIs.erase(Def); 1733 } 1734 } 1735 } 1736 } 1737 } 1738 1739 if (MI->isImplicitDef() || MI->isKill()) 1740 continue; 1741 1742 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) { 1743 // Blow away all non-allocatable physical registers knowledge since we 1744 // don't know what's correct anymore. 1745 // 1746 // FIXME: handle explicit asm clobbers. 1747 DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " << *MI 1748 << '\n'); 1749 NAPhysToVirtMIs.clear(); 1750 } 1751 1752 if ((isUncoalescableCopy(*MI) && 1753 optimizeUncoalescableCopy(MI, LocalMIs)) || 1754 (MI->isCompare() && optimizeCmpInstr(MI, &MBB)) || 1755 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) { 1756 // MI is deleted. 1757 LocalMIs.erase(MI); 1758 Changed = true; 1759 continue; 1760 } 1761 1762 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) { 1763 Changed = true; 1764 continue; 1765 } 1766 1767 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) { 1768 // MI is just rewritten. 1769 Changed = true; 1770 continue; 1771 } 1772 1773 if (MI->isCopy() && 1774 (foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs) || 1775 foldRedundantNAPhysCopy(MI, NAPhysToVirtMIs))) { 1776 LocalMIs.erase(MI); 1777 MI->eraseFromParent(); 1778 Changed = true; 1779 continue; 1780 } 1781 1782 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) { 1783 SeenMoveImm = true; 1784 } else { 1785 Changed |= optimizeExtInstr(MI, &MBB, LocalMIs); 1786 // optimizeExtInstr might have created new instructions after MI 1787 // and before the already incremented MII. Adjust MII so that the 1788 // next iteration sees the new instructions. 1789 MII = MI; 1790 ++MII; 1791 if (SeenMoveImm) 1792 Changed |= foldImmediate(MI, &MBB, ImmDefRegs, ImmDefMIs); 1793 } 1794 1795 // Check whether MI is a load candidate for folding into a later 1796 // instruction. If MI is not a candidate, check whether we can fold an 1797 // earlier load into MI. 1798 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) && 1799 !FoldAsLoadDefCandidates.empty()) { 1800 1801 // We visit each operand even after successfully folding a previous 1802 // one. This allows us to fold multiple loads into a single 1803 // instruction. We do assume that optimizeLoadInstr doesn't insert 1804 // foldable uses earlier in the argument list. Since we don't restart 1805 // iteration, we'd miss such cases. 1806 const MCInstrDesc &MIDesc = MI->getDesc(); 1807 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands(); 1808 ++i) { 1809 const MachineOperand &MOp = MI->getOperand(i); 1810 if (!MOp.isReg()) 1811 continue; 1812 unsigned FoldAsLoadDefReg = MOp.getReg(); 1813 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) { 1814 // We need to fold load after optimizeCmpInstr, since 1815 // optimizeCmpInstr can enable folding by converting SUB to CMP. 1816 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and 1817 // we need it for markUsesInDebugValueAsUndef(). 1818 unsigned FoldedReg = FoldAsLoadDefReg; 1819 MachineInstr *DefMI = nullptr; 1820 if (MachineInstr *FoldMI = 1821 TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) { 1822 // Update LocalMIs since we replaced MI with FoldMI and deleted 1823 // DefMI. 1824 DEBUG(dbgs() << "Replacing: " << *MI); 1825 DEBUG(dbgs() << " With: " << *FoldMI); 1826 LocalMIs.erase(MI); 1827 LocalMIs.erase(DefMI); 1828 LocalMIs.insert(FoldMI); 1829 MI->eraseFromParent(); 1830 DefMI->eraseFromParent(); 1831 MRI->markUsesInDebugValueAsUndef(FoldedReg); 1832 FoldAsLoadDefCandidates.erase(FoldedReg); 1833 ++NumLoadFold; 1834 1835 // MI is replaced with FoldMI so we can continue trying to fold 1836 Changed = true; 1837 MI = FoldMI; 1838 } 1839 } 1840 } 1841 } 1842 1843 // If we run into an instruction we can't fold across, discard 1844 // the load candidates. Note: We might be able to fold *into* this 1845 // instruction, so this needs to be after the folding logic. 1846 if (MI->isLoadFoldBarrier()) { 1847 DEBUG(dbgs() << "Encountered load fold barrier on " << *MI << "\n"); 1848 FoldAsLoadDefCandidates.clear(); 1849 } 1850 1851 } 1852 } 1853 1854 return Changed; 1855 } 1856 1857 ValueTrackerResult ValueTracker::getNextSourceFromCopy() { 1858 assert(Def->isCopy() && "Invalid definition"); 1859 // Copy instruction are supposed to be: Def = Src. 1860 // If someone breaks this assumption, bad things will happen everywhere. 1861 assert(Def->getNumOperands() == 2 && "Invalid number of operands"); 1862 1863 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg) 1864 // If we look for a different subreg, it means we want a subreg of src. 1865 // Bails as we do not support composing subregs yet. 1866 return ValueTrackerResult(); 1867 // Otherwise, we want the whole source. 1868 const MachineOperand &Src = Def->getOperand(1); 1869 return ValueTrackerResult(Src.getReg(), Src.getSubReg()); 1870 } 1871 1872 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() { 1873 assert(Def->isBitcast() && "Invalid definition"); 1874 1875 // Bail if there are effects that a plain copy will not expose. 1876 if (Def->hasUnmodeledSideEffects()) 1877 return ValueTrackerResult(); 1878 1879 // Bitcasts with more than one def are not supported. 1880 if (Def->getDesc().getNumDefs() != 1) 1881 return ValueTrackerResult(); 1882 const MachineOperand DefOp = Def->getOperand(DefIdx); 1883 if (DefOp.getSubReg() != DefSubReg) 1884 // If we look for a different subreg, it means we want a subreg of the src. 1885 // Bails as we do not support composing subregs yet. 1886 return ValueTrackerResult(); 1887 1888 unsigned SrcIdx = Def->getNumOperands(); 1889 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx; 1890 ++OpIdx) { 1891 const MachineOperand &MO = Def->getOperand(OpIdx); 1892 if (!MO.isReg() || !MO.getReg()) 1893 continue; 1894 // Ignore dead implicit defs. 1895 if (MO.isImplicit() && MO.isDead()) 1896 continue; 1897 assert(!MO.isDef() && "We should have skipped all the definitions by now"); 1898 if (SrcIdx != EndOpIdx) 1899 // Multiple sources? 1900 return ValueTrackerResult(); 1901 SrcIdx = OpIdx; 1902 } 1903 1904 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY 1905 // will break the assumed guarantees for the upper bits. 1906 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) { 1907 if (UseMI.isSubregToReg()) 1908 return ValueTrackerResult(); 1909 } 1910 1911 const MachineOperand &Src = Def->getOperand(SrcIdx); 1912 return ValueTrackerResult(Src.getReg(), Src.getSubReg()); 1913 } 1914 1915 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() { 1916 assert((Def->isRegSequence() || Def->isRegSequenceLike()) && 1917 "Invalid definition"); 1918 1919 if (Def->getOperand(DefIdx).getSubReg()) 1920 // If we are composing subregs, bail out. 1921 // The case we are checking is Def.<subreg> = REG_SEQUENCE. 1922 // This should almost never happen as the SSA property is tracked at 1923 // the register level (as opposed to the subreg level). 1924 // I.e., 1925 // Def.sub0 = 1926 // Def.sub1 = 1927 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for 1928 // Def. Thus, it must not be generated. 1929 // However, some code could theoretically generates a single 1930 // Def.sub0 (i.e, not defining the other subregs) and we would 1931 // have this case. 1932 // If we can ascertain (or force) that this never happens, we could 1933 // turn that into an assertion. 1934 return ValueTrackerResult(); 1935 1936 if (!TII) 1937 // We could handle the REG_SEQUENCE here, but we do not want to 1938 // duplicate the code from the generic TII. 1939 return ValueTrackerResult(); 1940 1941 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs; 1942 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs)) 1943 return ValueTrackerResult(); 1944 1945 // We are looking at: 1946 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ... 1947 // Check if one of the operand defines the subreg we are interested in. 1948 for (auto &RegSeqInput : RegSeqInputRegs) { 1949 if (RegSeqInput.SubIdx == DefSubReg) { 1950 if (RegSeqInput.SubReg) 1951 // Bail if we have to compose sub registers. 1952 return ValueTrackerResult(); 1953 1954 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg); 1955 } 1956 } 1957 1958 // If the subreg we are tracking is super-defined by another subreg, 1959 // we could follow this value. However, this would require to compose 1960 // the subreg and we do not do that for now. 1961 return ValueTrackerResult(); 1962 } 1963 1964 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() { 1965 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) && 1966 "Invalid definition"); 1967 1968 if (Def->getOperand(DefIdx).getSubReg()) 1969 // If we are composing subreg, bail out. 1970 // Same remark as getNextSourceFromRegSequence. 1971 // I.e., this may be turned into an assert. 1972 return ValueTrackerResult(); 1973 1974 if (!TII) 1975 // We could handle the REG_SEQUENCE here, but we do not want to 1976 // duplicate the code from the generic TII. 1977 return ValueTrackerResult(); 1978 1979 TargetInstrInfo::RegSubRegPair BaseReg; 1980 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg; 1981 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg)) 1982 return ValueTrackerResult(); 1983 1984 // We are looking at: 1985 // Def = INSERT_SUBREG v0, v1, sub1 1986 // There are two cases: 1987 // 1. DefSubReg == sub1, get v1. 1988 // 2. DefSubReg != sub1, the value may be available through v0. 1989 1990 // #1 Check if the inserted register matches the required sub index. 1991 if (InsertedReg.SubIdx == DefSubReg) { 1992 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg); 1993 } 1994 // #2 Otherwise, if the sub register we are looking for is not partial 1995 // defined by the inserted element, we can look through the main 1996 // register (v0). 1997 const MachineOperand &MODef = Def->getOperand(DefIdx); 1998 // If the result register (Def) and the base register (v0) do not 1999 // have the same register class or if we have to compose 2000 // subregisters, bail out. 2001 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) || 2002 BaseReg.SubReg) 2003 return ValueTrackerResult(); 2004 2005 // Get the TRI and check if the inserted sub-register overlaps with the 2006 // sub-register we are tracking. 2007 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo(); 2008 if (!TRI || 2009 !(TRI->getSubRegIndexLaneMask(DefSubReg) & 2010 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none()) 2011 return ValueTrackerResult(); 2012 // At this point, the value is available in v0 via the same subreg 2013 // we used for Def. 2014 return ValueTrackerResult(BaseReg.Reg, DefSubReg); 2015 } 2016 2017 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() { 2018 assert((Def->isExtractSubreg() || 2019 Def->isExtractSubregLike()) && "Invalid definition"); 2020 // We are looking at: 2021 // Def = EXTRACT_SUBREG v0, sub0 2022 2023 // Bail if we have to compose sub registers. 2024 // Indeed, if DefSubReg != 0, we would have to compose it with sub0. 2025 if (DefSubReg) 2026 return ValueTrackerResult(); 2027 2028 if (!TII) 2029 // We could handle the EXTRACT_SUBREG here, but we do not want to 2030 // duplicate the code from the generic TII. 2031 return ValueTrackerResult(); 2032 2033 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg; 2034 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg)) 2035 return ValueTrackerResult(); 2036 2037 // Bail if we have to compose sub registers. 2038 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0. 2039 if (ExtractSubregInputReg.SubReg) 2040 return ValueTrackerResult(); 2041 // Otherwise, the value is available in the v0.sub0. 2042 return ValueTrackerResult(ExtractSubregInputReg.Reg, 2043 ExtractSubregInputReg.SubIdx); 2044 } 2045 2046 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() { 2047 assert(Def->isSubregToReg() && "Invalid definition"); 2048 // We are looking at: 2049 // Def = SUBREG_TO_REG Imm, v0, sub0 2050 2051 // Bail if we have to compose sub registers. 2052 // If DefSubReg != sub0, we would have to check that all the bits 2053 // we track are included in sub0 and if yes, we would have to 2054 // determine the right subreg in v0. 2055 if (DefSubReg != Def->getOperand(3).getImm()) 2056 return ValueTrackerResult(); 2057 // Bail if we have to compose sub registers. 2058 // Likewise, if v0.subreg != 0, we would have to compose it with sub0. 2059 if (Def->getOperand(2).getSubReg()) 2060 return ValueTrackerResult(); 2061 2062 return ValueTrackerResult(Def->getOperand(2).getReg(), 2063 Def->getOperand(3).getImm()); 2064 } 2065 2066 /// \brief Explore each PHI incoming operand and return its sources 2067 ValueTrackerResult ValueTracker::getNextSourceFromPHI() { 2068 assert(Def->isPHI() && "Invalid definition"); 2069 ValueTrackerResult Res; 2070 2071 // If we look for a different subreg, bail as we do not support composing 2072 // subregs yet. 2073 if (Def->getOperand(0).getSubReg() != DefSubReg) 2074 return ValueTrackerResult(); 2075 2076 // Return all register sources for PHI instructions. 2077 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) { 2078 auto &MO = Def->getOperand(i); 2079 assert(MO.isReg() && "Invalid PHI instruction"); 2080 Res.addSource(MO.getReg(), MO.getSubReg()); 2081 } 2082 2083 return Res; 2084 } 2085 2086 ValueTrackerResult ValueTracker::getNextSourceImpl() { 2087 assert(Def && "This method needs a valid definition"); 2088 2089 assert(((Def->getOperand(DefIdx).isDef() && 2090 (DefIdx < Def->getDesc().getNumDefs() || 2091 Def->getDesc().isVariadic())) || 2092 Def->getOperand(DefIdx).isImplicit()) && 2093 "Invalid DefIdx"); 2094 if (Def->isCopy()) 2095 return getNextSourceFromCopy(); 2096 if (Def->isBitcast()) 2097 return getNextSourceFromBitcast(); 2098 // All the remaining cases involve "complex" instructions. 2099 // Bail if we did not ask for the advanced tracking. 2100 if (!UseAdvancedTracking) 2101 return ValueTrackerResult(); 2102 if (Def->isRegSequence() || Def->isRegSequenceLike()) 2103 return getNextSourceFromRegSequence(); 2104 if (Def->isInsertSubreg() || Def->isInsertSubregLike()) 2105 return getNextSourceFromInsertSubreg(); 2106 if (Def->isExtractSubreg() || Def->isExtractSubregLike()) 2107 return getNextSourceFromExtractSubreg(); 2108 if (Def->isSubregToReg()) 2109 return getNextSourceFromSubregToReg(); 2110 if (Def->isPHI()) 2111 return getNextSourceFromPHI(); 2112 return ValueTrackerResult(); 2113 } 2114 2115 ValueTrackerResult ValueTracker::getNextSource() { 2116 // If we reach a point where we cannot move up in the use-def chain, 2117 // there is nothing we can get. 2118 if (!Def) 2119 return ValueTrackerResult(); 2120 2121 ValueTrackerResult Res = getNextSourceImpl(); 2122 if (Res.isValid()) { 2123 // Update definition, definition index, and subregister for the 2124 // next call of getNextSource. 2125 // Update the current register. 2126 bool OneRegSrc = Res.getNumSources() == 1; 2127 if (OneRegSrc) 2128 Reg = Res.getSrcReg(0); 2129 // Update the result before moving up in the use-def chain 2130 // with the instruction containing the last found sources. 2131 Res.setInst(Def); 2132 2133 // If we can still move up in the use-def chain, move to the next 2134 // definition. 2135 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) { 2136 Def = MRI.getVRegDef(Reg); 2137 DefIdx = MRI.def_begin(Reg).getOperandNo(); 2138 DefSubReg = Res.getSrcSubReg(0); 2139 return Res; 2140 } 2141 } 2142 // If we end up here, this means we will not be able to find another source 2143 // for the next iteration. Make sure any new call to getNextSource bails out 2144 // early by cutting the use-def chain. 2145 Def = nullptr; 2146 return Res; 2147 } 2148