1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass munges the code in the input function to better prepare it for 10 // SelectionDAG-based code generation. This works around limitations in it's 11 // basic-block-at-a-time approach. It should eventually be removed. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/MapVector.h" 19 #include "llvm/ADT/PointerIntPair.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/BlockFrequencyInfo.h" 25 #include "llvm/Analysis/BranchProbabilityInfo.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/InstructionSimplify.h" 28 #include "llvm/Analysis/LoopInfo.h" 29 #include "llvm/Analysis/MemoryBuiltins.h" 30 #include "llvm/Analysis/ProfileSummaryInfo.h" 31 #include "llvm/Analysis/TargetLibraryInfo.h" 32 #include "llvm/Analysis/TargetTransformInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/Analysis/VectorUtils.h" 35 #include "llvm/CodeGen/Analysis.h" 36 #include "llvm/CodeGen/ISDOpcodes.h" 37 #include "llvm/CodeGen/SelectionDAGNodes.h" 38 #include "llvm/CodeGen/TargetLowering.h" 39 #include "llvm/CodeGen/TargetPassConfig.h" 40 #include "llvm/CodeGen/TargetSubtargetInfo.h" 41 #include "llvm/CodeGen/ValueTypes.h" 42 #include "llvm/Config/llvm-config.h" 43 #include "llvm/IR/Argument.h" 44 #include "llvm/IR/Attributes.h" 45 #include "llvm/IR/BasicBlock.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DerivedTypes.h" 50 #include "llvm/IR/Dominators.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/IR/GetElementPtrTypeIterator.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/GlobalVariable.h" 55 #include "llvm/IR/IRBuilder.h" 56 #include "llvm/IR/InlineAsm.h" 57 #include "llvm/IR/InstrTypes.h" 58 #include "llvm/IR/Instruction.h" 59 #include "llvm/IR/Instructions.h" 60 #include "llvm/IR/IntrinsicInst.h" 61 #include "llvm/IR/Intrinsics.h" 62 #include "llvm/IR/IntrinsicsAArch64.h" 63 #include "llvm/IR/LLVMContext.h" 64 #include "llvm/IR/MDBuilder.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/Operator.h" 67 #include "llvm/IR/PatternMatch.h" 68 #include "llvm/IR/Statepoint.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/IR/Use.h" 71 #include "llvm/IR/User.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/IR/ValueHandle.h" 74 #include "llvm/IR/ValueMap.h" 75 #include "llvm/InitializePasses.h" 76 #include "llvm/Pass.h" 77 #include "llvm/Support/BlockFrequency.h" 78 #include "llvm/Support/BranchProbability.h" 79 #include "llvm/Support/Casting.h" 80 #include "llvm/Support/CommandLine.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/MachineValueType.h" 85 #include "llvm/Support/MathExtras.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 90 #include "llvm/Transforms/Utils/BypassSlowDivision.h" 91 #include "llvm/Transforms/Utils/Local.h" 92 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 93 #include "llvm/Transforms/Utils/SizeOpts.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <limits> 99 #include <memory> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 using namespace llvm::PatternMatch; 105 106 #define DEBUG_TYPE "codegenprepare" 107 108 STATISTIC(NumBlocksElim, "Number of blocks eliminated"); 109 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); 110 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); 111 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " 112 "sunken Cmps"); 113 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " 114 "of sunken Casts"); 115 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " 116 "computations were sunk"); 117 STATISTIC(NumMemoryInstsPhiCreated, 118 "Number of phis created when address " 119 "computations were sunk to memory instructions"); 120 STATISTIC(NumMemoryInstsSelectCreated, 121 "Number of select created when address " 122 "computations were sunk to memory instructions"); 123 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); 124 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); 125 STATISTIC(NumAndsAdded, 126 "Number of and mask instructions added to form ext loads"); 127 STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); 128 STATISTIC(NumRetsDup, "Number of return instructions duplicated"); 129 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); 130 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); 131 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); 132 133 static cl::opt<bool> DisableBranchOpts( 134 "disable-cgp-branch-opts", cl::Hidden, cl::init(false), 135 cl::desc("Disable branch optimizations in CodeGenPrepare")); 136 137 static cl::opt<bool> 138 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), 139 cl::desc("Disable GC optimizations in CodeGenPrepare")); 140 141 static cl::opt<bool> DisableSelectToBranch( 142 "disable-cgp-select2branch", cl::Hidden, cl::init(false), 143 cl::desc("Disable select to branch conversion.")); 144 145 static cl::opt<bool> AddrSinkUsingGEPs( 146 "addr-sink-using-gep", cl::Hidden, cl::init(true), 147 cl::desc("Address sinking in CGP using GEPs.")); 148 149 static cl::opt<bool> EnableAndCmpSinking( 150 "enable-andcmp-sinking", cl::Hidden, cl::init(true), 151 cl::desc("Enable sinkinig and/cmp into branches.")); 152 153 static cl::opt<bool> DisableStoreExtract( 154 "disable-cgp-store-extract", cl::Hidden, cl::init(false), 155 cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); 156 157 static cl::opt<bool> StressStoreExtract( 158 "stress-cgp-store-extract", cl::Hidden, cl::init(false), 159 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); 160 161 static cl::opt<bool> DisableExtLdPromotion( 162 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), 163 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " 164 "CodeGenPrepare")); 165 166 static cl::opt<bool> StressExtLdPromotion( 167 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), 168 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " 169 "optimization in CodeGenPrepare")); 170 171 static cl::opt<bool> DisablePreheaderProtect( 172 "disable-preheader-prot", cl::Hidden, cl::init(false), 173 cl::desc("Disable protection against removing loop preheaders")); 174 175 static cl::opt<bool> ProfileGuidedSectionPrefix( 176 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, 177 cl::desc("Use profile info to add section prefix for hot/cold functions")); 178 179 static cl::opt<bool> ProfileUnknownInSpecialSection( 180 "profile-unknown-in-special-section", cl::Hidden, cl::init(false), 181 cl::ZeroOrMore, 182 cl::desc("In profiling mode like sampleFDO, if a function doesn't have " 183 "profile, we cannot tell the function is cold for sure because " 184 "it may be a function newly added without ever being sampled. " 185 "With the flag enabled, compiler can put such profile unknown " 186 "functions into a special section, so runtime system can choose " 187 "to handle it in a different way than .text section, to save " 188 "RAM for example. ")); 189 190 static cl::opt<unsigned> FreqRatioToSkipMerge( 191 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), 192 cl::desc("Skip merging empty blocks if (frequency of empty block) / " 193 "(frequency of destination block) is greater than this ratio")); 194 195 static cl::opt<bool> ForceSplitStore( 196 "force-split-store", cl::Hidden, cl::init(false), 197 cl::desc("Force store splitting no matter what the target query says.")); 198 199 static cl::opt<bool> 200 EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, 201 cl::desc("Enable merging of redundant sexts when one is dominating" 202 " the other."), cl::init(true)); 203 204 static cl::opt<bool> DisableComplexAddrModes( 205 "disable-complex-addr-modes", cl::Hidden, cl::init(false), 206 cl::desc("Disables combining addressing modes with different parts " 207 "in optimizeMemoryInst.")); 208 209 static cl::opt<bool> 210 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), 211 cl::desc("Allow creation of Phis in Address sinking.")); 212 213 static cl::opt<bool> 214 AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), 215 cl::desc("Allow creation of selects in Address sinking.")); 216 217 static cl::opt<bool> AddrSinkCombineBaseReg( 218 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true), 219 cl::desc("Allow combining of BaseReg field in Address sinking.")); 220 221 static cl::opt<bool> AddrSinkCombineBaseGV( 222 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true), 223 cl::desc("Allow combining of BaseGV field in Address sinking.")); 224 225 static cl::opt<bool> AddrSinkCombineBaseOffs( 226 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true), 227 cl::desc("Allow combining of BaseOffs field in Address sinking.")); 228 229 static cl::opt<bool> AddrSinkCombineScaledReg( 230 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), 231 cl::desc("Allow combining of ScaledReg field in Address sinking.")); 232 233 static cl::opt<bool> 234 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, 235 cl::init(true), 236 cl::desc("Enable splitting large offset of GEP.")); 237 238 static cl::opt<bool> EnableICMP_EQToICMP_ST( 239 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false), 240 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion.")); 241 242 static cl::opt<bool> 243 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false), 244 cl::desc("Enable BFI update verification for " 245 "CodeGenPrepare.")); 246 247 static cl::opt<bool> OptimizePhiTypes( 248 "cgp-optimize-phi-types", cl::Hidden, cl::init(false), 249 cl::desc("Enable converting phi types in CodeGenPrepare")); 250 251 namespace { 252 253 enum ExtType { 254 ZeroExtension, // Zero extension has been seen. 255 SignExtension, // Sign extension has been seen. 256 BothExtension // This extension type is used if we saw sext after 257 // ZeroExtension had been set, or if we saw zext after 258 // SignExtension had been set. It makes the type 259 // information of a promoted instruction invalid. 260 }; 261 262 using SetOfInstrs = SmallPtrSet<Instruction *, 16>; 263 using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>; 264 using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>; 265 using SExts = SmallVector<Instruction *, 16>; 266 using ValueToSExts = DenseMap<Value *, SExts>; 267 268 class TypePromotionTransaction; 269 270 class CodeGenPrepare : public FunctionPass { 271 const TargetMachine *TM = nullptr; 272 const TargetSubtargetInfo *SubtargetInfo; 273 const TargetLowering *TLI = nullptr; 274 const TargetRegisterInfo *TRI; 275 const TargetTransformInfo *TTI = nullptr; 276 const TargetLibraryInfo *TLInfo; 277 const LoopInfo *LI; 278 std::unique_ptr<BlockFrequencyInfo> BFI; 279 std::unique_ptr<BranchProbabilityInfo> BPI; 280 ProfileSummaryInfo *PSI; 281 282 /// As we scan instructions optimizing them, this is the next instruction 283 /// to optimize. Transforms that can invalidate this should update it. 284 BasicBlock::iterator CurInstIterator; 285 286 /// Keeps track of non-local addresses that have been sunk into a block. 287 /// This allows us to avoid inserting duplicate code for blocks with 288 /// multiple load/stores of the same address. The usage of WeakTrackingVH 289 /// enables SunkAddrs to be treated as a cache whose entries can be 290 /// invalidated if a sunken address computation has been erased. 291 ValueMap<Value*, WeakTrackingVH> SunkAddrs; 292 293 /// Keeps track of all instructions inserted for the current function. 294 SetOfInstrs InsertedInsts; 295 296 /// Keeps track of the type of the related instruction before their 297 /// promotion for the current function. 298 InstrToOrigTy PromotedInsts; 299 300 /// Keep track of instructions removed during promotion. 301 SetOfInstrs RemovedInsts; 302 303 /// Keep track of sext chains based on their initial value. 304 DenseMap<Value *, Instruction *> SeenChainsForSExt; 305 306 /// Keep track of GEPs accessing the same data structures such as structs or 307 /// arrays that are candidates to be split later because of their large 308 /// size. 309 MapVector< 310 AssertingVH<Value>, 311 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>> 312 LargeOffsetGEPMap; 313 314 /// Keep track of new GEP base after splitting the GEPs having large offset. 315 SmallSet<AssertingVH<Value>, 2> NewGEPBases; 316 317 /// Map serial numbers to Large offset GEPs. 318 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID; 319 320 /// Keep track of SExt promoted. 321 ValueToSExts ValToSExtendedUses; 322 323 /// True if the function has the OptSize attribute. 324 bool OptSize; 325 326 /// DataLayout for the Function being processed. 327 const DataLayout *DL = nullptr; 328 329 /// Building the dominator tree can be expensive, so we only build it 330 /// lazily and update it when required. 331 std::unique_ptr<DominatorTree> DT; 332 333 public: 334 static char ID; // Pass identification, replacement for typeid 335 336 CodeGenPrepare() : FunctionPass(ID) { 337 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); 338 } 339 340 bool runOnFunction(Function &F) override; 341 342 StringRef getPassName() const override { return "CodeGen Prepare"; } 343 344 void getAnalysisUsage(AnalysisUsage &AU) const override { 345 // FIXME: When we can selectively preserve passes, preserve the domtree. 346 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 347 AU.addRequired<TargetLibraryInfoWrapperPass>(); 348 AU.addRequired<TargetPassConfig>(); 349 AU.addRequired<TargetTransformInfoWrapperPass>(); 350 AU.addRequired<LoopInfoWrapperPass>(); 351 } 352 353 private: 354 template <typename F> 355 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) { 356 // Substituting can cause recursive simplifications, which can invalidate 357 // our iterator. Use a WeakTrackingVH to hold onto it in case this 358 // happens. 359 Value *CurValue = &*CurInstIterator; 360 WeakTrackingVH IterHandle(CurValue); 361 362 f(); 363 364 // If the iterator instruction was recursively deleted, start over at the 365 // start of the block. 366 if (IterHandle != CurValue) { 367 CurInstIterator = BB->begin(); 368 SunkAddrs.clear(); 369 } 370 } 371 372 // Get the DominatorTree, building if necessary. 373 DominatorTree &getDT(Function &F) { 374 if (!DT) 375 DT = std::make_unique<DominatorTree>(F); 376 return *DT; 377 } 378 379 void removeAllAssertingVHReferences(Value *V); 380 bool eliminateFallThrough(Function &F); 381 bool eliminateMostlyEmptyBlocks(Function &F); 382 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); 383 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; 384 void eliminateMostlyEmptyBlock(BasicBlock *BB); 385 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, 386 bool isPreheader); 387 bool makeBitReverse(Instruction &I); 388 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT); 389 bool optimizeInst(Instruction *I, bool &ModifiedDT); 390 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, 391 Type *AccessTy, unsigned AddrSpace); 392 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr); 393 bool optimizeInlineAsmInst(CallInst *CS); 394 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT); 395 bool optimizeExt(Instruction *&I); 396 bool optimizeExtUses(Instruction *I); 397 bool optimizeLoadExt(LoadInst *Load); 398 bool optimizeShiftInst(BinaryOperator *BO); 399 bool optimizeFunnelShift(IntrinsicInst *Fsh); 400 bool optimizeSelectInst(SelectInst *SI); 401 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI); 402 bool optimizeSwitchInst(SwitchInst *SI); 403 bool optimizeExtractElementInst(Instruction *Inst); 404 bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT); 405 bool fixupDbgValue(Instruction *I); 406 bool placeDbgValues(Function &F); 407 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, 408 LoadInst *&LI, Instruction *&Inst, bool HasPromoted); 409 bool tryToPromoteExts(TypePromotionTransaction &TPT, 410 const SmallVectorImpl<Instruction *> &Exts, 411 SmallVectorImpl<Instruction *> &ProfitablyMovedExts, 412 unsigned CreatedInstsCost = 0); 413 bool mergeSExts(Function &F); 414 bool splitLargeGEPOffsets(); 415 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited, 416 SmallPtrSetImpl<Instruction *> &DeletedInstrs); 417 bool optimizePhiTypes(Function &F); 418 bool performAddressTypePromotion( 419 Instruction *&Inst, 420 bool AllowPromotionWithoutCommonHeader, 421 bool HasPromoted, TypePromotionTransaction &TPT, 422 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); 423 bool splitBranchCondition(Function &F, bool &ModifiedDT); 424 bool simplifyOffsetableRelocate(GCStatepointInst &I); 425 426 bool tryToSinkFreeOperands(Instruction *I); 427 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, 428 Value *Arg1, CmpInst *Cmp, 429 Intrinsic::ID IID); 430 bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT); 431 bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT); 432 bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT); 433 void verifyBFIUpdates(Function &F); 434 }; 435 436 } // end anonymous namespace 437 438 char CodeGenPrepare::ID = 0; 439 440 INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE, 441 "Optimize for code generation", false, false) 442 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 443 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 444 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 445 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 446 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 447 INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, 448 "Optimize for code generation", false, false) 449 450 FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); } 451 452 bool CodeGenPrepare::runOnFunction(Function &F) { 453 if (skipFunction(F)) 454 return false; 455 456 DL = &F.getParent()->getDataLayout(); 457 458 bool EverMadeChange = false; 459 // Clear per function information. 460 InsertedInsts.clear(); 461 PromotedInsts.clear(); 462 463 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); 464 SubtargetInfo = TM->getSubtargetImpl(F); 465 TLI = SubtargetInfo->getTargetLowering(); 466 TRI = SubtargetInfo->getRegisterInfo(); 467 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 468 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 469 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 470 BPI.reset(new BranchProbabilityInfo(F, *LI)); 471 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI)); 472 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 473 OptSize = F.hasOptSize(); 474 if (ProfileGuidedSectionPrefix) { 475 if (PSI->isFunctionHotInCallGraph(&F, *BFI)) 476 F.setSectionPrefix(".hot"); 477 else if (PSI->isFunctionColdInCallGraph(&F, *BFI)) 478 F.setSectionPrefix(".unlikely"); 479 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() && 480 PSI->isFunctionHotnessUnknown(F)) 481 F.setSectionPrefix(".unknown"); 482 } 483 484 /// This optimization identifies DIV instructions that can be 485 /// profitably bypassed and carried out with a shorter, faster divide. 486 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) { 487 const DenseMap<unsigned int, unsigned int> &BypassWidths = 488 TLI->getBypassSlowDivWidths(); 489 BasicBlock* BB = &*F.begin(); 490 while (BB != nullptr) { 491 // bypassSlowDivision may create new BBs, but we don't want to reapply the 492 // optimization to those blocks. 493 BasicBlock* Next = BB->getNextNode(); 494 // F.hasOptSize is already checked in the outer if statement. 495 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) 496 EverMadeChange |= bypassSlowDivision(BB, BypassWidths); 497 BB = Next; 498 } 499 } 500 501 // Eliminate blocks that contain only PHI nodes and an 502 // unconditional branch. 503 EverMadeChange |= eliminateMostlyEmptyBlocks(F); 504 505 bool ModifiedDT = false; 506 if (!DisableBranchOpts) 507 EverMadeChange |= splitBranchCondition(F, ModifiedDT); 508 509 // Split some critical edges where one of the sources is an indirect branch, 510 // to help generate sane code for PHIs involving such edges. 511 EverMadeChange |= SplitIndirectBrCriticalEdges(F); 512 513 bool MadeChange = true; 514 while (MadeChange) { 515 MadeChange = false; 516 DT.reset(); 517 for (Function::iterator I = F.begin(); I != F.end(); ) { 518 BasicBlock *BB = &*I++; 519 bool ModifiedDTOnIteration = false; 520 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); 521 522 // Restart BB iteration if the dominator tree of the Function was changed 523 if (ModifiedDTOnIteration) 524 break; 525 } 526 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) 527 MadeChange |= mergeSExts(F); 528 if (!LargeOffsetGEPMap.empty()) 529 MadeChange |= splitLargeGEPOffsets(); 530 MadeChange |= optimizePhiTypes(F); 531 532 if (MadeChange) 533 eliminateFallThrough(F); 534 535 // Really free removed instructions during promotion. 536 for (Instruction *I : RemovedInsts) 537 I->deleteValue(); 538 539 EverMadeChange |= MadeChange; 540 SeenChainsForSExt.clear(); 541 ValToSExtendedUses.clear(); 542 RemovedInsts.clear(); 543 LargeOffsetGEPMap.clear(); 544 LargeOffsetGEPID.clear(); 545 } 546 547 SunkAddrs.clear(); 548 549 if (!DisableBranchOpts) { 550 MadeChange = false; 551 // Use a set vector to get deterministic iteration order. The order the 552 // blocks are removed may affect whether or not PHI nodes in successors 553 // are removed. 554 SmallSetVector<BasicBlock*, 8> WorkList; 555 for (BasicBlock &BB : F) { 556 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); 557 MadeChange |= ConstantFoldTerminator(&BB, true); 558 if (!MadeChange) continue; 559 560 for (SmallVectorImpl<BasicBlock*>::iterator 561 II = Successors.begin(), IE = Successors.end(); II != IE; ++II) 562 if (pred_begin(*II) == pred_end(*II)) 563 WorkList.insert(*II); 564 } 565 566 // Delete the dead blocks and any of their dead successors. 567 MadeChange |= !WorkList.empty(); 568 while (!WorkList.empty()) { 569 BasicBlock *BB = WorkList.pop_back_val(); 570 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); 571 572 DeleteDeadBlock(BB); 573 574 for (SmallVectorImpl<BasicBlock*>::iterator 575 II = Successors.begin(), IE = Successors.end(); II != IE; ++II) 576 if (pred_begin(*II) == pred_end(*II)) 577 WorkList.insert(*II); 578 } 579 580 // Merge pairs of basic blocks with unconditional branches, connected by 581 // a single edge. 582 if (EverMadeChange || MadeChange) 583 MadeChange |= eliminateFallThrough(F); 584 585 EverMadeChange |= MadeChange; 586 } 587 588 if (!DisableGCOpts) { 589 SmallVector<GCStatepointInst *, 2> Statepoints; 590 for (BasicBlock &BB : F) 591 for (Instruction &I : BB) 592 if (auto *SP = dyn_cast<GCStatepointInst>(&I)) 593 Statepoints.push_back(SP); 594 for (auto &I : Statepoints) 595 EverMadeChange |= simplifyOffsetableRelocate(*I); 596 } 597 598 // Do this last to clean up use-before-def scenarios introduced by other 599 // preparatory transforms. 600 EverMadeChange |= placeDbgValues(F); 601 602 #ifndef NDEBUG 603 if (VerifyBFIUpdates) 604 verifyBFIUpdates(F); 605 #endif 606 607 return EverMadeChange; 608 } 609 610 /// An instruction is about to be deleted, so remove all references to it in our 611 /// GEP-tracking data strcutures. 612 void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) { 613 LargeOffsetGEPMap.erase(V); 614 NewGEPBases.erase(V); 615 616 auto GEP = dyn_cast<GetElementPtrInst>(V); 617 if (!GEP) 618 return; 619 620 LargeOffsetGEPID.erase(GEP); 621 622 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand()); 623 if (VecI == LargeOffsetGEPMap.end()) 624 return; 625 626 auto &GEPVector = VecI->second; 627 const auto &I = std::find_if(GEPVector.begin(), GEPVector.end(), 628 [=](auto &Elt) { return Elt.first == GEP; }); 629 if (I == GEPVector.end()) 630 return; 631 632 GEPVector.erase(I); 633 if (GEPVector.empty()) 634 LargeOffsetGEPMap.erase(VecI); 635 } 636 637 // Verify BFI has been updated correctly by recomputing BFI and comparing them. 638 void LLVM_ATTRIBUTE_UNUSED CodeGenPrepare::verifyBFIUpdates(Function &F) { 639 DominatorTree NewDT(F); 640 LoopInfo NewLI(NewDT); 641 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo); 642 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI); 643 NewBFI.verifyMatch(*BFI); 644 } 645 646 /// Merge basic blocks which are connected by a single edge, where one of the 647 /// basic blocks has a single successor pointing to the other basic block, 648 /// which has a single predecessor. 649 bool CodeGenPrepare::eliminateFallThrough(Function &F) { 650 bool Changed = false; 651 // Scan all of the blocks in the function, except for the entry block. 652 // Use a temporary array to avoid iterator being invalidated when 653 // deleting blocks. 654 SmallVector<WeakTrackingVH, 16> Blocks; 655 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end())) 656 Blocks.push_back(&Block); 657 658 for (auto &Block : Blocks) { 659 auto *BB = cast_or_null<BasicBlock>(Block); 660 if (!BB) 661 continue; 662 // If the destination block has a single pred, then this is a trivial 663 // edge, just collapse it. 664 BasicBlock *SinglePred = BB->getSinglePredecessor(); 665 666 // Don't merge if BB's address is taken. 667 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; 668 669 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); 670 if (Term && !Term->isConditional()) { 671 Changed = true; 672 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n"); 673 674 // Merge BB into SinglePred and delete it. 675 MergeBlockIntoPredecessor(BB); 676 } 677 } 678 return Changed; 679 } 680 681 /// Find a destination block from BB if BB is mergeable empty block. 682 BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { 683 // If this block doesn't end with an uncond branch, ignore it. 684 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 685 if (!BI || !BI->isUnconditional()) 686 return nullptr; 687 688 // If the instruction before the branch (skipping debug info) isn't a phi 689 // node, then other stuff is happening here. 690 BasicBlock::iterator BBI = BI->getIterator(); 691 if (BBI != BB->begin()) { 692 --BBI; 693 while (isa<DbgInfoIntrinsic>(BBI)) { 694 if (BBI == BB->begin()) 695 break; 696 --BBI; 697 } 698 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) 699 return nullptr; 700 } 701 702 // Do not break infinite loops. 703 BasicBlock *DestBB = BI->getSuccessor(0); 704 if (DestBB == BB) 705 return nullptr; 706 707 if (!canMergeBlocks(BB, DestBB)) 708 DestBB = nullptr; 709 710 return DestBB; 711 } 712 713 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an 714 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split 715 /// edges in ways that are non-optimal for isel. Start by eliminating these 716 /// blocks so we can split them the way we want them. 717 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { 718 SmallPtrSet<BasicBlock *, 16> Preheaders; 719 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); 720 while (!LoopList.empty()) { 721 Loop *L = LoopList.pop_back_val(); 722 LoopList.insert(LoopList.end(), L->begin(), L->end()); 723 if (BasicBlock *Preheader = L->getLoopPreheader()) 724 Preheaders.insert(Preheader); 725 } 726 727 bool MadeChange = false; 728 // Copy blocks into a temporary array to avoid iterator invalidation issues 729 // as we remove them. 730 // Note that this intentionally skips the entry block. 731 SmallVector<WeakTrackingVH, 16> Blocks; 732 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end())) 733 Blocks.push_back(&Block); 734 735 for (auto &Block : Blocks) { 736 BasicBlock *BB = cast_or_null<BasicBlock>(Block); 737 if (!BB) 738 continue; 739 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); 740 if (!DestBB || 741 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) 742 continue; 743 744 eliminateMostlyEmptyBlock(BB); 745 MadeChange = true; 746 } 747 return MadeChange; 748 } 749 750 bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, 751 BasicBlock *DestBB, 752 bool isPreheader) { 753 // Do not delete loop preheaders if doing so would create a critical edge. 754 // Loop preheaders can be good locations to spill registers. If the 755 // preheader is deleted and we create a critical edge, registers may be 756 // spilled in the loop body instead. 757 if (!DisablePreheaderProtect && isPreheader && 758 !(BB->getSinglePredecessor() && 759 BB->getSinglePredecessor()->getSingleSuccessor())) 760 return false; 761 762 // Skip merging if the block's successor is also a successor to any callbr 763 // that leads to this block. 764 // FIXME: Is this really needed? Is this a correctness issue? 765 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 766 if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator())) 767 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i) 768 if (DestBB == CBI->getSuccessor(i)) 769 return false; 770 } 771 772 // Try to skip merging if the unique predecessor of BB is terminated by a 773 // switch or indirect branch instruction, and BB is used as an incoming block 774 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to 775 // add COPY instructions in the predecessor of BB instead of BB (if it is not 776 // merged). Note that the critical edge created by merging such blocks wont be 777 // split in MachineSink because the jump table is not analyzable. By keeping 778 // such empty block (BB), ISel will place COPY instructions in BB, not in the 779 // predecessor of BB. 780 BasicBlock *Pred = BB->getUniquePredecessor(); 781 if (!Pred || 782 !(isa<SwitchInst>(Pred->getTerminator()) || 783 isa<IndirectBrInst>(Pred->getTerminator()))) 784 return true; 785 786 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg()) 787 return true; 788 789 // We use a simple cost heuristic which determine skipping merging is 790 // profitable if the cost of skipping merging is less than the cost of 791 // merging : Cost(skipping merging) < Cost(merging BB), where the 792 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and 793 // the Cost(merging BB) is Freq(Pred) * Cost(Copy). 794 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : 795 // Freq(Pred) / Freq(BB) > 2. 796 // Note that if there are multiple empty blocks sharing the same incoming 797 // value for the PHIs in the DestBB, we consider them together. In such 798 // case, Cost(merging BB) will be the sum of their frequencies. 799 800 if (!isa<PHINode>(DestBB->begin())) 801 return true; 802 803 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; 804 805 // Find all other incoming blocks from which incoming values of all PHIs in 806 // DestBB are the same as the ones from BB. 807 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; 808 ++PI) { 809 BasicBlock *DestBBPred = *PI; 810 if (DestBBPred == BB) 811 continue; 812 813 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) { 814 return DestPN.getIncomingValueForBlock(BB) == 815 DestPN.getIncomingValueForBlock(DestBBPred); 816 })) 817 SameIncomingValueBBs.insert(DestBBPred); 818 } 819 820 // See if all BB's incoming values are same as the value from Pred. In this 821 // case, no reason to skip merging because COPYs are expected to be place in 822 // Pred already. 823 if (SameIncomingValueBBs.count(Pred)) 824 return true; 825 826 BlockFrequency PredFreq = BFI->getBlockFreq(Pred); 827 BlockFrequency BBFreq = BFI->getBlockFreq(BB); 828 829 for (auto *SameValueBB : SameIncomingValueBBs) 830 if (SameValueBB->getUniquePredecessor() == Pred && 831 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) 832 BBFreq += BFI->getBlockFreq(SameValueBB); 833 834 return PredFreq.getFrequency() <= 835 BBFreq.getFrequency() * FreqRatioToSkipMerge; 836 } 837 838 /// Return true if we can merge BB into DestBB if there is a single 839 /// unconditional branch between them, and BB contains no other non-phi 840 /// instructions. 841 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, 842 const BasicBlock *DestBB) const { 843 // We only want to eliminate blocks whose phi nodes are used by phi nodes in 844 // the successor. If there are more complex condition (e.g. preheaders), 845 // don't mess around with them. 846 for (const PHINode &PN : BB->phis()) { 847 for (const User *U : PN.users()) { 848 const Instruction *UI = cast<Instruction>(U); 849 if (UI->getParent() != DestBB || !isa<PHINode>(UI)) 850 return false; 851 // If User is inside DestBB block and it is a PHINode then check 852 // incoming value. If incoming value is not from BB then this is 853 // a complex condition (e.g. preheaders) we want to avoid here. 854 if (UI->getParent() == DestBB) { 855 if (const PHINode *UPN = dyn_cast<PHINode>(UI)) 856 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { 857 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); 858 if (Insn && Insn->getParent() == BB && 859 Insn->getParent() != UPN->getIncomingBlock(I)) 860 return false; 861 } 862 } 863 } 864 } 865 866 // If BB and DestBB contain any common predecessors, then the phi nodes in BB 867 // and DestBB may have conflicting incoming values for the block. If so, we 868 // can't merge the block. 869 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); 870 if (!DestBBPN) return true; // no conflict. 871 872 // Collect the preds of BB. 873 SmallPtrSet<const BasicBlock*, 16> BBPreds; 874 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { 875 // It is faster to get preds from a PHI than with pred_iterator. 876 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) 877 BBPreds.insert(BBPN->getIncomingBlock(i)); 878 } else { 879 BBPreds.insert(pred_begin(BB), pred_end(BB)); 880 } 881 882 // Walk the preds of DestBB. 883 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { 884 BasicBlock *Pred = DestBBPN->getIncomingBlock(i); 885 if (BBPreds.count(Pred)) { // Common predecessor? 886 for (const PHINode &PN : DestBB->phis()) { 887 const Value *V1 = PN.getIncomingValueForBlock(Pred); 888 const Value *V2 = PN.getIncomingValueForBlock(BB); 889 890 // If V2 is a phi node in BB, look up what the mapped value will be. 891 if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) 892 if (V2PN->getParent() == BB) 893 V2 = V2PN->getIncomingValueForBlock(Pred); 894 895 // If there is a conflict, bail out. 896 if (V1 != V2) return false; 897 } 898 } 899 } 900 901 return true; 902 } 903 904 /// Eliminate a basic block that has only phi's and an unconditional branch in 905 /// it. 906 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { 907 BranchInst *BI = cast<BranchInst>(BB->getTerminator()); 908 BasicBlock *DestBB = BI->getSuccessor(0); 909 910 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" 911 << *BB << *DestBB); 912 913 // If the destination block has a single pred, then this is a trivial edge, 914 // just collapse it. 915 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { 916 if (SinglePred != DestBB) { 917 assert(SinglePred == BB && 918 "Single predecessor not the same as predecessor"); 919 // Merge DestBB into SinglePred/BB and delete it. 920 MergeBlockIntoPredecessor(DestBB); 921 // Note: BB(=SinglePred) will not be deleted on this path. 922 // DestBB(=its single successor) is the one that was deleted. 923 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n"); 924 return; 925 } 926 } 927 928 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB 929 // to handle the new incoming edges it is about to have. 930 for (PHINode &PN : DestBB->phis()) { 931 // Remove the incoming value for BB, and remember it. 932 Value *InVal = PN.removeIncomingValue(BB, false); 933 934 // Two options: either the InVal is a phi node defined in BB or it is some 935 // value that dominates BB. 936 PHINode *InValPhi = dyn_cast<PHINode>(InVal); 937 if (InValPhi && InValPhi->getParent() == BB) { 938 // Add all of the input values of the input PHI as inputs of this phi. 939 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) 940 PN.addIncoming(InValPhi->getIncomingValue(i), 941 InValPhi->getIncomingBlock(i)); 942 } else { 943 // Otherwise, add one instance of the dominating value for each edge that 944 // we will be adding. 945 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { 946 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) 947 PN.addIncoming(InVal, BBPN->getIncomingBlock(i)); 948 } else { 949 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 950 PN.addIncoming(InVal, *PI); 951 } 952 } 953 } 954 955 // The PHIs are now updated, change everything that refers to BB to use 956 // DestBB and remove BB. 957 BB->replaceAllUsesWith(DestBB); 958 BB->eraseFromParent(); 959 ++NumBlocksElim; 960 961 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); 962 } 963 964 // Computes a map of base pointer relocation instructions to corresponding 965 // derived pointer relocation instructions given a vector of all relocate calls 966 static void computeBaseDerivedRelocateMap( 967 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, 968 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> 969 &RelocateInstMap) { 970 // Collect information in two maps: one primarily for locating the base object 971 // while filling the second map; the second map is the final structure holding 972 // a mapping between Base and corresponding Derived relocate calls 973 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; 974 for (auto *ThisRelocate : AllRelocateCalls) { 975 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), 976 ThisRelocate->getDerivedPtrIndex()); 977 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); 978 } 979 for (auto &Item : RelocateIdxMap) { 980 std::pair<unsigned, unsigned> Key = Item.first; 981 if (Key.first == Key.second) 982 // Base relocation: nothing to insert 983 continue; 984 985 GCRelocateInst *I = Item.second; 986 auto BaseKey = std::make_pair(Key.first, Key.first); 987 988 // We're iterating over RelocateIdxMap so we cannot modify it. 989 auto MaybeBase = RelocateIdxMap.find(BaseKey); 990 if (MaybeBase == RelocateIdxMap.end()) 991 // TODO: We might want to insert a new base object relocate and gep off 992 // that, if there are enough derived object relocates. 993 continue; 994 995 RelocateInstMap[MaybeBase->second].push_back(I); 996 } 997 } 998 999 // Accepts a GEP and extracts the operands into a vector provided they're all 1000 // small integer constants 1001 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, 1002 SmallVectorImpl<Value *> &OffsetV) { 1003 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 1004 // Only accept small constant integer operands 1005 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); 1006 if (!Op || Op->getZExtValue() > 20) 1007 return false; 1008 } 1009 1010 for (unsigned i = 1; i < GEP->getNumOperands(); i++) 1011 OffsetV.push_back(GEP->getOperand(i)); 1012 return true; 1013 } 1014 1015 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to 1016 // replace, computes a replacement, and affects it. 1017 static bool 1018 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, 1019 const SmallVectorImpl<GCRelocateInst *> &Targets) { 1020 bool MadeChange = false; 1021 // We must ensure the relocation of derived pointer is defined after 1022 // relocation of base pointer. If we find a relocation corresponding to base 1023 // defined earlier than relocation of base then we move relocation of base 1024 // right before found relocation. We consider only relocation in the same 1025 // basic block as relocation of base. Relocations from other basic block will 1026 // be skipped by optimization and we do not care about them. 1027 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt(); 1028 &*R != RelocatedBase; ++R) 1029 if (auto *RI = dyn_cast<GCRelocateInst>(R)) 1030 if (RI->getStatepoint() == RelocatedBase->getStatepoint()) 1031 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) { 1032 RelocatedBase->moveBefore(RI); 1033 break; 1034 } 1035 1036 for (GCRelocateInst *ToReplace : Targets) { 1037 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && 1038 "Not relocating a derived object of the original base object"); 1039 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { 1040 // A duplicate relocate call. TODO: coalesce duplicates. 1041 continue; 1042 } 1043 1044 if (RelocatedBase->getParent() != ToReplace->getParent()) { 1045 // Base and derived relocates are in different basic blocks. 1046 // In this case transform is only valid when base dominates derived 1047 // relocate. However it would be too expensive to check dominance 1048 // for each such relocate, so we skip the whole transformation. 1049 continue; 1050 } 1051 1052 Value *Base = ToReplace->getBasePtr(); 1053 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); 1054 if (!Derived || Derived->getPointerOperand() != Base) 1055 continue; 1056 1057 SmallVector<Value *, 2> OffsetV; 1058 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) 1059 continue; 1060 1061 // Create a Builder and replace the target callsite with a gep 1062 assert(RelocatedBase->getNextNode() && 1063 "Should always have one since it's not a terminator"); 1064 1065 // Insert after RelocatedBase 1066 IRBuilder<> Builder(RelocatedBase->getNextNode()); 1067 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); 1068 1069 // If gc_relocate does not match the actual type, cast it to the right type. 1070 // In theory, there must be a bitcast after gc_relocate if the type does not 1071 // match, and we should reuse it to get the derived pointer. But it could be 1072 // cases like this: 1073 // bb1: 1074 // ... 1075 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) 1076 // br label %merge 1077 // 1078 // bb2: 1079 // ... 1080 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) 1081 // br label %merge 1082 // 1083 // merge: 1084 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] 1085 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* 1086 // 1087 // In this case, we can not find the bitcast any more. So we insert a new bitcast 1088 // no matter there is already one or not. In this way, we can handle all cases, and 1089 // the extra bitcast should be optimized away in later passes. 1090 Value *ActualRelocatedBase = RelocatedBase; 1091 if (RelocatedBase->getType() != Base->getType()) { 1092 ActualRelocatedBase = 1093 Builder.CreateBitCast(RelocatedBase, Base->getType()); 1094 } 1095 Value *Replacement = Builder.CreateGEP( 1096 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); 1097 Replacement->takeName(ToReplace); 1098 // If the newly generated derived pointer's type does not match the original derived 1099 // pointer's type, cast the new derived pointer to match it. Same reasoning as above. 1100 Value *ActualReplacement = Replacement; 1101 if (Replacement->getType() != ToReplace->getType()) { 1102 ActualReplacement = 1103 Builder.CreateBitCast(Replacement, ToReplace->getType()); 1104 } 1105 ToReplace->replaceAllUsesWith(ActualReplacement); 1106 ToReplace->eraseFromParent(); 1107 1108 MadeChange = true; 1109 } 1110 return MadeChange; 1111 } 1112 1113 // Turns this: 1114 // 1115 // %base = ... 1116 // %ptr = gep %base + 15 1117 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) 1118 // %base' = relocate(%tok, i32 4, i32 4) 1119 // %ptr' = relocate(%tok, i32 4, i32 5) 1120 // %val = load %ptr' 1121 // 1122 // into this: 1123 // 1124 // %base = ... 1125 // %ptr = gep %base + 15 1126 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) 1127 // %base' = gc.relocate(%tok, i32 4, i32 4) 1128 // %ptr' = gep %base' + 15 1129 // %val = load %ptr' 1130 bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) { 1131 bool MadeChange = false; 1132 SmallVector<GCRelocateInst *, 2> AllRelocateCalls; 1133 for (auto *U : I.users()) 1134 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) 1135 // Collect all the relocate calls associated with a statepoint 1136 AllRelocateCalls.push_back(Relocate); 1137 1138 // We need at least one base pointer relocation + one derived pointer 1139 // relocation to mangle 1140 if (AllRelocateCalls.size() < 2) 1141 return false; 1142 1143 // RelocateInstMap is a mapping from the base relocate instruction to the 1144 // corresponding derived relocate instructions 1145 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; 1146 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); 1147 if (RelocateInstMap.empty()) 1148 return false; 1149 1150 for (auto &Item : RelocateInstMap) 1151 // Item.first is the RelocatedBase to offset against 1152 // Item.second is the vector of Targets to replace 1153 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); 1154 return MadeChange; 1155 } 1156 1157 /// Sink the specified cast instruction into its user blocks. 1158 static bool SinkCast(CastInst *CI) { 1159 BasicBlock *DefBB = CI->getParent(); 1160 1161 /// InsertedCasts - Only insert a cast in each block once. 1162 DenseMap<BasicBlock*, CastInst*> InsertedCasts; 1163 1164 bool MadeChange = false; 1165 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); 1166 UI != E; ) { 1167 Use &TheUse = UI.getUse(); 1168 Instruction *User = cast<Instruction>(*UI); 1169 1170 // Figure out which BB this cast is used in. For PHI's this is the 1171 // appropriate predecessor block. 1172 BasicBlock *UserBB = User->getParent(); 1173 if (PHINode *PN = dyn_cast<PHINode>(User)) { 1174 UserBB = PN->getIncomingBlock(TheUse); 1175 } 1176 1177 // Preincrement use iterator so we don't invalidate it. 1178 ++UI; 1179 1180 // The first insertion point of a block containing an EH pad is after the 1181 // pad. If the pad is the user, we cannot sink the cast past the pad. 1182 if (User->isEHPad()) 1183 continue; 1184 1185 // If the block selected to receive the cast is an EH pad that does not 1186 // allow non-PHI instructions before the terminator, we can't sink the 1187 // cast. 1188 if (UserBB->getTerminator()->isEHPad()) 1189 continue; 1190 1191 // If this user is in the same block as the cast, don't change the cast. 1192 if (UserBB == DefBB) continue; 1193 1194 // If we have already inserted a cast into this block, use it. 1195 CastInst *&InsertedCast = InsertedCasts[UserBB]; 1196 1197 if (!InsertedCast) { 1198 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 1199 assert(InsertPt != UserBB->end()); 1200 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), 1201 CI->getType(), "", &*InsertPt); 1202 InsertedCast->setDebugLoc(CI->getDebugLoc()); 1203 } 1204 1205 // Replace a use of the cast with a use of the new cast. 1206 TheUse = InsertedCast; 1207 MadeChange = true; 1208 ++NumCastUses; 1209 } 1210 1211 // If we removed all uses, nuke the cast. 1212 if (CI->use_empty()) { 1213 salvageDebugInfo(*CI); 1214 CI->eraseFromParent(); 1215 MadeChange = true; 1216 } 1217 1218 return MadeChange; 1219 } 1220 1221 /// If the specified cast instruction is a noop copy (e.g. it's casting from 1222 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to 1223 /// reduce the number of virtual registers that must be created and coalesced. 1224 /// 1225 /// Return true if any changes are made. 1226 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, 1227 const DataLayout &DL) { 1228 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition 1229 // than sinking only nop casts, but is helpful on some platforms. 1230 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { 1231 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(), 1232 ASC->getDestAddressSpace())) 1233 return false; 1234 } 1235 1236 // If this is a noop copy, 1237 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); 1238 EVT DstVT = TLI.getValueType(DL, CI->getType()); 1239 1240 // This is an fp<->int conversion? 1241 if (SrcVT.isInteger() != DstVT.isInteger()) 1242 return false; 1243 1244 // If this is an extension, it will be a zero or sign extension, which 1245 // isn't a noop. 1246 if (SrcVT.bitsLT(DstVT)) return false; 1247 1248 // If these values will be promoted, find out what they will be promoted 1249 // to. This helps us consider truncates on PPC as noop copies when they 1250 // are. 1251 if (TLI.getTypeAction(CI->getContext(), SrcVT) == 1252 TargetLowering::TypePromoteInteger) 1253 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); 1254 if (TLI.getTypeAction(CI->getContext(), DstVT) == 1255 TargetLowering::TypePromoteInteger) 1256 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); 1257 1258 // If, after promotion, these are the same types, this is a noop copy. 1259 if (SrcVT != DstVT) 1260 return false; 1261 1262 return SinkCast(CI); 1263 } 1264 1265 bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO, 1266 Value *Arg0, Value *Arg1, 1267 CmpInst *Cmp, 1268 Intrinsic::ID IID) { 1269 if (BO->getParent() != Cmp->getParent()) { 1270 // We used to use a dominator tree here to allow multi-block optimization. 1271 // But that was problematic because: 1272 // 1. It could cause a perf regression by hoisting the math op into the 1273 // critical path. 1274 // 2. It could cause a perf regression by creating a value that was live 1275 // across multiple blocks and increasing register pressure. 1276 // 3. Use of a dominator tree could cause large compile-time regression. 1277 // This is because we recompute the DT on every change in the main CGP 1278 // run-loop. The recomputing is probably unnecessary in many cases, so if 1279 // that was fixed, using a DT here would be ok. 1280 return false; 1281 } 1282 1283 // We allow matching the canonical IR (add X, C) back to (usubo X, -C). 1284 if (BO->getOpcode() == Instruction::Add && 1285 IID == Intrinsic::usub_with_overflow) { 1286 assert(isa<Constant>(Arg1) && "Unexpected input for usubo"); 1287 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1)); 1288 } 1289 1290 // Insert at the first instruction of the pair. 1291 Instruction *InsertPt = nullptr; 1292 for (Instruction &Iter : *Cmp->getParent()) { 1293 // If BO is an XOR, it is not guaranteed that it comes after both inputs to 1294 // the overflow intrinsic are defined. 1295 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) { 1296 InsertPt = &Iter; 1297 break; 1298 } 1299 } 1300 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop"); 1301 1302 IRBuilder<> Builder(InsertPt); 1303 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1); 1304 if (BO->getOpcode() != Instruction::Xor) { 1305 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math"); 1306 BO->replaceAllUsesWith(Math); 1307 } else 1308 assert(BO->hasOneUse() && 1309 "Patterns with XOr should use the BO only in the compare"); 1310 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov"); 1311 Cmp->replaceAllUsesWith(OV); 1312 Cmp->eraseFromParent(); 1313 BO->eraseFromParent(); 1314 return true; 1315 } 1316 1317 /// Match special-case patterns that check for unsigned add overflow. 1318 static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, 1319 BinaryOperator *&Add) { 1320 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val) 1321 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero) 1322 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); 1323 1324 // We are not expecting non-canonical/degenerate code. Just bail out. 1325 if (isa<Constant>(A)) 1326 return false; 1327 1328 ICmpInst::Predicate Pred = Cmp->getPredicate(); 1329 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes())) 1330 B = ConstantInt::get(B->getType(), 1); 1331 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) 1332 B = ConstantInt::get(B->getType(), -1); 1333 else 1334 return false; 1335 1336 // Check the users of the variable operand of the compare looking for an add 1337 // with the adjusted constant. 1338 for (User *U : A->users()) { 1339 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) { 1340 Add = cast<BinaryOperator>(U); 1341 return true; 1342 } 1343 } 1344 return false; 1345 } 1346 1347 /// Try to combine the compare into a call to the llvm.uadd.with.overflow 1348 /// intrinsic. Return true if any changes were made. 1349 bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp, 1350 bool &ModifiedDT) { 1351 Value *A, *B; 1352 BinaryOperator *Add; 1353 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) { 1354 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add)) 1355 return false; 1356 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases. 1357 A = Add->getOperand(0); 1358 B = Add->getOperand(1); 1359 } 1360 1361 if (!TLI->shouldFormOverflowOp(ISD::UADDO, 1362 TLI->getValueType(*DL, Add->getType()), 1363 Add->hasNUsesOrMore(2))) 1364 return false; 1365 1366 // We don't want to move around uses of condition values this late, so we 1367 // check if it is legal to create the call to the intrinsic in the basic 1368 // block containing the icmp. 1369 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse()) 1370 return false; 1371 1372 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp, 1373 Intrinsic::uadd_with_overflow)) 1374 return false; 1375 1376 // Reset callers - do not crash by iterating over a dead instruction. 1377 ModifiedDT = true; 1378 return true; 1379 } 1380 1381 bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp, 1382 bool &ModifiedDT) { 1383 // We are not expecting non-canonical/degenerate code. Just bail out. 1384 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); 1385 if (isa<Constant>(A) && isa<Constant>(B)) 1386 return false; 1387 1388 // Convert (A u> B) to (A u< B) to simplify pattern matching. 1389 ICmpInst::Predicate Pred = Cmp->getPredicate(); 1390 if (Pred == ICmpInst::ICMP_UGT) { 1391 std::swap(A, B); 1392 Pred = ICmpInst::ICMP_ULT; 1393 } 1394 // Convert special-case: (A == 0) is the same as (A u< 1). 1395 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) { 1396 B = ConstantInt::get(B->getType(), 1); 1397 Pred = ICmpInst::ICMP_ULT; 1398 } 1399 // Convert special-case: (A != 0) is the same as (0 u< A). 1400 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) { 1401 std::swap(A, B); 1402 Pred = ICmpInst::ICMP_ULT; 1403 } 1404 if (Pred != ICmpInst::ICMP_ULT) 1405 return false; 1406 1407 // Walk the users of a variable operand of a compare looking for a subtract or 1408 // add with that same operand. Also match the 2nd operand of the compare to 1409 // the add/sub, but that may be a negated constant operand of an add. 1410 Value *CmpVariableOperand = isa<Constant>(A) ? B : A; 1411 BinaryOperator *Sub = nullptr; 1412 for (User *U : CmpVariableOperand->users()) { 1413 // A - B, A u< B --> usubo(A, B) 1414 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) { 1415 Sub = cast<BinaryOperator>(U); 1416 break; 1417 } 1418 1419 // A + (-C), A u< C (canonicalized form of (sub A, C)) 1420 const APInt *CmpC, *AddC; 1421 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) && 1422 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) { 1423 Sub = cast<BinaryOperator>(U); 1424 break; 1425 } 1426 } 1427 if (!Sub) 1428 return false; 1429 1430 if (!TLI->shouldFormOverflowOp(ISD::USUBO, 1431 TLI->getValueType(*DL, Sub->getType()), 1432 Sub->hasNUsesOrMore(2))) 1433 return false; 1434 1435 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1), 1436 Cmp, Intrinsic::usub_with_overflow)) 1437 return false; 1438 1439 // Reset callers - do not crash by iterating over a dead instruction. 1440 ModifiedDT = true; 1441 return true; 1442 } 1443 1444 /// Sink the given CmpInst into user blocks to reduce the number of virtual 1445 /// registers that must be created and coalesced. This is a clear win except on 1446 /// targets with multiple condition code registers (PowerPC), where it might 1447 /// lose; some adjustment may be wanted there. 1448 /// 1449 /// Return true if any changes are made. 1450 static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) { 1451 if (TLI.hasMultipleConditionRegisters()) 1452 return false; 1453 1454 // Avoid sinking soft-FP comparisons, since this can move them into a loop. 1455 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp)) 1456 return false; 1457 1458 // Only insert a cmp in each block once. 1459 DenseMap<BasicBlock*, CmpInst*> InsertedCmps; 1460 1461 bool MadeChange = false; 1462 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end(); 1463 UI != E; ) { 1464 Use &TheUse = UI.getUse(); 1465 Instruction *User = cast<Instruction>(*UI); 1466 1467 // Preincrement use iterator so we don't invalidate it. 1468 ++UI; 1469 1470 // Don't bother for PHI nodes. 1471 if (isa<PHINode>(User)) 1472 continue; 1473 1474 // Figure out which BB this cmp is used in. 1475 BasicBlock *UserBB = User->getParent(); 1476 BasicBlock *DefBB = Cmp->getParent(); 1477 1478 // If this user is in the same block as the cmp, don't change the cmp. 1479 if (UserBB == DefBB) continue; 1480 1481 // If we have already inserted a cmp into this block, use it. 1482 CmpInst *&InsertedCmp = InsertedCmps[UserBB]; 1483 1484 if (!InsertedCmp) { 1485 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 1486 assert(InsertPt != UserBB->end()); 1487 InsertedCmp = 1488 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), 1489 Cmp->getOperand(0), Cmp->getOperand(1), "", 1490 &*InsertPt); 1491 // Propagate the debug info. 1492 InsertedCmp->setDebugLoc(Cmp->getDebugLoc()); 1493 } 1494 1495 // Replace a use of the cmp with a use of the new cmp. 1496 TheUse = InsertedCmp; 1497 MadeChange = true; 1498 ++NumCmpUses; 1499 } 1500 1501 // If we removed all uses, nuke the cmp. 1502 if (Cmp->use_empty()) { 1503 Cmp->eraseFromParent(); 1504 MadeChange = true; 1505 } 1506 1507 return MadeChange; 1508 } 1509 1510 /// For pattern like: 1511 /// 1512 /// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB) 1513 /// ... 1514 /// DomBB: 1515 /// ... 1516 /// br DomCond, TrueBB, CmpBB 1517 /// CmpBB: (with DomBB being the single predecessor) 1518 /// ... 1519 /// Cmp = icmp eq CmpOp0, CmpOp1 1520 /// ... 1521 /// 1522 /// It would use two comparison on targets that lowering of icmp sgt/slt is 1523 /// different from lowering of icmp eq (PowerPC). This function try to convert 1524 /// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'. 1525 /// After that, DomCond and Cmp can use the same comparison so reduce one 1526 /// comparison. 1527 /// 1528 /// Return true if any changes are made. 1529 static bool foldICmpWithDominatingICmp(CmpInst *Cmp, 1530 const TargetLowering &TLI) { 1531 if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp()) 1532 return false; 1533 1534 ICmpInst::Predicate Pred = Cmp->getPredicate(); 1535 if (Pred != ICmpInst::ICMP_EQ) 1536 return false; 1537 1538 // If icmp eq has users other than BranchInst and SelectInst, converting it to 1539 // icmp slt/sgt would introduce more redundant LLVM IR. 1540 for (User *U : Cmp->users()) { 1541 if (isa<BranchInst>(U)) 1542 continue; 1543 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp) 1544 continue; 1545 return false; 1546 } 1547 1548 // This is a cheap/incomplete check for dominance - just match a single 1549 // predecessor with a conditional branch. 1550 BasicBlock *CmpBB = Cmp->getParent(); 1551 BasicBlock *DomBB = CmpBB->getSinglePredecessor(); 1552 if (!DomBB) 1553 return false; 1554 1555 // We want to ensure that the only way control gets to the comparison of 1556 // interest is that a less/greater than comparison on the same operands is 1557 // false. 1558 Value *DomCond; 1559 BasicBlock *TrueBB, *FalseBB; 1560 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB))) 1561 return false; 1562 if (CmpBB != FalseBB) 1563 return false; 1564 1565 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1); 1566 ICmpInst::Predicate DomPred; 1567 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1)))) 1568 return false; 1569 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT) 1570 return false; 1571 1572 // Convert the equality comparison to the opposite of the dominating 1573 // comparison and swap the direction for all branch/select users. 1574 // We have conceptually converted: 1575 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>; 1576 // to 1577 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>; 1578 // And similarly for branches. 1579 for (User *U : Cmp->users()) { 1580 if (auto *BI = dyn_cast<BranchInst>(U)) { 1581 assert(BI->isConditional() && "Must be conditional"); 1582 BI->swapSuccessors(); 1583 continue; 1584 } 1585 if (auto *SI = dyn_cast<SelectInst>(U)) { 1586 // Swap operands 1587 SI->swapValues(); 1588 SI->swapProfMetadata(); 1589 continue; 1590 } 1591 llvm_unreachable("Must be a branch or a select"); 1592 } 1593 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred)); 1594 return true; 1595 } 1596 1597 bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) { 1598 if (sinkCmpExpression(Cmp, *TLI)) 1599 return true; 1600 1601 if (combineToUAddWithOverflow(Cmp, ModifiedDT)) 1602 return true; 1603 1604 if (combineToUSubWithOverflow(Cmp, ModifiedDT)) 1605 return true; 1606 1607 if (foldICmpWithDominatingICmp(Cmp, *TLI)) 1608 return true; 1609 1610 return false; 1611 } 1612 1613 /// Duplicate and sink the given 'and' instruction into user blocks where it is 1614 /// used in a compare to allow isel to generate better code for targets where 1615 /// this operation can be combined. 1616 /// 1617 /// Return true if any changes are made. 1618 static bool sinkAndCmp0Expression(Instruction *AndI, 1619 const TargetLowering &TLI, 1620 SetOfInstrs &InsertedInsts) { 1621 // Double-check that we're not trying to optimize an instruction that was 1622 // already optimized by some other part of this pass. 1623 assert(!InsertedInsts.count(AndI) && 1624 "Attempting to optimize already optimized and instruction"); 1625 (void) InsertedInsts; 1626 1627 // Nothing to do for single use in same basic block. 1628 if (AndI->hasOneUse() && 1629 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) 1630 return false; 1631 1632 // Try to avoid cases where sinking/duplicating is likely to increase register 1633 // pressure. 1634 if (!isa<ConstantInt>(AndI->getOperand(0)) && 1635 !isa<ConstantInt>(AndI->getOperand(1)) && 1636 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) 1637 return false; 1638 1639 for (auto *U : AndI->users()) { 1640 Instruction *User = cast<Instruction>(U); 1641 1642 // Only sink 'and' feeding icmp with 0. 1643 if (!isa<ICmpInst>(User)) 1644 return false; 1645 1646 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); 1647 if (!CmpC || !CmpC->isZero()) 1648 return false; 1649 } 1650 1651 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) 1652 return false; 1653 1654 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n"); 1655 LLVM_DEBUG(AndI->getParent()->dump()); 1656 1657 // Push the 'and' into the same block as the icmp 0. There should only be 1658 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any 1659 // others, so we don't need to keep track of which BBs we insert into. 1660 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); 1661 UI != E; ) { 1662 Use &TheUse = UI.getUse(); 1663 Instruction *User = cast<Instruction>(*UI); 1664 1665 // Preincrement use iterator so we don't invalidate it. 1666 ++UI; 1667 1668 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n"); 1669 1670 // Keep the 'and' in the same place if the use is already in the same block. 1671 Instruction *InsertPt = 1672 User->getParent() == AndI->getParent() ? AndI : User; 1673 Instruction *InsertedAnd = 1674 BinaryOperator::Create(Instruction::And, AndI->getOperand(0), 1675 AndI->getOperand(1), "", InsertPt); 1676 // Propagate the debug info. 1677 InsertedAnd->setDebugLoc(AndI->getDebugLoc()); 1678 1679 // Replace a use of the 'and' with a use of the new 'and'. 1680 TheUse = InsertedAnd; 1681 ++NumAndUses; 1682 LLVM_DEBUG(User->getParent()->dump()); 1683 } 1684 1685 // We removed all uses, nuke the and. 1686 AndI->eraseFromParent(); 1687 return true; 1688 } 1689 1690 /// Check if the candidates could be combined with a shift instruction, which 1691 /// includes: 1692 /// 1. Truncate instruction 1693 /// 2. And instruction and the imm is a mask of the low bits: 1694 /// imm & (imm+1) == 0 1695 static bool isExtractBitsCandidateUse(Instruction *User) { 1696 if (!isa<TruncInst>(User)) { 1697 if (User->getOpcode() != Instruction::And || 1698 !isa<ConstantInt>(User->getOperand(1))) 1699 return false; 1700 1701 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); 1702 1703 if ((Cimm & (Cimm + 1)).getBoolValue()) 1704 return false; 1705 } 1706 return true; 1707 } 1708 1709 /// Sink both shift and truncate instruction to the use of truncate's BB. 1710 static bool 1711 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, 1712 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, 1713 const TargetLowering &TLI, const DataLayout &DL) { 1714 BasicBlock *UserBB = User->getParent(); 1715 DenseMap<BasicBlock *, CastInst *> InsertedTruncs; 1716 auto *TruncI = cast<TruncInst>(User); 1717 bool MadeChange = false; 1718 1719 for (Value::user_iterator TruncUI = TruncI->user_begin(), 1720 TruncE = TruncI->user_end(); 1721 TruncUI != TruncE;) { 1722 1723 Use &TruncTheUse = TruncUI.getUse(); 1724 Instruction *TruncUser = cast<Instruction>(*TruncUI); 1725 // Preincrement use iterator so we don't invalidate it. 1726 1727 ++TruncUI; 1728 1729 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); 1730 if (!ISDOpcode) 1731 continue; 1732 1733 // If the use is actually a legal node, there will not be an 1734 // implicit truncate. 1735 // FIXME: always querying the result type is just an 1736 // approximation; some nodes' legality is determined by the 1737 // operand or other means. There's no good way to find out though. 1738 if (TLI.isOperationLegalOrCustom( 1739 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) 1740 continue; 1741 1742 // Don't bother for PHI nodes. 1743 if (isa<PHINode>(TruncUser)) 1744 continue; 1745 1746 BasicBlock *TruncUserBB = TruncUser->getParent(); 1747 1748 if (UserBB == TruncUserBB) 1749 continue; 1750 1751 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; 1752 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; 1753 1754 if (!InsertedShift && !InsertedTrunc) { 1755 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); 1756 assert(InsertPt != TruncUserBB->end()); 1757 // Sink the shift 1758 if (ShiftI->getOpcode() == Instruction::AShr) 1759 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, 1760 "", &*InsertPt); 1761 else 1762 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, 1763 "", &*InsertPt); 1764 InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); 1765 1766 // Sink the trunc 1767 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); 1768 TruncInsertPt++; 1769 assert(TruncInsertPt != TruncUserBB->end()); 1770 1771 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, 1772 TruncI->getType(), "", &*TruncInsertPt); 1773 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc()); 1774 1775 MadeChange = true; 1776 1777 TruncTheUse = InsertedTrunc; 1778 } 1779 } 1780 return MadeChange; 1781 } 1782 1783 /// Sink the shift *right* instruction into user blocks if the uses could 1784 /// potentially be combined with this shift instruction and generate BitExtract 1785 /// instruction. It will only be applied if the architecture supports BitExtract 1786 /// instruction. Here is an example: 1787 /// BB1: 1788 /// %x.extract.shift = lshr i64 %arg1, 32 1789 /// BB2: 1790 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 1791 /// ==> 1792 /// 1793 /// BB2: 1794 /// %x.extract.shift.1 = lshr i64 %arg1, 32 1795 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 1796 /// 1797 /// CodeGen will recognize the pattern in BB2 and generate BitExtract 1798 /// instruction. 1799 /// Return true if any changes are made. 1800 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, 1801 const TargetLowering &TLI, 1802 const DataLayout &DL) { 1803 BasicBlock *DefBB = ShiftI->getParent(); 1804 1805 /// Only insert instructions in each block once. 1806 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; 1807 1808 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); 1809 1810 bool MadeChange = false; 1811 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); 1812 UI != E;) { 1813 Use &TheUse = UI.getUse(); 1814 Instruction *User = cast<Instruction>(*UI); 1815 // Preincrement use iterator so we don't invalidate it. 1816 ++UI; 1817 1818 // Don't bother for PHI nodes. 1819 if (isa<PHINode>(User)) 1820 continue; 1821 1822 if (!isExtractBitsCandidateUse(User)) 1823 continue; 1824 1825 BasicBlock *UserBB = User->getParent(); 1826 1827 if (UserBB == DefBB) { 1828 // If the shift and truncate instruction are in the same BB. The use of 1829 // the truncate(TruncUse) may still introduce another truncate if not 1830 // legal. In this case, we would like to sink both shift and truncate 1831 // instruction to the BB of TruncUse. 1832 // for example: 1833 // BB1: 1834 // i64 shift.result = lshr i64 opnd, imm 1835 // trunc.result = trunc shift.result to i16 1836 // 1837 // BB2: 1838 // ----> We will have an implicit truncate here if the architecture does 1839 // not have i16 compare. 1840 // cmp i16 trunc.result, opnd2 1841 // 1842 if (isa<TruncInst>(User) && shiftIsLegal 1843 // If the type of the truncate is legal, no truncate will be 1844 // introduced in other basic blocks. 1845 && 1846 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) 1847 MadeChange = 1848 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); 1849 1850 continue; 1851 } 1852 // If we have already inserted a shift into this block, use it. 1853 BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; 1854 1855 if (!InsertedShift) { 1856 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 1857 assert(InsertPt != UserBB->end()); 1858 1859 if (ShiftI->getOpcode() == Instruction::AShr) 1860 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, 1861 "", &*InsertPt); 1862 else 1863 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, 1864 "", &*InsertPt); 1865 InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); 1866 1867 MadeChange = true; 1868 } 1869 1870 // Replace a use of the shift with a use of the new shift. 1871 TheUse = InsertedShift; 1872 } 1873 1874 // If we removed all uses, or there are none, nuke the shift. 1875 if (ShiftI->use_empty()) { 1876 salvageDebugInfo(*ShiftI); 1877 ShiftI->eraseFromParent(); 1878 MadeChange = true; 1879 } 1880 1881 return MadeChange; 1882 } 1883 1884 /// If counting leading or trailing zeros is an expensive operation and a zero 1885 /// input is defined, add a check for zero to avoid calling the intrinsic. 1886 /// 1887 /// We want to transform: 1888 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) 1889 /// 1890 /// into: 1891 /// entry: 1892 /// %cmpz = icmp eq i64 %A, 0 1893 /// br i1 %cmpz, label %cond.end, label %cond.false 1894 /// cond.false: 1895 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) 1896 /// br label %cond.end 1897 /// cond.end: 1898 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] 1899 /// 1900 /// If the transform is performed, return true and set ModifiedDT to true. 1901 static bool despeculateCountZeros(IntrinsicInst *CountZeros, 1902 const TargetLowering *TLI, 1903 const DataLayout *DL, 1904 bool &ModifiedDT) { 1905 // If a zero input is undefined, it doesn't make sense to despeculate that. 1906 if (match(CountZeros->getOperand(1), m_One())) 1907 return false; 1908 1909 // If it's cheap to speculate, there's nothing to do. 1910 auto IntrinsicID = CountZeros->getIntrinsicID(); 1911 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || 1912 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) 1913 return false; 1914 1915 // Only handle legal scalar cases. Anything else requires too much work. 1916 Type *Ty = CountZeros->getType(); 1917 unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); 1918 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) 1919 return false; 1920 1921 // The intrinsic will be sunk behind a compare against zero and branch. 1922 BasicBlock *StartBlock = CountZeros->getParent(); 1923 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); 1924 1925 // Create another block after the count zero intrinsic. A PHI will be added 1926 // in this block to select the result of the intrinsic or the bit-width 1927 // constant if the input to the intrinsic is zero. 1928 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); 1929 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); 1930 1931 // Set up a builder to create a compare, conditional branch, and PHI. 1932 IRBuilder<> Builder(CountZeros->getContext()); 1933 Builder.SetInsertPoint(StartBlock->getTerminator()); 1934 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); 1935 1936 // Replace the unconditional branch that was created by the first split with 1937 // a compare against zero and a conditional branch. 1938 Value *Zero = Constant::getNullValue(Ty); 1939 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); 1940 Builder.CreateCondBr(Cmp, EndBlock, CallBlock); 1941 StartBlock->getTerminator()->eraseFromParent(); 1942 1943 // Create a PHI in the end block to select either the output of the intrinsic 1944 // or the bit width of the operand. 1945 Builder.SetInsertPoint(&EndBlock->front()); 1946 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); 1947 CountZeros->replaceAllUsesWith(PN); 1948 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); 1949 PN->addIncoming(BitWidth, StartBlock); 1950 PN->addIncoming(CountZeros, CallBlock); 1951 1952 // We are explicitly handling the zero case, so we can set the intrinsic's 1953 // undefined zero argument to 'true'. This will also prevent reprocessing the 1954 // intrinsic; we only despeculate when a zero input is defined. 1955 CountZeros->setArgOperand(1, Builder.getTrue()); 1956 ModifiedDT = true; 1957 return true; 1958 } 1959 1960 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) { 1961 BasicBlock *BB = CI->getParent(); 1962 1963 // Lower inline assembly if we can. 1964 // If we found an inline asm expession, and if the target knows how to 1965 // lower it to normal LLVM code, do so now. 1966 if (CI->isInlineAsm()) { 1967 if (TLI->ExpandInlineAsm(CI)) { 1968 // Avoid invalidating the iterator. 1969 CurInstIterator = BB->begin(); 1970 // Avoid processing instructions out of order, which could cause 1971 // reuse before a value is defined. 1972 SunkAddrs.clear(); 1973 return true; 1974 } 1975 // Sink address computing for memory operands into the block. 1976 if (optimizeInlineAsmInst(CI)) 1977 return true; 1978 } 1979 1980 // Align the pointer arguments to this call if the target thinks it's a good 1981 // idea 1982 unsigned MinSize, PrefAlign; 1983 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { 1984 for (auto &Arg : CI->arg_operands()) { 1985 // We want to align both objects whose address is used directly and 1986 // objects whose address is used in casts and GEPs, though it only makes 1987 // sense for GEPs if the offset is a multiple of the desired alignment and 1988 // if size - offset meets the size threshold. 1989 if (!Arg->getType()->isPointerTy()) 1990 continue; 1991 APInt Offset(DL->getIndexSizeInBits( 1992 cast<PointerType>(Arg->getType())->getAddressSpace()), 1993 0); 1994 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); 1995 uint64_t Offset2 = Offset.getLimitedValue(); 1996 if ((Offset2 & (PrefAlign-1)) != 0) 1997 continue; 1998 AllocaInst *AI; 1999 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && 2000 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) 2001 AI->setAlignment(Align(PrefAlign)); 2002 // Global variables can only be aligned if they are defined in this 2003 // object (i.e. they are uniquely initialized in this object), and 2004 // over-aligning global variables that have an explicit section is 2005 // forbidden. 2006 GlobalVariable *GV; 2007 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && 2008 GV->getPointerAlignment(*DL) < PrefAlign && 2009 DL->getTypeAllocSize(GV->getValueType()) >= 2010 MinSize + Offset2) 2011 GV->setAlignment(MaybeAlign(PrefAlign)); 2012 } 2013 // If this is a memcpy (or similar) then we may be able to improve the 2014 // alignment 2015 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { 2016 Align DestAlign = getKnownAlignment(MI->getDest(), *DL); 2017 MaybeAlign MIDestAlign = MI->getDestAlign(); 2018 if (!MIDestAlign || DestAlign > *MIDestAlign) 2019 MI->setDestAlignment(DestAlign); 2020 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { 2021 MaybeAlign MTISrcAlign = MTI->getSourceAlign(); 2022 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL); 2023 if (!MTISrcAlign || SrcAlign > *MTISrcAlign) 2024 MTI->setSourceAlignment(SrcAlign); 2025 } 2026 } 2027 } 2028 2029 // If we have a cold call site, try to sink addressing computation into the 2030 // cold block. This interacts with our handling for loads and stores to 2031 // ensure that we can fold all uses of a potential addressing computation 2032 // into their uses. TODO: generalize this to work over profiling data 2033 if (CI->hasFnAttr(Attribute::Cold) && 2034 !OptSize && !llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) 2035 for (auto &Arg : CI->arg_operands()) { 2036 if (!Arg->getType()->isPointerTy()) 2037 continue; 2038 unsigned AS = Arg->getType()->getPointerAddressSpace(); 2039 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); 2040 } 2041 2042 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); 2043 if (II) { 2044 switch (II->getIntrinsicID()) { 2045 default: break; 2046 case Intrinsic::assume: { 2047 Value *Operand = II->getOperand(0); 2048 II->eraseFromParent(); 2049 // Prune the operand, it's most likely dead. 2050 RecursivelyDeleteTriviallyDeadInstructions( 2051 Operand, TLInfo, nullptr, 2052 [&](Value *V) { removeAllAssertingVHReferences(V); }); 2053 return true; 2054 } 2055 2056 case Intrinsic::experimental_widenable_condition: { 2057 // Give up on future widening oppurtunties so that we can fold away dead 2058 // paths and merge blocks before going into block-local instruction 2059 // selection. 2060 if (II->use_empty()) { 2061 II->eraseFromParent(); 2062 return true; 2063 } 2064 Constant *RetVal = ConstantInt::getTrue(II->getContext()); 2065 resetIteratorIfInvalidatedWhileCalling(BB, [&]() { 2066 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); 2067 }); 2068 return true; 2069 } 2070 case Intrinsic::objectsize: 2071 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 2072 case Intrinsic::is_constant: 2073 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 2074 case Intrinsic::aarch64_stlxr: 2075 case Intrinsic::aarch64_stxr: { 2076 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); 2077 if (!ExtVal || !ExtVal->hasOneUse() || 2078 ExtVal->getParent() == CI->getParent()) 2079 return false; 2080 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. 2081 ExtVal->moveBefore(CI); 2082 // Mark this instruction as "inserted by CGP", so that other 2083 // optimizations don't touch it. 2084 InsertedInsts.insert(ExtVal); 2085 return true; 2086 } 2087 2088 case Intrinsic::launder_invariant_group: 2089 case Intrinsic::strip_invariant_group: { 2090 Value *ArgVal = II->getArgOperand(0); 2091 auto it = LargeOffsetGEPMap.find(II); 2092 if (it != LargeOffsetGEPMap.end()) { 2093 // Merge entries in LargeOffsetGEPMap to reflect the RAUW. 2094 // Make sure not to have to deal with iterator invalidation 2095 // after possibly adding ArgVal to LargeOffsetGEPMap. 2096 auto GEPs = std::move(it->second); 2097 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end()); 2098 LargeOffsetGEPMap.erase(II); 2099 } 2100 2101 II->replaceAllUsesWith(ArgVal); 2102 II->eraseFromParent(); 2103 return true; 2104 } 2105 case Intrinsic::cttz: 2106 case Intrinsic::ctlz: 2107 // If counting zeros is expensive, try to avoid it. 2108 return despeculateCountZeros(II, TLI, DL, ModifiedDT); 2109 case Intrinsic::fshl: 2110 case Intrinsic::fshr: 2111 return optimizeFunnelShift(II); 2112 case Intrinsic::dbg_value: 2113 return fixupDbgValue(II); 2114 case Intrinsic::vscale: { 2115 // If datalayout has no special restrictions on vector data layout, 2116 // replace `llvm.vscale` by an equivalent constant expression 2117 // to benefit from cheap constant propagation. 2118 Type *ScalableVectorTy = 2119 VectorType::get(Type::getInt8Ty(II->getContext()), 1, true); 2120 if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinSize() == 8) { 2121 auto *Null = Constant::getNullValue(ScalableVectorTy->getPointerTo()); 2122 auto *One = ConstantInt::getSigned(II->getType(), 1); 2123 auto *CGep = 2124 ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One); 2125 II->replaceAllUsesWith(ConstantExpr::getPtrToInt(CGep, II->getType())); 2126 II->eraseFromParent(); 2127 return true; 2128 } 2129 break; 2130 } 2131 case Intrinsic::masked_gather: 2132 return optimizeGatherScatterInst(II, II->getArgOperand(0)); 2133 case Intrinsic::masked_scatter: 2134 return optimizeGatherScatterInst(II, II->getArgOperand(1)); 2135 } 2136 2137 SmallVector<Value *, 2> PtrOps; 2138 Type *AccessTy; 2139 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) 2140 while (!PtrOps.empty()) { 2141 Value *PtrVal = PtrOps.pop_back_val(); 2142 unsigned AS = PtrVal->getType()->getPointerAddressSpace(); 2143 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) 2144 return true; 2145 } 2146 } 2147 2148 // From here on out we're working with named functions. 2149 if (!CI->getCalledFunction()) return false; 2150 2151 // Lower all default uses of _chk calls. This is very similar 2152 // to what InstCombineCalls does, but here we are only lowering calls 2153 // to fortified library functions (e.g. __memcpy_chk) that have the default 2154 // "don't know" as the objectsize. Anything else should be left alone. 2155 FortifiedLibCallSimplifier Simplifier(TLInfo, true); 2156 IRBuilder<> Builder(CI); 2157 if (Value *V = Simplifier.optimizeCall(CI, Builder)) { 2158 CI->replaceAllUsesWith(V); 2159 CI->eraseFromParent(); 2160 return true; 2161 } 2162 2163 return false; 2164 } 2165 2166 /// Look for opportunities to duplicate return instructions to the predecessor 2167 /// to enable tail call optimizations. The case it is currently looking for is: 2168 /// @code 2169 /// bb0: 2170 /// %tmp0 = tail call i32 @f0() 2171 /// br label %return 2172 /// bb1: 2173 /// %tmp1 = tail call i32 @f1() 2174 /// br label %return 2175 /// bb2: 2176 /// %tmp2 = tail call i32 @f2() 2177 /// br label %return 2178 /// return: 2179 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] 2180 /// ret i32 %retval 2181 /// @endcode 2182 /// 2183 /// => 2184 /// 2185 /// @code 2186 /// bb0: 2187 /// %tmp0 = tail call i32 @f0() 2188 /// ret i32 %tmp0 2189 /// bb1: 2190 /// %tmp1 = tail call i32 @f1() 2191 /// ret i32 %tmp1 2192 /// bb2: 2193 /// %tmp2 = tail call i32 @f2() 2194 /// ret i32 %tmp2 2195 /// @endcode 2196 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) { 2197 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); 2198 if (!RetI) 2199 return false; 2200 2201 PHINode *PN = nullptr; 2202 ExtractValueInst *EVI = nullptr; 2203 BitCastInst *BCI = nullptr; 2204 Value *V = RetI->getReturnValue(); 2205 if (V) { 2206 BCI = dyn_cast<BitCastInst>(V); 2207 if (BCI) 2208 V = BCI->getOperand(0); 2209 2210 EVI = dyn_cast<ExtractValueInst>(V); 2211 if (EVI) { 2212 V = EVI->getOperand(0); 2213 if (!std::all_of(EVI->idx_begin(), EVI->idx_end(), 2214 [](unsigned idx) { return idx == 0; })) 2215 return false; 2216 } 2217 2218 PN = dyn_cast<PHINode>(V); 2219 if (!PN) 2220 return false; 2221 } 2222 2223 if (PN && PN->getParent() != BB) 2224 return false; 2225 2226 // Make sure there are no instructions between the PHI and return, or that the 2227 // return is the first instruction in the block. 2228 if (PN) { 2229 BasicBlock::iterator BI = BB->begin(); 2230 // Skip over debug and the bitcast. 2231 do { 2232 ++BI; 2233 } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI || &*BI == EVI); 2234 if (&*BI != RetI) 2235 return false; 2236 } else { 2237 BasicBlock::iterator BI = BB->begin(); 2238 while (isa<DbgInfoIntrinsic>(BI)) ++BI; 2239 if (&*BI != RetI) 2240 return false; 2241 } 2242 2243 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail 2244 /// call. 2245 const Function *F = BB->getParent(); 2246 SmallVector<BasicBlock*, 4> TailCallBBs; 2247 if (PN) { 2248 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { 2249 // Look through bitcasts. 2250 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts(); 2251 CallInst *CI = dyn_cast<CallInst>(IncomingVal); 2252 BasicBlock *PredBB = PN->getIncomingBlock(I); 2253 // Make sure the phi value is indeed produced by the tail call. 2254 if (CI && CI->hasOneUse() && CI->getParent() == PredBB && 2255 TLI->mayBeEmittedAsTailCall(CI) && 2256 attributesPermitTailCall(F, CI, RetI, *TLI)) 2257 TailCallBBs.push_back(PredBB); 2258 } 2259 } else { 2260 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 2261 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { 2262 if (!VisitedBBs.insert(*PI).second) 2263 continue; 2264 2265 BasicBlock::InstListType &InstList = (*PI)->getInstList(); 2266 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); 2267 BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); 2268 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); 2269 if (RI == RE) 2270 continue; 2271 2272 CallInst *CI = dyn_cast<CallInst>(&*RI); 2273 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && 2274 attributesPermitTailCall(F, CI, RetI, *TLI)) 2275 TailCallBBs.push_back(*PI); 2276 } 2277 } 2278 2279 bool Changed = false; 2280 for (auto const &TailCallBB : TailCallBBs) { 2281 // Make sure the call instruction is followed by an unconditional branch to 2282 // the return block. 2283 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator()); 2284 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) 2285 continue; 2286 2287 // Duplicate the return into TailCallBB. 2288 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB); 2289 assert(!VerifyBFIUpdates || 2290 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB)); 2291 BFI->setBlockFreq( 2292 BB, 2293 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency()); 2294 ModifiedDT = Changed = true; 2295 ++NumRetsDup; 2296 } 2297 2298 // If we eliminated all predecessors of the block, delete the block now. 2299 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) 2300 BB->eraseFromParent(); 2301 2302 return Changed; 2303 } 2304 2305 //===----------------------------------------------------------------------===// 2306 // Memory Optimization 2307 //===----------------------------------------------------------------------===// 2308 2309 namespace { 2310 2311 /// This is an extended version of TargetLowering::AddrMode 2312 /// which holds actual Value*'s for register values. 2313 struct ExtAddrMode : public TargetLowering::AddrMode { 2314 Value *BaseReg = nullptr; 2315 Value *ScaledReg = nullptr; 2316 Value *OriginalValue = nullptr; 2317 bool InBounds = true; 2318 2319 enum FieldName { 2320 NoField = 0x00, 2321 BaseRegField = 0x01, 2322 BaseGVField = 0x02, 2323 BaseOffsField = 0x04, 2324 ScaledRegField = 0x08, 2325 ScaleField = 0x10, 2326 MultipleFields = 0xff 2327 }; 2328 2329 2330 ExtAddrMode() = default; 2331 2332 void print(raw_ostream &OS) const; 2333 void dump() const; 2334 2335 FieldName compare(const ExtAddrMode &other) { 2336 // First check that the types are the same on each field, as differing types 2337 // is something we can't cope with later on. 2338 if (BaseReg && other.BaseReg && 2339 BaseReg->getType() != other.BaseReg->getType()) 2340 return MultipleFields; 2341 if (BaseGV && other.BaseGV && 2342 BaseGV->getType() != other.BaseGV->getType()) 2343 return MultipleFields; 2344 if (ScaledReg && other.ScaledReg && 2345 ScaledReg->getType() != other.ScaledReg->getType()) 2346 return MultipleFields; 2347 2348 // Conservatively reject 'inbounds' mismatches. 2349 if (InBounds != other.InBounds) 2350 return MultipleFields; 2351 2352 // Check each field to see if it differs. 2353 unsigned Result = NoField; 2354 if (BaseReg != other.BaseReg) 2355 Result |= BaseRegField; 2356 if (BaseGV != other.BaseGV) 2357 Result |= BaseGVField; 2358 if (BaseOffs != other.BaseOffs) 2359 Result |= BaseOffsField; 2360 if (ScaledReg != other.ScaledReg) 2361 Result |= ScaledRegField; 2362 // Don't count 0 as being a different scale, because that actually means 2363 // unscaled (which will already be counted by having no ScaledReg). 2364 if (Scale && other.Scale && Scale != other.Scale) 2365 Result |= ScaleField; 2366 2367 if (countPopulation(Result) > 1) 2368 return MultipleFields; 2369 else 2370 return static_cast<FieldName>(Result); 2371 } 2372 2373 // An AddrMode is trivial if it involves no calculation i.e. it is just a base 2374 // with no offset. 2375 bool isTrivial() { 2376 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is 2377 // trivial if at most one of these terms is nonzero, except that BaseGV and 2378 // BaseReg both being zero actually means a null pointer value, which we 2379 // consider to be 'non-zero' here. 2380 return !BaseOffs && !Scale && !(BaseGV && BaseReg); 2381 } 2382 2383 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) { 2384 switch (Field) { 2385 default: 2386 return nullptr; 2387 case BaseRegField: 2388 return BaseReg; 2389 case BaseGVField: 2390 return BaseGV; 2391 case ScaledRegField: 2392 return ScaledReg; 2393 case BaseOffsField: 2394 return ConstantInt::get(IntPtrTy, BaseOffs); 2395 } 2396 } 2397 2398 void SetCombinedField(FieldName Field, Value *V, 2399 const SmallVectorImpl<ExtAddrMode> &AddrModes) { 2400 switch (Field) { 2401 default: 2402 llvm_unreachable("Unhandled fields are expected to be rejected earlier"); 2403 break; 2404 case ExtAddrMode::BaseRegField: 2405 BaseReg = V; 2406 break; 2407 case ExtAddrMode::BaseGVField: 2408 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes 2409 // in the BaseReg field. 2410 assert(BaseReg == nullptr); 2411 BaseReg = V; 2412 BaseGV = nullptr; 2413 break; 2414 case ExtAddrMode::ScaledRegField: 2415 ScaledReg = V; 2416 // If we have a mix of scaled and unscaled addrmodes then we want scale 2417 // to be the scale and not zero. 2418 if (!Scale) 2419 for (const ExtAddrMode &AM : AddrModes) 2420 if (AM.Scale) { 2421 Scale = AM.Scale; 2422 break; 2423 } 2424 break; 2425 case ExtAddrMode::BaseOffsField: 2426 // The offset is no longer a constant, so it goes in ScaledReg with a 2427 // scale of 1. 2428 assert(ScaledReg == nullptr); 2429 ScaledReg = V; 2430 Scale = 1; 2431 BaseOffs = 0; 2432 break; 2433 } 2434 } 2435 }; 2436 2437 } // end anonymous namespace 2438 2439 #ifndef NDEBUG 2440 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { 2441 AM.print(OS); 2442 return OS; 2443 } 2444 #endif 2445 2446 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2447 void ExtAddrMode::print(raw_ostream &OS) const { 2448 bool NeedPlus = false; 2449 OS << "["; 2450 if (InBounds) 2451 OS << "inbounds "; 2452 if (BaseGV) { 2453 OS << (NeedPlus ? " + " : "") 2454 << "GV:"; 2455 BaseGV->printAsOperand(OS, /*PrintType=*/false); 2456 NeedPlus = true; 2457 } 2458 2459 if (BaseOffs) { 2460 OS << (NeedPlus ? " + " : "") 2461 << BaseOffs; 2462 NeedPlus = true; 2463 } 2464 2465 if (BaseReg) { 2466 OS << (NeedPlus ? " + " : "") 2467 << "Base:"; 2468 BaseReg->printAsOperand(OS, /*PrintType=*/false); 2469 NeedPlus = true; 2470 } 2471 if (Scale) { 2472 OS << (NeedPlus ? " + " : "") 2473 << Scale << "*"; 2474 ScaledReg->printAsOperand(OS, /*PrintType=*/false); 2475 } 2476 2477 OS << ']'; 2478 } 2479 2480 LLVM_DUMP_METHOD void ExtAddrMode::dump() const { 2481 print(dbgs()); 2482 dbgs() << '\n'; 2483 } 2484 #endif 2485 2486 namespace { 2487 2488 /// This class provides transaction based operation on the IR. 2489 /// Every change made through this class is recorded in the internal state and 2490 /// can be undone (rollback) until commit is called. 2491 /// CGP does not check if instructions could be speculatively executed when 2492 /// moved. Preserving the original location would pessimize the debugging 2493 /// experience, as well as negatively impact the quality of sample PGO. 2494 class TypePromotionTransaction { 2495 /// This represents the common interface of the individual transaction. 2496 /// Each class implements the logic for doing one specific modification on 2497 /// the IR via the TypePromotionTransaction. 2498 class TypePromotionAction { 2499 protected: 2500 /// The Instruction modified. 2501 Instruction *Inst; 2502 2503 public: 2504 /// Constructor of the action. 2505 /// The constructor performs the related action on the IR. 2506 TypePromotionAction(Instruction *Inst) : Inst(Inst) {} 2507 2508 virtual ~TypePromotionAction() = default; 2509 2510 /// Undo the modification done by this action. 2511 /// When this method is called, the IR must be in the same state as it was 2512 /// before this action was applied. 2513 /// \pre Undoing the action works if and only if the IR is in the exact same 2514 /// state as it was directly after this action was applied. 2515 virtual void undo() = 0; 2516 2517 /// Advocate every change made by this action. 2518 /// When the results on the IR of the action are to be kept, it is important 2519 /// to call this function, otherwise hidden information may be kept forever. 2520 virtual void commit() { 2521 // Nothing to be done, this action is not doing anything. 2522 } 2523 }; 2524 2525 /// Utility to remember the position of an instruction. 2526 class InsertionHandler { 2527 /// Position of an instruction. 2528 /// Either an instruction: 2529 /// - Is the first in a basic block: BB is used. 2530 /// - Has a previous instruction: PrevInst is used. 2531 union { 2532 Instruction *PrevInst; 2533 BasicBlock *BB; 2534 } Point; 2535 2536 /// Remember whether or not the instruction had a previous instruction. 2537 bool HasPrevInstruction; 2538 2539 public: 2540 /// Record the position of \p Inst. 2541 InsertionHandler(Instruction *Inst) { 2542 BasicBlock::iterator It = Inst->getIterator(); 2543 HasPrevInstruction = (It != (Inst->getParent()->begin())); 2544 if (HasPrevInstruction) 2545 Point.PrevInst = &*--It; 2546 else 2547 Point.BB = Inst->getParent(); 2548 } 2549 2550 /// Insert \p Inst at the recorded position. 2551 void insert(Instruction *Inst) { 2552 if (HasPrevInstruction) { 2553 if (Inst->getParent()) 2554 Inst->removeFromParent(); 2555 Inst->insertAfter(Point.PrevInst); 2556 } else { 2557 Instruction *Position = &*Point.BB->getFirstInsertionPt(); 2558 if (Inst->getParent()) 2559 Inst->moveBefore(Position); 2560 else 2561 Inst->insertBefore(Position); 2562 } 2563 } 2564 }; 2565 2566 /// Move an instruction before another. 2567 class InstructionMoveBefore : public TypePromotionAction { 2568 /// Original position of the instruction. 2569 InsertionHandler Position; 2570 2571 public: 2572 /// Move \p Inst before \p Before. 2573 InstructionMoveBefore(Instruction *Inst, Instruction *Before) 2574 : TypePromotionAction(Inst), Position(Inst) { 2575 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before 2576 << "\n"); 2577 Inst->moveBefore(Before); 2578 } 2579 2580 /// Move the instruction back to its original position. 2581 void undo() override { 2582 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); 2583 Position.insert(Inst); 2584 } 2585 }; 2586 2587 /// Set the operand of an instruction with a new value. 2588 class OperandSetter : public TypePromotionAction { 2589 /// Original operand of the instruction. 2590 Value *Origin; 2591 2592 /// Index of the modified instruction. 2593 unsigned Idx; 2594 2595 public: 2596 /// Set \p Idx operand of \p Inst with \p NewVal. 2597 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) 2598 : TypePromotionAction(Inst), Idx(Idx) { 2599 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" 2600 << "for:" << *Inst << "\n" 2601 << "with:" << *NewVal << "\n"); 2602 Origin = Inst->getOperand(Idx); 2603 Inst->setOperand(Idx, NewVal); 2604 } 2605 2606 /// Restore the original value of the instruction. 2607 void undo() override { 2608 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" 2609 << "for: " << *Inst << "\n" 2610 << "with: " << *Origin << "\n"); 2611 Inst->setOperand(Idx, Origin); 2612 } 2613 }; 2614 2615 /// Hide the operands of an instruction. 2616 /// Do as if this instruction was not using any of its operands. 2617 class OperandsHider : public TypePromotionAction { 2618 /// The list of original operands. 2619 SmallVector<Value *, 4> OriginalValues; 2620 2621 public: 2622 /// Remove \p Inst from the uses of the operands of \p Inst. 2623 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { 2624 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); 2625 unsigned NumOpnds = Inst->getNumOperands(); 2626 OriginalValues.reserve(NumOpnds); 2627 for (unsigned It = 0; It < NumOpnds; ++It) { 2628 // Save the current operand. 2629 Value *Val = Inst->getOperand(It); 2630 OriginalValues.push_back(Val); 2631 // Set a dummy one. 2632 // We could use OperandSetter here, but that would imply an overhead 2633 // that we are not willing to pay. 2634 Inst->setOperand(It, UndefValue::get(Val->getType())); 2635 } 2636 } 2637 2638 /// Restore the original list of uses. 2639 void undo() override { 2640 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); 2641 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) 2642 Inst->setOperand(It, OriginalValues[It]); 2643 } 2644 }; 2645 2646 /// Build a truncate instruction. 2647 class TruncBuilder : public TypePromotionAction { 2648 Value *Val; 2649 2650 public: 2651 /// Build a truncate instruction of \p Opnd producing a \p Ty 2652 /// result. 2653 /// trunc Opnd to Ty. 2654 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { 2655 IRBuilder<> Builder(Opnd); 2656 Builder.SetCurrentDebugLocation(DebugLoc()); 2657 Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); 2658 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); 2659 } 2660 2661 /// Get the built value. 2662 Value *getBuiltValue() { return Val; } 2663 2664 /// Remove the built instruction. 2665 void undo() override { 2666 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); 2667 if (Instruction *IVal = dyn_cast<Instruction>(Val)) 2668 IVal->eraseFromParent(); 2669 } 2670 }; 2671 2672 /// Build a sign extension instruction. 2673 class SExtBuilder : public TypePromotionAction { 2674 Value *Val; 2675 2676 public: 2677 /// Build a sign extension instruction of \p Opnd producing a \p Ty 2678 /// result. 2679 /// sext Opnd to Ty. 2680 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) 2681 : TypePromotionAction(InsertPt) { 2682 IRBuilder<> Builder(InsertPt); 2683 Val = Builder.CreateSExt(Opnd, Ty, "promoted"); 2684 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); 2685 } 2686 2687 /// Get the built value. 2688 Value *getBuiltValue() { return Val; } 2689 2690 /// Remove the built instruction. 2691 void undo() override { 2692 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); 2693 if (Instruction *IVal = dyn_cast<Instruction>(Val)) 2694 IVal->eraseFromParent(); 2695 } 2696 }; 2697 2698 /// Build a zero extension instruction. 2699 class ZExtBuilder : public TypePromotionAction { 2700 Value *Val; 2701 2702 public: 2703 /// Build a zero extension instruction of \p Opnd producing a \p Ty 2704 /// result. 2705 /// zext Opnd to Ty. 2706 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) 2707 : TypePromotionAction(InsertPt) { 2708 IRBuilder<> Builder(InsertPt); 2709 Builder.SetCurrentDebugLocation(DebugLoc()); 2710 Val = Builder.CreateZExt(Opnd, Ty, "promoted"); 2711 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); 2712 } 2713 2714 /// Get the built value. 2715 Value *getBuiltValue() { return Val; } 2716 2717 /// Remove the built instruction. 2718 void undo() override { 2719 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); 2720 if (Instruction *IVal = dyn_cast<Instruction>(Val)) 2721 IVal->eraseFromParent(); 2722 } 2723 }; 2724 2725 /// Mutate an instruction to another type. 2726 class TypeMutator : public TypePromotionAction { 2727 /// Record the original type. 2728 Type *OrigTy; 2729 2730 public: 2731 /// Mutate the type of \p Inst into \p NewTy. 2732 TypeMutator(Instruction *Inst, Type *NewTy) 2733 : TypePromotionAction(Inst), OrigTy(Inst->getType()) { 2734 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy 2735 << "\n"); 2736 Inst->mutateType(NewTy); 2737 } 2738 2739 /// Mutate the instruction back to its original type. 2740 void undo() override { 2741 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy 2742 << "\n"); 2743 Inst->mutateType(OrigTy); 2744 } 2745 }; 2746 2747 /// Replace the uses of an instruction by another instruction. 2748 class UsesReplacer : public TypePromotionAction { 2749 /// Helper structure to keep track of the replaced uses. 2750 struct InstructionAndIdx { 2751 /// The instruction using the instruction. 2752 Instruction *Inst; 2753 2754 /// The index where this instruction is used for Inst. 2755 unsigned Idx; 2756 2757 InstructionAndIdx(Instruction *Inst, unsigned Idx) 2758 : Inst(Inst), Idx(Idx) {} 2759 }; 2760 2761 /// Keep track of the original uses (pair Instruction, Index). 2762 SmallVector<InstructionAndIdx, 4> OriginalUses; 2763 /// Keep track of the debug users. 2764 SmallVector<DbgValueInst *, 1> DbgValues; 2765 2766 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator; 2767 2768 public: 2769 /// Replace all the use of \p Inst by \p New. 2770 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { 2771 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New 2772 << "\n"); 2773 // Record the original uses. 2774 for (Use &U : Inst->uses()) { 2775 Instruction *UserI = cast<Instruction>(U.getUser()); 2776 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); 2777 } 2778 // Record the debug uses separately. They are not in the instruction's 2779 // use list, but they are replaced by RAUW. 2780 findDbgValues(DbgValues, Inst); 2781 2782 // Now, we can replace the uses. 2783 Inst->replaceAllUsesWith(New); 2784 } 2785 2786 /// Reassign the original uses of Inst to Inst. 2787 void undo() override { 2788 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); 2789 for (use_iterator UseIt = OriginalUses.begin(), 2790 EndIt = OriginalUses.end(); 2791 UseIt != EndIt; ++UseIt) { 2792 UseIt->Inst->setOperand(UseIt->Idx, Inst); 2793 } 2794 // RAUW has replaced all original uses with references to the new value, 2795 // including the debug uses. Since we are undoing the replacements, 2796 // the original debug uses must also be reinstated to maintain the 2797 // correctness and utility of debug value instructions. 2798 for (auto *DVI: DbgValues) { 2799 LLVMContext &Ctx = Inst->getType()->getContext(); 2800 auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst)); 2801 DVI->setOperand(0, MV); 2802 } 2803 } 2804 }; 2805 2806 /// Remove an instruction from the IR. 2807 class InstructionRemover : public TypePromotionAction { 2808 /// Original position of the instruction. 2809 InsertionHandler Inserter; 2810 2811 /// Helper structure to hide all the link to the instruction. In other 2812 /// words, this helps to do as if the instruction was removed. 2813 OperandsHider Hider; 2814 2815 /// Keep track of the uses replaced, if any. 2816 UsesReplacer *Replacer = nullptr; 2817 2818 /// Keep track of instructions removed. 2819 SetOfInstrs &RemovedInsts; 2820 2821 public: 2822 /// Remove all reference of \p Inst and optionally replace all its 2823 /// uses with New. 2824 /// \p RemovedInsts Keep track of the instructions removed by this Action. 2825 /// \pre If !Inst->use_empty(), then New != nullptr 2826 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, 2827 Value *New = nullptr) 2828 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), 2829 RemovedInsts(RemovedInsts) { 2830 if (New) 2831 Replacer = new UsesReplacer(Inst, New); 2832 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); 2833 RemovedInsts.insert(Inst); 2834 /// The instructions removed here will be freed after completing 2835 /// optimizeBlock() for all blocks as we need to keep track of the 2836 /// removed instructions during promotion. 2837 Inst->removeFromParent(); 2838 } 2839 2840 ~InstructionRemover() override { delete Replacer; } 2841 2842 /// Resurrect the instruction and reassign it to the proper uses if 2843 /// new value was provided when build this action. 2844 void undo() override { 2845 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); 2846 Inserter.insert(Inst); 2847 if (Replacer) 2848 Replacer->undo(); 2849 Hider.undo(); 2850 RemovedInsts.erase(Inst); 2851 } 2852 }; 2853 2854 public: 2855 /// Restoration point. 2856 /// The restoration point is a pointer to an action instead of an iterator 2857 /// because the iterator may be invalidated but not the pointer. 2858 using ConstRestorationPt = const TypePromotionAction *; 2859 2860 TypePromotionTransaction(SetOfInstrs &RemovedInsts) 2861 : RemovedInsts(RemovedInsts) {} 2862 2863 /// Advocate every changes made in that transaction. Return true if any change 2864 /// happen. 2865 bool commit(); 2866 2867 /// Undo all the changes made after the given point. 2868 void rollback(ConstRestorationPt Point); 2869 2870 /// Get the current restoration point. 2871 ConstRestorationPt getRestorationPoint() const; 2872 2873 /// \name API for IR modification with state keeping to support rollback. 2874 /// @{ 2875 /// Same as Instruction::setOperand. 2876 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); 2877 2878 /// Same as Instruction::eraseFromParent. 2879 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); 2880 2881 /// Same as Value::replaceAllUsesWith. 2882 void replaceAllUsesWith(Instruction *Inst, Value *New); 2883 2884 /// Same as Value::mutateType. 2885 void mutateType(Instruction *Inst, Type *NewTy); 2886 2887 /// Same as IRBuilder::createTrunc. 2888 Value *createTrunc(Instruction *Opnd, Type *Ty); 2889 2890 /// Same as IRBuilder::createSExt. 2891 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); 2892 2893 /// Same as IRBuilder::createZExt. 2894 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); 2895 2896 /// Same as Instruction::moveBefore. 2897 void moveBefore(Instruction *Inst, Instruction *Before); 2898 /// @} 2899 2900 private: 2901 /// The ordered list of actions made so far. 2902 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; 2903 2904 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator; 2905 2906 SetOfInstrs &RemovedInsts; 2907 }; 2908 2909 } // end anonymous namespace 2910 2911 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, 2912 Value *NewVal) { 2913 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>( 2914 Inst, Idx, NewVal)); 2915 } 2916 2917 void TypePromotionTransaction::eraseInstruction(Instruction *Inst, 2918 Value *NewVal) { 2919 Actions.push_back( 2920 std::make_unique<TypePromotionTransaction::InstructionRemover>( 2921 Inst, RemovedInsts, NewVal)); 2922 } 2923 2924 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, 2925 Value *New) { 2926 Actions.push_back( 2927 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); 2928 } 2929 2930 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { 2931 Actions.push_back( 2932 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); 2933 } 2934 2935 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, 2936 Type *Ty) { 2937 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); 2938 Value *Val = Ptr->getBuiltValue(); 2939 Actions.push_back(std::move(Ptr)); 2940 return Val; 2941 } 2942 2943 Value *TypePromotionTransaction::createSExt(Instruction *Inst, 2944 Value *Opnd, Type *Ty) { 2945 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); 2946 Value *Val = Ptr->getBuiltValue(); 2947 Actions.push_back(std::move(Ptr)); 2948 return Val; 2949 } 2950 2951 Value *TypePromotionTransaction::createZExt(Instruction *Inst, 2952 Value *Opnd, Type *Ty) { 2953 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); 2954 Value *Val = Ptr->getBuiltValue(); 2955 Actions.push_back(std::move(Ptr)); 2956 return Val; 2957 } 2958 2959 void TypePromotionTransaction::moveBefore(Instruction *Inst, 2960 Instruction *Before) { 2961 Actions.push_back( 2962 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>( 2963 Inst, Before)); 2964 } 2965 2966 TypePromotionTransaction::ConstRestorationPt 2967 TypePromotionTransaction::getRestorationPoint() const { 2968 return !Actions.empty() ? Actions.back().get() : nullptr; 2969 } 2970 2971 bool TypePromotionTransaction::commit() { 2972 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; 2973 ++It) 2974 (*It)->commit(); 2975 bool Modified = !Actions.empty(); 2976 Actions.clear(); 2977 return Modified; 2978 } 2979 2980 void TypePromotionTransaction::rollback( 2981 TypePromotionTransaction::ConstRestorationPt Point) { 2982 while (!Actions.empty() && Point != Actions.back().get()) { 2983 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); 2984 Curr->undo(); 2985 } 2986 } 2987 2988 namespace { 2989 2990 /// A helper class for matching addressing modes. 2991 /// 2992 /// This encapsulates the logic for matching the target-legal addressing modes. 2993 class AddressingModeMatcher { 2994 SmallVectorImpl<Instruction*> &AddrModeInsts; 2995 const TargetLowering &TLI; 2996 const TargetRegisterInfo &TRI; 2997 const DataLayout &DL; 2998 2999 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and 3000 /// the memory instruction that we're computing this address for. 3001 Type *AccessTy; 3002 unsigned AddrSpace; 3003 Instruction *MemoryInst; 3004 3005 /// This is the addressing mode that we're building up. This is 3006 /// part of the return value of this addressing mode matching stuff. 3007 ExtAddrMode &AddrMode; 3008 3009 /// The instructions inserted by other CodeGenPrepare optimizations. 3010 const SetOfInstrs &InsertedInsts; 3011 3012 /// A map from the instructions to their type before promotion. 3013 InstrToOrigTy &PromotedInsts; 3014 3015 /// The ongoing transaction where every action should be registered. 3016 TypePromotionTransaction &TPT; 3017 3018 // A GEP which has too large offset to be folded into the addressing mode. 3019 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP; 3020 3021 /// This is set to true when we should not do profitability checks. 3022 /// When true, IsProfitableToFoldIntoAddressingMode always returns true. 3023 bool IgnoreProfitability; 3024 3025 /// True if we are optimizing for size. 3026 bool OptSize; 3027 3028 ProfileSummaryInfo *PSI; 3029 BlockFrequencyInfo *BFI; 3030 3031 AddressingModeMatcher( 3032 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI, 3033 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI, 3034 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts, 3035 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT, 3036 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, 3037 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) 3038 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), 3039 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), 3040 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), 3041 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP), 3042 OptSize(OptSize), PSI(PSI), BFI(BFI) { 3043 IgnoreProfitability = false; 3044 } 3045 3046 public: 3047 /// Find the maximal addressing mode that a load/store of V can fold, 3048 /// give an access type of AccessTy. This returns a list of involved 3049 /// instructions in AddrModeInsts. 3050 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare 3051 /// optimizations. 3052 /// \p PromotedInsts maps the instructions to their type before promotion. 3053 /// \p The ongoing transaction where every action should be registered. 3054 static ExtAddrMode 3055 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst, 3056 SmallVectorImpl<Instruction *> &AddrModeInsts, 3057 const TargetLowering &TLI, const TargetRegisterInfo &TRI, 3058 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts, 3059 TypePromotionTransaction &TPT, 3060 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, 3061 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) { 3062 ExtAddrMode Result; 3063 3064 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS, 3065 MemoryInst, Result, InsertedInsts, 3066 PromotedInsts, TPT, LargeOffsetGEP, 3067 OptSize, PSI, BFI) 3068 .matchAddr(V, 0); 3069 (void)Success; assert(Success && "Couldn't select *anything*?"); 3070 return Result; 3071 } 3072 3073 private: 3074 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); 3075 bool matchAddr(Value *Addr, unsigned Depth); 3076 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth, 3077 bool *MovedAway = nullptr); 3078 bool isProfitableToFoldIntoAddressingMode(Instruction *I, 3079 ExtAddrMode &AMBefore, 3080 ExtAddrMode &AMAfter); 3081 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); 3082 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, 3083 Value *PromotedOperand) const; 3084 }; 3085 3086 class PhiNodeSet; 3087 3088 /// An iterator for PhiNodeSet. 3089 class PhiNodeSetIterator { 3090 PhiNodeSet * const Set; 3091 size_t CurrentIndex = 0; 3092 3093 public: 3094 /// The constructor. Start should point to either a valid element, or be equal 3095 /// to the size of the underlying SmallVector of the PhiNodeSet. 3096 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start); 3097 PHINode * operator*() const; 3098 PhiNodeSetIterator& operator++(); 3099 bool operator==(const PhiNodeSetIterator &RHS) const; 3100 bool operator!=(const PhiNodeSetIterator &RHS) const; 3101 }; 3102 3103 /// Keeps a set of PHINodes. 3104 /// 3105 /// This is a minimal set implementation for a specific use case: 3106 /// It is very fast when there are very few elements, but also provides good 3107 /// performance when there are many. It is similar to SmallPtrSet, but also 3108 /// provides iteration by insertion order, which is deterministic and stable 3109 /// across runs. It is also similar to SmallSetVector, but provides removing 3110 /// elements in O(1) time. This is achieved by not actually removing the element 3111 /// from the underlying vector, so comes at the cost of using more memory, but 3112 /// that is fine, since PhiNodeSets are used as short lived objects. 3113 class PhiNodeSet { 3114 friend class PhiNodeSetIterator; 3115 3116 using MapType = SmallDenseMap<PHINode *, size_t, 32>; 3117 using iterator = PhiNodeSetIterator; 3118 3119 /// Keeps the elements in the order of their insertion in the underlying 3120 /// vector. To achieve constant time removal, it never deletes any element. 3121 SmallVector<PHINode *, 32> NodeList; 3122 3123 /// Keeps the elements in the underlying set implementation. This (and not the 3124 /// NodeList defined above) is the source of truth on whether an element 3125 /// is actually in the collection. 3126 MapType NodeMap; 3127 3128 /// Points to the first valid (not deleted) element when the set is not empty 3129 /// and the value is not zero. Equals to the size of the underlying vector 3130 /// when the set is empty. When the value is 0, as in the beginning, the 3131 /// first element may or may not be valid. 3132 size_t FirstValidElement = 0; 3133 3134 public: 3135 /// Inserts a new element to the collection. 3136 /// \returns true if the element is actually added, i.e. was not in the 3137 /// collection before the operation. 3138 bool insert(PHINode *Ptr) { 3139 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) { 3140 NodeList.push_back(Ptr); 3141 return true; 3142 } 3143 return false; 3144 } 3145 3146 /// Removes the element from the collection. 3147 /// \returns whether the element is actually removed, i.e. was in the 3148 /// collection before the operation. 3149 bool erase(PHINode *Ptr) { 3150 auto it = NodeMap.find(Ptr); 3151 if (it != NodeMap.end()) { 3152 NodeMap.erase(Ptr); 3153 SkipRemovedElements(FirstValidElement); 3154 return true; 3155 } 3156 return false; 3157 } 3158 3159 /// Removes all elements and clears the collection. 3160 void clear() { 3161 NodeMap.clear(); 3162 NodeList.clear(); 3163 FirstValidElement = 0; 3164 } 3165 3166 /// \returns an iterator that will iterate the elements in the order of 3167 /// insertion. 3168 iterator begin() { 3169 if (FirstValidElement == 0) 3170 SkipRemovedElements(FirstValidElement); 3171 return PhiNodeSetIterator(this, FirstValidElement); 3172 } 3173 3174 /// \returns an iterator that points to the end of the collection. 3175 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); } 3176 3177 /// Returns the number of elements in the collection. 3178 size_t size() const { 3179 return NodeMap.size(); 3180 } 3181 3182 /// \returns 1 if the given element is in the collection, and 0 if otherwise. 3183 size_t count(PHINode *Ptr) const { 3184 return NodeMap.count(Ptr); 3185 } 3186 3187 private: 3188 /// Updates the CurrentIndex so that it will point to a valid element. 3189 /// 3190 /// If the element of NodeList at CurrentIndex is valid, it does not 3191 /// change it. If there are no more valid elements, it updates CurrentIndex 3192 /// to point to the end of the NodeList. 3193 void SkipRemovedElements(size_t &CurrentIndex) { 3194 while (CurrentIndex < NodeList.size()) { 3195 auto it = NodeMap.find(NodeList[CurrentIndex]); 3196 // If the element has been deleted and added again later, NodeMap will 3197 // point to a different index, so CurrentIndex will still be invalid. 3198 if (it != NodeMap.end() && it->second == CurrentIndex) 3199 break; 3200 ++CurrentIndex; 3201 } 3202 } 3203 }; 3204 3205 PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start) 3206 : Set(Set), CurrentIndex(Start) {} 3207 3208 PHINode * PhiNodeSetIterator::operator*() const { 3209 assert(CurrentIndex < Set->NodeList.size() && 3210 "PhiNodeSet access out of range"); 3211 return Set->NodeList[CurrentIndex]; 3212 } 3213 3214 PhiNodeSetIterator& PhiNodeSetIterator::operator++() { 3215 assert(CurrentIndex < Set->NodeList.size() && 3216 "PhiNodeSet access out of range"); 3217 ++CurrentIndex; 3218 Set->SkipRemovedElements(CurrentIndex); 3219 return *this; 3220 } 3221 3222 bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const { 3223 return CurrentIndex == RHS.CurrentIndex; 3224 } 3225 3226 bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const { 3227 return !((*this) == RHS); 3228 } 3229 3230 /// Keep track of simplification of Phi nodes. 3231 /// Accept the set of all phi nodes and erase phi node from this set 3232 /// if it is simplified. 3233 class SimplificationTracker { 3234 DenseMap<Value *, Value *> Storage; 3235 const SimplifyQuery &SQ; 3236 // Tracks newly created Phi nodes. The elements are iterated by insertion 3237 // order. 3238 PhiNodeSet AllPhiNodes; 3239 // Tracks newly created Select nodes. 3240 SmallPtrSet<SelectInst *, 32> AllSelectNodes; 3241 3242 public: 3243 SimplificationTracker(const SimplifyQuery &sq) 3244 : SQ(sq) {} 3245 3246 Value *Get(Value *V) { 3247 do { 3248 auto SV = Storage.find(V); 3249 if (SV == Storage.end()) 3250 return V; 3251 V = SV->second; 3252 } while (true); 3253 } 3254 3255 Value *Simplify(Value *Val) { 3256 SmallVector<Value *, 32> WorkList; 3257 SmallPtrSet<Value *, 32> Visited; 3258 WorkList.push_back(Val); 3259 while (!WorkList.empty()) { 3260 auto *P = WorkList.pop_back_val(); 3261 if (!Visited.insert(P).second) 3262 continue; 3263 if (auto *PI = dyn_cast<Instruction>(P)) 3264 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) { 3265 for (auto *U : PI->users()) 3266 WorkList.push_back(cast<Value>(U)); 3267 Put(PI, V); 3268 PI->replaceAllUsesWith(V); 3269 if (auto *PHI = dyn_cast<PHINode>(PI)) 3270 AllPhiNodes.erase(PHI); 3271 if (auto *Select = dyn_cast<SelectInst>(PI)) 3272 AllSelectNodes.erase(Select); 3273 PI->eraseFromParent(); 3274 } 3275 } 3276 return Get(Val); 3277 } 3278 3279 void Put(Value *From, Value *To) { 3280 Storage.insert({ From, To }); 3281 } 3282 3283 void ReplacePhi(PHINode *From, PHINode *To) { 3284 Value* OldReplacement = Get(From); 3285 while (OldReplacement != From) { 3286 From = To; 3287 To = dyn_cast<PHINode>(OldReplacement); 3288 OldReplacement = Get(From); 3289 } 3290 assert(To && Get(To) == To && "Replacement PHI node is already replaced."); 3291 Put(From, To); 3292 From->replaceAllUsesWith(To); 3293 AllPhiNodes.erase(From); 3294 From->eraseFromParent(); 3295 } 3296 3297 PhiNodeSet& newPhiNodes() { return AllPhiNodes; } 3298 3299 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); } 3300 3301 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); } 3302 3303 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); } 3304 3305 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); } 3306 3307 void destroyNewNodes(Type *CommonType) { 3308 // For safe erasing, replace the uses with dummy value first. 3309 auto *Dummy = UndefValue::get(CommonType); 3310 for (auto *I : AllPhiNodes) { 3311 I->replaceAllUsesWith(Dummy); 3312 I->eraseFromParent(); 3313 } 3314 AllPhiNodes.clear(); 3315 for (auto *I : AllSelectNodes) { 3316 I->replaceAllUsesWith(Dummy); 3317 I->eraseFromParent(); 3318 } 3319 AllSelectNodes.clear(); 3320 } 3321 }; 3322 3323 /// A helper class for combining addressing modes. 3324 class AddressingModeCombiner { 3325 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping; 3326 typedef std::pair<PHINode *, PHINode *> PHIPair; 3327 3328 private: 3329 /// The addressing modes we've collected. 3330 SmallVector<ExtAddrMode, 16> AddrModes; 3331 3332 /// The field in which the AddrModes differ, when we have more than one. 3333 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField; 3334 3335 /// Are the AddrModes that we have all just equal to their original values? 3336 bool AllAddrModesTrivial = true; 3337 3338 /// Common Type for all different fields in addressing modes. 3339 Type *CommonType; 3340 3341 /// SimplifyQuery for simplifyInstruction utility. 3342 const SimplifyQuery &SQ; 3343 3344 /// Original Address. 3345 Value *Original; 3346 3347 public: 3348 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue) 3349 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {} 3350 3351 /// Get the combined AddrMode 3352 const ExtAddrMode &getAddrMode() const { 3353 return AddrModes[0]; 3354 } 3355 3356 /// Add a new AddrMode if it's compatible with the AddrModes we already 3357 /// have. 3358 /// \return True iff we succeeded in doing so. 3359 bool addNewAddrMode(ExtAddrMode &NewAddrMode) { 3360 // Take note of if we have any non-trivial AddrModes, as we need to detect 3361 // when all AddrModes are trivial as then we would introduce a phi or select 3362 // which just duplicates what's already there. 3363 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial(); 3364 3365 // If this is the first addrmode then everything is fine. 3366 if (AddrModes.empty()) { 3367 AddrModes.emplace_back(NewAddrMode); 3368 return true; 3369 } 3370 3371 // Figure out how different this is from the other address modes, which we 3372 // can do just by comparing against the first one given that we only care 3373 // about the cumulative difference. 3374 ExtAddrMode::FieldName ThisDifferentField = 3375 AddrModes[0].compare(NewAddrMode); 3376 if (DifferentField == ExtAddrMode::NoField) 3377 DifferentField = ThisDifferentField; 3378 else if (DifferentField != ThisDifferentField) 3379 DifferentField = ExtAddrMode::MultipleFields; 3380 3381 // If NewAddrMode differs in more than one dimension we cannot handle it. 3382 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields; 3383 3384 // If Scale Field is different then we reject. 3385 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField; 3386 3387 // We also must reject the case when base offset is different and 3388 // scale reg is not null, we cannot handle this case due to merge of 3389 // different offsets will be used as ScaleReg. 3390 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField || 3391 !NewAddrMode.ScaledReg); 3392 3393 // We also must reject the case when GV is different and BaseReg installed 3394 // due to we want to use base reg as a merge of GV values. 3395 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField || 3396 !NewAddrMode.HasBaseReg); 3397 3398 // Even if NewAddMode is the same we still need to collect it due to 3399 // original value is different. And later we will need all original values 3400 // as anchors during finding the common Phi node. 3401 if (CanHandle) 3402 AddrModes.emplace_back(NewAddrMode); 3403 else 3404 AddrModes.clear(); 3405 3406 return CanHandle; 3407 } 3408 3409 /// Combine the addressing modes we've collected into a single 3410 /// addressing mode. 3411 /// \return True iff we successfully combined them or we only had one so 3412 /// didn't need to combine them anyway. 3413 bool combineAddrModes() { 3414 // If we have no AddrModes then they can't be combined. 3415 if (AddrModes.size() == 0) 3416 return false; 3417 3418 // A single AddrMode can trivially be combined. 3419 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField) 3420 return true; 3421 3422 // If the AddrModes we collected are all just equal to the value they are 3423 // derived from then combining them wouldn't do anything useful. 3424 if (AllAddrModesTrivial) 3425 return false; 3426 3427 if (!addrModeCombiningAllowed()) 3428 return false; 3429 3430 // Build a map between <original value, basic block where we saw it> to 3431 // value of base register. 3432 // Bail out if there is no common type. 3433 FoldAddrToValueMapping Map; 3434 if (!initializeMap(Map)) 3435 return false; 3436 3437 Value *CommonValue = findCommon(Map); 3438 if (CommonValue) 3439 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes); 3440 return CommonValue != nullptr; 3441 } 3442 3443 private: 3444 /// Initialize Map with anchor values. For address seen 3445 /// we set the value of different field saw in this address. 3446 /// At the same time we find a common type for different field we will 3447 /// use to create new Phi/Select nodes. Keep it in CommonType field. 3448 /// Return false if there is no common type found. 3449 bool initializeMap(FoldAddrToValueMapping &Map) { 3450 // Keep track of keys where the value is null. We will need to replace it 3451 // with constant null when we know the common type. 3452 SmallVector<Value *, 2> NullValue; 3453 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType()); 3454 for (auto &AM : AddrModes) { 3455 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy); 3456 if (DV) { 3457 auto *Type = DV->getType(); 3458 if (CommonType && CommonType != Type) 3459 return false; 3460 CommonType = Type; 3461 Map[AM.OriginalValue] = DV; 3462 } else { 3463 NullValue.push_back(AM.OriginalValue); 3464 } 3465 } 3466 assert(CommonType && "At least one non-null value must be!"); 3467 for (auto *V : NullValue) 3468 Map[V] = Constant::getNullValue(CommonType); 3469 return true; 3470 } 3471 3472 /// We have mapping between value A and other value B where B was a field in 3473 /// addressing mode represented by A. Also we have an original value C 3474 /// representing an address we start with. Traversing from C through phi and 3475 /// selects we ended up with A's in a map. This utility function tries to find 3476 /// a value V which is a field in addressing mode C and traversing through phi 3477 /// nodes and selects we will end up in corresponded values B in a map. 3478 /// The utility will create a new Phi/Selects if needed. 3479 // The simple example looks as follows: 3480 // BB1: 3481 // p1 = b1 + 40 3482 // br cond BB2, BB3 3483 // BB2: 3484 // p2 = b2 + 40 3485 // br BB3 3486 // BB3: 3487 // p = phi [p1, BB1], [p2, BB2] 3488 // v = load p 3489 // Map is 3490 // p1 -> b1 3491 // p2 -> b2 3492 // Request is 3493 // p -> ? 3494 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3. 3495 Value *findCommon(FoldAddrToValueMapping &Map) { 3496 // Tracks the simplification of newly created phi nodes. The reason we use 3497 // this mapping is because we will add new created Phi nodes in AddrToBase. 3498 // Simplification of Phi nodes is recursive, so some Phi node may 3499 // be simplified after we added it to AddrToBase. In reality this 3500 // simplification is possible only if original phi/selects were not 3501 // simplified yet. 3502 // Using this mapping we can find the current value in AddrToBase. 3503 SimplificationTracker ST(SQ); 3504 3505 // First step, DFS to create PHI nodes for all intermediate blocks. 3506 // Also fill traverse order for the second step. 3507 SmallVector<Value *, 32> TraverseOrder; 3508 InsertPlaceholders(Map, TraverseOrder, ST); 3509 3510 // Second Step, fill new nodes by merged values and simplify if possible. 3511 FillPlaceholders(Map, TraverseOrder, ST); 3512 3513 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) { 3514 ST.destroyNewNodes(CommonType); 3515 return nullptr; 3516 } 3517 3518 // Now we'd like to match New Phi nodes to existed ones. 3519 unsigned PhiNotMatchedCount = 0; 3520 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) { 3521 ST.destroyNewNodes(CommonType); 3522 return nullptr; 3523 } 3524 3525 auto *Result = ST.Get(Map.find(Original)->second); 3526 if (Result) { 3527 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount; 3528 NumMemoryInstsSelectCreated += ST.countNewSelectNodes(); 3529 } 3530 return Result; 3531 } 3532 3533 /// Try to match PHI node to Candidate. 3534 /// Matcher tracks the matched Phi nodes. 3535 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate, 3536 SmallSetVector<PHIPair, 8> &Matcher, 3537 PhiNodeSet &PhiNodesToMatch) { 3538 SmallVector<PHIPair, 8> WorkList; 3539 Matcher.insert({ PHI, Candidate }); 3540 SmallSet<PHINode *, 8> MatchedPHIs; 3541 MatchedPHIs.insert(PHI); 3542 WorkList.push_back({ PHI, Candidate }); 3543 SmallSet<PHIPair, 8> Visited; 3544 while (!WorkList.empty()) { 3545 auto Item = WorkList.pop_back_val(); 3546 if (!Visited.insert(Item).second) 3547 continue; 3548 // We iterate over all incoming values to Phi to compare them. 3549 // If values are different and both of them Phi and the first one is a 3550 // Phi we added (subject to match) and both of them is in the same basic 3551 // block then we can match our pair if values match. So we state that 3552 // these values match and add it to work list to verify that. 3553 for (auto B : Item.first->blocks()) { 3554 Value *FirstValue = Item.first->getIncomingValueForBlock(B); 3555 Value *SecondValue = Item.second->getIncomingValueForBlock(B); 3556 if (FirstValue == SecondValue) 3557 continue; 3558 3559 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue); 3560 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue); 3561 3562 // One of them is not Phi or 3563 // The first one is not Phi node from the set we'd like to match or 3564 // Phi nodes from different basic blocks then 3565 // we will not be able to match. 3566 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) || 3567 FirstPhi->getParent() != SecondPhi->getParent()) 3568 return false; 3569 3570 // If we already matched them then continue. 3571 if (Matcher.count({ FirstPhi, SecondPhi })) 3572 continue; 3573 // So the values are different and does not match. So we need them to 3574 // match. (But we register no more than one match per PHI node, so that 3575 // we won't later try to replace them twice.) 3576 if (MatchedPHIs.insert(FirstPhi).second) 3577 Matcher.insert({ FirstPhi, SecondPhi }); 3578 // But me must check it. 3579 WorkList.push_back({ FirstPhi, SecondPhi }); 3580 } 3581 } 3582 return true; 3583 } 3584 3585 /// For the given set of PHI nodes (in the SimplificationTracker) try 3586 /// to find their equivalents. 3587 /// Returns false if this matching fails and creation of new Phi is disabled. 3588 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes, 3589 unsigned &PhiNotMatchedCount) { 3590 // Matched and PhiNodesToMatch iterate their elements in a deterministic 3591 // order, so the replacements (ReplacePhi) are also done in a deterministic 3592 // order. 3593 SmallSetVector<PHIPair, 8> Matched; 3594 SmallPtrSet<PHINode *, 8> WillNotMatch; 3595 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes(); 3596 while (PhiNodesToMatch.size()) { 3597 PHINode *PHI = *PhiNodesToMatch.begin(); 3598 3599 // Add us, if no Phi nodes in the basic block we do not match. 3600 WillNotMatch.clear(); 3601 WillNotMatch.insert(PHI); 3602 3603 // Traverse all Phis until we found equivalent or fail to do that. 3604 bool IsMatched = false; 3605 for (auto &P : PHI->getParent()->phis()) { 3606 if (&P == PHI) 3607 continue; 3608 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch))) 3609 break; 3610 // If it does not match, collect all Phi nodes from matcher. 3611 // if we end up with no match, them all these Phi nodes will not match 3612 // later. 3613 for (auto M : Matched) 3614 WillNotMatch.insert(M.first); 3615 Matched.clear(); 3616 } 3617 if (IsMatched) { 3618 // Replace all matched values and erase them. 3619 for (auto MV : Matched) 3620 ST.ReplacePhi(MV.first, MV.second); 3621 Matched.clear(); 3622 continue; 3623 } 3624 // If we are not allowed to create new nodes then bail out. 3625 if (!AllowNewPhiNodes) 3626 return false; 3627 // Just remove all seen values in matcher. They will not match anything. 3628 PhiNotMatchedCount += WillNotMatch.size(); 3629 for (auto *P : WillNotMatch) 3630 PhiNodesToMatch.erase(P); 3631 } 3632 return true; 3633 } 3634 /// Fill the placeholders with values from predecessors and simplify them. 3635 void FillPlaceholders(FoldAddrToValueMapping &Map, 3636 SmallVectorImpl<Value *> &TraverseOrder, 3637 SimplificationTracker &ST) { 3638 while (!TraverseOrder.empty()) { 3639 Value *Current = TraverseOrder.pop_back_val(); 3640 assert(Map.find(Current) != Map.end() && "No node to fill!!!"); 3641 Value *V = Map[Current]; 3642 3643 if (SelectInst *Select = dyn_cast<SelectInst>(V)) { 3644 // CurrentValue also must be Select. 3645 auto *CurrentSelect = cast<SelectInst>(Current); 3646 auto *TrueValue = CurrentSelect->getTrueValue(); 3647 assert(Map.find(TrueValue) != Map.end() && "No True Value!"); 3648 Select->setTrueValue(ST.Get(Map[TrueValue])); 3649 auto *FalseValue = CurrentSelect->getFalseValue(); 3650 assert(Map.find(FalseValue) != Map.end() && "No False Value!"); 3651 Select->setFalseValue(ST.Get(Map[FalseValue])); 3652 } else { 3653 // Must be a Phi node then. 3654 auto *PHI = cast<PHINode>(V); 3655 // Fill the Phi node with values from predecessors. 3656 for (auto *B : predecessors(PHI->getParent())) { 3657 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B); 3658 assert(Map.find(PV) != Map.end() && "No predecessor Value!"); 3659 PHI->addIncoming(ST.Get(Map[PV]), B); 3660 } 3661 } 3662 Map[Current] = ST.Simplify(V); 3663 } 3664 } 3665 3666 /// Starting from original value recursively iterates over def-use chain up to 3667 /// known ending values represented in a map. For each traversed phi/select 3668 /// inserts a placeholder Phi or Select. 3669 /// Reports all new created Phi/Select nodes by adding them to set. 3670 /// Also reports and order in what values have been traversed. 3671 void InsertPlaceholders(FoldAddrToValueMapping &Map, 3672 SmallVectorImpl<Value *> &TraverseOrder, 3673 SimplificationTracker &ST) { 3674 SmallVector<Value *, 32> Worklist; 3675 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) && 3676 "Address must be a Phi or Select node"); 3677 auto *Dummy = UndefValue::get(CommonType); 3678 Worklist.push_back(Original); 3679 while (!Worklist.empty()) { 3680 Value *Current = Worklist.pop_back_val(); 3681 // if it is already visited or it is an ending value then skip it. 3682 if (Map.find(Current) != Map.end()) 3683 continue; 3684 TraverseOrder.push_back(Current); 3685 3686 // CurrentValue must be a Phi node or select. All others must be covered 3687 // by anchors. 3688 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) { 3689 // Is it OK to get metadata from OrigSelect?! 3690 // Create a Select placeholder with dummy value. 3691 SelectInst *Select = SelectInst::Create( 3692 CurrentSelect->getCondition(), Dummy, Dummy, 3693 CurrentSelect->getName(), CurrentSelect, CurrentSelect); 3694 Map[Current] = Select; 3695 ST.insertNewSelect(Select); 3696 // We are interested in True and False values. 3697 Worklist.push_back(CurrentSelect->getTrueValue()); 3698 Worklist.push_back(CurrentSelect->getFalseValue()); 3699 } else { 3700 // It must be a Phi node then. 3701 PHINode *CurrentPhi = cast<PHINode>(Current); 3702 unsigned PredCount = CurrentPhi->getNumIncomingValues(); 3703 PHINode *PHI = 3704 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi); 3705 Map[Current] = PHI; 3706 ST.insertNewPhi(PHI); 3707 for (Value *P : CurrentPhi->incoming_values()) 3708 Worklist.push_back(P); 3709 } 3710 } 3711 } 3712 3713 bool addrModeCombiningAllowed() { 3714 if (DisableComplexAddrModes) 3715 return false; 3716 switch (DifferentField) { 3717 default: 3718 return false; 3719 case ExtAddrMode::BaseRegField: 3720 return AddrSinkCombineBaseReg; 3721 case ExtAddrMode::BaseGVField: 3722 return AddrSinkCombineBaseGV; 3723 case ExtAddrMode::BaseOffsField: 3724 return AddrSinkCombineBaseOffs; 3725 case ExtAddrMode::ScaledRegField: 3726 return AddrSinkCombineScaledReg; 3727 } 3728 } 3729 }; 3730 } // end anonymous namespace 3731 3732 /// Try adding ScaleReg*Scale to the current addressing mode. 3733 /// Return true and update AddrMode if this addr mode is legal for the target, 3734 /// false if not. 3735 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, 3736 unsigned Depth) { 3737 // If Scale is 1, then this is the same as adding ScaleReg to the addressing 3738 // mode. Just process that directly. 3739 if (Scale == 1) 3740 return matchAddr(ScaleReg, Depth); 3741 3742 // If the scale is 0, it takes nothing to add this. 3743 if (Scale == 0) 3744 return true; 3745 3746 // If we already have a scale of this value, we can add to it, otherwise, we 3747 // need an available scale field. 3748 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) 3749 return false; 3750 3751 ExtAddrMode TestAddrMode = AddrMode; 3752 3753 // Add scale to turn X*4+X*3 -> X*7. This could also do things like 3754 // [A+B + A*7] -> [B+A*8]. 3755 TestAddrMode.Scale += Scale; 3756 TestAddrMode.ScaledReg = ScaleReg; 3757 3758 // If the new address isn't legal, bail out. 3759 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) 3760 return false; 3761 3762 // It was legal, so commit it. 3763 AddrMode = TestAddrMode; 3764 3765 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now 3766 // to see if ScaleReg is actually X+C. If so, we can turn this into adding 3767 // X*Scale + C*Scale to addr mode. 3768 ConstantInt *CI = nullptr; Value *AddLHS = nullptr; 3769 if (isa<Instruction>(ScaleReg) && // not a constant expr. 3770 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) && 3771 CI->getValue().isSignedIntN(64)) { 3772 TestAddrMode.InBounds = false; 3773 TestAddrMode.ScaledReg = AddLHS; 3774 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale; 3775 3776 // If this addressing mode is legal, commit it and remember that we folded 3777 // this instruction. 3778 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { 3779 AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); 3780 AddrMode = TestAddrMode; 3781 return true; 3782 } 3783 } 3784 3785 // Otherwise, not (x+c)*scale, just return what we have. 3786 return true; 3787 } 3788 3789 /// This is a little filter, which returns true if an addressing computation 3790 /// involving I might be folded into a load/store accessing it. 3791 /// This doesn't need to be perfect, but needs to accept at least 3792 /// the set of instructions that MatchOperationAddr can. 3793 static bool MightBeFoldableInst(Instruction *I) { 3794 switch (I->getOpcode()) { 3795 case Instruction::BitCast: 3796 case Instruction::AddrSpaceCast: 3797 // Don't touch identity bitcasts. 3798 if (I->getType() == I->getOperand(0)->getType()) 3799 return false; 3800 return I->getType()->isIntOrPtrTy(); 3801 case Instruction::PtrToInt: 3802 // PtrToInt is always a noop, as we know that the int type is pointer sized. 3803 return true; 3804 case Instruction::IntToPtr: 3805 // We know the input is intptr_t, so this is foldable. 3806 return true; 3807 case Instruction::Add: 3808 return true; 3809 case Instruction::Mul: 3810 case Instruction::Shl: 3811 // Can only handle X*C and X << C. 3812 return isa<ConstantInt>(I->getOperand(1)); 3813 case Instruction::GetElementPtr: 3814 return true; 3815 default: 3816 return false; 3817 } 3818 } 3819 3820 /// Check whether or not \p Val is a legal instruction for \p TLI. 3821 /// \note \p Val is assumed to be the product of some type promotion. 3822 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed 3823 /// to be legal, as the non-promoted value would have had the same state. 3824 static bool isPromotedInstructionLegal(const TargetLowering &TLI, 3825 const DataLayout &DL, Value *Val) { 3826 Instruction *PromotedInst = dyn_cast<Instruction>(Val); 3827 if (!PromotedInst) 3828 return false; 3829 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); 3830 // If the ISDOpcode is undefined, it was undefined before the promotion. 3831 if (!ISDOpcode) 3832 return true; 3833 // Otherwise, check if the promoted instruction is legal or not. 3834 return TLI.isOperationLegalOrCustom( 3835 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); 3836 } 3837 3838 namespace { 3839 3840 /// Hepler class to perform type promotion. 3841 class TypePromotionHelper { 3842 /// Utility function to add a promoted instruction \p ExtOpnd to 3843 /// \p PromotedInsts and record the type of extension we have seen. 3844 static void addPromotedInst(InstrToOrigTy &PromotedInsts, 3845 Instruction *ExtOpnd, 3846 bool IsSExt) { 3847 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; 3848 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd); 3849 if (It != PromotedInsts.end()) { 3850 // If the new extension is same as original, the information in 3851 // PromotedInsts[ExtOpnd] is still correct. 3852 if (It->second.getInt() == ExtTy) 3853 return; 3854 3855 // Now the new extension is different from old extension, we make 3856 // the type information invalid by setting extension type to 3857 // BothExtension. 3858 ExtTy = BothExtension; 3859 } 3860 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy); 3861 } 3862 3863 /// Utility function to query the original type of instruction \p Opnd 3864 /// with a matched extension type. If the extension doesn't match, we 3865 /// cannot use the information we had on the original type. 3866 /// BothExtension doesn't match any extension type. 3867 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts, 3868 Instruction *Opnd, 3869 bool IsSExt) { 3870 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; 3871 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); 3872 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy) 3873 return It->second.getPointer(); 3874 return nullptr; 3875 } 3876 3877 /// Utility function to check whether or not a sign or zero extension 3878 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by 3879 /// either using the operands of \p Inst or promoting \p Inst. 3880 /// The type of the extension is defined by \p IsSExt. 3881 /// In other words, check if: 3882 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. 3883 /// #1 Promotion applies: 3884 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). 3885 /// #2 Operand reuses: 3886 /// ext opnd1 to ConsideredExtType. 3887 /// \p PromotedInsts maps the instructions to their type before promotion. 3888 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, 3889 const InstrToOrigTy &PromotedInsts, bool IsSExt); 3890 3891 /// Utility function to determine if \p OpIdx should be promoted when 3892 /// promoting \p Inst. 3893 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { 3894 return !(isa<SelectInst>(Inst) && OpIdx == 0); 3895 } 3896 3897 /// Utility function to promote the operand of \p Ext when this 3898 /// operand is a promotable trunc or sext or zext. 3899 /// \p PromotedInsts maps the instructions to their type before promotion. 3900 /// \p CreatedInstsCost[out] contains the cost of all instructions 3901 /// created to promote the operand of Ext. 3902 /// Newly added extensions are inserted in \p Exts. 3903 /// Newly added truncates are inserted in \p Truncs. 3904 /// Should never be called directly. 3905 /// \return The promoted value which is used instead of Ext. 3906 static Value *promoteOperandForTruncAndAnyExt( 3907 Instruction *Ext, TypePromotionTransaction &TPT, 3908 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 3909 SmallVectorImpl<Instruction *> *Exts, 3910 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); 3911 3912 /// Utility function to promote the operand of \p Ext when this 3913 /// operand is promotable and is not a supported trunc or sext. 3914 /// \p PromotedInsts maps the instructions to their type before promotion. 3915 /// \p CreatedInstsCost[out] contains the cost of all the instructions 3916 /// created to promote the operand of Ext. 3917 /// Newly added extensions are inserted in \p Exts. 3918 /// Newly added truncates are inserted in \p Truncs. 3919 /// Should never be called directly. 3920 /// \return The promoted value which is used instead of Ext. 3921 static Value *promoteOperandForOther(Instruction *Ext, 3922 TypePromotionTransaction &TPT, 3923 InstrToOrigTy &PromotedInsts, 3924 unsigned &CreatedInstsCost, 3925 SmallVectorImpl<Instruction *> *Exts, 3926 SmallVectorImpl<Instruction *> *Truncs, 3927 const TargetLowering &TLI, bool IsSExt); 3928 3929 /// \see promoteOperandForOther. 3930 static Value *signExtendOperandForOther( 3931 Instruction *Ext, TypePromotionTransaction &TPT, 3932 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 3933 SmallVectorImpl<Instruction *> *Exts, 3934 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { 3935 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, 3936 Exts, Truncs, TLI, true); 3937 } 3938 3939 /// \see promoteOperandForOther. 3940 static Value *zeroExtendOperandForOther( 3941 Instruction *Ext, TypePromotionTransaction &TPT, 3942 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 3943 SmallVectorImpl<Instruction *> *Exts, 3944 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { 3945 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, 3946 Exts, Truncs, TLI, false); 3947 } 3948 3949 public: 3950 /// Type for the utility function that promotes the operand of Ext. 3951 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT, 3952 InstrToOrigTy &PromotedInsts, 3953 unsigned &CreatedInstsCost, 3954 SmallVectorImpl<Instruction *> *Exts, 3955 SmallVectorImpl<Instruction *> *Truncs, 3956 const TargetLowering &TLI); 3957 3958 /// Given a sign/zero extend instruction \p Ext, return the appropriate 3959 /// action to promote the operand of \p Ext instead of using Ext. 3960 /// \return NULL if no promotable action is possible with the current 3961 /// sign extension. 3962 /// \p InsertedInsts keeps track of all the instructions inserted by the 3963 /// other CodeGenPrepare optimizations. This information is important 3964 /// because we do not want to promote these instructions as CodeGenPrepare 3965 /// will reinsert them later. Thus creating an infinite loop: create/remove. 3966 /// \p PromotedInsts maps the instructions to their type before promotion. 3967 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, 3968 const TargetLowering &TLI, 3969 const InstrToOrigTy &PromotedInsts); 3970 }; 3971 3972 } // end anonymous namespace 3973 3974 bool TypePromotionHelper::canGetThrough(const Instruction *Inst, 3975 Type *ConsideredExtType, 3976 const InstrToOrigTy &PromotedInsts, 3977 bool IsSExt) { 3978 // The promotion helper does not know how to deal with vector types yet. 3979 // To be able to fix that, we would need to fix the places where we 3980 // statically extend, e.g., constants and such. 3981 if (Inst->getType()->isVectorTy()) 3982 return false; 3983 3984 // We can always get through zext. 3985 if (isa<ZExtInst>(Inst)) 3986 return true; 3987 3988 // sext(sext) is ok too. 3989 if (IsSExt && isa<SExtInst>(Inst)) 3990 return true; 3991 3992 // We can get through binary operator, if it is legal. In other words, the 3993 // binary operator must have a nuw or nsw flag. 3994 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); 3995 if (isa_and_nonnull<OverflowingBinaryOperator>(BinOp) && 3996 ((!IsSExt && BinOp->hasNoUnsignedWrap()) || 3997 (IsSExt && BinOp->hasNoSignedWrap()))) 3998 return true; 3999 4000 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst)) 4001 if ((Inst->getOpcode() == Instruction::And || 4002 Inst->getOpcode() == Instruction::Or)) 4003 return true; 4004 4005 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst)) 4006 if (Inst->getOpcode() == Instruction::Xor) { 4007 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)); 4008 // Make sure it is not a NOT. 4009 if (Cst && !Cst->getValue().isAllOnesValue()) 4010 return true; 4011 } 4012 4013 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst)) 4014 // It may change a poisoned value into a regular value, like 4015 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12 4016 // poisoned value regular value 4017 // It should be OK since undef covers valid value. 4018 if (Inst->getOpcode() == Instruction::LShr && !IsSExt) 4019 return true; 4020 4021 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst) 4022 // It may change a poisoned value into a regular value, like 4023 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12 4024 // poisoned value regular value 4025 // It should be OK since undef covers valid value. 4026 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) { 4027 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin()); 4028 if (ExtInst->hasOneUse()) { 4029 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin()); 4030 if (AndInst && AndInst->getOpcode() == Instruction::And) { 4031 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1)); 4032 if (Cst && 4033 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth())) 4034 return true; 4035 } 4036 } 4037 } 4038 4039 // Check if we can do the following simplification. 4040 // ext(trunc(opnd)) --> ext(opnd) 4041 if (!isa<TruncInst>(Inst)) 4042 return false; 4043 4044 Value *OpndVal = Inst->getOperand(0); 4045 // Check if we can use this operand in the extension. 4046 // If the type is larger than the result type of the extension, we cannot. 4047 if (!OpndVal->getType()->isIntegerTy() || 4048 OpndVal->getType()->getIntegerBitWidth() > 4049 ConsideredExtType->getIntegerBitWidth()) 4050 return false; 4051 4052 // If the operand of the truncate is not an instruction, we will not have 4053 // any information on the dropped bits. 4054 // (Actually we could for constant but it is not worth the extra logic). 4055 Instruction *Opnd = dyn_cast<Instruction>(OpndVal); 4056 if (!Opnd) 4057 return false; 4058 4059 // Check if the source of the type is narrow enough. 4060 // I.e., check that trunc just drops extended bits of the same kind of 4061 // the extension. 4062 // #1 get the type of the operand and check the kind of the extended bits. 4063 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt); 4064 if (OpndType) 4065 ; 4066 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) 4067 OpndType = Opnd->getOperand(0)->getType(); 4068 else 4069 return false; 4070 4071 // #2 check that the truncate just drops extended bits. 4072 return Inst->getType()->getIntegerBitWidth() >= 4073 OpndType->getIntegerBitWidth(); 4074 } 4075 4076 TypePromotionHelper::Action TypePromotionHelper::getAction( 4077 Instruction *Ext, const SetOfInstrs &InsertedInsts, 4078 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { 4079 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4080 "Unexpected instruction type"); 4081 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); 4082 Type *ExtTy = Ext->getType(); 4083 bool IsSExt = isa<SExtInst>(Ext); 4084 // If the operand of the extension is not an instruction, we cannot 4085 // get through. 4086 // If it, check we can get through. 4087 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) 4088 return nullptr; 4089 4090 // Do not promote if the operand has been added by codegenprepare. 4091 // Otherwise, it means we are undoing an optimization that is likely to be 4092 // redone, thus causing potential infinite loop. 4093 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) 4094 return nullptr; 4095 4096 // SExt or Trunc instructions. 4097 // Return the related handler. 4098 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || 4099 isa<ZExtInst>(ExtOpnd)) 4100 return promoteOperandForTruncAndAnyExt; 4101 4102 // Regular instruction. 4103 // Abort early if we will have to insert non-free instructions. 4104 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) 4105 return nullptr; 4106 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; 4107 } 4108 4109 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( 4110 Instruction *SExt, TypePromotionTransaction &TPT, 4111 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 4112 SmallVectorImpl<Instruction *> *Exts, 4113 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { 4114 // By construction, the operand of SExt is an instruction. Otherwise we cannot 4115 // get through it and this method should not be called. 4116 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); 4117 Value *ExtVal = SExt; 4118 bool HasMergedNonFreeExt = false; 4119 if (isa<ZExtInst>(SExtOpnd)) { 4120 // Replace s|zext(zext(opnd)) 4121 // => zext(opnd). 4122 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); 4123 Value *ZExt = 4124 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); 4125 TPT.replaceAllUsesWith(SExt, ZExt); 4126 TPT.eraseInstruction(SExt); 4127 ExtVal = ZExt; 4128 } else { 4129 // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) 4130 // => z|sext(opnd). 4131 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); 4132 } 4133 CreatedInstsCost = 0; 4134 4135 // Remove dead code. 4136 if (SExtOpnd->use_empty()) 4137 TPT.eraseInstruction(SExtOpnd); 4138 4139 // Check if the extension is still needed. 4140 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); 4141 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { 4142 if (ExtInst) { 4143 if (Exts) 4144 Exts->push_back(ExtInst); 4145 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; 4146 } 4147 return ExtVal; 4148 } 4149 4150 // At this point we have: ext ty opnd to ty. 4151 // Reassign the uses of ExtInst to the opnd and remove ExtInst. 4152 Value *NextVal = ExtInst->getOperand(0); 4153 TPT.eraseInstruction(ExtInst, NextVal); 4154 return NextVal; 4155 } 4156 4157 Value *TypePromotionHelper::promoteOperandForOther( 4158 Instruction *Ext, TypePromotionTransaction &TPT, 4159 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 4160 SmallVectorImpl<Instruction *> *Exts, 4161 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, 4162 bool IsSExt) { 4163 // By construction, the operand of Ext is an instruction. Otherwise we cannot 4164 // get through it and this method should not be called. 4165 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); 4166 CreatedInstsCost = 0; 4167 if (!ExtOpnd->hasOneUse()) { 4168 // ExtOpnd will be promoted. 4169 // All its uses, but Ext, will need to use a truncated value of the 4170 // promoted version. 4171 // Create the truncate now. 4172 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); 4173 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { 4174 // Insert it just after the definition. 4175 ITrunc->moveAfter(ExtOpnd); 4176 if (Truncs) 4177 Truncs->push_back(ITrunc); 4178 } 4179 4180 TPT.replaceAllUsesWith(ExtOpnd, Trunc); 4181 // Restore the operand of Ext (which has been replaced by the previous call 4182 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. 4183 TPT.setOperand(Ext, 0, ExtOpnd); 4184 } 4185 4186 // Get through the Instruction: 4187 // 1. Update its type. 4188 // 2. Replace the uses of Ext by Inst. 4189 // 3. Extend each operand that needs to be extended. 4190 4191 // Remember the original type of the instruction before promotion. 4192 // This is useful to know that the high bits are sign extended bits. 4193 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt); 4194 // Step #1. 4195 TPT.mutateType(ExtOpnd, Ext->getType()); 4196 // Step #2. 4197 TPT.replaceAllUsesWith(Ext, ExtOpnd); 4198 // Step #3. 4199 Instruction *ExtForOpnd = Ext; 4200 4201 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n"); 4202 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; 4203 ++OpIdx) { 4204 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); 4205 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || 4206 !shouldExtOperand(ExtOpnd, OpIdx)) { 4207 LLVM_DEBUG(dbgs() << "No need to propagate\n"); 4208 continue; 4209 } 4210 // Check if we can statically extend the operand. 4211 Value *Opnd = ExtOpnd->getOperand(OpIdx); 4212 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { 4213 LLVM_DEBUG(dbgs() << "Statically extend\n"); 4214 unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); 4215 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) 4216 : Cst->getValue().zext(BitWidth); 4217 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); 4218 continue; 4219 } 4220 // UndefValue are typed, so we have to statically sign extend them. 4221 if (isa<UndefValue>(Opnd)) { 4222 LLVM_DEBUG(dbgs() << "Statically extend\n"); 4223 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); 4224 continue; 4225 } 4226 4227 // Otherwise we have to explicitly sign extend the operand. 4228 // Check if Ext was reused to extend an operand. 4229 if (!ExtForOpnd) { 4230 // If yes, create a new one. 4231 LLVM_DEBUG(dbgs() << "More operands to ext\n"); 4232 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) 4233 : TPT.createZExt(Ext, Opnd, Ext->getType()); 4234 if (!isa<Instruction>(ValForExtOpnd)) { 4235 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); 4236 continue; 4237 } 4238 ExtForOpnd = cast<Instruction>(ValForExtOpnd); 4239 } 4240 if (Exts) 4241 Exts->push_back(ExtForOpnd); 4242 TPT.setOperand(ExtForOpnd, 0, Opnd); 4243 4244 // Move the sign extension before the insertion point. 4245 TPT.moveBefore(ExtForOpnd, ExtOpnd); 4246 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); 4247 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); 4248 // If more sext are required, new instructions will have to be created. 4249 ExtForOpnd = nullptr; 4250 } 4251 if (ExtForOpnd == Ext) { 4252 LLVM_DEBUG(dbgs() << "Extension is useless now\n"); 4253 TPT.eraseInstruction(Ext); 4254 } 4255 return ExtOpnd; 4256 } 4257 4258 /// Check whether or not promoting an instruction to a wider type is profitable. 4259 /// \p NewCost gives the cost of extension instructions created by the 4260 /// promotion. 4261 /// \p OldCost gives the cost of extension instructions before the promotion 4262 /// plus the number of instructions that have been 4263 /// matched in the addressing mode the promotion. 4264 /// \p PromotedOperand is the value that has been promoted. 4265 /// \return True if the promotion is profitable, false otherwise. 4266 bool AddressingModeMatcher::isPromotionProfitable( 4267 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { 4268 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost 4269 << '\n'); 4270 // The cost of the new extensions is greater than the cost of the 4271 // old extension plus what we folded. 4272 // This is not profitable. 4273 if (NewCost > OldCost) 4274 return false; 4275 if (NewCost < OldCost) 4276 return true; 4277 // The promotion is neutral but it may help folding the sign extension in 4278 // loads for instance. 4279 // Check that we did not create an illegal instruction. 4280 return isPromotedInstructionLegal(TLI, DL, PromotedOperand); 4281 } 4282 4283 /// Given an instruction or constant expr, see if we can fold the operation 4284 /// into the addressing mode. If so, update the addressing mode and return 4285 /// true, otherwise return false without modifying AddrMode. 4286 /// If \p MovedAway is not NULL, it contains the information of whether or 4287 /// not AddrInst has to be folded into the addressing mode on success. 4288 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing 4289 /// because it has been moved away. 4290 /// Thus AddrInst must not be added in the matched instructions. 4291 /// This state can happen when AddrInst is a sext, since it may be moved away. 4292 /// Therefore, AddrInst may not be valid when MovedAway is true and it must 4293 /// not be referenced anymore. 4294 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, 4295 unsigned Depth, 4296 bool *MovedAway) { 4297 // Avoid exponential behavior on extremely deep expression trees. 4298 if (Depth >= 5) return false; 4299 4300 // By default, all matched instructions stay in place. 4301 if (MovedAway) 4302 *MovedAway = false; 4303 4304 switch (Opcode) { 4305 case Instruction::PtrToInt: 4306 // PtrToInt is always a noop, as we know that the int type is pointer sized. 4307 return matchAddr(AddrInst->getOperand(0), Depth); 4308 case Instruction::IntToPtr: { 4309 auto AS = AddrInst->getType()->getPointerAddressSpace(); 4310 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); 4311 // This inttoptr is a no-op if the integer type is pointer sized. 4312 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) 4313 return matchAddr(AddrInst->getOperand(0), Depth); 4314 return false; 4315 } 4316 case Instruction::BitCast: 4317 // BitCast is always a noop, and we can handle it as long as it is 4318 // int->int or pointer->pointer (we don't want int<->fp or something). 4319 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() && 4320 // Don't touch identity bitcasts. These were probably put here by LSR, 4321 // and we don't want to mess around with them. Assume it knows what it 4322 // is doing. 4323 AddrInst->getOperand(0)->getType() != AddrInst->getType()) 4324 return matchAddr(AddrInst->getOperand(0), Depth); 4325 return false; 4326 case Instruction::AddrSpaceCast: { 4327 unsigned SrcAS 4328 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); 4329 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); 4330 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS)) 4331 return matchAddr(AddrInst->getOperand(0), Depth); 4332 return false; 4333 } 4334 case Instruction::Add: { 4335 // Check to see if we can merge in the RHS then the LHS. If so, we win. 4336 ExtAddrMode BackupAddrMode = AddrMode; 4337 unsigned OldSize = AddrModeInsts.size(); 4338 // Start a transaction at this point. 4339 // The LHS may match but not the RHS. 4340 // Therefore, we need a higher level restoration point to undo partially 4341 // matched operation. 4342 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4343 TPT.getRestorationPoint(); 4344 4345 AddrMode.InBounds = false; 4346 if (matchAddr(AddrInst->getOperand(1), Depth+1) && 4347 matchAddr(AddrInst->getOperand(0), Depth+1)) 4348 return true; 4349 4350 // Restore the old addr mode info. 4351 AddrMode = BackupAddrMode; 4352 AddrModeInsts.resize(OldSize); 4353 TPT.rollback(LastKnownGood); 4354 4355 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. 4356 if (matchAddr(AddrInst->getOperand(0), Depth+1) && 4357 matchAddr(AddrInst->getOperand(1), Depth+1)) 4358 return true; 4359 4360 // Otherwise we definitely can't merge the ADD in. 4361 AddrMode = BackupAddrMode; 4362 AddrModeInsts.resize(OldSize); 4363 TPT.rollback(LastKnownGood); 4364 break; 4365 } 4366 //case Instruction::Or: 4367 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. 4368 //break; 4369 case Instruction::Mul: 4370 case Instruction::Shl: { 4371 // Can only handle X*C and X << C. 4372 AddrMode.InBounds = false; 4373 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); 4374 if (!RHS || RHS->getBitWidth() > 64) 4375 return false; 4376 int64_t Scale = RHS->getSExtValue(); 4377 if (Opcode == Instruction::Shl) 4378 Scale = 1LL << Scale; 4379 4380 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); 4381 } 4382 case Instruction::GetElementPtr: { 4383 // Scan the GEP. We check it if it contains constant offsets and at most 4384 // one variable offset. 4385 int VariableOperand = -1; 4386 unsigned VariableScale = 0; 4387 4388 int64_t ConstantOffset = 0; 4389 gep_type_iterator GTI = gep_type_begin(AddrInst); 4390 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { 4391 if (StructType *STy = GTI.getStructTypeOrNull()) { 4392 const StructLayout *SL = DL.getStructLayout(STy); 4393 unsigned Idx = 4394 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); 4395 ConstantOffset += SL->getElementOffset(Idx); 4396 } else { 4397 TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType()); 4398 if (TS.isNonZero()) { 4399 // The optimisations below currently only work for fixed offsets. 4400 if (TS.isScalable()) 4401 return false; 4402 int64_t TypeSize = TS.getFixedSize(); 4403 if (ConstantInt *CI = 4404 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { 4405 const APInt &CVal = CI->getValue(); 4406 if (CVal.getMinSignedBits() <= 64) { 4407 ConstantOffset += CVal.getSExtValue() * TypeSize; 4408 continue; 4409 } 4410 } 4411 // We only allow one variable index at the moment. 4412 if (VariableOperand != -1) 4413 return false; 4414 4415 // Remember the variable index. 4416 VariableOperand = i; 4417 VariableScale = TypeSize; 4418 } 4419 } 4420 } 4421 4422 // A common case is for the GEP to only do a constant offset. In this case, 4423 // just add it to the disp field and check validity. 4424 if (VariableOperand == -1) { 4425 AddrMode.BaseOffs += ConstantOffset; 4426 if (ConstantOffset == 0 || 4427 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { 4428 // Check to see if we can fold the base pointer in too. 4429 if (matchAddr(AddrInst->getOperand(0), Depth+1)) { 4430 if (!cast<GEPOperator>(AddrInst)->isInBounds()) 4431 AddrMode.InBounds = false; 4432 return true; 4433 } 4434 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) && 4435 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 && 4436 ConstantOffset > 0) { 4437 // Record GEPs with non-zero offsets as candidates for splitting in the 4438 // event that the offset cannot fit into the r+i addressing mode. 4439 // Simple and common case that only one GEP is used in calculating the 4440 // address for the memory access. 4441 Value *Base = AddrInst->getOperand(0); 4442 auto *BaseI = dyn_cast<Instruction>(Base); 4443 auto *GEP = cast<GetElementPtrInst>(AddrInst); 4444 if (isa<Argument>(Base) || isa<GlobalValue>(Base) || 4445 (BaseI && !isa<CastInst>(BaseI) && 4446 !isa<GetElementPtrInst>(BaseI))) { 4447 // Make sure the parent block allows inserting non-PHI instructions 4448 // before the terminator. 4449 BasicBlock *Parent = 4450 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock(); 4451 if (!Parent->getTerminator()->isEHPad()) 4452 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset); 4453 } 4454 } 4455 AddrMode.BaseOffs -= ConstantOffset; 4456 return false; 4457 } 4458 4459 // Save the valid addressing mode in case we can't match. 4460 ExtAddrMode BackupAddrMode = AddrMode; 4461 unsigned OldSize = AddrModeInsts.size(); 4462 4463 // See if the scale and offset amount is valid for this target. 4464 AddrMode.BaseOffs += ConstantOffset; 4465 if (!cast<GEPOperator>(AddrInst)->isInBounds()) 4466 AddrMode.InBounds = false; 4467 4468 // Match the base operand of the GEP. 4469 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { 4470 // If it couldn't be matched, just stuff the value in a register. 4471 if (AddrMode.HasBaseReg) { 4472 AddrMode = BackupAddrMode; 4473 AddrModeInsts.resize(OldSize); 4474 return false; 4475 } 4476 AddrMode.HasBaseReg = true; 4477 AddrMode.BaseReg = AddrInst->getOperand(0); 4478 } 4479 4480 // Match the remaining variable portion of the GEP. 4481 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, 4482 Depth)) { 4483 // If it couldn't be matched, try stuffing the base into a register 4484 // instead of matching it, and retrying the match of the scale. 4485 AddrMode = BackupAddrMode; 4486 AddrModeInsts.resize(OldSize); 4487 if (AddrMode.HasBaseReg) 4488 return false; 4489 AddrMode.HasBaseReg = true; 4490 AddrMode.BaseReg = AddrInst->getOperand(0); 4491 AddrMode.BaseOffs += ConstantOffset; 4492 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), 4493 VariableScale, Depth)) { 4494 // If even that didn't work, bail. 4495 AddrMode = BackupAddrMode; 4496 AddrModeInsts.resize(OldSize); 4497 return false; 4498 } 4499 } 4500 4501 return true; 4502 } 4503 case Instruction::SExt: 4504 case Instruction::ZExt: { 4505 Instruction *Ext = dyn_cast<Instruction>(AddrInst); 4506 if (!Ext) 4507 return false; 4508 4509 // Try to move this ext out of the way of the addressing mode. 4510 // Ask for a method for doing so. 4511 TypePromotionHelper::Action TPH = 4512 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); 4513 if (!TPH) 4514 return false; 4515 4516 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4517 TPT.getRestorationPoint(); 4518 unsigned CreatedInstsCost = 0; 4519 unsigned ExtCost = !TLI.isExtFree(Ext); 4520 Value *PromotedOperand = 4521 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); 4522 // SExt has been moved away. 4523 // Thus either it will be rematched later in the recursive calls or it is 4524 // gone. Anyway, we must not fold it into the addressing mode at this point. 4525 // E.g., 4526 // op = add opnd, 1 4527 // idx = ext op 4528 // addr = gep base, idx 4529 // is now: 4530 // promotedOpnd = ext opnd <- no match here 4531 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) 4532 // addr = gep base, op <- match 4533 if (MovedAway) 4534 *MovedAway = true; 4535 4536 assert(PromotedOperand && 4537 "TypePromotionHelper should have filtered out those cases"); 4538 4539 ExtAddrMode BackupAddrMode = AddrMode; 4540 unsigned OldSize = AddrModeInsts.size(); 4541 4542 if (!matchAddr(PromotedOperand, Depth) || 4543 // The total of the new cost is equal to the cost of the created 4544 // instructions. 4545 // The total of the old cost is equal to the cost of the extension plus 4546 // what we have saved in the addressing mode. 4547 !isPromotionProfitable(CreatedInstsCost, 4548 ExtCost + (AddrModeInsts.size() - OldSize), 4549 PromotedOperand)) { 4550 AddrMode = BackupAddrMode; 4551 AddrModeInsts.resize(OldSize); 4552 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); 4553 TPT.rollback(LastKnownGood); 4554 return false; 4555 } 4556 return true; 4557 } 4558 } 4559 return false; 4560 } 4561 4562 /// If we can, try to add the value of 'Addr' into the current addressing mode. 4563 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode 4564 /// unmodified. This assumes that Addr is either a pointer type or intptr_t 4565 /// for the target. 4566 /// 4567 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { 4568 // Start a transaction at this point that we will rollback if the matching 4569 // fails. 4570 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4571 TPT.getRestorationPoint(); 4572 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { 4573 if (CI->getValue().isSignedIntN(64)) { 4574 // Fold in immediates if legal for the target. 4575 AddrMode.BaseOffs += CI->getSExtValue(); 4576 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4577 return true; 4578 AddrMode.BaseOffs -= CI->getSExtValue(); 4579 } 4580 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { 4581 // If this is a global variable, try to fold it into the addressing mode. 4582 if (!AddrMode.BaseGV) { 4583 AddrMode.BaseGV = GV; 4584 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4585 return true; 4586 AddrMode.BaseGV = nullptr; 4587 } 4588 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { 4589 ExtAddrMode BackupAddrMode = AddrMode; 4590 unsigned OldSize = AddrModeInsts.size(); 4591 4592 // Check to see if it is possible to fold this operation. 4593 bool MovedAway = false; 4594 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { 4595 // This instruction may have been moved away. If so, there is nothing 4596 // to check here. 4597 if (MovedAway) 4598 return true; 4599 // Okay, it's possible to fold this. Check to see if it is actually 4600 // *profitable* to do so. We use a simple cost model to avoid increasing 4601 // register pressure too much. 4602 if (I->hasOneUse() || 4603 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { 4604 AddrModeInsts.push_back(I); 4605 return true; 4606 } 4607 4608 // It isn't profitable to do this, roll back. 4609 //cerr << "NOT FOLDING: " << *I; 4610 AddrMode = BackupAddrMode; 4611 AddrModeInsts.resize(OldSize); 4612 TPT.rollback(LastKnownGood); 4613 } 4614 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { 4615 if (matchOperationAddr(CE, CE->getOpcode(), Depth)) 4616 return true; 4617 TPT.rollback(LastKnownGood); 4618 } else if (isa<ConstantPointerNull>(Addr)) { 4619 // Null pointer gets folded without affecting the addressing mode. 4620 return true; 4621 } 4622 4623 // Worse case, the target should support [reg] addressing modes. :) 4624 if (!AddrMode.HasBaseReg) { 4625 AddrMode.HasBaseReg = true; 4626 AddrMode.BaseReg = Addr; 4627 // Still check for legality in case the target supports [imm] but not [i+r]. 4628 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4629 return true; 4630 AddrMode.HasBaseReg = false; 4631 AddrMode.BaseReg = nullptr; 4632 } 4633 4634 // If the base register is already taken, see if we can do [r+r]. 4635 if (AddrMode.Scale == 0) { 4636 AddrMode.Scale = 1; 4637 AddrMode.ScaledReg = Addr; 4638 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4639 return true; 4640 AddrMode.Scale = 0; 4641 AddrMode.ScaledReg = nullptr; 4642 } 4643 // Couldn't match. 4644 TPT.rollback(LastKnownGood); 4645 return false; 4646 } 4647 4648 /// Check to see if all uses of OpVal by the specified inline asm call are due 4649 /// to memory operands. If so, return true, otherwise return false. 4650 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, 4651 const TargetLowering &TLI, 4652 const TargetRegisterInfo &TRI) { 4653 const Function *F = CI->getFunction(); 4654 TargetLowering::AsmOperandInfoVector TargetConstraints = 4655 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI); 4656 4657 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 4658 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 4659 4660 // Compute the constraint code and ConstraintType to use. 4661 TLI.ComputeConstraintToUse(OpInfo, SDValue()); 4662 4663 // If this asm operand is our Value*, and if it isn't an indirect memory 4664 // operand, we can't fold it! 4665 if (OpInfo.CallOperandVal == OpVal && 4666 (OpInfo.ConstraintType != TargetLowering::C_Memory || 4667 !OpInfo.isIndirect)) 4668 return false; 4669 } 4670 4671 return true; 4672 } 4673 4674 // Max number of memory uses to look at before aborting the search to conserve 4675 // compile time. 4676 static constexpr int MaxMemoryUsesToScan = 20; 4677 4678 /// Recursively walk all the uses of I until we find a memory use. 4679 /// If we find an obviously non-foldable instruction, return true. 4680 /// Add the ultimately found memory instructions to MemoryUses. 4681 static bool FindAllMemoryUses( 4682 Instruction *I, 4683 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, 4684 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI, 4685 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, 4686 BlockFrequencyInfo *BFI, int SeenInsts = 0) { 4687 // If we already considered this instruction, we're done. 4688 if (!ConsideredInsts.insert(I).second) 4689 return false; 4690 4691 // If this is an obviously unfoldable instruction, bail out. 4692 if (!MightBeFoldableInst(I)) 4693 return true; 4694 4695 // Loop over all the uses, recursively processing them. 4696 for (Use &U : I->uses()) { 4697 // Conservatively return true if we're seeing a large number or a deep chain 4698 // of users. This avoids excessive compilation times in pathological cases. 4699 if (SeenInsts++ >= MaxMemoryUsesToScan) 4700 return true; 4701 4702 Instruction *UserI = cast<Instruction>(U.getUser()); 4703 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { 4704 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); 4705 continue; 4706 } 4707 4708 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { 4709 unsigned opNo = U.getOperandNo(); 4710 if (opNo != StoreInst::getPointerOperandIndex()) 4711 return true; // Storing addr, not into addr. 4712 MemoryUses.push_back(std::make_pair(SI, opNo)); 4713 continue; 4714 } 4715 4716 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { 4717 unsigned opNo = U.getOperandNo(); 4718 if (opNo != AtomicRMWInst::getPointerOperandIndex()) 4719 return true; // Storing addr, not into addr. 4720 MemoryUses.push_back(std::make_pair(RMW, opNo)); 4721 continue; 4722 } 4723 4724 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { 4725 unsigned opNo = U.getOperandNo(); 4726 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) 4727 return true; // Storing addr, not into addr. 4728 MemoryUses.push_back(std::make_pair(CmpX, opNo)); 4729 continue; 4730 } 4731 4732 if (CallInst *CI = dyn_cast<CallInst>(UserI)) { 4733 if (CI->hasFnAttr(Attribute::Cold)) { 4734 // If this is a cold call, we can sink the addressing calculation into 4735 // the cold path. See optimizeCallInst 4736 bool OptForSize = OptSize || 4737 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI); 4738 if (!OptForSize) 4739 continue; 4740 } 4741 4742 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand()); 4743 if (!IA) return true; 4744 4745 // If this is a memory operand, we're cool, otherwise bail out. 4746 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) 4747 return true; 4748 continue; 4749 } 4750 4751 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, 4752 PSI, BFI, SeenInsts)) 4753 return true; 4754 } 4755 4756 return false; 4757 } 4758 4759 /// Return true if Val is already known to be live at the use site that we're 4760 /// folding it into. If so, there is no cost to include it in the addressing 4761 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the 4762 /// instruction already. 4763 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, 4764 Value *KnownLive2) { 4765 // If Val is either of the known-live values, we know it is live! 4766 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) 4767 return true; 4768 4769 // All values other than instructions and arguments (e.g. constants) are live. 4770 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; 4771 4772 // If Val is a constant sized alloca in the entry block, it is live, this is 4773 // true because it is just a reference to the stack/frame pointer, which is 4774 // live for the whole function. 4775 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) 4776 if (AI->isStaticAlloca()) 4777 return true; 4778 4779 // Check to see if this value is already used in the memory instruction's 4780 // block. If so, it's already live into the block at the very least, so we 4781 // can reasonably fold it. 4782 return Val->isUsedInBasicBlock(MemoryInst->getParent()); 4783 } 4784 4785 /// It is possible for the addressing mode of the machine to fold the specified 4786 /// instruction into a load or store that ultimately uses it. 4787 /// However, the specified instruction has multiple uses. 4788 /// Given this, it may actually increase register pressure to fold it 4789 /// into the load. For example, consider this code: 4790 /// 4791 /// X = ... 4792 /// Y = X+1 4793 /// use(Y) -> nonload/store 4794 /// Z = Y+1 4795 /// load Z 4796 /// 4797 /// In this case, Y has multiple uses, and can be folded into the load of Z 4798 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to 4799 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one 4800 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the 4801 /// number of computations either. 4802 /// 4803 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If 4804 /// X was live across 'load Z' for other reasons, we actually *would* want to 4805 /// fold the addressing mode in the Z case. This would make Y die earlier. 4806 bool AddressingModeMatcher:: 4807 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, 4808 ExtAddrMode &AMAfter) { 4809 if (IgnoreProfitability) return true; 4810 4811 // AMBefore is the addressing mode before this instruction was folded into it, 4812 // and AMAfter is the addressing mode after the instruction was folded. Get 4813 // the set of registers referenced by AMAfter and subtract out those 4814 // referenced by AMBefore: this is the set of values which folding in this 4815 // address extends the lifetime of. 4816 // 4817 // Note that there are only two potential values being referenced here, 4818 // BaseReg and ScaleReg (global addresses are always available, as are any 4819 // folded immediates). 4820 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; 4821 4822 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their 4823 // lifetime wasn't extended by adding this instruction. 4824 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) 4825 BaseReg = nullptr; 4826 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) 4827 ScaledReg = nullptr; 4828 4829 // If folding this instruction (and it's subexprs) didn't extend any live 4830 // ranges, we're ok with it. 4831 if (!BaseReg && !ScaledReg) 4832 return true; 4833 4834 // If all uses of this instruction can have the address mode sunk into them, 4835 // we can remove the addressing mode and effectively trade one live register 4836 // for another (at worst.) In this context, folding an addressing mode into 4837 // the use is just a particularly nice way of sinking it. 4838 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; 4839 SmallPtrSet<Instruction*, 16> ConsideredInsts; 4840 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, 4841 PSI, BFI)) 4842 return false; // Has a non-memory, non-foldable use! 4843 4844 // Now that we know that all uses of this instruction are part of a chain of 4845 // computation involving only operations that could theoretically be folded 4846 // into a memory use, loop over each of these memory operation uses and see 4847 // if they could *actually* fold the instruction. The assumption is that 4848 // addressing modes are cheap and that duplicating the computation involved 4849 // many times is worthwhile, even on a fastpath. For sinking candidates 4850 // (i.e. cold call sites), this serves as a way to prevent excessive code 4851 // growth since most architectures have some reasonable small and fast way to 4852 // compute an effective address. (i.e LEA on x86) 4853 SmallVector<Instruction*, 32> MatchedAddrModeInsts; 4854 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { 4855 Instruction *User = MemoryUses[i].first; 4856 unsigned OpNo = MemoryUses[i].second; 4857 4858 // Get the access type of this use. If the use isn't a pointer, we don't 4859 // know what it accesses. 4860 Value *Address = User->getOperand(OpNo); 4861 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); 4862 if (!AddrTy) 4863 return false; 4864 Type *AddressAccessTy = AddrTy->getElementType(); 4865 unsigned AS = AddrTy->getAddressSpace(); 4866 4867 // Do a match against the root of this address, ignoring profitability. This 4868 // will tell us if the addressing mode for the memory operation will 4869 // *actually* cover the shared instruction. 4870 ExtAddrMode Result; 4871 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, 4872 0); 4873 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4874 TPT.getRestorationPoint(); 4875 AddressingModeMatcher Matcher( 4876 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result, 4877 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, BFI); 4878 Matcher.IgnoreProfitability = true; 4879 bool Success = Matcher.matchAddr(Address, 0); 4880 (void)Success; assert(Success && "Couldn't select *anything*?"); 4881 4882 // The match was to check the profitability, the changes made are not 4883 // part of the original matcher. Therefore, they should be dropped 4884 // otherwise the original matcher will not present the right state. 4885 TPT.rollback(LastKnownGood); 4886 4887 // If the match didn't cover I, then it won't be shared by it. 4888 if (!is_contained(MatchedAddrModeInsts, I)) 4889 return false; 4890 4891 MatchedAddrModeInsts.clear(); 4892 } 4893 4894 return true; 4895 } 4896 4897 /// Return true if the specified values are defined in a 4898 /// different basic block than BB. 4899 static bool IsNonLocalValue(Value *V, BasicBlock *BB) { 4900 if (Instruction *I = dyn_cast<Instruction>(V)) 4901 return I->getParent() != BB; 4902 return false; 4903 } 4904 4905 /// Sink addressing mode computation immediate before MemoryInst if doing so 4906 /// can be done without increasing register pressure. The need for the 4907 /// register pressure constraint means this can end up being an all or nothing 4908 /// decision for all uses of the same addressing computation. 4909 /// 4910 /// Load and Store Instructions often have addressing modes that can do 4911 /// significant amounts of computation. As such, instruction selection will try 4912 /// to get the load or store to do as much computation as possible for the 4913 /// program. The problem is that isel can only see within a single block. As 4914 /// such, we sink as much legal addressing mode work into the block as possible. 4915 /// 4916 /// This method is used to optimize both load/store and inline asms with memory 4917 /// operands. It's also used to sink addressing computations feeding into cold 4918 /// call sites into their (cold) basic block. 4919 /// 4920 /// The motivation for handling sinking into cold blocks is that doing so can 4921 /// both enable other address mode sinking (by satisfying the register pressure 4922 /// constraint above), and reduce register pressure globally (by removing the 4923 /// addressing mode computation from the fast path entirely.). 4924 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, 4925 Type *AccessTy, unsigned AddrSpace) { 4926 Value *Repl = Addr; 4927 4928 // Try to collapse single-value PHI nodes. This is necessary to undo 4929 // unprofitable PRE transformations. 4930 SmallVector<Value*, 8> worklist; 4931 SmallPtrSet<Value*, 16> Visited; 4932 worklist.push_back(Addr); 4933 4934 // Use a worklist to iteratively look through PHI and select nodes, and 4935 // ensure that the addressing mode obtained from the non-PHI/select roots of 4936 // the graph are compatible. 4937 bool PhiOrSelectSeen = false; 4938 SmallVector<Instruction*, 16> AddrModeInsts; 4939 const SimplifyQuery SQ(*DL, TLInfo); 4940 AddressingModeCombiner AddrModes(SQ, Addr); 4941 TypePromotionTransaction TPT(RemovedInsts); 4942 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4943 TPT.getRestorationPoint(); 4944 while (!worklist.empty()) { 4945 Value *V = worklist.back(); 4946 worklist.pop_back(); 4947 4948 // We allow traversing cyclic Phi nodes. 4949 // In case of success after this loop we ensure that traversing through 4950 // Phi nodes ends up with all cases to compute address of the form 4951 // BaseGV + Base + Scale * Index + Offset 4952 // where Scale and Offset are constans and BaseGV, Base and Index 4953 // are exactly the same Values in all cases. 4954 // It means that BaseGV, Scale and Offset dominate our memory instruction 4955 // and have the same value as they had in address computation represented 4956 // as Phi. So we can safely sink address computation to memory instruction. 4957 if (!Visited.insert(V).second) 4958 continue; 4959 4960 // For a PHI node, push all of its incoming values. 4961 if (PHINode *P = dyn_cast<PHINode>(V)) { 4962 for (Value *IncValue : P->incoming_values()) 4963 worklist.push_back(IncValue); 4964 PhiOrSelectSeen = true; 4965 continue; 4966 } 4967 // Similar for select. 4968 if (SelectInst *SI = dyn_cast<SelectInst>(V)) { 4969 worklist.push_back(SI->getFalseValue()); 4970 worklist.push_back(SI->getTrueValue()); 4971 PhiOrSelectSeen = true; 4972 continue; 4973 } 4974 4975 // For non-PHIs, determine the addressing mode being computed. Note that 4976 // the result may differ depending on what other uses our candidate 4977 // addressing instructions might have. 4978 AddrModeInsts.clear(); 4979 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, 4980 0); 4981 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( 4982 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI, 4983 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, 4984 BFI.get()); 4985 4986 GetElementPtrInst *GEP = LargeOffsetGEP.first; 4987 if (GEP && !NewGEPBases.count(GEP)) { 4988 // If splitting the underlying data structure can reduce the offset of a 4989 // GEP, collect the GEP. Skip the GEPs that are the new bases of 4990 // previously split data structures. 4991 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP); 4992 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end()) 4993 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size(); 4994 } 4995 4996 NewAddrMode.OriginalValue = V; 4997 if (!AddrModes.addNewAddrMode(NewAddrMode)) 4998 break; 4999 } 5000 5001 // Try to combine the AddrModes we've collected. If we couldn't collect any, 5002 // or we have multiple but either couldn't combine them or combining them 5003 // wouldn't do anything useful, bail out now. 5004 if (!AddrModes.combineAddrModes()) { 5005 TPT.rollback(LastKnownGood); 5006 return false; 5007 } 5008 bool Modified = TPT.commit(); 5009 5010 // Get the combined AddrMode (or the only AddrMode, if we only had one). 5011 ExtAddrMode AddrMode = AddrModes.getAddrMode(); 5012 5013 // If all the instructions matched are already in this BB, don't do anything. 5014 // If we saw a Phi node then it is not local definitely, and if we saw a select 5015 // then we want to push the address calculation past it even if it's already 5016 // in this BB. 5017 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) { 5018 return IsNonLocalValue(V, MemoryInst->getParent()); 5019 })) { 5020 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode 5021 << "\n"); 5022 return Modified; 5023 } 5024 5025 // Insert this computation right after this user. Since our caller is 5026 // scanning from the top of the BB to the bottom, reuse of the expr are 5027 // guaranteed to happen later. 5028 IRBuilder<> Builder(MemoryInst); 5029 5030 // Now that we determined the addressing expression we want to use and know 5031 // that we have to sink it into this block. Check to see if we have already 5032 // done this for some other load/store instr in this block. If so, reuse 5033 // the computation. Before attempting reuse, check if the address is valid 5034 // as it may have been erased. 5035 5036 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr]; 5037 5038 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; 5039 if (SunkAddr) { 5040 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode 5041 << " for " << *MemoryInst << "\n"); 5042 if (SunkAddr->getType() != Addr->getType()) 5043 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); 5044 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() && 5045 SubtargetInfo->addrSinkUsingGEPs())) { 5046 // By default, we use the GEP-based method when AA is used later. This 5047 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. 5048 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode 5049 << " for " << *MemoryInst << "\n"); 5050 Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); 5051 Value *ResultPtr = nullptr, *ResultIndex = nullptr; 5052 5053 // First, find the pointer. 5054 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { 5055 ResultPtr = AddrMode.BaseReg; 5056 AddrMode.BaseReg = nullptr; 5057 } 5058 5059 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { 5060 // We can't add more than one pointer together, nor can we scale a 5061 // pointer (both of which seem meaningless). 5062 if (ResultPtr || AddrMode.Scale != 1) 5063 return Modified; 5064 5065 ResultPtr = AddrMode.ScaledReg; 5066 AddrMode.Scale = 0; 5067 } 5068 5069 // It is only safe to sign extend the BaseReg if we know that the math 5070 // required to create it did not overflow before we extend it. Since 5071 // the original IR value was tossed in favor of a constant back when 5072 // the AddrMode was created we need to bail out gracefully if widths 5073 // do not match instead of extending it. 5074 // 5075 // (See below for code to add the scale.) 5076 if (AddrMode.Scale) { 5077 Type *ScaledRegTy = AddrMode.ScaledReg->getType(); 5078 if (cast<IntegerType>(IntPtrTy)->getBitWidth() > 5079 cast<IntegerType>(ScaledRegTy)->getBitWidth()) 5080 return Modified; 5081 } 5082 5083 if (AddrMode.BaseGV) { 5084 if (ResultPtr) 5085 return Modified; 5086 5087 ResultPtr = AddrMode.BaseGV; 5088 } 5089 5090 // If the real base value actually came from an inttoptr, then the matcher 5091 // will look through it and provide only the integer value. In that case, 5092 // use it here. 5093 if (!DL->isNonIntegralPointerType(Addr->getType())) { 5094 if (!ResultPtr && AddrMode.BaseReg) { 5095 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), 5096 "sunkaddr"); 5097 AddrMode.BaseReg = nullptr; 5098 } else if (!ResultPtr && AddrMode.Scale == 1) { 5099 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), 5100 "sunkaddr"); 5101 AddrMode.Scale = 0; 5102 } 5103 } 5104 5105 if (!ResultPtr && 5106 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { 5107 SunkAddr = Constant::getNullValue(Addr->getType()); 5108 } else if (!ResultPtr) { 5109 return Modified; 5110 } else { 5111 Type *I8PtrTy = 5112 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); 5113 Type *I8Ty = Builder.getInt8Ty(); 5114 5115 // Start with the base register. Do this first so that subsequent address 5116 // matching finds it last, which will prevent it from trying to match it 5117 // as the scaled value in case it happens to be a mul. That would be 5118 // problematic if we've sunk a different mul for the scale, because then 5119 // we'd end up sinking both muls. 5120 if (AddrMode.BaseReg) { 5121 Value *V = AddrMode.BaseReg; 5122 if (V->getType() != IntPtrTy) 5123 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); 5124 5125 ResultIndex = V; 5126 } 5127 5128 // Add the scale value. 5129 if (AddrMode.Scale) { 5130 Value *V = AddrMode.ScaledReg; 5131 if (V->getType() == IntPtrTy) { 5132 // done. 5133 } else { 5134 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() < 5135 cast<IntegerType>(V->getType())->getBitWidth() && 5136 "We can't transform if ScaledReg is too narrow"); 5137 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); 5138 } 5139 5140 if (AddrMode.Scale != 1) 5141 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), 5142 "sunkaddr"); 5143 if (ResultIndex) 5144 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); 5145 else 5146 ResultIndex = V; 5147 } 5148 5149 // Add in the Base Offset if present. 5150 if (AddrMode.BaseOffs) { 5151 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); 5152 if (ResultIndex) { 5153 // We need to add this separately from the scale above to help with 5154 // SDAG consecutive load/store merging. 5155 if (ResultPtr->getType() != I8PtrTy) 5156 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); 5157 ResultPtr = 5158 AddrMode.InBounds 5159 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, 5160 "sunkaddr") 5161 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); 5162 } 5163 5164 ResultIndex = V; 5165 } 5166 5167 if (!ResultIndex) { 5168 SunkAddr = ResultPtr; 5169 } else { 5170 if (ResultPtr->getType() != I8PtrTy) 5171 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); 5172 SunkAddr = 5173 AddrMode.InBounds 5174 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, 5175 "sunkaddr") 5176 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); 5177 } 5178 5179 if (SunkAddr->getType() != Addr->getType()) 5180 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); 5181 } 5182 } else { 5183 // We'd require a ptrtoint/inttoptr down the line, which we can't do for 5184 // non-integral pointers, so in that case bail out now. 5185 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr; 5186 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr; 5187 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy); 5188 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy); 5189 if (DL->isNonIntegralPointerType(Addr->getType()) || 5190 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) || 5191 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) || 5192 (AddrMode.BaseGV && 5193 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType()))) 5194 return Modified; 5195 5196 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode 5197 << " for " << *MemoryInst << "\n"); 5198 Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); 5199 Value *Result = nullptr; 5200 5201 // Start with the base register. Do this first so that subsequent address 5202 // matching finds it last, which will prevent it from trying to match it 5203 // as the scaled value in case it happens to be a mul. That would be 5204 // problematic if we've sunk a different mul for the scale, because then 5205 // we'd end up sinking both muls. 5206 if (AddrMode.BaseReg) { 5207 Value *V = AddrMode.BaseReg; 5208 if (V->getType()->isPointerTy()) 5209 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); 5210 if (V->getType() != IntPtrTy) 5211 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); 5212 Result = V; 5213 } 5214 5215 // Add the scale value. 5216 if (AddrMode.Scale) { 5217 Value *V = AddrMode.ScaledReg; 5218 if (V->getType() == IntPtrTy) { 5219 // done. 5220 } else if (V->getType()->isPointerTy()) { 5221 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); 5222 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < 5223 cast<IntegerType>(V->getType())->getBitWidth()) { 5224 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); 5225 } else { 5226 // It is only safe to sign extend the BaseReg if we know that the math 5227 // required to create it did not overflow before we extend it. Since 5228 // the original IR value was tossed in favor of a constant back when 5229 // the AddrMode was created we need to bail out gracefully if widths 5230 // do not match instead of extending it. 5231 Instruction *I = dyn_cast_or_null<Instruction>(Result); 5232 if (I && (Result != AddrMode.BaseReg)) 5233 I->eraseFromParent(); 5234 return Modified; 5235 } 5236 if (AddrMode.Scale != 1) 5237 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), 5238 "sunkaddr"); 5239 if (Result) 5240 Result = Builder.CreateAdd(Result, V, "sunkaddr"); 5241 else 5242 Result = V; 5243 } 5244 5245 // Add in the BaseGV if present. 5246 if (AddrMode.BaseGV) { 5247 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); 5248 if (Result) 5249 Result = Builder.CreateAdd(Result, V, "sunkaddr"); 5250 else 5251 Result = V; 5252 } 5253 5254 // Add in the Base Offset if present. 5255 if (AddrMode.BaseOffs) { 5256 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); 5257 if (Result) 5258 Result = Builder.CreateAdd(Result, V, "sunkaddr"); 5259 else 5260 Result = V; 5261 } 5262 5263 if (!Result) 5264 SunkAddr = Constant::getNullValue(Addr->getType()); 5265 else 5266 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); 5267 } 5268 5269 MemoryInst->replaceUsesOfWith(Repl, SunkAddr); 5270 // Store the newly computed address into the cache. In the case we reused a 5271 // value, this should be idempotent. 5272 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr); 5273 5274 // If we have no uses, recursively delete the value and all dead instructions 5275 // using it. 5276 if (Repl->use_empty()) { 5277 // This can cause recursive deletion, which can invalidate our iterator. 5278 // Use a WeakTrackingVH to hold onto it in case this happens. 5279 Value *CurValue = &*CurInstIterator; 5280 WeakTrackingVH IterHandle(CurValue); 5281 BasicBlock *BB = CurInstIterator->getParent(); 5282 5283 RecursivelyDeleteTriviallyDeadInstructions( 5284 Repl, TLInfo, nullptr, 5285 [&](Value *V) { removeAllAssertingVHReferences(V); }); 5286 5287 if (IterHandle != CurValue) { 5288 // If the iterator instruction was recursively deleted, start over at the 5289 // start of the block. 5290 CurInstIterator = BB->begin(); 5291 SunkAddrs.clear(); 5292 } 5293 } 5294 ++NumMemoryInsts; 5295 return true; 5296 } 5297 5298 /// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find 5299 /// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can 5300 /// only handle a 2 operand GEP in the same basic block or a splat constant 5301 /// vector. The 2 operands to the GEP must have a scalar pointer and a vector 5302 /// index. 5303 /// 5304 /// If the existing GEP has a vector base pointer that is splat, we can look 5305 /// through the splat to find the scalar pointer. If we can't find a scalar 5306 /// pointer there's nothing we can do. 5307 /// 5308 /// If we have a GEP with more than 2 indices where the middle indices are all 5309 /// zeroes, we can replace it with 2 GEPs where the second has 2 operands. 5310 /// 5311 /// If the final index isn't a vector or is a splat, we can emit a scalar GEP 5312 /// followed by a GEP with an all zeroes vector index. This will enable 5313 /// SelectionDAGBuilder to use a the scalar GEP as the uniform base and have a 5314 /// zero index. 5315 bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst, 5316 Value *Ptr) { 5317 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 5318 if (!GEP || !GEP->hasIndices()) 5319 return false; 5320 5321 // If the GEP and the gather/scatter aren't in the same BB, don't optimize. 5322 // FIXME: We should support this by sinking the GEP. 5323 if (MemoryInst->getParent() != GEP->getParent()) 5324 return false; 5325 5326 SmallVector<Value *, 2> Ops(GEP->op_begin(), GEP->op_end()); 5327 5328 bool RewriteGEP = false; 5329 5330 if (Ops[0]->getType()->isVectorTy()) { 5331 Ops[0] = const_cast<Value *>(getSplatValue(Ops[0])); 5332 if (!Ops[0]) 5333 return false; 5334 RewriteGEP = true; 5335 } 5336 5337 unsigned FinalIndex = Ops.size() - 1; 5338 5339 // Ensure all but the last index is 0. 5340 // FIXME: This isn't strictly required. All that's required is that they are 5341 // all scalars or splats. 5342 for (unsigned i = 1; i < FinalIndex; ++i) { 5343 auto *C = dyn_cast<Constant>(Ops[i]); 5344 if (!C) 5345 return false; 5346 if (isa<VectorType>(C->getType())) 5347 C = C->getSplatValue(); 5348 auto *CI = dyn_cast_or_null<ConstantInt>(C); 5349 if (!CI || !CI->isZero()) 5350 return false; 5351 // Scalarize the index if needed. 5352 Ops[i] = CI; 5353 } 5354 5355 // Try to scalarize the final index. 5356 if (Ops[FinalIndex]->getType()->isVectorTy()) { 5357 if (Value *V = const_cast<Value *>(getSplatValue(Ops[FinalIndex]))) { 5358 auto *C = dyn_cast<ConstantInt>(V); 5359 // Don't scalarize all zeros vector. 5360 if (!C || !C->isZero()) { 5361 Ops[FinalIndex] = V; 5362 RewriteGEP = true; 5363 } 5364 } 5365 } 5366 5367 // If we made any changes or the we have extra operands, we need to generate 5368 // new instructions. 5369 if (!RewriteGEP && Ops.size() == 2) 5370 return false; 5371 5372 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 5373 5374 IRBuilder<> Builder(MemoryInst); 5375 5376 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType()); 5377 5378 Value *NewAddr; 5379 5380 // If the final index isn't a vector, emit a scalar GEP containing all ops 5381 // and a vector GEP with all zeroes final index. 5382 if (!Ops[FinalIndex]->getType()->isVectorTy()) { 5383 NewAddr = Builder.CreateGEP(Ops[0], makeArrayRef(Ops).drop_front()); 5384 auto *IndexTy = FixedVectorType::get(ScalarIndexTy, NumElts); 5385 NewAddr = Builder.CreateGEP(NewAddr, Constant::getNullValue(IndexTy)); 5386 } else { 5387 Value *Base = Ops[0]; 5388 Value *Index = Ops[FinalIndex]; 5389 5390 // Create a scalar GEP if there are more than 2 operands. 5391 if (Ops.size() != 2) { 5392 // Replace the last index with 0. 5393 Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy); 5394 Base = Builder.CreateGEP(Base, makeArrayRef(Ops).drop_front()); 5395 } 5396 5397 // Now create the GEP with scalar pointer and vector index. 5398 NewAddr = Builder.CreateGEP(Base, Index); 5399 } 5400 5401 MemoryInst->replaceUsesOfWith(Ptr, NewAddr); 5402 5403 // If we have no uses, recursively delete the value and all dead instructions 5404 // using it. 5405 if (Ptr->use_empty()) 5406 RecursivelyDeleteTriviallyDeadInstructions( 5407 Ptr, TLInfo, nullptr, 5408 [&](Value *V) { removeAllAssertingVHReferences(V); }); 5409 5410 return true; 5411 } 5412 5413 /// If there are any memory operands, use OptimizeMemoryInst to sink their 5414 /// address computing into the block when possible / profitable. 5415 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { 5416 bool MadeChange = false; 5417 5418 const TargetRegisterInfo *TRI = 5419 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo(); 5420 TargetLowering::AsmOperandInfoVector TargetConstraints = 5421 TLI->ParseConstraints(*DL, TRI, *CS); 5422 unsigned ArgNo = 0; 5423 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 5424 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 5425 5426 // Compute the constraint code and ConstraintType to use. 5427 TLI->ComputeConstraintToUse(OpInfo, SDValue()); 5428 5429 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 5430 OpInfo.isIndirect) { 5431 Value *OpVal = CS->getArgOperand(ArgNo++); 5432 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); 5433 } else if (OpInfo.Type == InlineAsm::isInput) 5434 ArgNo++; 5435 } 5436 5437 return MadeChange; 5438 } 5439 5440 /// Check if all the uses of \p Val are equivalent (or free) zero or 5441 /// sign extensions. 5442 static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { 5443 assert(!Val->use_empty() && "Input must have at least one use"); 5444 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); 5445 bool IsSExt = isa<SExtInst>(FirstUser); 5446 Type *ExtTy = FirstUser->getType(); 5447 for (const User *U : Val->users()) { 5448 const Instruction *UI = cast<Instruction>(U); 5449 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) 5450 return false; 5451 Type *CurTy = UI->getType(); 5452 // Same input and output types: Same instruction after CSE. 5453 if (CurTy == ExtTy) 5454 continue; 5455 5456 // If IsSExt is true, we are in this situation: 5457 // a = Val 5458 // b = sext ty1 a to ty2 5459 // c = sext ty1 a to ty3 5460 // Assuming ty2 is shorter than ty3, this could be turned into: 5461 // a = Val 5462 // b = sext ty1 a to ty2 5463 // c = sext ty2 b to ty3 5464 // However, the last sext is not free. 5465 if (IsSExt) 5466 return false; 5467 5468 // This is a ZExt, maybe this is free to extend from one type to another. 5469 // In that case, we would not account for a different use. 5470 Type *NarrowTy; 5471 Type *LargeTy; 5472 if (ExtTy->getScalarType()->getIntegerBitWidth() > 5473 CurTy->getScalarType()->getIntegerBitWidth()) { 5474 NarrowTy = CurTy; 5475 LargeTy = ExtTy; 5476 } else { 5477 NarrowTy = ExtTy; 5478 LargeTy = CurTy; 5479 } 5480 5481 if (!TLI.isZExtFree(NarrowTy, LargeTy)) 5482 return false; 5483 } 5484 // All uses are the same or can be derived from one another for free. 5485 return true; 5486 } 5487 5488 /// Try to speculatively promote extensions in \p Exts and continue 5489 /// promoting through newly promoted operands recursively as far as doing so is 5490 /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. 5491 /// When some promotion happened, \p TPT contains the proper state to revert 5492 /// them. 5493 /// 5494 /// \return true if some promotion happened, false otherwise. 5495 bool CodeGenPrepare::tryToPromoteExts( 5496 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, 5497 SmallVectorImpl<Instruction *> &ProfitablyMovedExts, 5498 unsigned CreatedInstsCost) { 5499 bool Promoted = false; 5500 5501 // Iterate over all the extensions to try to promote them. 5502 for (auto *I : Exts) { 5503 // Early check if we directly have ext(load). 5504 if (isa<LoadInst>(I->getOperand(0))) { 5505 ProfitablyMovedExts.push_back(I); 5506 continue; 5507 } 5508 5509 // Check whether or not we want to do any promotion. The reason we have 5510 // this check inside the for loop is to catch the case where an extension 5511 // is directly fed by a load because in such case the extension can be moved 5512 // up without any promotion on its operands. 5513 if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion) 5514 return false; 5515 5516 // Get the action to perform the promotion. 5517 TypePromotionHelper::Action TPH = 5518 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); 5519 // Check if we can promote. 5520 if (!TPH) { 5521 // Save the current extension as we cannot move up through its operand. 5522 ProfitablyMovedExts.push_back(I); 5523 continue; 5524 } 5525 5526 // Save the current state. 5527 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 5528 TPT.getRestorationPoint(); 5529 SmallVector<Instruction *, 4> NewExts; 5530 unsigned NewCreatedInstsCost = 0; 5531 unsigned ExtCost = !TLI->isExtFree(I); 5532 // Promote. 5533 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, 5534 &NewExts, nullptr, *TLI); 5535 assert(PromotedVal && 5536 "TypePromotionHelper should have filtered out those cases"); 5537 5538 // We would be able to merge only one extension in a load. 5539 // Therefore, if we have more than 1 new extension we heuristically 5540 // cut this search path, because it means we degrade the code quality. 5541 // With exactly 2, the transformation is neutral, because we will merge 5542 // one extension but leave one. However, we optimistically keep going, 5543 // because the new extension may be removed too. 5544 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; 5545 // FIXME: It would be possible to propagate a negative value instead of 5546 // conservatively ceiling it to 0. 5547 TotalCreatedInstsCost = 5548 std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); 5549 if (!StressExtLdPromotion && 5550 (TotalCreatedInstsCost > 1 || 5551 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { 5552 // This promotion is not profitable, rollback to the previous state, and 5553 // save the current extension in ProfitablyMovedExts as the latest 5554 // speculative promotion turned out to be unprofitable. 5555 TPT.rollback(LastKnownGood); 5556 ProfitablyMovedExts.push_back(I); 5557 continue; 5558 } 5559 // Continue promoting NewExts as far as doing so is profitable. 5560 SmallVector<Instruction *, 2> NewlyMovedExts; 5561 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); 5562 bool NewPromoted = false; 5563 for (auto *ExtInst : NewlyMovedExts) { 5564 Instruction *MovedExt = cast<Instruction>(ExtInst); 5565 Value *ExtOperand = MovedExt->getOperand(0); 5566 // If we have reached to a load, we need this extra profitability check 5567 // as it could potentially be merged into an ext(load). 5568 if (isa<LoadInst>(ExtOperand) && 5569 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || 5570 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) 5571 continue; 5572 5573 ProfitablyMovedExts.push_back(MovedExt); 5574 NewPromoted = true; 5575 } 5576 5577 // If none of speculative promotions for NewExts is profitable, rollback 5578 // and save the current extension (I) as the last profitable extension. 5579 if (!NewPromoted) { 5580 TPT.rollback(LastKnownGood); 5581 ProfitablyMovedExts.push_back(I); 5582 continue; 5583 } 5584 // The promotion is profitable. 5585 Promoted = true; 5586 } 5587 return Promoted; 5588 } 5589 5590 /// Merging redundant sexts when one is dominating the other. 5591 bool CodeGenPrepare::mergeSExts(Function &F) { 5592 bool Changed = false; 5593 for (auto &Entry : ValToSExtendedUses) { 5594 SExts &Insts = Entry.second; 5595 SExts CurPts; 5596 for (Instruction *Inst : Insts) { 5597 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || 5598 Inst->getOperand(0) != Entry.first) 5599 continue; 5600 bool inserted = false; 5601 for (auto &Pt : CurPts) { 5602 if (getDT(F).dominates(Inst, Pt)) { 5603 Pt->replaceAllUsesWith(Inst); 5604 RemovedInsts.insert(Pt); 5605 Pt->removeFromParent(); 5606 Pt = Inst; 5607 inserted = true; 5608 Changed = true; 5609 break; 5610 } 5611 if (!getDT(F).dominates(Pt, Inst)) 5612 // Give up if we need to merge in a common dominator as the 5613 // experiments show it is not profitable. 5614 continue; 5615 Inst->replaceAllUsesWith(Pt); 5616 RemovedInsts.insert(Inst); 5617 Inst->removeFromParent(); 5618 inserted = true; 5619 Changed = true; 5620 break; 5621 } 5622 if (!inserted) 5623 CurPts.push_back(Inst); 5624 } 5625 } 5626 return Changed; 5627 } 5628 5629 // Splitting large data structures so that the GEPs accessing them can have 5630 // smaller offsets so that they can be sunk to the same blocks as their users. 5631 // For example, a large struct starting from %base is split into two parts 5632 // where the second part starts from %new_base. 5633 // 5634 // Before: 5635 // BB0: 5636 // %base = 5637 // 5638 // BB1: 5639 // %gep0 = gep %base, off0 5640 // %gep1 = gep %base, off1 5641 // %gep2 = gep %base, off2 5642 // 5643 // BB2: 5644 // %load1 = load %gep0 5645 // %load2 = load %gep1 5646 // %load3 = load %gep2 5647 // 5648 // After: 5649 // BB0: 5650 // %base = 5651 // %new_base = gep %base, off0 5652 // 5653 // BB1: 5654 // %new_gep0 = %new_base 5655 // %new_gep1 = gep %new_base, off1 - off0 5656 // %new_gep2 = gep %new_base, off2 - off0 5657 // 5658 // BB2: 5659 // %load1 = load i32, i32* %new_gep0 5660 // %load2 = load i32, i32* %new_gep1 5661 // %load3 = load i32, i32* %new_gep2 5662 // 5663 // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because 5664 // their offsets are smaller enough to fit into the addressing mode. 5665 bool CodeGenPrepare::splitLargeGEPOffsets() { 5666 bool Changed = false; 5667 for (auto &Entry : LargeOffsetGEPMap) { 5668 Value *OldBase = Entry.first; 5669 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>> 5670 &LargeOffsetGEPs = Entry.second; 5671 auto compareGEPOffset = 5672 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS, 5673 const std::pair<GetElementPtrInst *, int64_t> &RHS) { 5674 if (LHS.first == RHS.first) 5675 return false; 5676 if (LHS.second != RHS.second) 5677 return LHS.second < RHS.second; 5678 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first]; 5679 }; 5680 // Sorting all the GEPs of the same data structures based on the offsets. 5681 llvm::sort(LargeOffsetGEPs, compareGEPOffset); 5682 LargeOffsetGEPs.erase( 5683 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()), 5684 LargeOffsetGEPs.end()); 5685 // Skip if all the GEPs have the same offsets. 5686 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second) 5687 continue; 5688 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first; 5689 int64_t BaseOffset = LargeOffsetGEPs.begin()->second; 5690 Value *NewBaseGEP = nullptr; 5691 5692 auto *LargeOffsetGEP = LargeOffsetGEPs.begin(); 5693 while (LargeOffsetGEP != LargeOffsetGEPs.end()) { 5694 GetElementPtrInst *GEP = LargeOffsetGEP->first; 5695 int64_t Offset = LargeOffsetGEP->second; 5696 if (Offset != BaseOffset) { 5697 TargetLowering::AddrMode AddrMode; 5698 AddrMode.BaseOffs = Offset - BaseOffset; 5699 // The result type of the GEP might not be the type of the memory 5700 // access. 5701 if (!TLI->isLegalAddressingMode(*DL, AddrMode, 5702 GEP->getResultElementType(), 5703 GEP->getAddressSpace())) { 5704 // We need to create a new base if the offset to the current base is 5705 // too large to fit into the addressing mode. So, a very large struct 5706 // may be split into several parts. 5707 BaseGEP = GEP; 5708 BaseOffset = Offset; 5709 NewBaseGEP = nullptr; 5710 } 5711 } 5712 5713 // Generate a new GEP to replace the current one. 5714 LLVMContext &Ctx = GEP->getContext(); 5715 Type *IntPtrTy = DL->getIntPtrType(GEP->getType()); 5716 Type *I8PtrTy = 5717 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace()); 5718 Type *I8Ty = Type::getInt8Ty(Ctx); 5719 5720 if (!NewBaseGEP) { 5721 // Create a new base if we don't have one yet. Find the insertion 5722 // pointer for the new base first. 5723 BasicBlock::iterator NewBaseInsertPt; 5724 BasicBlock *NewBaseInsertBB; 5725 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) { 5726 // If the base of the struct is an instruction, the new base will be 5727 // inserted close to it. 5728 NewBaseInsertBB = BaseI->getParent(); 5729 if (isa<PHINode>(BaseI)) 5730 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); 5731 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) { 5732 NewBaseInsertBB = 5733 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest()); 5734 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); 5735 } else 5736 NewBaseInsertPt = std::next(BaseI->getIterator()); 5737 } else { 5738 // If the current base is an argument or global value, the new base 5739 // will be inserted to the entry block. 5740 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock(); 5741 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); 5742 } 5743 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt); 5744 // Create a new base. 5745 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset); 5746 NewBaseGEP = OldBase; 5747 if (NewBaseGEP->getType() != I8PtrTy) 5748 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy); 5749 NewBaseGEP = 5750 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep"); 5751 NewGEPBases.insert(NewBaseGEP); 5752 } 5753 5754 IRBuilder<> Builder(GEP); 5755 Value *NewGEP = NewBaseGEP; 5756 if (Offset == BaseOffset) { 5757 if (GEP->getType() != I8PtrTy) 5758 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); 5759 } else { 5760 // Calculate the new offset for the new GEP. 5761 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset); 5762 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index); 5763 5764 if (GEP->getType() != I8PtrTy) 5765 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); 5766 } 5767 GEP->replaceAllUsesWith(NewGEP); 5768 LargeOffsetGEPID.erase(GEP); 5769 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP); 5770 GEP->eraseFromParent(); 5771 Changed = true; 5772 } 5773 } 5774 return Changed; 5775 } 5776 5777 bool CodeGenPrepare::optimizePhiType( 5778 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited, 5779 SmallPtrSetImpl<Instruction *> &DeletedInstrs) { 5780 // We are looking for a collection on interconnected phi nodes that together 5781 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts 5782 // are of the same type. Convert the whole set of nodes to the type of the 5783 // bitcast. 5784 Type *PhiTy = I->getType(); 5785 Type *ConvertTy = nullptr; 5786 if (Visited.count(I) || 5787 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy())) 5788 return false; 5789 5790 SmallVector<Instruction *, 4> Worklist; 5791 Worklist.push_back(cast<Instruction>(I)); 5792 SmallPtrSet<PHINode *, 4> PhiNodes; 5793 PhiNodes.insert(I); 5794 Visited.insert(I); 5795 SmallPtrSet<Instruction *, 4> Defs; 5796 SmallPtrSet<Instruction *, 4> Uses; 5797 5798 while (!Worklist.empty()) { 5799 Instruction *II = Worklist.pop_back_val(); 5800 5801 if (auto *Phi = dyn_cast<PHINode>(II)) { 5802 // Handle Defs, which might also be PHI's 5803 for (Value *V : Phi->incoming_values()) { 5804 if (auto *OpPhi = dyn_cast<PHINode>(V)) { 5805 if (!PhiNodes.count(OpPhi)) { 5806 if (Visited.count(OpPhi)) 5807 return false; 5808 PhiNodes.insert(OpPhi); 5809 Visited.insert(OpPhi); 5810 Worklist.push_back(OpPhi); 5811 } 5812 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) { 5813 if (!Defs.count(OpLoad)) { 5814 Defs.insert(OpLoad); 5815 Worklist.push_back(OpLoad); 5816 } 5817 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) { 5818 if (!Defs.count(OpEx)) { 5819 Defs.insert(OpEx); 5820 Worklist.push_back(OpEx); 5821 } 5822 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) { 5823 if (!ConvertTy) 5824 ConvertTy = OpBC->getOperand(0)->getType(); 5825 if (OpBC->getOperand(0)->getType() != ConvertTy) 5826 return false; 5827 if (!Defs.count(OpBC)) { 5828 Defs.insert(OpBC); 5829 Worklist.push_back(OpBC); 5830 } 5831 } else if (!isa<UndefValue>(V)) 5832 return false; 5833 } 5834 } 5835 5836 // Handle uses which might also be phi's 5837 for (User *V : II->users()) { 5838 if (auto *OpPhi = dyn_cast<PHINode>(V)) { 5839 if (!PhiNodes.count(OpPhi)) { 5840 if (Visited.count(OpPhi)) 5841 return false; 5842 PhiNodes.insert(OpPhi); 5843 Visited.insert(OpPhi); 5844 Worklist.push_back(OpPhi); 5845 } 5846 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) { 5847 if (OpStore->getOperand(0) != II) 5848 return false; 5849 Uses.insert(OpStore); 5850 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) { 5851 if (!ConvertTy) 5852 ConvertTy = OpBC->getType(); 5853 if (OpBC->getType() != ConvertTy) 5854 return false; 5855 Uses.insert(OpBC); 5856 } else 5857 return false; 5858 } 5859 } 5860 5861 if (!ConvertTy || !TLI->shouldConvertPhiType(PhiTy, ConvertTy)) 5862 return false; 5863 5864 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to " 5865 << *ConvertTy << "\n"); 5866 5867 // Create all the new phi nodes of the new type, and bitcast any loads to the 5868 // correct type. 5869 ValueToValueMap ValMap; 5870 ValMap[UndefValue::get(PhiTy)] = UndefValue::get(ConvertTy); 5871 for (Instruction *D : Defs) { 5872 if (isa<BitCastInst>(D)) 5873 ValMap[D] = D->getOperand(0); 5874 else 5875 ValMap[D] = 5876 new BitCastInst(D, ConvertTy, D->getName() + ".bc", D->getNextNode()); 5877 } 5878 for (PHINode *Phi : PhiNodes) 5879 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(), 5880 Phi->getName() + ".tc", Phi); 5881 // Pipe together all the PhiNodes. 5882 for (PHINode *Phi : PhiNodes) { 5883 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]); 5884 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++) 5885 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)], 5886 Phi->getIncomingBlock(i)); 5887 } 5888 // And finally pipe up the stores and bitcasts 5889 for (Instruction *U : Uses) { 5890 if (isa<BitCastInst>(U)) { 5891 DeletedInstrs.insert(U); 5892 U->replaceAllUsesWith(ValMap[U->getOperand(0)]); 5893 } else 5894 U->setOperand(0, 5895 new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc", U)); 5896 } 5897 5898 // Save the removed phis to be deleted later. 5899 for (PHINode *Phi : PhiNodes) 5900 DeletedInstrs.insert(Phi); 5901 return true; 5902 } 5903 5904 bool CodeGenPrepare::optimizePhiTypes(Function &F) { 5905 if (!OptimizePhiTypes) 5906 return false; 5907 5908 bool Changed = false; 5909 SmallPtrSet<PHINode *, 4> Visited; 5910 SmallPtrSet<Instruction *, 4> DeletedInstrs; 5911 5912 // Attempt to optimize all the phis in the functions to the correct type. 5913 for (auto &BB : F) 5914 for (auto &Phi : BB.phis()) 5915 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs); 5916 5917 // Remove any old phi's that have been converted. 5918 for (auto *I : DeletedInstrs) { 5919 I->replaceAllUsesWith(UndefValue::get(I->getType())); 5920 I->eraseFromParent(); 5921 } 5922 5923 return Changed; 5924 } 5925 5926 /// Return true, if an ext(load) can be formed from an extension in 5927 /// \p MovedExts. 5928 bool CodeGenPrepare::canFormExtLd( 5929 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, 5930 Instruction *&Inst, bool HasPromoted) { 5931 for (auto *MovedExtInst : MovedExts) { 5932 if (isa<LoadInst>(MovedExtInst->getOperand(0))) { 5933 LI = cast<LoadInst>(MovedExtInst->getOperand(0)); 5934 Inst = MovedExtInst; 5935 break; 5936 } 5937 } 5938 if (!LI) 5939 return false; 5940 5941 // If they're already in the same block, there's nothing to do. 5942 // Make the cheap checks first if we did not promote. 5943 // If we promoted, we need to check if it is indeed profitable. 5944 if (!HasPromoted && LI->getParent() == Inst->getParent()) 5945 return false; 5946 5947 return TLI->isExtLoad(LI, Inst, *DL); 5948 } 5949 5950 /// Move a zext or sext fed by a load into the same basic block as the load, 5951 /// unless conditions are unfavorable. This allows SelectionDAG to fold the 5952 /// extend into the load. 5953 /// 5954 /// E.g., 5955 /// \code 5956 /// %ld = load i32* %addr 5957 /// %add = add nuw i32 %ld, 4 5958 /// %zext = zext i32 %add to i64 5959 // \endcode 5960 /// => 5961 /// \code 5962 /// %ld = load i32* %addr 5963 /// %zext = zext i32 %ld to i64 5964 /// %add = add nuw i64 %zext, 4 5965 /// \encode 5966 /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which 5967 /// allow us to match zext(load i32*) to i64. 5968 /// 5969 /// Also, try to promote the computations used to obtain a sign extended 5970 /// value used into memory accesses. 5971 /// E.g., 5972 /// \code 5973 /// a = add nsw i32 b, 3 5974 /// d = sext i32 a to i64 5975 /// e = getelementptr ..., i64 d 5976 /// \endcode 5977 /// => 5978 /// \code 5979 /// f = sext i32 b to i64 5980 /// a = add nsw i64 f, 3 5981 /// e = getelementptr ..., i64 a 5982 /// \endcode 5983 /// 5984 /// \p Inst[in/out] the extension may be modified during the process if some 5985 /// promotions apply. 5986 bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { 5987 bool AllowPromotionWithoutCommonHeader = false; 5988 /// See if it is an interesting sext operations for the address type 5989 /// promotion before trying to promote it, e.g., the ones with the right 5990 /// type and used in memory accesses. 5991 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( 5992 *Inst, AllowPromotionWithoutCommonHeader); 5993 TypePromotionTransaction TPT(RemovedInsts); 5994 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 5995 TPT.getRestorationPoint(); 5996 SmallVector<Instruction *, 1> Exts; 5997 SmallVector<Instruction *, 2> SpeculativelyMovedExts; 5998 Exts.push_back(Inst); 5999 6000 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); 6001 6002 // Look for a load being extended. 6003 LoadInst *LI = nullptr; 6004 Instruction *ExtFedByLoad; 6005 6006 // Try to promote a chain of computation if it allows to form an extended 6007 // load. 6008 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { 6009 assert(LI && ExtFedByLoad && "Expect a valid load and extension"); 6010 TPT.commit(); 6011 // Move the extend into the same block as the load. 6012 ExtFedByLoad->moveAfter(LI); 6013 ++NumExtsMoved; 6014 Inst = ExtFedByLoad; 6015 return true; 6016 } 6017 6018 // Continue promoting SExts if known as considerable depending on targets. 6019 if (ATPConsiderable && 6020 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, 6021 HasPromoted, TPT, SpeculativelyMovedExts)) 6022 return true; 6023 6024 TPT.rollback(LastKnownGood); 6025 return false; 6026 } 6027 6028 // Perform address type promotion if doing so is profitable. 6029 // If AllowPromotionWithoutCommonHeader == false, we should find other sext 6030 // instructions that sign extended the same initial value. However, if 6031 // AllowPromotionWithoutCommonHeader == true, we expect promoting the 6032 // extension is just profitable. 6033 bool CodeGenPrepare::performAddressTypePromotion( 6034 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, 6035 bool HasPromoted, TypePromotionTransaction &TPT, 6036 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { 6037 bool Promoted = false; 6038 SmallPtrSet<Instruction *, 1> UnhandledExts; 6039 bool AllSeenFirst = true; 6040 for (auto *I : SpeculativelyMovedExts) { 6041 Value *HeadOfChain = I->getOperand(0); 6042 DenseMap<Value *, Instruction *>::iterator AlreadySeen = 6043 SeenChainsForSExt.find(HeadOfChain); 6044 // If there is an unhandled SExt which has the same header, try to promote 6045 // it as well. 6046 if (AlreadySeen != SeenChainsForSExt.end()) { 6047 if (AlreadySeen->second != nullptr) 6048 UnhandledExts.insert(AlreadySeen->second); 6049 AllSeenFirst = false; 6050 } 6051 } 6052 6053 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && 6054 SpeculativelyMovedExts.size() == 1)) { 6055 TPT.commit(); 6056 if (HasPromoted) 6057 Promoted = true; 6058 for (auto *I : SpeculativelyMovedExts) { 6059 Value *HeadOfChain = I->getOperand(0); 6060 SeenChainsForSExt[HeadOfChain] = nullptr; 6061 ValToSExtendedUses[HeadOfChain].push_back(I); 6062 } 6063 // Update Inst as promotion happen. 6064 Inst = SpeculativelyMovedExts.pop_back_val(); 6065 } else { 6066 // This is the first chain visited from the header, keep the current chain 6067 // as unhandled. Defer to promote this until we encounter another SExt 6068 // chain derived from the same header. 6069 for (auto *I : SpeculativelyMovedExts) { 6070 Value *HeadOfChain = I->getOperand(0); 6071 SeenChainsForSExt[HeadOfChain] = Inst; 6072 } 6073 return false; 6074 } 6075 6076 if (!AllSeenFirst && !UnhandledExts.empty()) 6077 for (auto *VisitedSExt : UnhandledExts) { 6078 if (RemovedInsts.count(VisitedSExt)) 6079 continue; 6080 TypePromotionTransaction TPT(RemovedInsts); 6081 SmallVector<Instruction *, 1> Exts; 6082 SmallVector<Instruction *, 2> Chains; 6083 Exts.push_back(VisitedSExt); 6084 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); 6085 TPT.commit(); 6086 if (HasPromoted) 6087 Promoted = true; 6088 for (auto *I : Chains) { 6089 Value *HeadOfChain = I->getOperand(0); 6090 // Mark this as handled. 6091 SeenChainsForSExt[HeadOfChain] = nullptr; 6092 ValToSExtendedUses[HeadOfChain].push_back(I); 6093 } 6094 } 6095 return Promoted; 6096 } 6097 6098 bool CodeGenPrepare::optimizeExtUses(Instruction *I) { 6099 BasicBlock *DefBB = I->getParent(); 6100 6101 // If the result of a {s|z}ext and its source are both live out, rewrite all 6102 // other uses of the source with result of extension. 6103 Value *Src = I->getOperand(0); 6104 if (Src->hasOneUse()) 6105 return false; 6106 6107 // Only do this xform if truncating is free. 6108 if (!TLI->isTruncateFree(I->getType(), Src->getType())) 6109 return false; 6110 6111 // Only safe to perform the optimization if the source is also defined in 6112 // this block. 6113 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) 6114 return false; 6115 6116 bool DefIsLiveOut = false; 6117 for (User *U : I->users()) { 6118 Instruction *UI = cast<Instruction>(U); 6119 6120 // Figure out which BB this ext is used in. 6121 BasicBlock *UserBB = UI->getParent(); 6122 if (UserBB == DefBB) continue; 6123 DefIsLiveOut = true; 6124 break; 6125 } 6126 if (!DefIsLiveOut) 6127 return false; 6128 6129 // Make sure none of the uses are PHI nodes. 6130 for (User *U : Src->users()) { 6131 Instruction *UI = cast<Instruction>(U); 6132 BasicBlock *UserBB = UI->getParent(); 6133 if (UserBB == DefBB) continue; 6134 // Be conservative. We don't want this xform to end up introducing 6135 // reloads just before load / store instructions. 6136 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) 6137 return false; 6138 } 6139 6140 // InsertedTruncs - Only insert one trunc in each block once. 6141 DenseMap<BasicBlock*, Instruction*> InsertedTruncs; 6142 6143 bool MadeChange = false; 6144 for (Use &U : Src->uses()) { 6145 Instruction *User = cast<Instruction>(U.getUser()); 6146 6147 // Figure out which BB this ext is used in. 6148 BasicBlock *UserBB = User->getParent(); 6149 if (UserBB == DefBB) continue; 6150 6151 // Both src and def are live in this block. Rewrite the use. 6152 Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; 6153 6154 if (!InsertedTrunc) { 6155 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 6156 assert(InsertPt != UserBB->end()); 6157 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); 6158 InsertedInsts.insert(InsertedTrunc); 6159 } 6160 6161 // Replace a use of the {s|z}ext source with a use of the result. 6162 U = InsertedTrunc; 6163 ++NumExtUses; 6164 MadeChange = true; 6165 } 6166 6167 return MadeChange; 6168 } 6169 6170 // Find loads whose uses only use some of the loaded value's bits. Add an "and" 6171 // just after the load if the target can fold this into one extload instruction, 6172 // with the hope of eliminating some of the other later "and" instructions using 6173 // the loaded value. "and"s that are made trivially redundant by the insertion 6174 // of the new "and" are removed by this function, while others (e.g. those whose 6175 // path from the load goes through a phi) are left for isel to potentially 6176 // remove. 6177 // 6178 // For example: 6179 // 6180 // b0: 6181 // x = load i32 6182 // ... 6183 // b1: 6184 // y = and x, 0xff 6185 // z = use y 6186 // 6187 // becomes: 6188 // 6189 // b0: 6190 // x = load i32 6191 // x' = and x, 0xff 6192 // ... 6193 // b1: 6194 // z = use x' 6195 // 6196 // whereas: 6197 // 6198 // b0: 6199 // x1 = load i32 6200 // ... 6201 // b1: 6202 // x2 = load i32 6203 // ... 6204 // b2: 6205 // x = phi x1, x2 6206 // y = and x, 0xff 6207 // 6208 // becomes (after a call to optimizeLoadExt for each load): 6209 // 6210 // b0: 6211 // x1 = load i32 6212 // x1' = and x1, 0xff 6213 // ... 6214 // b1: 6215 // x2 = load i32 6216 // x2' = and x2, 0xff 6217 // ... 6218 // b2: 6219 // x = phi x1', x2' 6220 // y = and x, 0xff 6221 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { 6222 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy()) 6223 return false; 6224 6225 // Skip loads we've already transformed. 6226 if (Load->hasOneUse() && 6227 InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) 6228 return false; 6229 6230 // Look at all uses of Load, looking through phis, to determine how many bits 6231 // of the loaded value are needed. 6232 SmallVector<Instruction *, 8> WorkList; 6233 SmallPtrSet<Instruction *, 16> Visited; 6234 SmallVector<Instruction *, 8> AndsToMaybeRemove; 6235 for (auto *U : Load->users()) 6236 WorkList.push_back(cast<Instruction>(U)); 6237 6238 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); 6239 unsigned BitWidth = LoadResultVT.getSizeInBits(); 6240 APInt DemandBits(BitWidth, 0); 6241 APInt WidestAndBits(BitWidth, 0); 6242 6243 while (!WorkList.empty()) { 6244 Instruction *I = WorkList.back(); 6245 WorkList.pop_back(); 6246 6247 // Break use-def graph loops. 6248 if (!Visited.insert(I).second) 6249 continue; 6250 6251 // For a PHI node, push all of its users. 6252 if (auto *Phi = dyn_cast<PHINode>(I)) { 6253 for (auto *U : Phi->users()) 6254 WorkList.push_back(cast<Instruction>(U)); 6255 continue; 6256 } 6257 6258 switch (I->getOpcode()) { 6259 case Instruction::And: { 6260 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); 6261 if (!AndC) 6262 return false; 6263 APInt AndBits = AndC->getValue(); 6264 DemandBits |= AndBits; 6265 // Keep track of the widest and mask we see. 6266 if (AndBits.ugt(WidestAndBits)) 6267 WidestAndBits = AndBits; 6268 if (AndBits == WidestAndBits && I->getOperand(0) == Load) 6269 AndsToMaybeRemove.push_back(I); 6270 break; 6271 } 6272 6273 case Instruction::Shl: { 6274 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); 6275 if (!ShlC) 6276 return false; 6277 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); 6278 DemandBits.setLowBits(BitWidth - ShiftAmt); 6279 break; 6280 } 6281 6282 case Instruction::Trunc: { 6283 EVT TruncVT = TLI->getValueType(*DL, I->getType()); 6284 unsigned TruncBitWidth = TruncVT.getSizeInBits(); 6285 DemandBits.setLowBits(TruncBitWidth); 6286 break; 6287 } 6288 6289 default: 6290 return false; 6291 } 6292 } 6293 6294 uint32_t ActiveBits = DemandBits.getActiveBits(); 6295 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the 6296 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, 6297 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but 6298 // (and (load x) 1) is not matched as a single instruction, rather as a LDR 6299 // followed by an AND. 6300 // TODO: Look into removing this restriction by fixing backends to either 6301 // return false for isLoadExtLegal for i1 or have them select this pattern to 6302 // a single instruction. 6303 // 6304 // Also avoid hoisting if we didn't see any ands with the exact DemandBits 6305 // mask, since these are the only ands that will be removed by isel. 6306 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || 6307 WidestAndBits != DemandBits) 6308 return false; 6309 6310 LLVMContext &Ctx = Load->getType()->getContext(); 6311 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); 6312 EVT TruncVT = TLI->getValueType(*DL, TruncTy); 6313 6314 // Reject cases that won't be matched as extloads. 6315 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || 6316 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) 6317 return false; 6318 6319 IRBuilder<> Builder(Load->getNextNode()); 6320 auto *NewAnd = cast<Instruction>( 6321 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); 6322 // Mark this instruction as "inserted by CGP", so that other 6323 // optimizations don't touch it. 6324 InsertedInsts.insert(NewAnd); 6325 6326 // Replace all uses of load with new and (except for the use of load in the 6327 // new and itself). 6328 Load->replaceAllUsesWith(NewAnd); 6329 NewAnd->setOperand(0, Load); 6330 6331 // Remove any and instructions that are now redundant. 6332 for (auto *And : AndsToMaybeRemove) 6333 // Check that the and mask is the same as the one we decided to put on the 6334 // new and. 6335 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { 6336 And->replaceAllUsesWith(NewAnd); 6337 if (&*CurInstIterator == And) 6338 CurInstIterator = std::next(And->getIterator()); 6339 And->eraseFromParent(); 6340 ++NumAndUses; 6341 } 6342 6343 ++NumAndsAdded; 6344 return true; 6345 } 6346 6347 /// Check if V (an operand of a select instruction) is an expensive instruction 6348 /// that is only used once. 6349 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { 6350 auto *I = dyn_cast<Instruction>(V); 6351 // If it's safe to speculatively execute, then it should not have side 6352 // effects; therefore, it's safe to sink and possibly *not* execute. 6353 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && 6354 TTI->getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency) >= 6355 TargetTransformInfo::TCC_Expensive; 6356 } 6357 6358 /// Returns true if a SelectInst should be turned into an explicit branch. 6359 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, 6360 const TargetLowering *TLI, 6361 SelectInst *SI) { 6362 // If even a predictable select is cheap, then a branch can't be cheaper. 6363 if (!TLI->isPredictableSelectExpensive()) 6364 return false; 6365 6366 // FIXME: This should use the same heuristics as IfConversion to determine 6367 // whether a select is better represented as a branch. 6368 6369 // If metadata tells us that the select condition is obviously predictable, 6370 // then we want to replace the select with a branch. 6371 uint64_t TrueWeight, FalseWeight; 6372 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { 6373 uint64_t Max = std::max(TrueWeight, FalseWeight); 6374 uint64_t Sum = TrueWeight + FalseWeight; 6375 if (Sum != 0) { 6376 auto Probability = BranchProbability::getBranchProbability(Max, Sum); 6377 if (Probability > TLI->getPredictableBranchThreshold()) 6378 return true; 6379 } 6380 } 6381 6382 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 6383 6384 // If a branch is predictable, an out-of-order CPU can avoid blocking on its 6385 // comparison condition. If the compare has more than one use, there's 6386 // probably another cmov or setcc around, so it's not worth emitting a branch. 6387 if (!Cmp || !Cmp->hasOneUse()) 6388 return false; 6389 6390 // If either operand of the select is expensive and only needed on one side 6391 // of the select, we should form a branch. 6392 if (sinkSelectOperand(TTI, SI->getTrueValue()) || 6393 sinkSelectOperand(TTI, SI->getFalseValue())) 6394 return true; 6395 6396 return false; 6397 } 6398 6399 /// If \p isTrue is true, return the true value of \p SI, otherwise return 6400 /// false value of \p SI. If the true/false value of \p SI is defined by any 6401 /// select instructions in \p Selects, look through the defining select 6402 /// instruction until the true/false value is not defined in \p Selects. 6403 static Value *getTrueOrFalseValue( 6404 SelectInst *SI, bool isTrue, 6405 const SmallPtrSet<const Instruction *, 2> &Selects) { 6406 Value *V = nullptr; 6407 6408 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); 6409 DefSI = dyn_cast<SelectInst>(V)) { 6410 assert(DefSI->getCondition() == SI->getCondition() && 6411 "The condition of DefSI does not match with SI"); 6412 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); 6413 } 6414 6415 assert(V && "Failed to get select true/false value"); 6416 return V; 6417 } 6418 6419 bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) { 6420 assert(Shift->isShift() && "Expected a shift"); 6421 6422 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than 6423 // general vector shifts, and (3) the shift amount is a select-of-splatted 6424 // values, hoist the shifts before the select: 6425 // shift Op0, (select Cond, TVal, FVal) --> 6426 // select Cond, (shift Op0, TVal), (shift Op0, FVal) 6427 // 6428 // This is inverting a generic IR transform when we know that the cost of a 6429 // general vector shift is more than the cost of 2 shift-by-scalars. 6430 // We can't do this effectively in SDAG because we may not be able to 6431 // determine if the select operands are splats from within a basic block. 6432 Type *Ty = Shift->getType(); 6433 if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) 6434 return false; 6435 Value *Cond, *TVal, *FVal; 6436 if (!match(Shift->getOperand(1), 6437 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) 6438 return false; 6439 if (!isSplatValue(TVal) || !isSplatValue(FVal)) 6440 return false; 6441 6442 IRBuilder<> Builder(Shift); 6443 BinaryOperator::BinaryOps Opcode = Shift->getOpcode(); 6444 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal); 6445 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal); 6446 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); 6447 Shift->replaceAllUsesWith(NewSel); 6448 Shift->eraseFromParent(); 6449 return true; 6450 } 6451 6452 bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) { 6453 Intrinsic::ID Opcode = Fsh->getIntrinsicID(); 6454 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && 6455 "Expected a funnel shift"); 6456 6457 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper 6458 // than general vector shifts, and (3) the shift amount is select-of-splatted 6459 // values, hoist the funnel shifts before the select: 6460 // fsh Op0, Op1, (select Cond, TVal, FVal) --> 6461 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal) 6462 // 6463 // This is inverting a generic IR transform when we know that the cost of a 6464 // general vector shift is more than the cost of 2 shift-by-scalars. 6465 // We can't do this effectively in SDAG because we may not be able to 6466 // determine if the select operands are splats from within a basic block. 6467 Type *Ty = Fsh->getType(); 6468 if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) 6469 return false; 6470 Value *Cond, *TVal, *FVal; 6471 if (!match(Fsh->getOperand(2), 6472 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) 6473 return false; 6474 if (!isSplatValue(TVal) || !isSplatValue(FVal)) 6475 return false; 6476 6477 IRBuilder<> Builder(Fsh); 6478 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1); 6479 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, TVal }); 6480 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, FVal }); 6481 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); 6482 Fsh->replaceAllUsesWith(NewSel); 6483 Fsh->eraseFromParent(); 6484 return true; 6485 } 6486 6487 /// If we have a SelectInst that will likely profit from branch prediction, 6488 /// turn it into a branch. 6489 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { 6490 if (DisableSelectToBranch) 6491 return false; 6492 6493 // Find all consecutive select instructions that share the same condition. 6494 SmallVector<SelectInst *, 2> ASI; 6495 ASI.push_back(SI); 6496 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); 6497 It != SI->getParent()->end(); ++It) { 6498 SelectInst *I = dyn_cast<SelectInst>(&*It); 6499 if (I && SI->getCondition() == I->getCondition()) { 6500 ASI.push_back(I); 6501 } else { 6502 break; 6503 } 6504 } 6505 6506 SelectInst *LastSI = ASI.back(); 6507 // Increment the current iterator to skip all the rest of select instructions 6508 // because they will be either "not lowered" or "all lowered" to branch. 6509 CurInstIterator = std::next(LastSI->getIterator()); 6510 6511 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); 6512 6513 // Can we convert the 'select' to CF ? 6514 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable)) 6515 return false; 6516 6517 TargetLowering::SelectSupportKind SelectKind; 6518 if (VectorCond) 6519 SelectKind = TargetLowering::VectorMaskSelect; 6520 else if (SI->getType()->isVectorTy()) 6521 SelectKind = TargetLowering::ScalarCondVectorVal; 6522 else 6523 SelectKind = TargetLowering::ScalarValSelect; 6524 6525 if (TLI->isSelectSupported(SelectKind) && 6526 (!isFormingBranchFromSelectProfitable(TTI, TLI, SI) || OptSize || 6527 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI.get()))) 6528 return false; 6529 6530 // The DominatorTree needs to be rebuilt by any consumers after this 6531 // transformation. We simply reset here rather than setting the ModifiedDT 6532 // flag to avoid restarting the function walk in runOnFunction for each 6533 // select optimized. 6534 DT.reset(); 6535 6536 // Transform a sequence like this: 6537 // start: 6538 // %cmp = cmp uge i32 %a, %b 6539 // %sel = select i1 %cmp, i32 %c, i32 %d 6540 // 6541 // Into: 6542 // start: 6543 // %cmp = cmp uge i32 %a, %b 6544 // %cmp.frozen = freeze %cmp 6545 // br i1 %cmp.frozen, label %select.true, label %select.false 6546 // select.true: 6547 // br label %select.end 6548 // select.false: 6549 // br label %select.end 6550 // select.end: 6551 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] 6552 // 6553 // %cmp should be frozen, otherwise it may introduce undefined behavior. 6554 // In addition, we may sink instructions that produce %c or %d from 6555 // the entry block into the destination(s) of the new branch. 6556 // If the true or false blocks do not contain a sunken instruction, that 6557 // block and its branch may be optimized away. In that case, one side of the 6558 // first branch will point directly to select.end, and the corresponding PHI 6559 // predecessor block will be the start block. 6560 6561 // First, we split the block containing the select into 2 blocks. 6562 BasicBlock *StartBlock = SI->getParent(); 6563 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); 6564 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); 6565 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock).getFrequency()); 6566 6567 // Delete the unconditional branch that was just created by the split. 6568 StartBlock->getTerminator()->eraseFromParent(); 6569 6570 // These are the new basic blocks for the conditional branch. 6571 // At least one will become an actual new basic block. 6572 BasicBlock *TrueBlock = nullptr; 6573 BasicBlock *FalseBlock = nullptr; 6574 BranchInst *TrueBranch = nullptr; 6575 BranchInst *FalseBranch = nullptr; 6576 6577 // Sink expensive instructions into the conditional blocks to avoid executing 6578 // them speculatively. 6579 for (SelectInst *SI : ASI) { 6580 if (sinkSelectOperand(TTI, SI->getTrueValue())) { 6581 if (TrueBlock == nullptr) { 6582 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", 6583 EndBlock->getParent(), EndBlock); 6584 TrueBranch = BranchInst::Create(EndBlock, TrueBlock); 6585 TrueBranch->setDebugLoc(SI->getDebugLoc()); 6586 } 6587 auto *TrueInst = cast<Instruction>(SI->getTrueValue()); 6588 TrueInst->moveBefore(TrueBranch); 6589 } 6590 if (sinkSelectOperand(TTI, SI->getFalseValue())) { 6591 if (FalseBlock == nullptr) { 6592 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", 6593 EndBlock->getParent(), EndBlock); 6594 FalseBranch = BranchInst::Create(EndBlock, FalseBlock); 6595 FalseBranch->setDebugLoc(SI->getDebugLoc()); 6596 } 6597 auto *FalseInst = cast<Instruction>(SI->getFalseValue()); 6598 FalseInst->moveBefore(FalseBranch); 6599 } 6600 } 6601 6602 // If there was nothing to sink, then arbitrarily choose the 'false' side 6603 // for a new input value to the PHI. 6604 if (TrueBlock == FalseBlock) { 6605 assert(TrueBlock == nullptr && 6606 "Unexpected basic block transform while optimizing select"); 6607 6608 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", 6609 EndBlock->getParent(), EndBlock); 6610 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); 6611 FalseBranch->setDebugLoc(SI->getDebugLoc()); 6612 } 6613 6614 // Insert the real conditional branch based on the original condition. 6615 // If we did not create a new block for one of the 'true' or 'false' paths 6616 // of the condition, it means that side of the branch goes to the end block 6617 // directly and the path originates from the start block from the point of 6618 // view of the new PHI. 6619 BasicBlock *TT, *FT; 6620 if (TrueBlock == nullptr) { 6621 TT = EndBlock; 6622 FT = FalseBlock; 6623 TrueBlock = StartBlock; 6624 } else if (FalseBlock == nullptr) { 6625 TT = TrueBlock; 6626 FT = EndBlock; 6627 FalseBlock = StartBlock; 6628 } else { 6629 TT = TrueBlock; 6630 FT = FalseBlock; 6631 } 6632 IRBuilder<> IB(SI); 6633 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen"); 6634 IB.CreateCondBr(CondFr, TT, FT, SI); 6635 6636 SmallPtrSet<const Instruction *, 2> INS; 6637 INS.insert(ASI.begin(), ASI.end()); 6638 // Use reverse iterator because later select may use the value of the 6639 // earlier select, and we need to propagate value through earlier select 6640 // to get the PHI operand. 6641 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { 6642 SelectInst *SI = *It; 6643 // The select itself is replaced with a PHI Node. 6644 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); 6645 PN->takeName(SI); 6646 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); 6647 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); 6648 PN->setDebugLoc(SI->getDebugLoc()); 6649 6650 SI->replaceAllUsesWith(PN); 6651 SI->eraseFromParent(); 6652 INS.erase(SI); 6653 ++NumSelectsExpanded; 6654 } 6655 6656 // Instruct OptimizeBlock to skip to the next block. 6657 CurInstIterator = StartBlock->end(); 6658 return true; 6659 } 6660 6661 /// Some targets only accept certain types for splat inputs. For example a VDUP 6662 /// in MVE takes a GPR (integer) register, and the instruction that incorporate 6663 /// a VDUP (such as a VADD qd, qm, rm) also require a gpr register. 6664 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { 6665 if (!match(SVI, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 6666 m_Undef(), m_ZeroMask()))) 6667 return false; 6668 Type *NewType = TLI->shouldConvertSplatType(SVI); 6669 if (!NewType) 6670 return false; 6671 6672 auto *SVIVecType = cast<FixedVectorType>(SVI->getType()); 6673 assert(!NewType->isVectorTy() && "Expected a scalar type!"); 6674 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && 6675 "Expected a type of the same size!"); 6676 auto *NewVecType = 6677 FixedVectorType::get(NewType, SVIVecType->getNumElements()); 6678 6679 // Create a bitcast (shuffle (insert (bitcast(..)))) 6680 IRBuilder<> Builder(SVI->getContext()); 6681 Builder.SetInsertPoint(SVI); 6682 Value *BC1 = Builder.CreateBitCast( 6683 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType); 6684 Value *Insert = Builder.CreateInsertElement(UndefValue::get(NewVecType), BC1, 6685 (uint64_t)0); 6686 Value *Shuffle = Builder.CreateShuffleVector( 6687 Insert, UndefValue::get(NewVecType), SVI->getShuffleMask()); 6688 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType); 6689 6690 SVI->replaceAllUsesWith(BC2); 6691 RecursivelyDeleteTriviallyDeadInstructions( 6692 SVI, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); }); 6693 6694 // Also hoist the bitcast up to its operand if it they are not in the same 6695 // block. 6696 if (auto *BCI = dyn_cast<Instruction>(BC1)) 6697 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0))) 6698 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) && 6699 !Op->isTerminator() && !Op->isEHPad()) 6700 BCI->moveAfter(Op); 6701 6702 return true; 6703 } 6704 6705 bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) { 6706 // If the operands of I can be folded into a target instruction together with 6707 // I, duplicate and sink them. 6708 SmallVector<Use *, 4> OpsToSink; 6709 if (!TLI->shouldSinkOperands(I, OpsToSink)) 6710 return false; 6711 6712 // OpsToSink can contain multiple uses in a use chain (e.g. 6713 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating 6714 // uses must come first, so we process the ops in reverse order so as to not 6715 // create invalid IR. 6716 BasicBlock *TargetBB = I->getParent(); 6717 bool Changed = false; 6718 SmallVector<Use *, 4> ToReplace; 6719 for (Use *U : reverse(OpsToSink)) { 6720 auto *UI = cast<Instruction>(U->get()); 6721 if (UI->getParent() == TargetBB || isa<PHINode>(UI)) 6722 continue; 6723 ToReplace.push_back(U); 6724 } 6725 6726 SetVector<Instruction *> MaybeDead; 6727 DenseMap<Instruction *, Instruction *> NewInstructions; 6728 Instruction *InsertPoint = I; 6729 for (Use *U : ToReplace) { 6730 auto *UI = cast<Instruction>(U->get()); 6731 Instruction *NI = UI->clone(); 6732 NewInstructions[UI] = NI; 6733 MaybeDead.insert(UI); 6734 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n"); 6735 NI->insertBefore(InsertPoint); 6736 InsertPoint = NI; 6737 InsertedInsts.insert(NI); 6738 6739 // Update the use for the new instruction, making sure that we update the 6740 // sunk instruction uses, if it is part of a chain that has already been 6741 // sunk. 6742 Instruction *OldI = cast<Instruction>(U->getUser()); 6743 if (NewInstructions.count(OldI)) 6744 NewInstructions[OldI]->setOperand(U->getOperandNo(), NI); 6745 else 6746 U->set(NI); 6747 Changed = true; 6748 } 6749 6750 // Remove instructions that are dead after sinking. 6751 for (auto *I : MaybeDead) { 6752 if (!I->hasNUsesOrMore(1)) { 6753 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n"); 6754 I->eraseFromParent(); 6755 } 6756 } 6757 6758 return Changed; 6759 } 6760 6761 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { 6762 Value *Cond = SI->getCondition(); 6763 Type *OldType = Cond->getType(); 6764 LLVMContext &Context = Cond->getContext(); 6765 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); 6766 unsigned RegWidth = RegType.getSizeInBits(); 6767 6768 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) 6769 return false; 6770 6771 // If the register width is greater than the type width, expand the condition 6772 // of the switch instruction and each case constant to the width of the 6773 // register. By widening the type of the switch condition, subsequent 6774 // comparisons (for case comparisons) will not need to be extended to the 6775 // preferred register width, so we will potentially eliminate N-1 extends, 6776 // where N is the number of cases in the switch. 6777 auto *NewType = Type::getIntNTy(Context, RegWidth); 6778 6779 // Zero-extend the switch condition and case constants unless the switch 6780 // condition is a function argument that is already being sign-extended. 6781 // In that case, we can avoid an unnecessary mask/extension by sign-extending 6782 // everything instead. 6783 Instruction::CastOps ExtType = Instruction::ZExt; 6784 if (auto *Arg = dyn_cast<Argument>(Cond)) 6785 if (Arg->hasSExtAttr()) 6786 ExtType = Instruction::SExt; 6787 6788 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); 6789 ExtInst->insertBefore(SI); 6790 ExtInst->setDebugLoc(SI->getDebugLoc()); 6791 SI->setCondition(ExtInst); 6792 for (auto Case : SI->cases()) { 6793 APInt NarrowConst = Case.getCaseValue()->getValue(); 6794 APInt WideConst = (ExtType == Instruction::ZExt) ? 6795 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); 6796 Case.setValue(ConstantInt::get(Context, WideConst)); 6797 } 6798 6799 return true; 6800 } 6801 6802 6803 namespace { 6804 6805 /// Helper class to promote a scalar operation to a vector one. 6806 /// This class is used to move downward extractelement transition. 6807 /// E.g., 6808 /// a = vector_op <2 x i32> 6809 /// b = extractelement <2 x i32> a, i32 0 6810 /// c = scalar_op b 6811 /// store c 6812 /// 6813 /// => 6814 /// a = vector_op <2 x i32> 6815 /// c = vector_op a (equivalent to scalar_op on the related lane) 6816 /// * d = extractelement <2 x i32> c, i32 0 6817 /// * store d 6818 /// Assuming both extractelement and store can be combine, we get rid of the 6819 /// transition. 6820 class VectorPromoteHelper { 6821 /// DataLayout associated with the current module. 6822 const DataLayout &DL; 6823 6824 /// Used to perform some checks on the legality of vector operations. 6825 const TargetLowering &TLI; 6826 6827 /// Used to estimated the cost of the promoted chain. 6828 const TargetTransformInfo &TTI; 6829 6830 /// The transition being moved downwards. 6831 Instruction *Transition; 6832 6833 /// The sequence of instructions to be promoted. 6834 SmallVector<Instruction *, 4> InstsToBePromoted; 6835 6836 /// Cost of combining a store and an extract. 6837 unsigned StoreExtractCombineCost; 6838 6839 /// Instruction that will be combined with the transition. 6840 Instruction *CombineInst = nullptr; 6841 6842 /// The instruction that represents the current end of the transition. 6843 /// Since we are faking the promotion until we reach the end of the chain 6844 /// of computation, we need a way to get the current end of the transition. 6845 Instruction *getEndOfTransition() const { 6846 if (InstsToBePromoted.empty()) 6847 return Transition; 6848 return InstsToBePromoted.back(); 6849 } 6850 6851 /// Return the index of the original value in the transition. 6852 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, 6853 /// c, is at index 0. 6854 unsigned getTransitionOriginalValueIdx() const { 6855 assert(isa<ExtractElementInst>(Transition) && 6856 "Other kind of transitions are not supported yet"); 6857 return 0; 6858 } 6859 6860 /// Return the index of the index in the transition. 6861 /// E.g., for "extractelement <2 x i32> c, i32 0" the index 6862 /// is at index 1. 6863 unsigned getTransitionIdx() const { 6864 assert(isa<ExtractElementInst>(Transition) && 6865 "Other kind of transitions are not supported yet"); 6866 return 1; 6867 } 6868 6869 /// Get the type of the transition. 6870 /// This is the type of the original value. 6871 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the 6872 /// transition is <2 x i32>. 6873 Type *getTransitionType() const { 6874 return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); 6875 } 6876 6877 /// Promote \p ToBePromoted by moving \p Def downward through. 6878 /// I.e., we have the following sequence: 6879 /// Def = Transition <ty1> a to <ty2> 6880 /// b = ToBePromoted <ty2> Def, ... 6881 /// => 6882 /// b = ToBePromoted <ty1> a, ... 6883 /// Def = Transition <ty1> ToBePromoted to <ty2> 6884 void promoteImpl(Instruction *ToBePromoted); 6885 6886 /// Check whether or not it is profitable to promote all the 6887 /// instructions enqueued to be promoted. 6888 bool isProfitableToPromote() { 6889 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); 6890 unsigned Index = isa<ConstantInt>(ValIdx) 6891 ? cast<ConstantInt>(ValIdx)->getZExtValue() 6892 : -1; 6893 Type *PromotedType = getTransitionType(); 6894 6895 StoreInst *ST = cast<StoreInst>(CombineInst); 6896 unsigned AS = ST->getPointerAddressSpace(); 6897 unsigned Align = ST->getAlignment(); 6898 // Check if this store is supported. 6899 if (!TLI.allowsMisalignedMemoryAccesses( 6900 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, 6901 Align)) { 6902 // If this is not supported, there is no way we can combine 6903 // the extract with the store. 6904 return false; 6905 } 6906 6907 // The scalar chain of computation has to pay for the transition 6908 // scalar to vector. 6909 // The vector chain has to account for the combining cost. 6910 uint64_t ScalarCost = 6911 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); 6912 uint64_t VectorCost = StoreExtractCombineCost; 6913 enum TargetTransformInfo::TargetCostKind CostKind = 6914 TargetTransformInfo::TCK_RecipThroughput; 6915 for (const auto &Inst : InstsToBePromoted) { 6916 // Compute the cost. 6917 // By construction, all instructions being promoted are arithmetic ones. 6918 // Moreover, one argument is a constant that can be viewed as a splat 6919 // constant. 6920 Value *Arg0 = Inst->getOperand(0); 6921 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || 6922 isa<ConstantFP>(Arg0); 6923 TargetTransformInfo::OperandValueKind Arg0OVK = 6924 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue 6925 : TargetTransformInfo::OK_AnyValue; 6926 TargetTransformInfo::OperandValueKind Arg1OVK = 6927 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue 6928 : TargetTransformInfo::OK_AnyValue; 6929 ScalarCost += TTI.getArithmeticInstrCost( 6930 Inst->getOpcode(), Inst->getType(), CostKind, Arg0OVK, Arg1OVK); 6931 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, 6932 CostKind, 6933 Arg0OVK, Arg1OVK); 6934 } 6935 LLVM_DEBUG( 6936 dbgs() << "Estimated cost of computation to be promoted:\nScalar: " 6937 << ScalarCost << "\nVector: " << VectorCost << '\n'); 6938 return ScalarCost > VectorCost; 6939 } 6940 6941 /// Generate a constant vector with \p Val with the same 6942 /// number of elements as the transition. 6943 /// \p UseSplat defines whether or not \p Val should be replicated 6944 /// across the whole vector. 6945 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, 6946 /// otherwise we generate a vector with as many undef as possible: 6947 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only 6948 /// used at the index of the extract. 6949 Value *getConstantVector(Constant *Val, bool UseSplat) const { 6950 unsigned ExtractIdx = std::numeric_limits<unsigned>::max(); 6951 if (!UseSplat) { 6952 // If we cannot determine where the constant must be, we have to 6953 // use a splat constant. 6954 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); 6955 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) 6956 ExtractIdx = CstVal->getSExtValue(); 6957 else 6958 UseSplat = true; 6959 } 6960 6961 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount(); 6962 if (UseSplat) 6963 return ConstantVector::getSplat(EC, Val); 6964 6965 if (!EC.isScalable()) { 6966 SmallVector<Constant *, 4> ConstVec; 6967 UndefValue *UndefVal = UndefValue::get(Val->getType()); 6968 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) { 6969 if (Idx == ExtractIdx) 6970 ConstVec.push_back(Val); 6971 else 6972 ConstVec.push_back(UndefVal); 6973 } 6974 return ConstantVector::get(ConstVec); 6975 } else 6976 llvm_unreachable( 6977 "Generate scalable vector for non-splat is unimplemented"); 6978 } 6979 6980 /// Check if promoting to a vector type an operand at \p OperandIdx 6981 /// in \p Use can trigger undefined behavior. 6982 static bool canCauseUndefinedBehavior(const Instruction *Use, 6983 unsigned OperandIdx) { 6984 // This is not safe to introduce undef when the operand is on 6985 // the right hand side of a division-like instruction. 6986 if (OperandIdx != 1) 6987 return false; 6988 switch (Use->getOpcode()) { 6989 default: 6990 return false; 6991 case Instruction::SDiv: 6992 case Instruction::UDiv: 6993 case Instruction::SRem: 6994 case Instruction::URem: 6995 return true; 6996 case Instruction::FDiv: 6997 case Instruction::FRem: 6998 return !Use->hasNoNaNs(); 6999 } 7000 llvm_unreachable(nullptr); 7001 } 7002 7003 public: 7004 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, 7005 const TargetTransformInfo &TTI, Instruction *Transition, 7006 unsigned CombineCost) 7007 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), 7008 StoreExtractCombineCost(CombineCost) { 7009 assert(Transition && "Do not know how to promote null"); 7010 } 7011 7012 /// Check if we can promote \p ToBePromoted to \p Type. 7013 bool canPromote(const Instruction *ToBePromoted) const { 7014 // We could support CastInst too. 7015 return isa<BinaryOperator>(ToBePromoted); 7016 } 7017 7018 /// Check if it is profitable to promote \p ToBePromoted 7019 /// by moving downward the transition through. 7020 bool shouldPromote(const Instruction *ToBePromoted) const { 7021 // Promote only if all the operands can be statically expanded. 7022 // Indeed, we do not want to introduce any new kind of transitions. 7023 for (const Use &U : ToBePromoted->operands()) { 7024 const Value *Val = U.get(); 7025 if (Val == getEndOfTransition()) { 7026 // If the use is a division and the transition is on the rhs, 7027 // we cannot promote the operation, otherwise we may create a 7028 // division by zero. 7029 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) 7030 return false; 7031 continue; 7032 } 7033 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && 7034 !isa<ConstantFP>(Val)) 7035 return false; 7036 } 7037 // Check that the resulting operation is legal. 7038 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); 7039 if (!ISDOpcode) 7040 return false; 7041 return StressStoreExtract || 7042 TLI.isOperationLegalOrCustom( 7043 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); 7044 } 7045 7046 /// Check whether or not \p Use can be combined 7047 /// with the transition. 7048 /// I.e., is it possible to do Use(Transition) => AnotherUse? 7049 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } 7050 7051 /// Record \p ToBePromoted as part of the chain to be promoted. 7052 void enqueueForPromotion(Instruction *ToBePromoted) { 7053 InstsToBePromoted.push_back(ToBePromoted); 7054 } 7055 7056 /// Set the instruction that will be combined with the transition. 7057 void recordCombineInstruction(Instruction *ToBeCombined) { 7058 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); 7059 CombineInst = ToBeCombined; 7060 } 7061 7062 /// Promote all the instructions enqueued for promotion if it is 7063 /// is profitable. 7064 /// \return True if the promotion happened, false otherwise. 7065 bool promote() { 7066 // Check if there is something to promote. 7067 // Right now, if we do not have anything to combine with, 7068 // we assume the promotion is not profitable. 7069 if (InstsToBePromoted.empty() || !CombineInst) 7070 return false; 7071 7072 // Check cost. 7073 if (!StressStoreExtract && !isProfitableToPromote()) 7074 return false; 7075 7076 // Promote. 7077 for (auto &ToBePromoted : InstsToBePromoted) 7078 promoteImpl(ToBePromoted); 7079 InstsToBePromoted.clear(); 7080 return true; 7081 } 7082 }; 7083 7084 } // end anonymous namespace 7085 7086 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { 7087 // At this point, we know that all the operands of ToBePromoted but Def 7088 // can be statically promoted. 7089 // For Def, we need to use its parameter in ToBePromoted: 7090 // b = ToBePromoted ty1 a 7091 // Def = Transition ty1 b to ty2 7092 // Move the transition down. 7093 // 1. Replace all uses of the promoted operation by the transition. 7094 // = ... b => = ... Def. 7095 assert(ToBePromoted->getType() == Transition->getType() && 7096 "The type of the result of the transition does not match " 7097 "the final type"); 7098 ToBePromoted->replaceAllUsesWith(Transition); 7099 // 2. Update the type of the uses. 7100 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. 7101 Type *TransitionTy = getTransitionType(); 7102 ToBePromoted->mutateType(TransitionTy); 7103 // 3. Update all the operands of the promoted operation with promoted 7104 // operands. 7105 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. 7106 for (Use &U : ToBePromoted->operands()) { 7107 Value *Val = U.get(); 7108 Value *NewVal = nullptr; 7109 if (Val == Transition) 7110 NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); 7111 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || 7112 isa<ConstantFP>(Val)) { 7113 // Use a splat constant if it is not safe to use undef. 7114 NewVal = getConstantVector( 7115 cast<Constant>(Val), 7116 isa<UndefValue>(Val) || 7117 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); 7118 } else 7119 llvm_unreachable("Did you modified shouldPromote and forgot to update " 7120 "this?"); 7121 ToBePromoted->setOperand(U.getOperandNo(), NewVal); 7122 } 7123 Transition->moveAfter(ToBePromoted); 7124 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); 7125 } 7126 7127 /// Some targets can do store(extractelement) with one instruction. 7128 /// Try to push the extractelement towards the stores when the target 7129 /// has this feature and this is profitable. 7130 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { 7131 unsigned CombineCost = std::numeric_limits<unsigned>::max(); 7132 if (DisableStoreExtract || 7133 (!StressStoreExtract && 7134 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), 7135 Inst->getOperand(1), CombineCost))) 7136 return false; 7137 7138 // At this point we know that Inst is a vector to scalar transition. 7139 // Try to move it down the def-use chain, until: 7140 // - We can combine the transition with its single use 7141 // => we got rid of the transition. 7142 // - We escape the current basic block 7143 // => we would need to check that we are moving it at a cheaper place and 7144 // we do not do that for now. 7145 BasicBlock *Parent = Inst->getParent(); 7146 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); 7147 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); 7148 // If the transition has more than one use, assume this is not going to be 7149 // beneficial. 7150 while (Inst->hasOneUse()) { 7151 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); 7152 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); 7153 7154 if (ToBePromoted->getParent() != Parent) { 7155 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block (" 7156 << ToBePromoted->getParent()->getName() 7157 << ") than the transition (" << Parent->getName() 7158 << ").\n"); 7159 return false; 7160 } 7161 7162 if (VPH.canCombine(ToBePromoted)) { 7163 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n' 7164 << "will be combined with: " << *ToBePromoted << '\n'); 7165 VPH.recordCombineInstruction(ToBePromoted); 7166 bool Changed = VPH.promote(); 7167 NumStoreExtractExposed += Changed; 7168 return Changed; 7169 } 7170 7171 LLVM_DEBUG(dbgs() << "Try promoting.\n"); 7172 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) 7173 return false; 7174 7175 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); 7176 7177 VPH.enqueueForPromotion(ToBePromoted); 7178 Inst = ToBePromoted; 7179 } 7180 return false; 7181 } 7182 7183 /// For the instruction sequence of store below, F and I values 7184 /// are bundled together as an i64 value before being stored into memory. 7185 /// Sometimes it is more efficient to generate separate stores for F and I, 7186 /// which can remove the bitwise instructions or sink them to colder places. 7187 /// 7188 /// (store (or (zext (bitcast F to i32) to i64), 7189 /// (shl (zext I to i64), 32)), addr) --> 7190 /// (store F, addr) and (store I, addr+4) 7191 /// 7192 /// Similarly, splitting for other merged store can also be beneficial, like: 7193 /// For pair of {i32, i32}, i64 store --> two i32 stores. 7194 /// For pair of {i32, i16}, i64 store --> two i32 stores. 7195 /// For pair of {i16, i16}, i32 store --> two i16 stores. 7196 /// For pair of {i16, i8}, i32 store --> two i16 stores. 7197 /// For pair of {i8, i8}, i16 store --> two i8 stores. 7198 /// 7199 /// We allow each target to determine specifically which kind of splitting is 7200 /// supported. 7201 /// 7202 /// The store patterns are commonly seen from the simple code snippet below 7203 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 7204 /// void goo(const std::pair<int, float> &); 7205 /// hoo() { 7206 /// ... 7207 /// goo(std::make_pair(tmp, ftmp)); 7208 /// ... 7209 /// } 7210 /// 7211 /// Although we already have similar splitting in DAG Combine, we duplicate 7212 /// it in CodeGenPrepare to catch the case in which pattern is across 7213 /// multiple BBs. The logic in DAG Combine is kept to catch case generated 7214 /// during code expansion. 7215 static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, 7216 const TargetLowering &TLI) { 7217 // Handle simple but common cases only. 7218 Type *StoreType = SI.getValueOperand()->getType(); 7219 7220 // The code below assumes shifting a value by <number of bits>, 7221 // whereas scalable vectors would have to be shifted by 7222 // <2log(vscale) + number of bits> in order to store the 7223 // low/high parts. Bailing out for now. 7224 if (isa<ScalableVectorType>(StoreType)) 7225 return false; 7226 7227 if (!DL.typeSizeEqualsStoreSize(StoreType) || 7228 DL.getTypeSizeInBits(StoreType) == 0) 7229 return false; 7230 7231 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; 7232 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); 7233 if (!DL.typeSizeEqualsStoreSize(SplitStoreType)) 7234 return false; 7235 7236 // Don't split the store if it is volatile. 7237 if (SI.isVolatile()) 7238 return false; 7239 7240 // Match the following patterns: 7241 // (store (or (zext LValue to i64), 7242 // (shl (zext HValue to i64), 32)), HalfValBitSize) 7243 // or 7244 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) 7245 // (zext LValue to i64), 7246 // Expect both operands of OR and the first operand of SHL have only 7247 // one use. 7248 Value *LValue, *HValue; 7249 if (!match(SI.getValueOperand(), 7250 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), 7251 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), 7252 m_SpecificInt(HalfValBitSize)))))) 7253 return false; 7254 7255 // Check LValue and HValue are int with size less or equal than 32. 7256 if (!LValue->getType()->isIntegerTy() || 7257 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || 7258 !HValue->getType()->isIntegerTy() || 7259 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) 7260 return false; 7261 7262 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast 7263 // as the input of target query. 7264 auto *LBC = dyn_cast<BitCastInst>(LValue); 7265 auto *HBC = dyn_cast<BitCastInst>(HValue); 7266 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) 7267 : EVT::getEVT(LValue->getType()); 7268 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) 7269 : EVT::getEVT(HValue->getType()); 7270 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 7271 return false; 7272 7273 // Start to split store. 7274 IRBuilder<> Builder(SI.getContext()); 7275 Builder.SetInsertPoint(&SI); 7276 7277 // If LValue/HValue is a bitcast in another BB, create a new one in current 7278 // BB so it may be merged with the splitted stores by dag combiner. 7279 if (LBC && LBC->getParent() != SI.getParent()) 7280 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); 7281 if (HBC && HBC->getParent() != SI.getParent()) 7282 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); 7283 7284 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian(); 7285 auto CreateSplitStore = [&](Value *V, bool Upper) { 7286 V = Builder.CreateZExtOrBitCast(V, SplitStoreType); 7287 Value *Addr = Builder.CreateBitCast( 7288 SI.getOperand(1), 7289 SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); 7290 Align Alignment = SI.getAlign(); 7291 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper); 7292 if (IsOffsetStore) { 7293 Addr = Builder.CreateGEP( 7294 SplitStoreType, Addr, 7295 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); 7296 7297 // When splitting the store in half, naturally one half will retain the 7298 // alignment of the original wider store, regardless of whether it was 7299 // over-aligned or not, while the other will require adjustment. 7300 Alignment = commonAlignment(Alignment, HalfValBitSize / 8); 7301 } 7302 Builder.CreateAlignedStore(V, Addr, Alignment); 7303 }; 7304 7305 CreateSplitStore(LValue, false); 7306 CreateSplitStore(HValue, true); 7307 7308 // Delete the old store. 7309 SI.eraseFromParent(); 7310 return true; 7311 } 7312 7313 // Return true if the GEP has two operands, the first operand is of a sequential 7314 // type, and the second operand is a constant. 7315 static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) { 7316 gep_type_iterator I = gep_type_begin(*GEP); 7317 return GEP->getNumOperands() == 2 && 7318 I.isSequential() && 7319 isa<ConstantInt>(GEP->getOperand(1)); 7320 } 7321 7322 // Try unmerging GEPs to reduce liveness interference (register pressure) across 7323 // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks, 7324 // reducing liveness interference across those edges benefits global register 7325 // allocation. Currently handles only certain cases. 7326 // 7327 // For example, unmerge %GEPI and %UGEPI as below. 7328 // 7329 // ---------- BEFORE ---------- 7330 // SrcBlock: 7331 // ... 7332 // %GEPIOp = ... 7333 // ... 7334 // %GEPI = gep %GEPIOp, Idx 7335 // ... 7336 // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ] 7337 // (* %GEPI is alive on the indirectbr edges due to other uses ahead) 7338 // (* %GEPIOp is alive on the indirectbr edges only because of it's used by 7339 // %UGEPI) 7340 // 7341 // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged) 7342 // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged) 7343 // ... 7344 // 7345 // DstBi: 7346 // ... 7347 // %UGEPI = gep %GEPIOp, UIdx 7348 // ... 7349 // --------------------------- 7350 // 7351 // ---------- AFTER ---------- 7352 // SrcBlock: 7353 // ... (same as above) 7354 // (* %GEPI is still alive on the indirectbr edges) 7355 // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the 7356 // unmerging) 7357 // ... 7358 // 7359 // DstBi: 7360 // ... 7361 // %UGEPI = gep %GEPI, (UIdx-Idx) 7362 // ... 7363 // --------------------------- 7364 // 7365 // The register pressure on the IndirectBr edges is reduced because %GEPIOp is 7366 // no longer alive on them. 7367 // 7368 // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging 7369 // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as 7370 // not to disable further simplications and optimizations as a result of GEP 7371 // merging. 7372 // 7373 // Note this unmerging may increase the length of the data flow critical path 7374 // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff 7375 // between the register pressure and the length of data-flow critical 7376 // path. Restricting this to the uncommon IndirectBr case would minimize the 7377 // impact of potentially longer critical path, if any, and the impact on compile 7378 // time. 7379 static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, 7380 const TargetTransformInfo *TTI) { 7381 BasicBlock *SrcBlock = GEPI->getParent(); 7382 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common 7383 // (non-IndirectBr) cases exit early here. 7384 if (!isa<IndirectBrInst>(SrcBlock->getTerminator())) 7385 return false; 7386 // Check that GEPI is a simple gep with a single constant index. 7387 if (!GEPSequentialConstIndexed(GEPI)) 7388 return false; 7389 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1)); 7390 // Check that GEPI is a cheap one. 7391 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(), 7392 TargetTransformInfo::TCK_SizeAndLatency) 7393 > TargetTransformInfo::TCC_Basic) 7394 return false; 7395 Value *GEPIOp = GEPI->getOperand(0); 7396 // Check that GEPIOp is an instruction that's also defined in SrcBlock. 7397 if (!isa<Instruction>(GEPIOp)) 7398 return false; 7399 auto *GEPIOpI = cast<Instruction>(GEPIOp); 7400 if (GEPIOpI->getParent() != SrcBlock) 7401 return false; 7402 // Check that GEP is used outside the block, meaning it's alive on the 7403 // IndirectBr edge(s). 7404 if (find_if(GEPI->users(), [&](User *Usr) { 7405 if (auto *I = dyn_cast<Instruction>(Usr)) { 7406 if (I->getParent() != SrcBlock) { 7407 return true; 7408 } 7409 } 7410 return false; 7411 }) == GEPI->users().end()) 7412 return false; 7413 // The second elements of the GEP chains to be unmerged. 7414 std::vector<GetElementPtrInst *> UGEPIs; 7415 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive 7416 // on IndirectBr edges. 7417 for (User *Usr : GEPIOp->users()) { 7418 if (Usr == GEPI) continue; 7419 // Check if Usr is an Instruction. If not, give up. 7420 if (!isa<Instruction>(Usr)) 7421 return false; 7422 auto *UI = cast<Instruction>(Usr); 7423 // Check if Usr in the same block as GEPIOp, which is fine, skip. 7424 if (UI->getParent() == SrcBlock) 7425 continue; 7426 // Check if Usr is a GEP. If not, give up. 7427 if (!isa<GetElementPtrInst>(Usr)) 7428 return false; 7429 auto *UGEPI = cast<GetElementPtrInst>(Usr); 7430 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is 7431 // the pointer operand to it. If so, record it in the vector. If not, give 7432 // up. 7433 if (!GEPSequentialConstIndexed(UGEPI)) 7434 return false; 7435 if (UGEPI->getOperand(0) != GEPIOp) 7436 return false; 7437 if (GEPIIdx->getType() != 7438 cast<ConstantInt>(UGEPI->getOperand(1))->getType()) 7439 return false; 7440 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); 7441 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(), 7442 TargetTransformInfo::TCK_SizeAndLatency) 7443 > TargetTransformInfo::TCC_Basic) 7444 return false; 7445 UGEPIs.push_back(UGEPI); 7446 } 7447 if (UGEPIs.size() == 0) 7448 return false; 7449 // Check the materializing cost of (Uidx-Idx). 7450 for (GetElementPtrInst *UGEPI : UGEPIs) { 7451 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); 7452 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue(); 7453 unsigned ImmCost = 7454 TTI->getIntImmCost(NewIdx, GEPIIdx->getType(), 7455 TargetTransformInfo::TCK_SizeAndLatency); 7456 if (ImmCost > TargetTransformInfo::TCC_Basic) 7457 return false; 7458 } 7459 // Now unmerge between GEPI and UGEPIs. 7460 for (GetElementPtrInst *UGEPI : UGEPIs) { 7461 UGEPI->setOperand(0, GEPI); 7462 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); 7463 Constant *NewUGEPIIdx = 7464 ConstantInt::get(GEPIIdx->getType(), 7465 UGEPIIdx->getValue() - GEPIIdx->getValue()); 7466 UGEPI->setOperand(1, NewUGEPIIdx); 7467 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not 7468 // inbounds to avoid UB. 7469 if (!GEPI->isInBounds()) { 7470 UGEPI->setIsInBounds(false); 7471 } 7472 } 7473 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not 7474 // alive on IndirectBr edges). 7475 assert(find_if(GEPIOp->users(), [&](User *Usr) { 7476 return cast<Instruction>(Usr)->getParent() != SrcBlock; 7477 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock"); 7478 return true; 7479 } 7480 7481 bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) { 7482 // Bail out if we inserted the instruction to prevent optimizations from 7483 // stepping on each other's toes. 7484 if (InsertedInsts.count(I)) 7485 return false; 7486 7487 // TODO: Move into the switch on opcode below here. 7488 if (PHINode *P = dyn_cast<PHINode>(I)) { 7489 // It is possible for very late stage optimizations (such as SimplifyCFG) 7490 // to introduce PHI nodes too late to be cleaned up. If we detect such a 7491 // trivial PHI, go ahead and zap it here. 7492 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) { 7493 LargeOffsetGEPMap.erase(P); 7494 P->replaceAllUsesWith(V); 7495 P->eraseFromParent(); 7496 ++NumPHIsElim; 7497 return true; 7498 } 7499 return false; 7500 } 7501 7502 if (CastInst *CI = dyn_cast<CastInst>(I)) { 7503 // If the source of the cast is a constant, then this should have 7504 // already been constant folded. The only reason NOT to constant fold 7505 // it is if something (e.g. LSR) was careful to place the constant 7506 // evaluation in a block other than then one that uses it (e.g. to hoist 7507 // the address of globals out of a loop). If this is the case, we don't 7508 // want to forward-subst the cast. 7509 if (isa<Constant>(CI->getOperand(0))) 7510 return false; 7511 7512 if (OptimizeNoopCopyExpression(CI, *TLI, *DL)) 7513 return true; 7514 7515 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { 7516 /// Sink a zext or sext into its user blocks if the target type doesn't 7517 /// fit in one register 7518 if (TLI->getTypeAction(CI->getContext(), 7519 TLI->getValueType(*DL, CI->getType())) == 7520 TargetLowering::TypeExpandInteger) { 7521 return SinkCast(CI); 7522 } else { 7523 bool MadeChange = optimizeExt(I); 7524 return MadeChange | optimizeExtUses(I); 7525 } 7526 } 7527 return false; 7528 } 7529 7530 if (auto *Cmp = dyn_cast<CmpInst>(I)) 7531 if (optimizeCmp(Cmp, ModifiedDT)) 7532 return true; 7533 7534 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7535 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); 7536 bool Modified = optimizeLoadExt(LI); 7537 unsigned AS = LI->getPointerAddressSpace(); 7538 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); 7539 return Modified; 7540 } 7541 7542 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 7543 if (splitMergedValStore(*SI, *DL, *TLI)) 7544 return true; 7545 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); 7546 unsigned AS = SI->getPointerAddressSpace(); 7547 return optimizeMemoryInst(I, SI->getOperand(1), 7548 SI->getOperand(0)->getType(), AS); 7549 } 7550 7551 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { 7552 unsigned AS = RMW->getPointerAddressSpace(); 7553 return optimizeMemoryInst(I, RMW->getPointerOperand(), 7554 RMW->getType(), AS); 7555 } 7556 7557 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { 7558 unsigned AS = CmpX->getPointerAddressSpace(); 7559 return optimizeMemoryInst(I, CmpX->getPointerOperand(), 7560 CmpX->getCompareOperand()->getType(), AS); 7561 } 7562 7563 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); 7564 7565 if (BinOp && (BinOp->getOpcode() == Instruction::And) && EnableAndCmpSinking) 7566 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); 7567 7568 // TODO: Move this into the switch on opcode - it handles shifts already. 7569 if (BinOp && (BinOp->getOpcode() == Instruction::AShr || 7570 BinOp->getOpcode() == Instruction::LShr)) { 7571 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); 7572 if (CI && TLI->hasExtractBitsInsn()) 7573 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL)) 7574 return true; 7575 } 7576 7577 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 7578 if (GEPI->hasAllZeroIndices()) { 7579 /// The GEP operand must be a pointer, so must its result -> BitCast 7580 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), 7581 GEPI->getName(), GEPI); 7582 NC->setDebugLoc(GEPI->getDebugLoc()); 7583 GEPI->replaceAllUsesWith(NC); 7584 GEPI->eraseFromParent(); 7585 ++NumGEPsElim; 7586 optimizeInst(NC, ModifiedDT); 7587 return true; 7588 } 7589 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) { 7590 return true; 7591 } 7592 return false; 7593 } 7594 7595 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) { 7596 // freeze(icmp a, const)) -> icmp (freeze a), const 7597 // This helps generate efficient conditional jumps. 7598 Instruction *CmpI = nullptr; 7599 if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0))) 7600 CmpI = II; 7601 else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0))) 7602 CmpI = F->getFastMathFlags().none() ? F : nullptr; 7603 7604 if (CmpI && CmpI->hasOneUse()) { 7605 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1); 7606 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) || 7607 isa<ConstantPointerNull>(Op0); 7608 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) || 7609 isa<ConstantPointerNull>(Op1); 7610 if (Const0 || Const1) { 7611 if (!Const0 || !Const1) { 7612 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI); 7613 F->takeName(FI); 7614 CmpI->setOperand(Const0 ? 1 : 0, F); 7615 } 7616 FI->replaceAllUsesWith(CmpI); 7617 FI->eraseFromParent(); 7618 return true; 7619 } 7620 } 7621 return false; 7622 } 7623 7624 if (tryToSinkFreeOperands(I)) 7625 return true; 7626 7627 switch (I->getOpcode()) { 7628 case Instruction::Shl: 7629 case Instruction::LShr: 7630 case Instruction::AShr: 7631 return optimizeShiftInst(cast<BinaryOperator>(I)); 7632 case Instruction::Call: 7633 return optimizeCallInst(cast<CallInst>(I), ModifiedDT); 7634 case Instruction::Select: 7635 return optimizeSelectInst(cast<SelectInst>(I)); 7636 case Instruction::ShuffleVector: 7637 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I)); 7638 case Instruction::Switch: 7639 return optimizeSwitchInst(cast<SwitchInst>(I)); 7640 case Instruction::ExtractElement: 7641 return optimizeExtractElementInst(cast<ExtractElementInst>(I)); 7642 } 7643 7644 return false; 7645 } 7646 7647 /// Given an OR instruction, check to see if this is a bitreverse 7648 /// idiom. If so, insert the new intrinsic and return true. 7649 bool CodeGenPrepare::makeBitReverse(Instruction &I) { 7650 if (!I.getType()->isIntegerTy() || 7651 !TLI->isOperationLegalOrCustom(ISD::BITREVERSE, 7652 TLI->getValueType(*DL, I.getType(), true))) 7653 return false; 7654 7655 SmallVector<Instruction*, 4> Insts; 7656 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) 7657 return false; 7658 Instruction *LastInst = Insts.back(); 7659 I.replaceAllUsesWith(LastInst); 7660 RecursivelyDeleteTriviallyDeadInstructions( 7661 &I, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); }); 7662 return true; 7663 } 7664 7665 // In this pass we look for GEP and cast instructions that are used 7666 // across basic blocks and rewrite them to improve basic-block-at-a-time 7667 // selection. 7668 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) { 7669 SunkAddrs.clear(); 7670 bool MadeChange = false; 7671 7672 CurInstIterator = BB.begin(); 7673 while (CurInstIterator != BB.end()) { 7674 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); 7675 if (ModifiedDT) 7676 return true; 7677 } 7678 7679 bool MadeBitReverse = true; 7680 while (MadeBitReverse) { 7681 MadeBitReverse = false; 7682 for (auto &I : reverse(BB)) { 7683 if (makeBitReverse(I)) { 7684 MadeBitReverse = MadeChange = true; 7685 break; 7686 } 7687 } 7688 } 7689 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT); 7690 7691 return MadeChange; 7692 } 7693 7694 // Some CGP optimizations may move or alter what's computed in a block. Check 7695 // whether a dbg.value intrinsic could be pointed at a more appropriate operand. 7696 bool CodeGenPrepare::fixupDbgValue(Instruction *I) { 7697 assert(isa<DbgValueInst>(I)); 7698 DbgValueInst &DVI = *cast<DbgValueInst>(I); 7699 7700 // Does this dbg.value refer to a sunk address calculation? 7701 Value *Location = DVI.getVariableLocation(); 7702 WeakTrackingVH SunkAddrVH = SunkAddrs[Location]; 7703 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; 7704 if (SunkAddr) { 7705 // Point dbg.value at locally computed address, which should give the best 7706 // opportunity to be accurately lowered. This update may change the type of 7707 // pointer being referred to; however this makes no difference to debugging 7708 // information, and we can't generate bitcasts that may affect codegen. 7709 DVI.setOperand(0, MetadataAsValue::get(DVI.getContext(), 7710 ValueAsMetadata::get(SunkAddr))); 7711 return true; 7712 } 7713 return false; 7714 } 7715 7716 // A llvm.dbg.value may be using a value before its definition, due to 7717 // optimizations in this pass and others. Scan for such dbg.values, and rescue 7718 // them by moving the dbg.value to immediately after the value definition. 7719 // FIXME: Ideally this should never be necessary, and this has the potential 7720 // to re-order dbg.value intrinsics. 7721 bool CodeGenPrepare::placeDbgValues(Function &F) { 7722 bool MadeChange = false; 7723 DominatorTree DT(F); 7724 7725 for (BasicBlock &BB : F) { 7726 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { 7727 Instruction *Insn = &*BI++; 7728 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); 7729 if (!DVI) 7730 continue; 7731 7732 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); 7733 7734 if (!VI || VI->isTerminator()) 7735 continue; 7736 7737 // If VI is a phi in a block with an EHPad terminator, we can't insert 7738 // after it. 7739 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) 7740 continue; 7741 7742 // If the defining instruction dominates the dbg.value, we do not need 7743 // to move the dbg.value. 7744 if (DT.dominates(VI, DVI)) 7745 continue; 7746 7747 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n" 7748 << *DVI << ' ' << *VI); 7749 DVI->removeFromParent(); 7750 if (isa<PHINode>(VI)) 7751 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); 7752 else 7753 DVI->insertAfter(VI); 7754 MadeChange = true; 7755 ++NumDbgValueMoved; 7756 } 7757 } 7758 return MadeChange; 7759 } 7760 7761 /// Scale down both weights to fit into uint32_t. 7762 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { 7763 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; 7764 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1; 7765 NewTrue = NewTrue / Scale; 7766 NewFalse = NewFalse / Scale; 7767 } 7768 7769 /// Some targets prefer to split a conditional branch like: 7770 /// \code 7771 /// %0 = icmp ne i32 %a, 0 7772 /// %1 = icmp ne i32 %b, 0 7773 /// %or.cond = or i1 %0, %1 7774 /// br i1 %or.cond, label %TrueBB, label %FalseBB 7775 /// \endcode 7776 /// into multiple branch instructions like: 7777 /// \code 7778 /// bb1: 7779 /// %0 = icmp ne i32 %a, 0 7780 /// br i1 %0, label %TrueBB, label %bb2 7781 /// bb2: 7782 /// %1 = icmp ne i32 %b, 0 7783 /// br i1 %1, label %TrueBB, label %FalseBB 7784 /// \endcode 7785 /// This usually allows instruction selection to do even further optimizations 7786 /// and combine the compare with the branch instruction. Currently this is 7787 /// applied for targets which have "cheap" jump instructions. 7788 /// 7789 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. 7790 /// 7791 bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) { 7792 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive()) 7793 return false; 7794 7795 bool MadeChange = false; 7796 for (auto &BB : F) { 7797 // Does this BB end with the following? 7798 // %cond1 = icmp|fcmp|binary instruction ... 7799 // %cond2 = icmp|fcmp|binary instruction ... 7800 // %cond.or = or|and i1 %cond1, cond2 7801 // br i1 %cond.or label %dest1, label %dest2" 7802 BinaryOperator *LogicOp; 7803 BasicBlock *TBB, *FBB; 7804 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) 7805 continue; 7806 7807 auto *Br1 = cast<BranchInst>(BB.getTerminator()); 7808 if (Br1->getMetadata(LLVMContext::MD_unpredictable)) 7809 continue; 7810 7811 // The merging of mostly empty BB can cause a degenerate branch. 7812 if (TBB == FBB) 7813 continue; 7814 7815 unsigned Opc; 7816 Value *Cond1, *Cond2; 7817 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), 7818 m_OneUse(m_Value(Cond2))))) 7819 Opc = Instruction::And; 7820 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), 7821 m_OneUse(m_Value(Cond2))))) 7822 Opc = Instruction::Or; 7823 else 7824 continue; 7825 7826 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || 7827 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) 7828 continue; 7829 7830 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); 7831 7832 // Create a new BB. 7833 auto *TmpBB = 7834 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", 7835 BB.getParent(), BB.getNextNode()); 7836 7837 // Update original basic block by using the first condition directly by the 7838 // branch instruction and removing the no longer needed and/or instruction. 7839 Br1->setCondition(Cond1); 7840 LogicOp->eraseFromParent(); 7841 7842 // Depending on the condition we have to either replace the true or the 7843 // false successor of the original branch instruction. 7844 if (Opc == Instruction::And) 7845 Br1->setSuccessor(0, TmpBB); 7846 else 7847 Br1->setSuccessor(1, TmpBB); 7848 7849 // Fill in the new basic block. 7850 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); 7851 if (auto *I = dyn_cast<Instruction>(Cond2)) { 7852 I->removeFromParent(); 7853 I->insertBefore(Br2); 7854 } 7855 7856 // Update PHI nodes in both successors. The original BB needs to be 7857 // replaced in one successor's PHI nodes, because the branch comes now from 7858 // the newly generated BB (NewBB). In the other successor we need to add one 7859 // incoming edge to the PHI nodes, because both branch instructions target 7860 // now the same successor. Depending on the original branch condition 7861 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that 7862 // we perform the correct update for the PHI nodes. 7863 // This doesn't change the successor order of the just created branch 7864 // instruction (or any other instruction). 7865 if (Opc == Instruction::Or) 7866 std::swap(TBB, FBB); 7867 7868 // Replace the old BB with the new BB. 7869 TBB->replacePhiUsesWith(&BB, TmpBB); 7870 7871 // Add another incoming edge form the new BB. 7872 for (PHINode &PN : FBB->phis()) { 7873 auto *Val = PN.getIncomingValueForBlock(&BB); 7874 PN.addIncoming(Val, TmpBB); 7875 } 7876 7877 // Update the branch weights (from SelectionDAGBuilder:: 7878 // FindMergedConditions). 7879 if (Opc == Instruction::Or) { 7880 // Codegen X | Y as: 7881 // BB1: 7882 // jmp_if_X TBB 7883 // jmp TmpBB 7884 // TmpBB: 7885 // jmp_if_Y TBB 7886 // jmp FBB 7887 // 7888 7889 // We have flexibility in setting Prob for BB1 and Prob for NewBB. 7890 // The requirement is that 7891 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 7892 // = TrueProb for original BB. 7893 // Assuming the original weights are A and B, one choice is to set BB1's 7894 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice 7895 // assumes that 7896 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 7897 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 7898 // TmpBB, but the math is more complicated. 7899 uint64_t TrueWeight, FalseWeight; 7900 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { 7901 uint64_t NewTrueWeight = TrueWeight; 7902 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; 7903 scaleWeights(NewTrueWeight, NewFalseWeight); 7904 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) 7905 .createBranchWeights(TrueWeight, FalseWeight)); 7906 7907 NewTrueWeight = TrueWeight; 7908 NewFalseWeight = 2 * FalseWeight; 7909 scaleWeights(NewTrueWeight, NewFalseWeight); 7910 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) 7911 .createBranchWeights(TrueWeight, FalseWeight)); 7912 } 7913 } else { 7914 // Codegen X & Y as: 7915 // BB1: 7916 // jmp_if_X TmpBB 7917 // jmp FBB 7918 // TmpBB: 7919 // jmp_if_Y TBB 7920 // jmp FBB 7921 // 7922 // This requires creation of TmpBB after CurBB. 7923 7924 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 7925 // The requirement is that 7926 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 7927 // = FalseProb for original BB. 7928 // Assuming the original weights are A and B, one choice is to set BB1's 7929 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice 7930 // assumes that 7931 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. 7932 uint64_t TrueWeight, FalseWeight; 7933 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { 7934 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; 7935 uint64_t NewFalseWeight = FalseWeight; 7936 scaleWeights(NewTrueWeight, NewFalseWeight); 7937 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) 7938 .createBranchWeights(TrueWeight, FalseWeight)); 7939 7940 NewTrueWeight = 2 * TrueWeight; 7941 NewFalseWeight = FalseWeight; 7942 scaleWeights(NewTrueWeight, NewFalseWeight); 7943 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) 7944 .createBranchWeights(TrueWeight, FalseWeight)); 7945 } 7946 } 7947 7948 ModifiedDT = true; 7949 MadeChange = true; 7950 7951 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); 7952 TmpBB->dump()); 7953 } 7954 return MadeChange; 7955 } 7956