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