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