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