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