1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/BlockFrequencyInfo.h"
25 #include "llvm/Analysis/BranchProbabilityInfo.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/InstructionSimplify.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/ProfileSummaryInfo.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/ISDOpcodes.h"
36 #include "llvm/CodeGen/MachineValueType.h"
37 #include "llvm/CodeGen/SelectionDAGNodes.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetPassConfig.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/CodeGen/ValueTypes.h"
42 #include "llvm/IR/Argument.h"
43 #include "llvm/IR/Attributes.h"
44 #include "llvm/IR/BasicBlock.h"
45 #include "llvm/IR/CallSite.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DerivedTypes.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/GlobalVariable.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/InlineAsm.h"
57 #include "llvm/IR/InstrTypes.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/MDBuilder.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/Operator.h"
66 #include "llvm/IR/PatternMatch.h"
67 #include "llvm/IR/Statepoint.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #include "llvm/IR/ValueMap.h"
74 #include "llvm/Pass.h"
75 #include "llvm/Support/BlockFrequency.h"
76 #include "llvm/Support/BranchProbability.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Target/TargetMachine.h"
85 #include "llvm/Target/TargetOptions.h"
86 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
87 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
88 #include "llvm/Transforms/Utils/Local.h"
89 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
100 using namespace llvm::PatternMatch;
102 #define DEBUG_TYPE "codegenprepare"
104 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
105 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
106 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
107 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
109 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
111 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
112 "computations were sunk");
113 STATISTIC(NumMemoryInstsPhiCreated,
114 "Number of phis created when address "
115 "computations were sunk to memory instructions");
116 STATISTIC(NumMemoryInstsSelectCreated,
117 "Number of select created when address "
118 "computations were sunk to memory instructions");
119 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
120 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
121 STATISTIC(NumAndsAdded,
122 "Number of and mask instructions added to form ext loads");
123 STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
124 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
125 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
126 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
127 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
129 static cl::opt<bool> DisableBranchOpts(
130 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
131 cl::desc("Disable branch optimizations in CodeGenPrepare"));
134 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
135 cl::desc("Disable GC optimizations in CodeGenPrepare"));
137 static cl::opt<bool> DisableSelectToBranch(
138 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
139 cl::desc("Disable select to branch conversion."));
141 static cl::opt<bool> AddrSinkUsingGEPs(
142 "addr-sink-using-gep", cl::Hidden, cl::init(true),
143 cl::desc("Address sinking in CGP using GEPs."));
145 static cl::opt<bool> EnableAndCmpSinking(
146 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
147 cl::desc("Enable sinkinig and/cmp into branches."));
149 static cl::opt<bool> DisableStoreExtract(
150 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
151 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
153 static cl::opt<bool> StressStoreExtract(
154 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
155 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
157 static cl::opt<bool> DisableExtLdPromotion(
158 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
159 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
162 static cl::opt<bool> StressExtLdPromotion(
163 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
165 "optimization in CodeGenPrepare"));
167 static cl::opt<bool> DisablePreheaderProtect(
168 "disable-preheader-prot", cl::Hidden, cl::init(false),
169 cl::desc("Disable protection against removing loop preheaders"));
171 static cl::opt<bool> ProfileGuidedSectionPrefix(
172 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
173 cl::desc("Use profile info to add section prefix for hot/cold functions"));
175 static cl::opt<unsigned> FreqRatioToSkipMerge(
176 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
177 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
178 "(frequency of destination block) is greater than this ratio"));
180 static cl::opt<bool> ForceSplitStore(
181 "force-split-store", cl::Hidden, cl::init(false),
182 cl::desc("Force store splitting no matter what the target query says."));
185 EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
186 cl::desc("Enable merging of redundant sexts when one is dominating"
187 " the other."), cl::init(true));
189 static cl::opt<bool> DisableComplexAddrModes(
190 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
191 cl::desc("Disables combining addressing modes with different parts "
192 "in optimizeMemoryInst."));
195 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
196 cl::desc("Allow creation of Phis in Address sinking."));
199 AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(false),
200 cl::desc("Allow creation of selects in Address sinking."));
202 static cl::opt<bool> AddrSinkCombineBaseReg(
203 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
204 cl::desc("Allow combining of BaseReg field in Address sinking."));
206 static cl::opt<bool> AddrSinkCombineBaseGV(
207 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
208 cl::desc("Allow combining of BaseGV field in Address sinking."));
210 static cl::opt<bool> AddrSinkCombineBaseOffs(
211 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
212 cl::desc("Allow combining of BaseOffs field in Address sinking."));
214 static cl::opt<bool> AddrSinkCombineScaledReg(
215 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
216 cl::desc("Allow combining of ScaledReg field in Address sinking."));
220 using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
221 using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
222 using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
223 using SExts = SmallVector<Instruction *, 16>;
224 using ValueToSExts = DenseMap<Value *, SExts>;
226 class TypePromotionTransaction;
228 class CodeGenPrepare : public FunctionPass {
229 const TargetMachine *TM = nullptr;
230 const TargetSubtargetInfo *SubtargetInfo;
231 const TargetLowering *TLI = nullptr;
232 const TargetRegisterInfo *TRI;
233 const TargetTransformInfo *TTI = nullptr;
234 const TargetLibraryInfo *TLInfo;
236 std::unique_ptr<BlockFrequencyInfo> BFI;
237 std::unique_ptr<BranchProbabilityInfo> BPI;
239 /// As we scan instructions optimizing them, this is the next instruction
240 /// to optimize. Transforms that can invalidate this should update it.
241 BasicBlock::iterator CurInstIterator;
243 /// Keeps track of non-local addresses that have been sunk into a block.
244 /// This allows us to avoid inserting duplicate code for blocks with
245 /// multiple load/stores of the same address. The usage of WeakTrackingVH
246 /// enables SunkAddrs to be treated as a cache whose entries can be
247 /// invalidated if a sunken address computation has been erased.
248 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
250 /// Keeps track of all instructions inserted for the current function.
251 SetOfInstrs InsertedInsts;
253 /// Keeps track of the type of the related instruction before their
254 /// promotion for the current function.
255 InstrToOrigTy PromotedInsts;
257 /// Keep track of instructions removed during promotion.
258 SetOfInstrs RemovedInsts;
260 /// Keep track of sext chains based on their initial value.
261 DenseMap<Value *, Instruction *> SeenChainsForSExt;
263 /// Keep track of SExt promoted.
264 ValueToSExts ValToSExtendedUses;
266 /// True if CFG is modified in any way.
269 /// True if optimizing for size.
272 /// DataLayout for the Function being processed.
273 const DataLayout *DL = nullptr;
276 static char ID; // Pass identification, replacement for typeid
278 CodeGenPrepare() : FunctionPass(ID) {
279 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
282 bool runOnFunction(Function &F) override;
284 StringRef getPassName() const override { return "CodeGen Prepare"; }
286 void getAnalysisUsage(AnalysisUsage &AU) const override {
287 // FIXME: When we can selectively preserve passes, preserve the domtree.
288 AU.addRequired<ProfileSummaryInfoWrapperPass>();
289 AU.addRequired<TargetLibraryInfoWrapperPass>();
290 AU.addRequired<TargetTransformInfoWrapperPass>();
291 AU.addRequired<LoopInfoWrapperPass>();
295 bool eliminateFallThrough(Function &F);
296 bool eliminateMostlyEmptyBlocks(Function &F);
297 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
298 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
299 void eliminateMostlyEmptyBlock(BasicBlock *BB);
300 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
302 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
303 bool optimizeInst(Instruction *I, bool &ModifiedDT);
304 bool optimizeMemoryInst(Instruction *I, Value *Addr,
305 Type *AccessTy, unsigned AS);
306 bool optimizeInlineAsmInst(CallInst *CS);
307 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
308 bool optimizeExt(Instruction *&I);
309 bool optimizeExtUses(Instruction *I);
310 bool optimizeLoadExt(LoadInst *I);
311 bool optimizeSelectInst(SelectInst *SI);
312 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
313 bool optimizeSwitchInst(SwitchInst *CI);
314 bool optimizeExtractElementInst(Instruction *Inst);
315 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
316 bool placeDbgValues(Function &F);
317 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
318 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
319 bool tryToPromoteExts(TypePromotionTransaction &TPT,
320 const SmallVectorImpl<Instruction *> &Exts,
321 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
322 unsigned CreatedInstsCost = 0);
323 bool mergeSExts(Function &F);
324 bool performAddressTypePromotion(
326 bool AllowPromotionWithoutCommonHeader,
327 bool HasPromoted, TypePromotionTransaction &TPT,
328 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
329 bool splitBranchCondition(Function &F);
330 bool simplifyOffsetableRelocate(Instruction &I);
333 } // end anonymous namespace
335 char CodeGenPrepare::ID = 0;
337 INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
338 "Optimize for code generation", false, false)
339 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
340 INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
341 "Optimize for code generation", false, false)
343 FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
345 bool CodeGenPrepare::runOnFunction(Function &F) {
349 DL = &F.getParent()->getDataLayout();
351 bool EverMadeChange = false;
352 // Clear per function information.
353 InsertedInsts.clear();
354 PromotedInsts.clear();
357 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
358 TM = &TPC->getTM<TargetMachine>();
359 SubtargetInfo = TM->getSubtargetImpl(F);
360 TLI = SubtargetInfo->getTargetLowering();
361 TRI = SubtargetInfo->getRegisterInfo();
363 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
364 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
365 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
366 BPI.reset(new BranchProbabilityInfo(F, *LI));
367 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
368 OptSize = F.optForSize();
370 ProfileSummaryInfo *PSI =
371 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
372 if (ProfileGuidedSectionPrefix) {
373 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
374 F.setSectionPrefix(".hot");
375 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
376 F.setSectionPrefix(".unlikely");
379 /// This optimization identifies DIV instructions that can be
380 /// profitably bypassed and carried out with a shorter, faster divide.
381 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
382 TLI->isSlowDivBypassed()) {
383 const DenseMap<unsigned int, unsigned int> &BypassWidths =
384 TLI->getBypassSlowDivWidths();
385 BasicBlock* BB = &*F.begin();
386 while (BB != nullptr) {
387 // bypassSlowDivision may create new BBs, but we don't want to reapply the
388 // optimization to those blocks.
389 BasicBlock* Next = BB->getNextNode();
390 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
395 // Eliminate blocks that contain only PHI nodes and an
396 // unconditional branch.
397 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
399 // llvm.dbg.value is far away from the value then iSel may not be able
400 // handle it properly. iSel will drop llvm.dbg.value if it can not
401 // find a node corresponding to the value.
402 EverMadeChange |= placeDbgValues(F);
404 if (!DisableBranchOpts)
405 EverMadeChange |= splitBranchCondition(F);
407 // Split some critical edges where one of the sources is an indirect branch,
408 // to help generate sane code for PHIs involving such edges.
409 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
411 bool MadeChange = true;
414 SeenChainsForSExt.clear();
415 ValToSExtendedUses.clear();
416 RemovedInsts.clear();
417 for (Function::iterator I = F.begin(); I != F.end(); ) {
418 BasicBlock *BB = &*I++;
419 bool ModifiedDTOnIteration = false;
420 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
422 // Restart BB iteration if the dominator tree of the Function was changed
423 if (ModifiedDTOnIteration)
426 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
427 MadeChange |= mergeSExts(F);
429 // Really free removed instructions during promotion.
430 for (Instruction *I : RemovedInsts)
433 EverMadeChange |= MadeChange;
438 if (!DisableBranchOpts) {
440 SmallPtrSet<BasicBlock*, 8> WorkList;
441 for (BasicBlock &BB : F) {
442 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
443 MadeChange |= ConstantFoldTerminator(&BB, true);
444 if (!MadeChange) continue;
446 for (SmallVectorImpl<BasicBlock*>::iterator
447 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
448 if (pred_begin(*II) == pred_end(*II))
449 WorkList.insert(*II);
452 // Delete the dead blocks and any of their dead successors.
453 MadeChange |= !WorkList.empty();
454 while (!WorkList.empty()) {
455 BasicBlock *BB = *WorkList.begin();
457 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
461 for (SmallVectorImpl<BasicBlock*>::iterator
462 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
463 if (pred_begin(*II) == pred_end(*II))
464 WorkList.insert(*II);
467 // Merge pairs of basic blocks with unconditional branches, connected by
469 if (EverMadeChange || MadeChange)
470 MadeChange |= eliminateFallThrough(F);
472 EverMadeChange |= MadeChange;
475 if (!DisableGCOpts) {
476 SmallVector<Instruction *, 2> Statepoints;
477 for (BasicBlock &BB : F)
478 for (Instruction &I : BB)
480 Statepoints.push_back(&I);
481 for (auto &I : Statepoints)
482 EverMadeChange |= simplifyOffsetableRelocate(*I);
485 return EverMadeChange;
488 /// Merge basic blocks which are connected by a single edge, where one of the
489 /// basic blocks has a single successor pointing to the other basic block,
490 /// which has a single predecessor.
491 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
492 bool Changed = false;
493 // Scan all of the blocks in the function, except for the entry block.
494 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
495 BasicBlock *BB = &*I++;
496 // If the destination block has a single pred, then this is a trivial
497 // edge, just collapse it.
498 BasicBlock *SinglePred = BB->getSinglePredecessor();
500 // Don't merge if BB's address is taken.
501 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
503 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
504 if (Term && !Term->isConditional()) {
506 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
507 // Remember if SinglePred was the entry block of the function.
508 // If so, we will need to move BB back to the entry position.
509 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
510 MergeBasicBlockIntoOnlyPred(BB, nullptr);
512 if (isEntry && BB != &BB->getParent()->getEntryBlock())
513 BB->moveBefore(&BB->getParent()->getEntryBlock());
515 // We have erased a block. Update the iterator.
516 I = BB->getIterator();
522 /// Find a destination block from BB if BB is mergeable empty block.
523 BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
524 // If this block doesn't end with an uncond branch, ignore it.
525 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
526 if (!BI || !BI->isUnconditional())
529 // If the instruction before the branch (skipping debug info) isn't a phi
530 // node, then other stuff is happening here.
531 BasicBlock::iterator BBI = BI->getIterator();
532 if (BBI != BB->begin()) {
534 while (isa<DbgInfoIntrinsic>(BBI)) {
535 if (BBI == BB->begin())
539 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
543 // Do not break infinite loops.
544 BasicBlock *DestBB = BI->getSuccessor(0);
548 if (!canMergeBlocks(BB, DestBB))
554 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
555 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
556 /// edges in ways that are non-optimal for isel. Start by eliminating these
557 /// blocks so we can split them the way we want them.
558 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
559 SmallPtrSet<BasicBlock *, 16> Preheaders;
560 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
561 while (!LoopList.empty()) {
562 Loop *L = LoopList.pop_back_val();
563 LoopList.insert(LoopList.end(), L->begin(), L->end());
564 if (BasicBlock *Preheader = L->getLoopPreheader())
565 Preheaders.insert(Preheader);
568 bool MadeChange = false;
569 // Note that this intentionally skips the entry block.
570 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
571 BasicBlock *BB = &*I++;
572 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
574 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
577 eliminateMostlyEmptyBlock(BB);
583 bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
586 // Do not delete loop preheaders if doing so would create a critical edge.
587 // Loop preheaders can be good locations to spill registers. If the
588 // preheader is deleted and we create a critical edge, registers may be
589 // spilled in the loop body instead.
590 if (!DisablePreheaderProtect && isPreheader &&
591 !(BB->getSinglePredecessor() &&
592 BB->getSinglePredecessor()->getSingleSuccessor()))
595 // Try to skip merging if the unique predecessor of BB is terminated by a
596 // switch or indirect branch instruction, and BB is used as an incoming block
597 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
598 // add COPY instructions in the predecessor of BB instead of BB (if it is not
599 // merged). Note that the critical edge created by merging such blocks wont be
600 // split in MachineSink because the jump table is not analyzable. By keeping
601 // such empty block (BB), ISel will place COPY instructions in BB, not in the
602 // predecessor of BB.
603 BasicBlock *Pred = BB->getUniquePredecessor();
605 !(isa<SwitchInst>(Pred->getTerminator()) ||
606 isa<IndirectBrInst>(Pred->getTerminator())))
609 if (BB->getTerminator() != BB->getFirstNonPHI())
612 // We use a simple cost heuristic which determine skipping merging is
613 // profitable if the cost of skipping merging is less than the cost of
614 // merging : Cost(skipping merging) < Cost(merging BB), where the
615 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
616 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
617 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
618 // Freq(Pred) / Freq(BB) > 2.
619 // Note that if there are multiple empty blocks sharing the same incoming
620 // value for the PHIs in the DestBB, we consider them together. In such
621 // case, Cost(merging BB) will be the sum of their frequencies.
623 if (!isa<PHINode>(DestBB->begin()))
626 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
628 // Find all other incoming blocks from which incoming values of all PHIs in
629 // DestBB are the same as the ones from BB.
630 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
632 BasicBlock *DestBBPred = *PI;
633 if (DestBBPred == BB)
636 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
637 return DestPN.getIncomingValueForBlock(BB) ==
638 DestPN.getIncomingValueForBlock(DestBBPred);
640 SameIncomingValueBBs.insert(DestBBPred);
643 // See if all BB's incoming values are same as the value from Pred. In this
644 // case, no reason to skip merging because COPYs are expected to be place in
646 if (SameIncomingValueBBs.count(Pred))
649 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
650 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
652 for (auto SameValueBB : SameIncomingValueBBs)
653 if (SameValueBB->getUniquePredecessor() == Pred &&
654 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
655 BBFreq += BFI->getBlockFreq(SameValueBB);
657 return PredFreq.getFrequency() <=
658 BBFreq.getFrequency() * FreqRatioToSkipMerge;
661 /// Return true if we can merge BB into DestBB if there is a single
662 /// unconditional branch between them, and BB contains no other non-phi
664 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
665 const BasicBlock *DestBB) const {
666 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
667 // the successor. If there are more complex condition (e.g. preheaders),
668 // don't mess around with them.
669 for (const PHINode &PN : BB->phis()) {
670 for (const User *U : PN.users()) {
671 const Instruction *UI = cast<Instruction>(U);
672 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
674 // If User is inside DestBB block and it is a PHINode then check
675 // incoming value. If incoming value is not from BB then this is
676 // a complex condition (e.g. preheaders) we want to avoid here.
677 if (UI->getParent() == DestBB) {
678 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
679 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
680 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
681 if (Insn && Insn->getParent() == BB &&
682 Insn->getParent() != UPN->getIncomingBlock(I))
689 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
690 // and DestBB may have conflicting incoming values for the block. If so, we
691 // can't merge the block.
692 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
693 if (!DestBBPN) return true; // no conflict.
695 // Collect the preds of BB.
696 SmallPtrSet<const BasicBlock*, 16> BBPreds;
697 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
698 // It is faster to get preds from a PHI than with pred_iterator.
699 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
700 BBPreds.insert(BBPN->getIncomingBlock(i));
702 BBPreds.insert(pred_begin(BB), pred_end(BB));
705 // Walk the preds of DestBB.
706 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
707 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
708 if (BBPreds.count(Pred)) { // Common predecessor?
709 for (const PHINode &PN : DestBB->phis()) {
710 const Value *V1 = PN.getIncomingValueForBlock(Pred);
711 const Value *V2 = PN.getIncomingValueForBlock(BB);
713 // If V2 is a phi node in BB, look up what the mapped value will be.
714 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
715 if (V2PN->getParent() == BB)
716 V2 = V2PN->getIncomingValueForBlock(Pred);
718 // If there is a conflict, bail out.
719 if (V1 != V2) return false;
727 /// Eliminate a basic block that has only phi's and an unconditional branch in
729 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
730 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
731 BasicBlock *DestBB = BI->getSuccessor(0);
733 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
735 // If the destination block has a single pred, then this is a trivial edge,
737 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
738 if (SinglePred != DestBB) {
739 // Remember if SinglePred was the entry block of the function. If so, we
740 // will need to move BB back to the entry position.
741 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
742 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
744 if (isEntry && BB != &BB->getParent()->getEntryBlock())
745 BB->moveBefore(&BB->getParent()->getEntryBlock());
747 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
752 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
753 // to handle the new incoming edges it is about to have.
754 for (PHINode &PN : DestBB->phis()) {
755 // Remove the incoming value for BB, and remember it.
756 Value *InVal = PN.removeIncomingValue(BB, false);
758 // Two options: either the InVal is a phi node defined in BB or it is some
759 // value that dominates BB.
760 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
761 if (InValPhi && InValPhi->getParent() == BB) {
762 // Add all of the input values of the input PHI as inputs of this phi.
763 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
764 PN.addIncoming(InValPhi->getIncomingValue(i),
765 InValPhi->getIncomingBlock(i));
767 // Otherwise, add one instance of the dominating value for each edge that
768 // we will be adding.
769 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
770 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
771 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
773 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
774 PN.addIncoming(InVal, *PI);
779 // The PHIs are now updated, change everything that refers to BB to use
780 // DestBB and remove BB.
781 BB->replaceAllUsesWith(DestBB);
782 BB->eraseFromParent();
785 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
788 // Computes a map of base pointer relocation instructions to corresponding
789 // derived pointer relocation instructions given a vector of all relocate calls
790 static void computeBaseDerivedRelocateMap(
791 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
792 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
794 // Collect information in two maps: one primarily for locating the base object
795 // while filling the second map; the second map is the final structure holding
796 // a mapping between Base and corresponding Derived relocate calls
797 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
798 for (auto *ThisRelocate : AllRelocateCalls) {
799 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
800 ThisRelocate->getDerivedPtrIndex());
801 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
803 for (auto &Item : RelocateIdxMap) {
804 std::pair<unsigned, unsigned> Key = Item.first;
805 if (Key.first == Key.second)
806 // Base relocation: nothing to insert
809 GCRelocateInst *I = Item.second;
810 auto BaseKey = std::make_pair(Key.first, Key.first);
812 // We're iterating over RelocateIdxMap so we cannot modify it.
813 auto MaybeBase = RelocateIdxMap.find(BaseKey);
814 if (MaybeBase == RelocateIdxMap.end())
815 // TODO: We might want to insert a new base object relocate and gep off
816 // that, if there are enough derived object relocates.
819 RelocateInstMap[MaybeBase->second].push_back(I);
823 // Accepts a GEP and extracts the operands into a vector provided they're all
824 // small integer constants
825 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
826 SmallVectorImpl<Value *> &OffsetV) {
827 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
828 // Only accept small constant integer operands
829 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
830 if (!Op || Op->getZExtValue() > 20)
834 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
835 OffsetV.push_back(GEP->getOperand(i));
839 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
840 // replace, computes a replacement, and affects it.
842 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
843 const SmallVectorImpl<GCRelocateInst *> &Targets) {
844 bool MadeChange = false;
845 // We must ensure the relocation of derived pointer is defined after
846 // relocation of base pointer. If we find a relocation corresponding to base
847 // defined earlier than relocation of base then we move relocation of base
848 // right before found relocation. We consider only relocation in the same
849 // basic block as relocation of base. Relocations from other basic block will
850 // be skipped by optimization and we do not care about them.
851 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
852 &*R != RelocatedBase; ++R)
853 if (auto RI = dyn_cast<GCRelocateInst>(R))
854 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
855 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
856 RelocatedBase->moveBefore(RI);
860 for (GCRelocateInst *ToReplace : Targets) {
861 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
862 "Not relocating a derived object of the original base object");
863 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
864 // A duplicate relocate call. TODO: coalesce duplicates.
868 if (RelocatedBase->getParent() != ToReplace->getParent()) {
869 // Base and derived relocates are in different basic blocks.
870 // In this case transform is only valid when base dominates derived
871 // relocate. However it would be too expensive to check dominance
872 // for each such relocate, so we skip the whole transformation.
876 Value *Base = ToReplace->getBasePtr();
877 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
878 if (!Derived || Derived->getPointerOperand() != Base)
881 SmallVector<Value *, 2> OffsetV;
882 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
885 // Create a Builder and replace the target callsite with a gep
886 assert(RelocatedBase->getNextNode() &&
887 "Should always have one since it's not a terminator");
889 // Insert after RelocatedBase
890 IRBuilder<> Builder(RelocatedBase->getNextNode());
891 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
893 // If gc_relocate does not match the actual type, cast it to the right type.
894 // In theory, there must be a bitcast after gc_relocate if the type does not
895 // match, and we should reuse it to get the derived pointer. But it could be
899 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
904 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
908 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
909 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
911 // In this case, we can not find the bitcast any more. So we insert a new bitcast
912 // no matter there is already one or not. In this way, we can handle all cases, and
913 // the extra bitcast should be optimized away in later passes.
914 Value *ActualRelocatedBase = RelocatedBase;
915 if (RelocatedBase->getType() != Base->getType()) {
916 ActualRelocatedBase =
917 Builder.CreateBitCast(RelocatedBase, Base->getType());
919 Value *Replacement = Builder.CreateGEP(
920 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
921 Replacement->takeName(ToReplace);
922 // If the newly generated derived pointer's type does not match the original derived
923 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
924 Value *ActualReplacement = Replacement;
925 if (Replacement->getType() != ToReplace->getType()) {
927 Builder.CreateBitCast(Replacement, ToReplace->getType());
929 ToReplace->replaceAllUsesWith(ActualReplacement);
930 ToReplace->eraseFromParent();
940 // %ptr = gep %base + 15
941 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
942 // %base' = relocate(%tok, i32 4, i32 4)
943 // %ptr' = relocate(%tok, i32 4, i32 5)
949 // %ptr = gep %base + 15
950 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
951 // %base' = gc.relocate(%tok, i32 4, i32 4)
952 // %ptr' = gep %base' + 15
954 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
955 bool MadeChange = false;
956 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
958 for (auto *U : I.users())
959 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
960 // Collect all the relocate calls associated with a statepoint
961 AllRelocateCalls.push_back(Relocate);
963 // We need atleast one base pointer relocation + one derived pointer
964 // relocation to mangle
965 if (AllRelocateCalls.size() < 2)
968 // RelocateInstMap is a mapping from the base relocate instruction to the
969 // corresponding derived relocate instructions
970 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
971 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
972 if (RelocateInstMap.empty())
975 for (auto &Item : RelocateInstMap)
976 // Item.first is the RelocatedBase to offset against
977 // Item.second is the vector of Targets to replace
978 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
982 /// SinkCast - Sink the specified cast instruction into its user blocks
983 static bool SinkCast(CastInst *CI) {
984 BasicBlock *DefBB = CI->getParent();
986 /// InsertedCasts - Only insert a cast in each block once.
987 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
989 bool MadeChange = false;
990 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
992 Use &TheUse = UI.getUse();
993 Instruction *User = cast<Instruction>(*UI);
995 // Figure out which BB this cast is used in. For PHI's this is the
996 // appropriate predecessor block.
997 BasicBlock *UserBB = User->getParent();
998 if (PHINode *PN = dyn_cast<PHINode>(User)) {
999 UserBB = PN->getIncomingBlock(TheUse);
1002 // Preincrement use iterator so we don't invalidate it.
1005 // The first insertion point of a block containing an EH pad is after the
1006 // pad. If the pad is the user, we cannot sink the cast past the pad.
1007 if (User->isEHPad())
1010 // If the block selected to receive the cast is an EH pad that does not
1011 // allow non-PHI instructions before the terminator, we can't sink the
1013 if (UserBB->getTerminator()->isEHPad())
1016 // If this user is in the same block as the cast, don't change the cast.
1017 if (UserBB == DefBB) continue;
1019 // If we have already inserted a cast into this block, use it.
1020 CastInst *&InsertedCast = InsertedCasts[UserBB];
1022 if (!InsertedCast) {
1023 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1024 assert(InsertPt != UserBB->end());
1025 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1026 CI->getType(), "", &*InsertPt);
1029 // Replace a use of the cast with a use of the new cast.
1030 TheUse = InsertedCast;
1035 // If we removed all uses, nuke the cast.
1036 if (CI->use_empty()) {
1037 salvageDebugInfo(*CI);
1038 CI->eraseFromParent();
1045 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1046 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1047 /// reduce the number of virtual registers that must be created and coalesced.
1049 /// Return true if any changes are made.
1050 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1051 const DataLayout &DL) {
1052 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1053 // than sinking only nop casts, but is helpful on some platforms.
1054 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1055 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1056 ASC->getDestAddressSpace()))
1060 // If this is a noop copy,
1061 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1062 EVT DstVT = TLI.getValueType(DL, CI->getType());
1064 // This is an fp<->int conversion?
1065 if (SrcVT.isInteger() != DstVT.isInteger())
1068 // If this is an extension, it will be a zero or sign extension, which
1070 if (SrcVT.bitsLT(DstVT)) return false;
1072 // If these values will be promoted, find out what they will be promoted
1073 // to. This helps us consider truncates on PPC as noop copies when they
1075 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1076 TargetLowering::TypePromoteInteger)
1077 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1078 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1079 TargetLowering::TypePromoteInteger)
1080 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1082 // If, after promotion, these are the same types, this is a noop copy.
1086 return SinkCast(CI);
1089 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1092 /// Return true if any changes were made.
1093 static bool CombineUAddWithOverflow(CmpInst *CI) {
1097 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1100 Type *Ty = AddI->getType();
1101 if (!isa<IntegerType>(Ty))
1104 // We don't want to move around uses of condition values this late, so we we
1105 // check if it is legal to create the call to the intrinsic in the basic
1106 // block containing the icmp:
1108 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1112 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1114 if (AddI->hasOneUse())
1115 assert(*AddI->user_begin() == CI && "expected!");
1118 Module *M = CI->getModule();
1119 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1121 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1123 auto *UAddWithOverflow =
1124 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1125 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1127 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1129 CI->replaceAllUsesWith(Overflow);
1130 AddI->replaceAllUsesWith(UAdd);
1131 CI->eraseFromParent();
1132 AddI->eraseFromParent();
1136 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1137 /// registers that must be created and coalesced. This is a clear win except on
1138 /// targets with multiple condition code registers (PowerPC), where it might
1139 /// lose; some adjustment may be wanted there.
1141 /// Return true if any changes are made.
1142 static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
1143 BasicBlock *DefBB = CI->getParent();
1145 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1146 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
1149 // Only insert a cmp in each block once.
1150 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1152 bool MadeChange = false;
1153 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1155 Use &TheUse = UI.getUse();
1156 Instruction *User = cast<Instruction>(*UI);
1158 // Preincrement use iterator so we don't invalidate it.
1161 // Don't bother for PHI nodes.
1162 if (isa<PHINode>(User))
1165 // Figure out which BB this cmp is used in.
1166 BasicBlock *UserBB = User->getParent();
1168 // If this user is in the same block as the cmp, don't change the cmp.
1169 if (UserBB == DefBB) continue;
1171 // If we have already inserted a cmp into this block, use it.
1172 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1175 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1176 assert(InsertPt != UserBB->end());
1178 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1179 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1180 // Propagate the debug info.
1181 InsertedCmp->setDebugLoc(CI->getDebugLoc());
1184 // Replace a use of the cmp with a use of the new cmp.
1185 TheUse = InsertedCmp;
1190 // If we removed all uses, nuke the cmp.
1191 if (CI->use_empty()) {
1192 CI->eraseFromParent();
1199 static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
1200 if (SinkCmpExpression(CI, TLI))
1203 if (CombineUAddWithOverflow(CI))
1209 /// Duplicate and sink the given 'and' instruction into user blocks where it is
1210 /// used in a compare to allow isel to generate better code for targets where
1211 /// this operation can be combined.
1213 /// Return true if any changes are made.
1214 static bool sinkAndCmp0Expression(Instruction *AndI,
1215 const TargetLowering &TLI,
1216 SetOfInstrs &InsertedInsts) {
1217 // Double-check that we're not trying to optimize an instruction that was
1218 // already optimized by some other part of this pass.
1219 assert(!InsertedInsts.count(AndI) &&
1220 "Attempting to optimize already optimized and instruction");
1221 (void) InsertedInsts;
1223 // Nothing to do for single use in same basic block.
1224 if (AndI->hasOneUse() &&
1225 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1228 // Try to avoid cases where sinking/duplicating is likely to increase register
1230 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1231 !isa<ConstantInt>(AndI->getOperand(1)) &&
1232 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1235 for (auto *U : AndI->users()) {
1236 Instruction *User = cast<Instruction>(U);
1238 // Only sink for and mask feeding icmp with 0.
1239 if (!isa<ICmpInst>(User))
1242 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1243 if (!CmpC || !CmpC->isZero())
1247 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1250 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1251 DEBUG(AndI->getParent()->dump());
1253 // Push the 'and' into the same block as the icmp 0. There should only be
1254 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1255 // others, so we don't need to keep track of which BBs we insert into.
1256 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1258 Use &TheUse = UI.getUse();
1259 Instruction *User = cast<Instruction>(*UI);
1261 // Preincrement use iterator so we don't invalidate it.
1264 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1266 // Keep the 'and' in the same place if the use is already in the same block.
1267 Instruction *InsertPt =
1268 User->getParent() == AndI->getParent() ? AndI : User;
1269 Instruction *InsertedAnd =
1270 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1271 AndI->getOperand(1), "", InsertPt);
1272 // Propagate the debug info.
1273 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1275 // Replace a use of the 'and' with a use of the new 'and'.
1276 TheUse = InsertedAnd;
1278 DEBUG(User->getParent()->dump());
1281 // We removed all uses, nuke the and.
1282 AndI->eraseFromParent();
1286 /// Check if the candidates could be combined with a shift instruction, which
1288 /// 1. Truncate instruction
1289 /// 2. And instruction and the imm is a mask of the low bits:
1290 /// imm & (imm+1) == 0
1291 static bool isExtractBitsCandidateUse(Instruction *User) {
1292 if (!isa<TruncInst>(User)) {
1293 if (User->getOpcode() != Instruction::And ||
1294 !isa<ConstantInt>(User->getOperand(1)))
1297 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1299 if ((Cimm & (Cimm + 1)).getBoolValue())
1305 /// Sink both shift and truncate instruction to the use of truncate's BB.
1307 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1308 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1309 const TargetLowering &TLI, const DataLayout &DL) {
1310 BasicBlock *UserBB = User->getParent();
1311 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1312 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1313 bool MadeChange = false;
1315 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1316 TruncE = TruncI->user_end();
1317 TruncUI != TruncE;) {
1319 Use &TruncTheUse = TruncUI.getUse();
1320 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1321 // Preincrement use iterator so we don't invalidate it.
1325 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1329 // If the use is actually a legal node, there will not be an
1330 // implicit truncate.
1331 // FIXME: always querying the result type is just an
1332 // approximation; some nodes' legality is determined by the
1333 // operand or other means. There's no good way to find out though.
1334 if (TLI.isOperationLegalOrCustom(
1335 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1338 // Don't bother for PHI nodes.
1339 if (isa<PHINode>(TruncUser))
1342 BasicBlock *TruncUserBB = TruncUser->getParent();
1344 if (UserBB == TruncUserBB)
1347 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1348 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1350 if (!InsertedShift && !InsertedTrunc) {
1351 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1352 assert(InsertPt != TruncUserBB->end());
1354 if (ShiftI->getOpcode() == Instruction::AShr)
1355 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1358 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1362 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1364 assert(TruncInsertPt != TruncUserBB->end());
1366 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1367 TruncI->getType(), "", &*TruncInsertPt);
1371 TruncTheUse = InsertedTrunc;
1377 /// Sink the shift *right* instruction into user blocks if the uses could
1378 /// potentially be combined with this shift instruction and generate BitExtract
1379 /// instruction. It will only be applied if the architecture supports BitExtract
1380 /// instruction. Here is an example:
1382 /// %x.extract.shift = lshr i64 %arg1, 32
1384 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1388 /// %x.extract.shift.1 = lshr i64 %arg1, 32
1389 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1391 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1393 /// Return true if any changes are made.
1394 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1395 const TargetLowering &TLI,
1396 const DataLayout &DL) {
1397 BasicBlock *DefBB = ShiftI->getParent();
1399 /// Only insert instructions in each block once.
1400 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1402 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1404 bool MadeChange = false;
1405 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1407 Use &TheUse = UI.getUse();
1408 Instruction *User = cast<Instruction>(*UI);
1409 // Preincrement use iterator so we don't invalidate it.
1412 // Don't bother for PHI nodes.
1413 if (isa<PHINode>(User))
1416 if (!isExtractBitsCandidateUse(User))
1419 BasicBlock *UserBB = User->getParent();
1421 if (UserBB == DefBB) {
1422 // If the shift and truncate instruction are in the same BB. The use of
1423 // the truncate(TruncUse) may still introduce another truncate if not
1424 // legal. In this case, we would like to sink both shift and truncate
1425 // instruction to the BB of TruncUse.
1428 // i64 shift.result = lshr i64 opnd, imm
1429 // trunc.result = trunc shift.result to i16
1432 // ----> We will have an implicit truncate here if the architecture does
1433 // not have i16 compare.
1434 // cmp i16 trunc.result, opnd2
1436 if (isa<TruncInst>(User) && shiftIsLegal
1437 // If the type of the truncate is legal, no trucate will be
1438 // introduced in other basic blocks.
1440 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1442 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1446 // If we have already inserted a shift into this block, use it.
1447 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1449 if (!InsertedShift) {
1450 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1451 assert(InsertPt != UserBB->end());
1453 if (ShiftI->getOpcode() == Instruction::AShr)
1454 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1457 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1463 // Replace a use of the shift with a use of the new shift.
1464 TheUse = InsertedShift;
1467 // If we removed all uses, nuke the shift.
1468 if (ShiftI->use_empty())
1469 ShiftI->eraseFromParent();
1474 /// If counting leading or trailing zeros is an expensive operation and a zero
1475 /// input is defined, add a check for zero to avoid calling the intrinsic.
1477 /// We want to transform:
1478 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1482 /// %cmpz = icmp eq i64 %A, 0
1483 /// br i1 %cmpz, label %cond.end, label %cond.false
1485 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1486 /// br label %cond.end
1488 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1490 /// If the transform is performed, return true and set ModifiedDT to true.
1491 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1492 const TargetLowering *TLI,
1493 const DataLayout *DL,
1498 // If a zero input is undefined, it doesn't make sense to despeculate that.
1499 if (match(CountZeros->getOperand(1), m_One()))
1502 // If it's cheap to speculate, there's nothing to do.
1503 auto IntrinsicID = CountZeros->getIntrinsicID();
1504 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1505 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1508 // Only handle legal scalar cases. Anything else requires too much work.
1509 Type *Ty = CountZeros->getType();
1510 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1511 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
1514 // The intrinsic will be sunk behind a compare against zero and branch.
1515 BasicBlock *StartBlock = CountZeros->getParent();
1516 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1518 // Create another block after the count zero intrinsic. A PHI will be added
1519 // in this block to select the result of the intrinsic or the bit-width
1520 // constant if the input to the intrinsic is zero.
1521 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1522 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1524 // Set up a builder to create a compare, conditional branch, and PHI.
1525 IRBuilder<> Builder(CountZeros->getContext());
1526 Builder.SetInsertPoint(StartBlock->getTerminator());
1527 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1529 // Replace the unconditional branch that was created by the first split with
1530 // a compare against zero and a conditional branch.
1531 Value *Zero = Constant::getNullValue(Ty);
1532 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1533 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1534 StartBlock->getTerminator()->eraseFromParent();
1536 // Create a PHI in the end block to select either the output of the intrinsic
1537 // or the bit width of the operand.
1538 Builder.SetInsertPoint(&EndBlock->front());
1539 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1540 CountZeros->replaceAllUsesWith(PN);
1541 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1542 PN->addIncoming(BitWidth, StartBlock);
1543 PN->addIncoming(CountZeros, CallBlock);
1545 // We are explicitly handling the zero case, so we can set the intrinsic's
1546 // undefined zero argument to 'true'. This will also prevent reprocessing the
1547 // intrinsic; we only despeculate when a zero input is defined.
1548 CountZeros->setArgOperand(1, Builder.getTrue());
1553 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
1554 BasicBlock *BB = CI->getParent();
1556 // Lower inline assembly if we can.
1557 // If we found an inline asm expession, and if the target knows how to
1558 // lower it to normal LLVM code, do so now.
1559 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1560 if (TLI->ExpandInlineAsm(CI)) {
1561 // Avoid invalidating the iterator.
1562 CurInstIterator = BB->begin();
1563 // Avoid processing instructions out of order, which could cause
1564 // reuse before a value is defined.
1568 // Sink address computing for memory operands into the block.
1569 if (optimizeInlineAsmInst(CI))
1573 // Align the pointer arguments to this call if the target thinks it's a good
1575 unsigned MinSize, PrefAlign;
1576 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1577 for (auto &Arg : CI->arg_operands()) {
1578 // We want to align both objects whose address is used directly and
1579 // objects whose address is used in casts and GEPs, though it only makes
1580 // sense for GEPs if the offset is a multiple of the desired alignment and
1581 // if size - offset meets the size threshold.
1582 if (!Arg->getType()->isPointerTy())
1584 APInt Offset(DL->getPointerSizeInBits(
1585 cast<PointerType>(Arg->getType())->getAddressSpace()),
1587 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
1588 uint64_t Offset2 = Offset.getLimitedValue();
1589 if ((Offset2 & (PrefAlign-1)) != 0)
1592 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1593 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
1594 AI->setAlignment(PrefAlign);
1595 // Global variables can only be aligned if they are defined in this
1596 // object (i.e. they are uniquely initialized in this object), and
1597 // over-aligning global variables that have an explicit section is
1600 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
1601 GV->getPointerAlignment(*DL) < PrefAlign &&
1602 DL->getTypeAllocSize(GV->getValueType()) >=
1604 GV->setAlignment(PrefAlign);
1606 // If this is a memcpy (or similar) then we may be able to improve the
1608 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
1609 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
1610 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
1611 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
1612 if (Align > MI->getAlignment())
1613 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1617 // If we have a cold call site, try to sink addressing computation into the
1618 // cold block. This interacts with our handling for loads and stores to
1619 // ensure that we can fold all uses of a potential addressing computation
1620 // into their uses. TODO: generalize this to work over profiling data
1621 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1622 for (auto &Arg : CI->arg_operands()) {
1623 if (!Arg->getType()->isPointerTy())
1625 unsigned AS = Arg->getType()->getPointerAddressSpace();
1626 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1629 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
1631 switch (II->getIntrinsicID()) {
1633 case Intrinsic::objectsize: {
1634 // Lower all uses of llvm.objectsize.*
1635 ConstantInt *RetVal =
1636 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
1637 // Substituting this can cause recursive simplifications, which can
1638 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1641 Value *CurValue = &*CurInstIterator;
1642 WeakTrackingVH IterHandle(CurValue);
1644 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1646 // If the iterator instruction was recursively deleted, start over at the
1647 // start of the block.
1648 if (IterHandle != CurValue) {
1649 CurInstIterator = BB->begin();
1654 case Intrinsic::aarch64_stlxr:
1655 case Intrinsic::aarch64_stxr: {
1656 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1657 if (!ExtVal || !ExtVal->hasOneUse() ||
1658 ExtVal->getParent() == CI->getParent())
1660 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1661 ExtVal->moveBefore(CI);
1662 // Mark this instruction as "inserted by CGP", so that other
1663 // optimizations don't touch it.
1664 InsertedInsts.insert(ExtVal);
1667 case Intrinsic::invariant_group_barrier:
1668 II->replaceAllUsesWith(II->getArgOperand(0));
1669 II->eraseFromParent();
1672 case Intrinsic::cttz:
1673 case Intrinsic::ctlz:
1674 // If counting zeros is expensive, try to avoid it.
1675 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
1679 SmallVector<Value*, 2> PtrOps;
1681 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1682 while (!PtrOps.empty()) {
1683 Value *PtrVal = PtrOps.pop_back_val();
1684 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1685 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
1691 // From here on out we're working with named functions.
1692 if (!CI->getCalledFunction()) return false;
1694 // Lower all default uses of _chk calls. This is very similar
1695 // to what InstCombineCalls does, but here we are only lowering calls
1696 // to fortified library functions (e.g. __memcpy_chk) that have the default
1697 // "don't know" as the objectsize. Anything else should be left alone.
1698 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
1699 if (Value *V = Simplifier.optimizeCall(CI)) {
1700 CI->replaceAllUsesWith(V);
1701 CI->eraseFromParent();
1708 /// Look for opportunities to duplicate return instructions to the predecessor
1709 /// to enable tail call optimizations. The case it is currently looking for is:
1712 /// %tmp0 = tail call i32 @f0()
1713 /// br label %return
1715 /// %tmp1 = tail call i32 @f1()
1716 /// br label %return
1718 /// %tmp2 = tail call i32 @f2()
1719 /// br label %return
1721 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1729 /// %tmp0 = tail call i32 @f0()
1732 /// %tmp1 = tail call i32 @f1()
1735 /// %tmp2 = tail call i32 @f2()
1738 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
1742 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1746 PHINode *PN = nullptr;
1747 BitCastInst *BCI = nullptr;
1748 Value *V = RetI->getReturnValue();
1750 BCI = dyn_cast<BitCastInst>(V);
1752 V = BCI->getOperand(0);
1754 PN = dyn_cast<PHINode>(V);
1759 if (PN && PN->getParent() != BB)
1762 // Make sure there are no instructions between the PHI and return, or that the
1763 // return is the first instruction in the block.
1765 BasicBlock::iterator BI = BB->begin();
1766 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
1768 // Also skip over the bitcast.
1773 BasicBlock::iterator BI = BB->begin();
1774 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1779 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1781 const Function *F = BB->getParent();
1782 SmallVector<CallInst*, 4> TailCalls;
1784 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1785 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1786 // Make sure the phi value is indeed produced by the tail call.
1787 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1788 TLI->mayBeEmittedAsTailCall(CI) &&
1789 attributesPermitTailCall(F, CI, RetI, *TLI))
1790 TailCalls.push_back(CI);
1793 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1794 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1795 if (!VisitedBBs.insert(*PI).second)
1798 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1799 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1800 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1801 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1805 CallInst *CI = dyn_cast<CallInst>(&*RI);
1806 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1807 attributesPermitTailCall(F, CI, RetI, *TLI))
1808 TailCalls.push_back(CI);
1812 bool Changed = false;
1813 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1814 CallInst *CI = TailCalls[i];
1817 // Conservatively require the attributes of the call to match those of the
1818 // return. Ignore noalias because it doesn't affect the call sequence.
1819 AttributeList CalleeAttrs = CS.getAttributes();
1820 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1821 .removeAttribute(Attribute::NoAlias) !=
1822 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1823 .removeAttribute(Attribute::NoAlias))
1826 // Make sure the call instruction is followed by an unconditional branch to
1827 // the return block.
1828 BasicBlock *CallBB = CI->getParent();
1829 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1830 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1833 // Duplicate the return into CallBB.
1834 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
1835 ModifiedDT = Changed = true;
1839 // If we eliminated all predecessors of the block, delete the block now.
1840 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1841 BB->eraseFromParent();
1846 //===----------------------------------------------------------------------===//
1847 // Memory Optimization
1848 //===----------------------------------------------------------------------===//
1852 /// This is an extended version of TargetLowering::AddrMode
1853 /// which holds actual Value*'s for register values.
1854 struct ExtAddrMode : public TargetLowering::AddrMode {
1855 Value *BaseReg = nullptr;
1856 Value *ScaledReg = nullptr;
1857 Value *OriginalValue = nullptr;
1861 BaseRegField = 0x01,
1863 BaseOffsField = 0x04,
1864 ScaledRegField = 0x08,
1866 MultipleFields = 0xff
1869 ExtAddrMode() = default;
1871 void print(raw_ostream &OS) const;
1874 FieldName compare(const ExtAddrMode &other) {
1875 // First check that the types are the same on each field, as differing types
1876 // is something we can't cope with later on.
1877 if (BaseReg && other.BaseReg &&
1878 BaseReg->getType() != other.BaseReg->getType())
1879 return MultipleFields;
1880 if (BaseGV && other.BaseGV &&
1881 BaseGV->getType() != other.BaseGV->getType())
1882 return MultipleFields;
1883 if (ScaledReg && other.ScaledReg &&
1884 ScaledReg->getType() != other.ScaledReg->getType())
1885 return MultipleFields;
1887 // Check each field to see if it differs.
1888 unsigned Result = NoField;
1889 if (BaseReg != other.BaseReg)
1890 Result |= BaseRegField;
1891 if (BaseGV != other.BaseGV)
1892 Result |= BaseGVField;
1893 if (BaseOffs != other.BaseOffs)
1894 Result |= BaseOffsField;
1895 if (ScaledReg != other.ScaledReg)
1896 Result |= ScaledRegField;
1897 // Don't count 0 as being a different scale, because that actually means
1898 // unscaled (which will already be counted by having no ScaledReg).
1899 if (Scale && other.Scale && Scale != other.Scale)
1900 Result |= ScaleField;
1902 if (countPopulation(Result) > 1)
1903 return MultipleFields;
1905 return static_cast<FieldName>(Result);
1908 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1911 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1912 // trivial if at most one of these terms is nonzero, except that BaseGV and
1913 // BaseReg both being zero actually means a null pointer value, which we
1914 // consider to be 'non-zero' here.
1915 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
1918 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1926 case ScaledRegField:
1929 return ConstantInt::get(IntPtrTy, BaseOffs);
1933 void SetCombinedField(FieldName Field, Value *V,
1934 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1937 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1939 case ExtAddrMode::BaseRegField:
1942 case ExtAddrMode::BaseGVField:
1943 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1944 // in the BaseReg field.
1945 assert(BaseReg == nullptr);
1949 case ExtAddrMode::ScaledRegField:
1951 // If we have a mix of scaled and unscaled addrmodes then we want scale
1952 // to be the scale and not zero.
1954 for (const ExtAddrMode &AM : AddrModes)
1960 case ExtAddrMode::BaseOffsField:
1961 // The offset is no longer a constant, so it goes in ScaledReg with a
1963 assert(ScaledReg == nullptr);
1972 } // end anonymous namespace
1975 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1981 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1982 void ExtAddrMode::print(raw_ostream &OS) const {
1983 bool NeedPlus = false;
1986 OS << (NeedPlus ? " + " : "")
1988 BaseGV->printAsOperand(OS, /*PrintType=*/false);
1993 OS << (NeedPlus ? " + " : "")
1999 OS << (NeedPlus ? " + " : "")
2001 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2005 OS << (NeedPlus ? " + " : "")
2007 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2013 LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
2021 /// \brief This class provides transaction based operation on the IR.
2022 /// Every change made through this class is recorded in the internal state and
2023 /// can be undone (rollback) until commit is called.
2024 class TypePromotionTransaction {
2025 /// \brief This represents the common interface of the individual transaction.
2026 /// Each class implements the logic for doing one specific modification on
2027 /// the IR via the TypePromotionTransaction.
2028 class TypePromotionAction {
2030 /// The Instruction modified.
2034 /// \brief Constructor of the action.
2035 /// The constructor performs the related action on the IR.
2036 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2038 virtual ~TypePromotionAction() = default;
2040 /// \brief Undo the modification done by this action.
2041 /// When this method is called, the IR must be in the same state as it was
2042 /// before this action was applied.
2043 /// \pre Undoing the action works if and only if the IR is in the exact same
2044 /// state as it was directly after this action was applied.
2045 virtual void undo() = 0;
2047 /// \brief Advocate every change made by this action.
2048 /// When the results on the IR of the action are to be kept, it is important
2049 /// to call this function, otherwise hidden information may be kept forever.
2050 virtual void commit() {
2051 // Nothing to be done, this action is not doing anything.
2055 /// \brief Utility to remember the position of an instruction.
2056 class InsertionHandler {
2057 /// Position of an instruction.
2058 /// Either an instruction:
2059 /// - Is the first in a basic block: BB is used.
2060 /// - Has a previous instructon: PrevInst is used.
2062 Instruction *PrevInst;
2066 /// Remember whether or not the instruction had a previous instruction.
2067 bool HasPrevInstruction;
2070 /// \brief Record the position of \p Inst.
2071 InsertionHandler(Instruction *Inst) {
2072 BasicBlock::iterator It = Inst->getIterator();
2073 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2074 if (HasPrevInstruction)
2075 Point.PrevInst = &*--It;
2077 Point.BB = Inst->getParent();
2080 /// \brief Insert \p Inst at the recorded position.
2081 void insert(Instruction *Inst) {
2082 if (HasPrevInstruction) {
2083 if (Inst->getParent())
2084 Inst->removeFromParent();
2085 Inst->insertAfter(Point.PrevInst);
2087 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2088 if (Inst->getParent())
2089 Inst->moveBefore(Position);
2091 Inst->insertBefore(Position);
2096 /// \brief Move an instruction before another.
2097 class InstructionMoveBefore : public TypePromotionAction {
2098 /// Original position of the instruction.
2099 InsertionHandler Position;
2102 /// \brief Move \p Inst before \p Before.
2103 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2104 : TypePromotionAction(Inst), Position(Inst) {
2105 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2106 Inst->moveBefore(Before);
2109 /// \brief Move the instruction back to its original position.
2110 void undo() override {
2111 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2112 Position.insert(Inst);
2116 /// \brief Set the operand of an instruction with a new value.
2117 class OperandSetter : public TypePromotionAction {
2118 /// Original operand of the instruction.
2121 /// Index of the modified instruction.
2125 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2126 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2127 : TypePromotionAction(Inst), Idx(Idx) {
2128 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2129 << "for:" << *Inst << "\n"
2130 << "with:" << *NewVal << "\n");
2131 Origin = Inst->getOperand(Idx);
2132 Inst->setOperand(Idx, NewVal);
2135 /// \brief Restore the original value of the instruction.
2136 void undo() override {
2137 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2138 << "for: " << *Inst << "\n"
2139 << "with: " << *Origin << "\n");
2140 Inst->setOperand(Idx, Origin);
2144 /// \brief Hide the operands of an instruction.
2145 /// Do as if this instruction was not using any of its operands.
2146 class OperandsHider : public TypePromotionAction {
2147 /// The list of original operands.
2148 SmallVector<Value *, 4> OriginalValues;
2151 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2152 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2153 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2154 unsigned NumOpnds = Inst->getNumOperands();
2155 OriginalValues.reserve(NumOpnds);
2156 for (unsigned It = 0; It < NumOpnds; ++It) {
2157 // Save the current operand.
2158 Value *Val = Inst->getOperand(It);
2159 OriginalValues.push_back(Val);
2161 // We could use OperandSetter here, but that would imply an overhead
2162 // that we are not willing to pay.
2163 Inst->setOperand(It, UndefValue::get(Val->getType()));
2167 /// \brief Restore the original list of uses.
2168 void undo() override {
2169 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2170 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2171 Inst->setOperand(It, OriginalValues[It]);
2175 /// \brief Build a truncate instruction.
2176 class TruncBuilder : public TypePromotionAction {
2180 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2182 /// trunc Opnd to Ty.
2183 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2184 IRBuilder<> Builder(Opnd);
2185 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2186 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
2189 /// \brief Get the built value.
2190 Value *getBuiltValue() { return Val; }
2192 /// \brief Remove the built instruction.
2193 void undo() override {
2194 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2195 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2196 IVal->eraseFromParent();
2200 /// \brief Build a sign extension instruction.
2201 class SExtBuilder : public TypePromotionAction {
2205 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2207 /// sext Opnd to Ty.
2208 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2209 : TypePromotionAction(InsertPt) {
2210 IRBuilder<> Builder(InsertPt);
2211 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2212 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
2215 /// \brief Get the built value.
2216 Value *getBuiltValue() { return Val; }
2218 /// \brief Remove the built instruction.
2219 void undo() override {
2220 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2221 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2222 IVal->eraseFromParent();
2226 /// \brief Build a zero extension instruction.
2227 class ZExtBuilder : public TypePromotionAction {
2231 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2233 /// zext Opnd to Ty.
2234 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2235 : TypePromotionAction(InsertPt) {
2236 IRBuilder<> Builder(InsertPt);
2237 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2238 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
2241 /// \brief Get the built value.
2242 Value *getBuiltValue() { return Val; }
2244 /// \brief Remove the built instruction.
2245 void undo() override {
2246 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2247 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2248 IVal->eraseFromParent();
2252 /// \brief Mutate an instruction to another type.
2253 class TypeMutator : public TypePromotionAction {
2254 /// Record the original type.
2258 /// \brief Mutate the type of \p Inst into \p NewTy.
2259 TypeMutator(Instruction *Inst, Type *NewTy)
2260 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2261 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2263 Inst->mutateType(NewTy);
2266 /// \brief Mutate the instruction back to its original type.
2267 void undo() override {
2268 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2270 Inst->mutateType(OrigTy);
2274 /// \brief Replace the uses of an instruction by another instruction.
2275 class UsesReplacer : public TypePromotionAction {
2276 /// Helper structure to keep track of the replaced uses.
2277 struct InstructionAndIdx {
2278 /// The instruction using the instruction.
2281 /// The index where this instruction is used for Inst.
2284 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2285 : Inst(Inst), Idx(Idx) {}
2288 /// Keep track of the original uses (pair Instruction, Index).
2289 SmallVector<InstructionAndIdx, 4> OriginalUses;
2291 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
2294 /// \brief Replace all the use of \p Inst by \p New.
2295 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2296 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2298 // Record the original uses.
2299 for (Use &U : Inst->uses()) {
2300 Instruction *UserI = cast<Instruction>(U.getUser());
2301 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2303 // Now, we can replace the uses.
2304 Inst->replaceAllUsesWith(New);
2307 /// \brief Reassign the original uses of Inst to Inst.
2308 void undo() override {
2309 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2310 for (use_iterator UseIt = OriginalUses.begin(),
2311 EndIt = OriginalUses.end();
2312 UseIt != EndIt; ++UseIt) {
2313 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2318 /// \brief Remove an instruction from the IR.
2319 class InstructionRemover : public TypePromotionAction {
2320 /// Original position of the instruction.
2321 InsertionHandler Inserter;
2323 /// Helper structure to hide all the link to the instruction. In other
2324 /// words, this helps to do as if the instruction was removed.
2325 OperandsHider Hider;
2327 /// Keep track of the uses replaced, if any.
2328 UsesReplacer *Replacer = nullptr;
2330 /// Keep track of instructions removed.
2331 SetOfInstrs &RemovedInsts;
2334 /// \brief Remove all reference of \p Inst and optinally replace all its
2336 /// \p RemovedInsts Keep track of the instructions removed by this Action.
2337 /// \pre If !Inst->use_empty(), then New != nullptr
2338 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2339 Value *New = nullptr)
2340 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2341 RemovedInsts(RemovedInsts) {
2343 Replacer = new UsesReplacer(Inst, New);
2344 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2345 RemovedInsts.insert(Inst);
2346 /// The instructions removed here will be freed after completing
2347 /// optimizeBlock() for all blocks as we need to keep track of the
2348 /// removed instructions during promotion.
2349 Inst->removeFromParent();
2352 ~InstructionRemover() override { delete Replacer; }
2354 /// \brief Resurrect the instruction and reassign it to the proper uses if
2355 /// new value was provided when build this action.
2356 void undo() override {
2357 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2358 Inserter.insert(Inst);
2362 RemovedInsts.erase(Inst);
2367 /// Restoration point.
2368 /// The restoration point is a pointer to an action instead of an iterator
2369 /// because the iterator may be invalidated but not the pointer.
2370 using ConstRestorationPt = const TypePromotionAction *;
2372 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2373 : RemovedInsts(RemovedInsts) {}
2375 /// Advocate every changes made in that transaction.
2378 /// Undo all the changes made after the given point.
2379 void rollback(ConstRestorationPt Point);
2381 /// Get the current restoration point.
2382 ConstRestorationPt getRestorationPoint() const;
2384 /// \name API for IR modification with state keeping to support rollback.
2386 /// Same as Instruction::setOperand.
2387 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2389 /// Same as Instruction::eraseFromParent.
2390 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
2392 /// Same as Value::replaceAllUsesWith.
2393 void replaceAllUsesWith(Instruction *Inst, Value *New);
2395 /// Same as Value::mutateType.
2396 void mutateType(Instruction *Inst, Type *NewTy);
2398 /// Same as IRBuilder::createTrunc.
2399 Value *createTrunc(Instruction *Opnd, Type *Ty);
2401 /// Same as IRBuilder::createSExt.
2402 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
2404 /// Same as IRBuilder::createZExt.
2405 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
2407 /// Same as Instruction::moveBefore.
2408 void moveBefore(Instruction *Inst, Instruction *Before);
2412 /// The ordered list of actions made so far.
2413 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2415 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2417 SetOfInstrs &RemovedInsts;
2420 } // end anonymous namespace
2422 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2424 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2425 Inst, Idx, NewVal));
2428 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2431 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2432 Inst, RemovedInsts, NewVal));
2435 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2438 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
2441 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
2443 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
2446 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2448 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
2449 Value *Val = Ptr->getBuiltValue();
2450 Actions.push_back(std::move(Ptr));
2454 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2455 Value *Opnd, Type *Ty) {
2456 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
2457 Value *Val = Ptr->getBuiltValue();
2458 Actions.push_back(std::move(Ptr));
2462 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2463 Value *Opnd, Type *Ty) {
2464 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
2465 Value *Val = Ptr->getBuiltValue();
2466 Actions.push_back(std::move(Ptr));
2470 void TypePromotionTransaction::moveBefore(Instruction *Inst,
2471 Instruction *Before) {
2473 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2477 TypePromotionTransaction::ConstRestorationPt
2478 TypePromotionTransaction::getRestorationPoint() const {
2479 return !Actions.empty() ? Actions.back().get() : nullptr;
2482 void TypePromotionTransaction::commit() {
2483 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
2489 void TypePromotionTransaction::rollback(
2490 TypePromotionTransaction::ConstRestorationPt Point) {
2491 while (!Actions.empty() && Point != Actions.back().get()) {
2492 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
2499 /// \brief A helper class for matching addressing modes.
2501 /// This encapsulates the logic for matching the target-legal addressing modes.
2502 class AddressingModeMatcher {
2503 SmallVectorImpl<Instruction*> &AddrModeInsts;
2504 const TargetLowering &TLI;
2505 const TargetRegisterInfo &TRI;
2506 const DataLayout &DL;
2508 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2509 /// the memory instruction that we're computing this address for.
2512 Instruction *MemoryInst;
2514 /// This is the addressing mode that we're building up. This is
2515 /// part of the return value of this addressing mode matching stuff.
2516 ExtAddrMode &AddrMode;
2518 /// The instructions inserted by other CodeGenPrepare optimizations.
2519 const SetOfInstrs &InsertedInsts;
2521 /// A map from the instructions to their type before promotion.
2522 InstrToOrigTy &PromotedInsts;
2524 /// The ongoing transaction where every action should be registered.
2525 TypePromotionTransaction &TPT;
2527 /// This is set to true when we should not do profitability checks.
2528 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
2529 bool IgnoreProfitability;
2531 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
2532 const TargetLowering &TLI,
2533 const TargetRegisterInfo &TRI,
2534 Type *AT, unsigned AS,
2535 Instruction *MI, ExtAddrMode &AM,
2536 const SetOfInstrs &InsertedInsts,
2537 InstrToOrigTy &PromotedInsts,
2538 TypePromotionTransaction &TPT)
2539 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
2540 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2541 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2542 PromotedInsts(PromotedInsts), TPT(TPT) {
2543 IgnoreProfitability = false;
2547 /// Find the maximal addressing mode that a load/store of V can fold,
2548 /// give an access type of AccessTy. This returns a list of involved
2549 /// instructions in AddrModeInsts.
2550 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
2552 /// \p PromotedInsts maps the instructions to their type before promotion.
2553 /// \p The ongoing transaction where every action should be registered.
2554 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
2555 Instruction *MemoryInst,
2556 SmallVectorImpl<Instruction*> &AddrModeInsts,
2557 const TargetLowering &TLI,
2558 const TargetRegisterInfo &TRI,
2559 const SetOfInstrs &InsertedInsts,
2560 InstrToOrigTy &PromotedInsts,
2561 TypePromotionTransaction &TPT) {
2564 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2566 MemoryInst, Result, InsertedInsts,
2567 PromotedInsts, TPT).matchAddr(V, 0);
2568 (void)Success; assert(Success && "Couldn't select *anything*?");
2573 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2574 bool matchAddr(Value *V, unsigned Depth);
2575 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
2576 bool *MovedAway = nullptr);
2577 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
2578 ExtAddrMode &AMBefore,
2579 ExtAddrMode &AMAfter);
2580 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2581 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
2582 Value *PromotedOperand) const;
2585 /// \brief Keep track of simplification of Phi nodes.
2586 /// Accept the set of all phi nodes and erase phi node from this set
2587 /// if it is simplified.
2588 class SimplificationTracker {
2589 DenseMap<Value *, Value *> Storage;
2590 const SimplifyQuery &SQ;
2591 SmallPtrSetImpl<PHINode *> &AllPhiNodes;
2592 SmallPtrSetImpl<SelectInst *> &AllSelectNodes;
2595 SimplificationTracker(const SimplifyQuery &sq,
2596 SmallPtrSetImpl<PHINode *> &APN,
2597 SmallPtrSetImpl<SelectInst *> &ASN)
2598 : SQ(sq), AllPhiNodes(APN), AllSelectNodes(ASN) {}
2600 Value *Get(Value *V) {
2602 auto SV = Storage.find(V);
2603 if (SV == Storage.end())
2609 Value *Simplify(Value *Val) {
2610 SmallVector<Value *, 32> WorkList;
2611 SmallPtrSet<Value *, 32> Visited;
2612 WorkList.push_back(Val);
2613 while (!WorkList.empty()) {
2614 auto P = WorkList.pop_back_val();
2615 if (!Visited.insert(P).second)
2617 if (auto *PI = dyn_cast<Instruction>(P))
2618 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2619 for (auto *U : PI->users())
2620 WorkList.push_back(cast<Value>(U));
2622 PI->replaceAllUsesWith(V);
2623 if (auto *PHI = dyn_cast<PHINode>(PI))
2624 AllPhiNodes.erase(PHI);
2625 if (auto *Select = dyn_cast<SelectInst>(PI))
2626 AllSelectNodes.erase(Select);
2627 PI->eraseFromParent();
2633 void Put(Value *From, Value *To) {
2634 Storage.insert({ From, To });
2638 /// \brief A helper class for combining addressing modes.
2639 class AddressingModeCombiner {
2640 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2641 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2642 typedef std::pair<PHINode *, PHINode *> PHIPair;
2645 /// The addressing modes we've collected.
2646 SmallVector<ExtAddrMode, 16> AddrModes;
2648 /// The field in which the AddrModes differ, when we have more than one.
2649 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2651 /// Are the AddrModes that we have all just equal to their original values?
2652 bool AllAddrModesTrivial = true;
2654 /// Common Type for all different fields in addressing modes.
2657 /// SimplifyQuery for simplifyInstruction utility.
2658 const SimplifyQuery &SQ;
2660 /// Original Address.
2664 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2665 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2667 /// \brief Get the combined AddrMode
2668 const ExtAddrMode &getAddrMode() const {
2669 return AddrModes[0];
2672 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
2674 /// \return True iff we succeeded in doing so.
2675 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2676 // Take note of if we have any non-trivial AddrModes, as we need to detect
2677 // when all AddrModes are trivial as then we would introduce a phi or select
2678 // which just duplicates what's already there.
2679 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2681 // If this is the first addrmode then everything is fine.
2682 if (AddrModes.empty()) {
2683 AddrModes.emplace_back(NewAddrMode);
2687 // Figure out how different this is from the other address modes, which we
2688 // can do just by comparing against the first one given that we only care
2689 // about the cumulative difference.
2690 ExtAddrMode::FieldName ThisDifferentField =
2691 AddrModes[0].compare(NewAddrMode);
2692 if (DifferentField == ExtAddrMode::NoField)
2693 DifferentField = ThisDifferentField;
2694 else if (DifferentField != ThisDifferentField)
2695 DifferentField = ExtAddrMode::MultipleFields;
2697 // If NewAddrMode differs in only one dimension, and that dimension isn't
2698 // the amount that ScaledReg is scaled by, then we can handle it by
2699 // inserting a phi/select later on. Even if NewAddMode is the same
2700 // we still need to collect it due to original value is different.
2701 // And later we will need all original values as anchors during
2702 // finding the common Phi node.
2703 if (DifferentField != ExtAddrMode::MultipleFields &&
2704 DifferentField != ExtAddrMode::ScaleField) {
2705 AddrModes.emplace_back(NewAddrMode);
2709 // We couldn't combine NewAddrMode with the rest, so return failure.
2714 /// \brief Combine the addressing modes we've collected into a single
2715 /// addressing mode.
2716 /// \return True iff we successfully combined them or we only had one so
2717 /// didn't need to combine them anyway.
2718 bool combineAddrModes() {
2719 // If we have no AddrModes then they can't be combined.
2720 if (AddrModes.size() == 0)
2723 // A single AddrMode can trivially be combined.
2724 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
2727 // If the AddrModes we collected are all just equal to the value they are
2728 // derived from then combining them wouldn't do anything useful.
2729 if (AllAddrModesTrivial)
2732 if (!addrModeCombiningAllowed())
2735 // Build a map between <original value, basic block where we saw it> to
2736 // value of base register.
2737 // Bail out if there is no common type.
2738 FoldAddrToValueMapping Map;
2739 if (!initializeMap(Map))
2742 Value *CommonValue = findCommon(Map);
2744 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
2745 return CommonValue != nullptr;
2749 /// \brief Initialize Map with anchor values. For address seen in some BB
2750 /// we set the value of different field saw in this address.
2751 /// If address is not an instruction than basic block is set to null.
2752 /// At the same time we find a common type for different field we will
2753 /// use to create new Phi/Select nodes. Keep it in CommonType field.
2754 /// Return false if there is no common type found.
2755 bool initializeMap(FoldAddrToValueMapping &Map) {
2756 // Keep track of keys where the value is null. We will need to replace it
2757 // with constant null when we know the common type.
2758 SmallVector<ValueInBB, 2> NullValue;
2759 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
2760 for (auto &AM : AddrModes) {
2761 BasicBlock *BB = nullptr;
2762 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2763 BB = I->getParent();
2765 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
2767 auto *Type = DV->getType();
2768 if (CommonType && CommonType != Type)
2771 Map[{ AM.OriginalValue, BB }] = DV;
2773 NullValue.push_back({ AM.OriginalValue, BB });
2776 assert(CommonType && "At least one non-null value must be!");
2777 for (auto VIBB : NullValue)
2778 Map[VIBB] = Constant::getNullValue(CommonType);
2782 /// \brief We have mapping between value A and basic block where value A
2783 /// seen to other value B where B was a field in addressing mode represented
2784 /// by A. Also we have an original value C representin an address in some
2785 /// basic block. Traversing from C through phi and selects we ended up with
2786 /// A's in a map. This utility function tries to find a value V which is a
2787 /// field in addressing mode C and traversing through phi nodes and selects
2788 /// we will end up in corresponded values B in a map.
2789 /// The utility will create a new Phi/Selects if needed.
2790 // The simple example looks as follows:
2798 // p = phi [p1, BB1], [p2, BB2]
2805 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2806 Value *findCommon(FoldAddrToValueMapping &Map) {
2807 // Tracks of new created Phi nodes.
2808 SmallPtrSet<PHINode *, 32> NewPhiNodes;
2809 // Tracks of new created Select nodes.
2810 SmallPtrSet<SelectInst *, 32> NewSelectNodes;
2811 // Tracks the simplification of new created phi nodes. The reason we use
2812 // this mapping is because we will add new created Phi nodes in AddrToBase.
2813 // Simplification of Phi nodes is recursive, so some Phi node may
2814 // be simplified after we added it to AddrToBase.
2815 // Using this mapping we can find the current value in AddrToBase.
2816 SimplificationTracker ST(SQ, NewPhiNodes, NewSelectNodes);
2818 // First step, DFS to create PHI nodes for all intermediate blocks.
2819 // Also fill traverse order for the second step.
2820 SmallVector<ValueInBB, 32> TraverseOrder;
2821 InsertPlaceholders(Map, TraverseOrder, NewPhiNodes, NewSelectNodes);
2823 // Second Step, fill new nodes by merged values and simplify if possible.
2824 FillPlaceholders(Map, TraverseOrder, ST);
2826 if (!AddrSinkNewSelects && NewSelectNodes.size() > 0) {
2827 DestroyNodes(NewPhiNodes);
2828 DestroyNodes(NewSelectNodes);
2832 // Now we'd like to match New Phi nodes to existed ones.
2833 unsigned PhiNotMatchedCount = 0;
2834 if (!MatchPhiSet(NewPhiNodes, ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2835 DestroyNodes(NewPhiNodes);
2836 DestroyNodes(NewSelectNodes);
2840 auto *Result = ST.Get(Map.find(Original)->second);
2842 NumMemoryInstsPhiCreated += NewPhiNodes.size() + PhiNotMatchedCount;
2843 NumMemoryInstsSelectCreated += NewSelectNodes.size();
2848 /// \brief Destroy nodes from a set.
2849 template <typename T> void DestroyNodes(SmallPtrSetImpl<T *> &Instructions) {
2850 // For safe erasing, replace the Phi with dummy value first.
2851 auto Dummy = UndefValue::get(CommonType);
2852 for (auto I : Instructions) {
2853 I->replaceAllUsesWith(Dummy);
2854 I->eraseFromParent();
2858 /// \brief Try to match PHI node to Candidate.
2859 /// Matcher tracks the matched Phi nodes.
2860 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
2861 DenseSet<PHIPair> &Matcher,
2862 SmallPtrSetImpl<PHINode *> &PhiNodesToMatch) {
2863 SmallVector<PHIPair, 8> WorkList;
2864 Matcher.insert({ PHI, Candidate });
2865 WorkList.push_back({ PHI, Candidate });
2866 SmallSet<PHIPair, 8> Visited;
2867 while (!WorkList.empty()) {
2868 auto Item = WorkList.pop_back_val();
2869 if (!Visited.insert(Item).second)
2871 // We iterate over all incoming values to Phi to compare them.
2872 // If values are different and both of them Phi and the first one is a
2873 // Phi we added (subject to match) and both of them is in the same basic
2874 // block then we can match our pair if values match. So we state that
2875 // these values match and add it to work list to verify that.
2876 for (auto B : Item.first->blocks()) {
2877 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2878 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2879 if (FirstValue == SecondValue)
2882 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2883 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2885 // One of them is not Phi or
2886 // The first one is not Phi node from the set we'd like to match or
2887 // Phi nodes from different basic blocks then
2888 // we will not be able to match.
2889 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2890 FirstPhi->getParent() != SecondPhi->getParent())
2893 // If we already matched them then continue.
2894 if (Matcher.count({ FirstPhi, SecondPhi }))
2896 // So the values are different and does not match. So we need them to
2898 Matcher.insert({ FirstPhi, SecondPhi });
2899 // But me must check it.
2900 WorkList.push_back({ FirstPhi, SecondPhi });
2906 /// \brief For the given set of PHI nodes try to find their equivalents.
2907 /// Returns false if this matching fails and creation of new Phi is disabled.
2908 bool MatchPhiSet(SmallPtrSetImpl<PHINode *> &PhiNodesToMatch,
2909 SimplificationTracker &ST, bool AllowNewPhiNodes,
2910 unsigned &PhiNotMatchedCount) {
2911 DenseSet<PHIPair> Matched;
2912 SmallPtrSet<PHINode *, 8> WillNotMatch;
2913 while (PhiNodesToMatch.size()) {
2914 PHINode *PHI = *PhiNodesToMatch.begin();
2916 // Add us, if no Phi nodes in the basic block we do not match.
2917 WillNotMatch.clear();
2918 WillNotMatch.insert(PHI);
2920 // Traverse all Phis until we found equivalent or fail to do that.
2921 bool IsMatched = false;
2922 for (auto &P : PHI->getParent()->phis()) {
2925 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
2927 // If it does not match, collect all Phi nodes from matcher.
2928 // if we end up with no match, them all these Phi nodes will not match
2930 for (auto M : Matched)
2931 WillNotMatch.insert(M.first);
2935 // Replace all matched values and erase them.
2936 for (auto MV : Matched) {
2937 MV.first->replaceAllUsesWith(MV.second);
2938 PhiNodesToMatch.erase(MV.first);
2939 ST.Put(MV.first, MV.second);
2940 MV.first->eraseFromParent();
2945 // If we are not allowed to create new nodes then bail out.
2946 if (!AllowNewPhiNodes)
2948 // Just remove all seen values in matcher. They will not match anything.
2949 PhiNotMatchedCount += WillNotMatch.size();
2950 for (auto *P : WillNotMatch)
2951 PhiNodesToMatch.erase(P);
2955 /// \brief Fill the placeholder with values from predecessors and simplify it.
2956 void FillPlaceholders(FoldAddrToValueMapping &Map,
2957 SmallVectorImpl<ValueInBB> &TraverseOrder,
2958 SimplificationTracker &ST) {
2959 while (!TraverseOrder.empty()) {
2960 auto Current = TraverseOrder.pop_back_val();
2961 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
2962 Value *CurrentValue = Current.first;
2963 BasicBlock *CurrentBlock = Current.second;
2964 Value *V = Map[Current];
2966 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
2967 // CurrentValue also must be Select.
2968 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
2969 auto *TrueValue = CurrentSelect->getTrueValue();
2970 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
2973 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
2974 Select->setTrueValue(ST.Get(Map[TrueItem]));
2975 auto *FalseValue = CurrentSelect->getFalseValue();
2976 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
2979 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
2980 Select->setFalseValue(ST.Get(Map[FalseItem]));
2982 // Must be a Phi node then.
2983 PHINode *PHI = cast<PHINode>(V);
2984 // Fill the Phi node with values from predecessors.
2985 bool IsDefinedInThisBB =
2986 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
2987 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
2988 for (auto B : predecessors(CurrentBlock)) {
2989 Value *PV = IsDefinedInThisBB
2990 ? CurrentPhi->getIncomingValueForBlock(B)
2992 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
2993 assert(Map.find(item) != Map.end() && "No predecessor Value!");
2994 PHI->addIncoming(ST.Get(Map[item]), B);
2997 // Simplify if possible.
2998 Map[Current] = ST.Simplify(V);
3002 /// Starting from value recursively iterates over predecessors up to known
3003 /// ending values represented in a map. For each traversed block inserts
3004 /// a placeholder Phi or Select.
3005 /// Reports all new created Phi/Select nodes by adding them to set.
3006 /// Also reports and order in what basic blocks have been traversed.
3007 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3008 SmallVectorImpl<ValueInBB> &TraverseOrder,
3009 SmallPtrSetImpl<PHINode *> &NewPhiNodes,
3010 SmallPtrSetImpl<SelectInst *> &NewSelectNodes) {
3011 SmallVector<ValueInBB, 32> Worklist;
3012 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3013 "Address must be a Phi or Select node");
3014 auto *Dummy = UndefValue::get(CommonType);
3015 Worklist.push_back(Original);
3016 while (!Worklist.empty()) {
3017 auto Current = Worklist.pop_back_val();
3018 // If value is not an instruction it is something global, constant,
3019 // parameter and we can say that this value is observable in any block.
3020 // Set block to null to denote it.
3021 // Also please take into account that it is how we build anchors.
3022 if (!isa<Instruction>(Current.first))
3023 Current.second = nullptr;
3024 // if it is already visited or it is an ending value then skip it.
3025 if (Map.find(Current) != Map.end())
3027 TraverseOrder.push_back(Current);
3029 Value *CurrentValue = Current.first;
3030 BasicBlock *CurrentBlock = Current.second;
3031 // CurrentValue must be a Phi node or select. All others must be covered
3033 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3034 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3036 unsigned PredCount =
3037 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3038 // if Current Value is not defined in this basic block we are interested
3039 // in values in predecessors.
3040 if (!IsDefinedInThisBB) {
3041 assert(PredCount && "Unreachable block?!");
3042 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3043 &CurrentBlock->front());
3045 NewPhiNodes.insert(PHI);
3046 // Add all predecessors in work list.
3047 for (auto B : predecessors(CurrentBlock))
3048 Worklist.push_back({ CurrentValue, B });
3051 // Value is defined in this basic block.
3052 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3053 // Is it OK to get metadata from OrigSelect?!
3054 // Create a Select placeholder with dummy value.
3055 SelectInst *Select =
3056 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3057 OrigSelect->getName(), OrigSelect, OrigSelect);
3058 Map[Current] = Select;
3059 NewSelectNodes.insert(Select);
3060 // We are interested in True and False value in this basic block.
3061 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3062 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3064 // It must be a Phi node then.
3065 auto *CurrentPhi = cast<PHINode>(CurrentI);
3066 // Create new Phi node for merge of bases.
3067 assert(PredCount && "Unreachable block?!");
3068 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3069 &CurrentBlock->front());
3071 NewPhiNodes.insert(PHI);
3073 // Add all predecessors in work list.
3074 for (auto B : predecessors(CurrentBlock))
3075 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3080 bool addrModeCombiningAllowed() {
3081 if (DisableComplexAddrModes)
3083 switch (DifferentField) {
3086 case ExtAddrMode::BaseRegField:
3087 return AddrSinkCombineBaseReg;
3088 case ExtAddrMode::BaseGVField:
3089 return AddrSinkCombineBaseGV;
3090 case ExtAddrMode::BaseOffsField:
3091 return AddrSinkCombineBaseOffs;
3092 case ExtAddrMode::ScaledRegField:
3093 return AddrSinkCombineScaledReg;
3097 } // end anonymous namespace
3099 /// Try adding ScaleReg*Scale to the current addressing mode.
3100 /// Return true and update AddrMode if this addr mode is legal for the target,
3102 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3104 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3105 // mode. Just process that directly.
3107 return matchAddr(ScaleReg, Depth);
3109 // If the scale is 0, it takes nothing to add this.
3113 // If we already have a scale of this value, we can add to it, otherwise, we
3114 // need an available scale field.
3115 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3118 ExtAddrMode TestAddrMode = AddrMode;
3120 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3121 // [A+B + A*7] -> [B+A*8].
3122 TestAddrMode.Scale += Scale;
3123 TestAddrMode.ScaledReg = ScaleReg;
3125 // If the new address isn't legal, bail out.
3126 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3129 // It was legal, so commit it.
3130 AddrMode = TestAddrMode;
3132 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3133 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3134 // X*Scale + C*Scale to addr mode.
3135 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3136 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3137 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3138 TestAddrMode.ScaledReg = AddLHS;
3139 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3141 // If this addressing mode is legal, commit it and remember that we folded
3142 // this instruction.
3143 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3144 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3145 AddrMode = TestAddrMode;
3150 // Otherwise, not (x+c)*scale, just return what we have.
3154 /// This is a little filter, which returns true if an addressing computation
3155 /// involving I might be folded into a load/store accessing it.
3156 /// This doesn't need to be perfect, but needs to accept at least
3157 /// the set of instructions that MatchOperationAddr can.
3158 static bool MightBeFoldableInst(Instruction *I) {
3159 switch (I->getOpcode()) {
3160 case Instruction::BitCast:
3161 case Instruction::AddrSpaceCast:
3162 // Don't touch identity bitcasts.
3163 if (I->getType() == I->getOperand(0)->getType())
3165 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3166 case Instruction::PtrToInt:
3167 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3169 case Instruction::IntToPtr:
3170 // We know the input is intptr_t, so this is foldable.
3172 case Instruction::Add:
3174 case Instruction::Mul:
3175 case Instruction::Shl:
3176 // Can only handle X*C and X << C.
3177 return isa<ConstantInt>(I->getOperand(1));
3178 case Instruction::GetElementPtr:
3185 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3186 /// \note \p Val is assumed to be the product of some type promotion.
3187 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3188 /// to be legal, as the non-promoted value would have had the same state.
3189 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3190 const DataLayout &DL, Value *Val) {
3191 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3194 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3195 // If the ISDOpcode is undefined, it was undefined before the promotion.
3198 // Otherwise, check if the promoted instruction is legal or not.
3199 return TLI.isOperationLegalOrCustom(
3200 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3205 /// \brief Hepler class to perform type promotion.
3206 class TypePromotionHelper {
3207 /// \brief Utility function to check whether or not a sign or zero extension
3208 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3209 /// either using the operands of \p Inst or promoting \p Inst.
3210 /// The type of the extension is defined by \p IsSExt.
3211 /// In other words, check if:
3212 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3213 /// #1 Promotion applies:
3214 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3215 /// #2 Operand reuses:
3216 /// ext opnd1 to ConsideredExtType.
3217 /// \p PromotedInsts maps the instructions to their type before promotion.
3218 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3219 const InstrToOrigTy &PromotedInsts, bool IsSExt);
3221 /// \brief Utility function to determine if \p OpIdx should be promoted when
3222 /// promoting \p Inst.
3223 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3224 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3227 /// \brief Utility function to promote the operand of \p Ext when this
3228 /// operand is a promotable trunc or sext or zext.
3229 /// \p PromotedInsts maps the instructions to their type before promotion.
3230 /// \p CreatedInstsCost[out] contains the cost of all instructions
3231 /// created to promote the operand of Ext.
3232 /// Newly added extensions are inserted in \p Exts.
3233 /// Newly added truncates are inserted in \p Truncs.
3234 /// Should never be called directly.
3235 /// \return The promoted value which is used instead of Ext.
3236 static Value *promoteOperandForTruncAndAnyExt(
3237 Instruction *Ext, TypePromotionTransaction &TPT,
3238 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3239 SmallVectorImpl<Instruction *> *Exts,
3240 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3242 /// \brief Utility function to promote the operand of \p Ext when this
3243 /// operand is promotable and is not a supported trunc or sext.
3244 /// \p PromotedInsts maps the instructions to their type before promotion.
3245 /// \p CreatedInstsCost[out] contains the cost of all the instructions
3246 /// created to promote the operand of Ext.
3247 /// Newly added extensions are inserted in \p Exts.
3248 /// Newly added truncates are inserted in \p Truncs.
3249 /// Should never be called directly.
3250 /// \return The promoted value which is used instead of Ext.
3251 static Value *promoteOperandForOther(Instruction *Ext,
3252 TypePromotionTransaction &TPT,
3253 InstrToOrigTy &PromotedInsts,
3254 unsigned &CreatedInstsCost,
3255 SmallVectorImpl<Instruction *> *Exts,
3256 SmallVectorImpl<Instruction *> *Truncs,
3257 const TargetLowering &TLI, bool IsSExt);
3259 /// \see promoteOperandForOther.
3260 static Value *signExtendOperandForOther(
3261 Instruction *Ext, TypePromotionTransaction &TPT,
3262 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3263 SmallVectorImpl<Instruction *> *Exts,
3264 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3265 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3266 Exts, Truncs, TLI, true);
3269 /// \see promoteOperandForOther.
3270 static Value *zeroExtendOperandForOther(
3271 Instruction *Ext, TypePromotionTransaction &TPT,
3272 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3273 SmallVectorImpl<Instruction *> *Exts,
3274 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3275 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3276 Exts, Truncs, TLI, false);
3280 /// Type for the utility function that promotes the operand of Ext.
3281 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3282 InstrToOrigTy &PromotedInsts,
3283 unsigned &CreatedInstsCost,
3284 SmallVectorImpl<Instruction *> *Exts,
3285 SmallVectorImpl<Instruction *> *Truncs,
3286 const TargetLowering &TLI);
3288 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3289 /// action to promote the operand of \p Ext instead of using Ext.
3290 /// \return NULL if no promotable action is possible with the current
3292 /// \p InsertedInsts keeps track of all the instructions inserted by the
3293 /// other CodeGenPrepare optimizations. This information is important
3294 /// because we do not want to promote these instructions as CodeGenPrepare
3295 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3296 /// \p PromotedInsts maps the instructions to their type before promotion.
3297 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3298 const TargetLowering &TLI,
3299 const InstrToOrigTy &PromotedInsts);
3302 } // end anonymous namespace
3304 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3305 Type *ConsideredExtType,
3306 const InstrToOrigTy &PromotedInsts,
3308 // The promotion helper does not know how to deal with vector types yet.
3309 // To be able to fix that, we would need to fix the places where we
3310 // statically extend, e.g., constants and such.
3311 if (Inst->getType()->isVectorTy())
3314 // We can always get through zext.
3315 if (isa<ZExtInst>(Inst))
3318 // sext(sext) is ok too.
3319 if (IsSExt && isa<SExtInst>(Inst))
3322 // We can get through binary operator, if it is legal. In other words, the
3323 // binary operator must have a nuw or nsw flag.
3324 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3325 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3326 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3327 (IsSExt && BinOp->hasNoSignedWrap())))
3330 // Check if we can do the following simplification.
3331 // ext(trunc(opnd)) --> ext(opnd)
3332 if (!isa<TruncInst>(Inst))
3335 Value *OpndVal = Inst->getOperand(0);
3336 // Check if we can use this operand in the extension.
3337 // If the type is larger than the result type of the extension, we cannot.
3338 if (!OpndVal->getType()->isIntegerTy() ||
3339 OpndVal->getType()->getIntegerBitWidth() >
3340 ConsideredExtType->getIntegerBitWidth())
3343 // If the operand of the truncate is not an instruction, we will not have
3344 // any information on the dropped bits.
3345 // (Actually we could for constant but it is not worth the extra logic).
3346 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3350 // Check if the source of the type is narrow enough.
3351 // I.e., check that trunc just drops extended bits of the same kind of
3353 // #1 get the type of the operand and check the kind of the extended bits.
3354 const Type *OpndType;
3355 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3356 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3357 OpndType = It->second.getPointer();
3358 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3359 OpndType = Opnd->getOperand(0)->getType();
3363 // #2 check that the truncate just drops extended bits.
3364 return Inst->getType()->getIntegerBitWidth() >=
3365 OpndType->getIntegerBitWidth();
3368 TypePromotionHelper::Action TypePromotionHelper::getAction(
3369 Instruction *Ext, const SetOfInstrs &InsertedInsts,
3370 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3371 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3372 "Unexpected instruction type");
3373 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3374 Type *ExtTy = Ext->getType();
3375 bool IsSExt = isa<SExtInst>(Ext);
3376 // If the operand of the extension is not an instruction, we cannot
3378 // If it, check we can get through.
3379 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3382 // Do not promote if the operand has been added by codegenprepare.
3383 // Otherwise, it means we are undoing an optimization that is likely to be
3384 // redone, thus causing potential infinite loop.
3385 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3388 // SExt or Trunc instructions.
3389 // Return the related handler.
3390 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3391 isa<ZExtInst>(ExtOpnd))
3392 return promoteOperandForTruncAndAnyExt;
3394 // Regular instruction.
3395 // Abort early if we will have to insert non-free instructions.
3396 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3398 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3401 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3402 Instruction *SExt, TypePromotionTransaction &TPT,
3403 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3404 SmallVectorImpl<Instruction *> *Exts,
3405 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3406 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3407 // get through it and this method should not be called.
3408 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3409 Value *ExtVal = SExt;
3410 bool HasMergedNonFreeExt = false;
3411 if (isa<ZExtInst>(SExtOpnd)) {
3412 // Replace s|zext(zext(opnd))
3414 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3416 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3417 TPT.replaceAllUsesWith(SExt, ZExt);
3418 TPT.eraseInstruction(SExt);
3421 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3423 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3425 CreatedInstsCost = 0;
3427 // Remove dead code.
3428 if (SExtOpnd->use_empty())
3429 TPT.eraseInstruction(SExtOpnd);
3431 // Check if the extension is still needed.
3432 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
3433 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3436 Exts->push_back(ExtInst);
3437 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3442 // At this point we have: ext ty opnd to ty.
3443 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3444 Value *NextVal = ExtInst->getOperand(0);
3445 TPT.eraseInstruction(ExtInst, NextVal);
3449 Value *TypePromotionHelper::promoteOperandForOther(
3450 Instruction *Ext, TypePromotionTransaction &TPT,
3451 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3452 SmallVectorImpl<Instruction *> *Exts,
3453 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3455 // By construction, the operand of Ext is an instruction. Otherwise we cannot
3456 // get through it and this method should not be called.
3457 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3458 CreatedInstsCost = 0;
3459 if (!ExtOpnd->hasOneUse()) {
3460 // ExtOpnd will be promoted.
3461 // All its uses, but Ext, will need to use a truncated value of the
3462 // promoted version.
3463 // Create the truncate now.
3464 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
3465 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3466 // Insert it just after the definition.
3467 ITrunc->moveAfter(ExtOpnd);
3469 Truncs->push_back(ITrunc);
3472 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3473 // Restore the operand of Ext (which has been replaced by the previous call
3474 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
3475 TPT.setOperand(Ext, 0, ExtOpnd);
3478 // Get through the Instruction:
3479 // 1. Update its type.
3480 // 2. Replace the uses of Ext by Inst.
3481 // 3. Extend each operand that needs to be extended.
3483 // Remember the original type of the instruction before promotion.
3484 // This is useful to know that the high bits are sign extended bits.
3485 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3486 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
3488 TPT.mutateType(ExtOpnd, Ext->getType());
3490 TPT.replaceAllUsesWith(Ext, ExtOpnd);
3492 Instruction *ExtForOpnd = Ext;
3494 DEBUG(dbgs() << "Propagate Ext to operands\n");
3495 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
3497 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3498 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3499 !shouldExtOperand(ExtOpnd, OpIdx)) {
3500 DEBUG(dbgs() << "No need to propagate\n");
3503 // Check if we can statically extend the operand.
3504 Value *Opnd = ExtOpnd->getOperand(OpIdx);
3505 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3506 DEBUG(dbgs() << "Statically extend\n");
3507 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3508 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3509 : Cst->getValue().zext(BitWidth);
3510 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
3513 // UndefValue are typed, so we have to statically sign extend them.
3514 if (isa<UndefValue>(Opnd)) {
3515 DEBUG(dbgs() << "Statically extend\n");
3516 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
3520 // Otherwise we have to explicity sign extend the operand.
3521 // Check if Ext was reused to extend an operand.
3523 // If yes, create a new one.
3524 DEBUG(dbgs() << "More operands to ext\n");
3525 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3526 : TPT.createZExt(Ext, Opnd, Ext->getType());
3527 if (!isa<Instruction>(ValForExtOpnd)) {
3528 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3531 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3534 Exts->push_back(ExtForOpnd);
3535 TPT.setOperand(ExtForOpnd, 0, Opnd);
3537 // Move the sign extension before the insertion point.
3538 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3539 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3540 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
3541 // If more sext are required, new instructions will have to be created.
3542 ExtForOpnd = nullptr;
3544 if (ExtForOpnd == Ext) {
3545 DEBUG(dbgs() << "Extension is useless now\n");
3546 TPT.eraseInstruction(Ext);
3551 /// Check whether or not promoting an instruction to a wider type is profitable.
3552 /// \p NewCost gives the cost of extension instructions created by the
3554 /// \p OldCost gives the cost of extension instructions before the promotion
3555 /// plus the number of instructions that have been
3556 /// matched in the addressing mode the promotion.
3557 /// \p PromotedOperand is the value that has been promoted.
3558 /// \return True if the promotion is profitable, false otherwise.
3559 bool AddressingModeMatcher::isPromotionProfitable(
3560 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3561 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3562 // The cost of the new extensions is greater than the cost of the
3563 // old extension plus what we folded.
3564 // This is not profitable.
3565 if (NewCost > OldCost)
3567 if (NewCost < OldCost)
3569 // The promotion is neutral but it may help folding the sign extension in
3570 // loads for instance.
3571 // Check that we did not create an illegal instruction.
3572 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
3575 /// Given an instruction or constant expr, see if we can fold the operation
3576 /// into the addressing mode. If so, update the addressing mode and return
3577 /// true, otherwise return false without modifying AddrMode.
3578 /// If \p MovedAway is not NULL, it contains the information of whether or
3579 /// not AddrInst has to be folded into the addressing mode on success.
3580 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3581 /// because it has been moved away.
3582 /// Thus AddrInst must not be added in the matched instructions.
3583 /// This state can happen when AddrInst is a sext, since it may be moved away.
3584 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
3585 /// not be referenced anymore.
3586 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
3589 // Avoid exponential behavior on extremely deep expression trees.
3590 if (Depth >= 5) return false;
3592 // By default, all matched instructions stay in place.
3597 case Instruction::PtrToInt:
3598 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3599 return matchAddr(AddrInst->getOperand(0), Depth);
3600 case Instruction::IntToPtr: {
3601 auto AS = AddrInst->getType()->getPointerAddressSpace();
3602 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
3603 // This inttoptr is a no-op if the integer type is pointer sized.
3604 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
3605 return matchAddr(AddrInst->getOperand(0), Depth);
3608 case Instruction::BitCast:
3609 // BitCast is always a noop, and we can handle it as long as it is
3610 // int->int or pointer->pointer (we don't want int<->fp or something).
3611 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3612 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3613 // Don't touch identity bitcasts. These were probably put here by LSR,
3614 // and we don't want to mess around with them. Assume it knows what it
3616 AddrInst->getOperand(0)->getType() != AddrInst->getType())
3617 return matchAddr(AddrInst->getOperand(0), Depth);
3619 case Instruction::AddrSpaceCast: {
3621 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3622 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3623 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3624 return matchAddr(AddrInst->getOperand(0), Depth);
3627 case Instruction::Add: {
3628 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3629 ExtAddrMode BackupAddrMode = AddrMode;
3630 unsigned OldSize = AddrModeInsts.size();
3631 // Start a transaction at this point.
3632 // The LHS may match but not the RHS.
3633 // Therefore, we need a higher level restoration point to undo partially
3634 // matched operation.
3635 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3636 TPT.getRestorationPoint();
3638 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3639 matchAddr(AddrInst->getOperand(0), Depth+1))
3642 // Restore the old addr mode info.
3643 AddrMode = BackupAddrMode;
3644 AddrModeInsts.resize(OldSize);
3645 TPT.rollback(LastKnownGood);
3647 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
3648 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3649 matchAddr(AddrInst->getOperand(1), Depth+1))
3652 // Otherwise we definitely can't merge the ADD in.
3653 AddrMode = BackupAddrMode;
3654 AddrModeInsts.resize(OldSize);
3655 TPT.rollback(LastKnownGood);
3658 //case Instruction::Or:
3659 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3661 case Instruction::Mul:
3662 case Instruction::Shl: {
3663 // Can only handle X*C and X << C.
3664 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
3665 if (!RHS || RHS->getBitWidth() > 64)
3667 int64_t Scale = RHS->getSExtValue();
3668 if (Opcode == Instruction::Shl)
3669 Scale = 1LL << Scale;
3671 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
3673 case Instruction::GetElementPtr: {
3674 // Scan the GEP. We check it if it contains constant offsets and at most
3675 // one variable offset.
3676 int VariableOperand = -1;
3677 unsigned VariableScale = 0;
3679 int64_t ConstantOffset = 0;
3680 gep_type_iterator GTI = gep_type_begin(AddrInst);
3681 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3682 if (StructType *STy = GTI.getStructTypeOrNull()) {
3683 const StructLayout *SL = DL.getStructLayout(STy);
3685 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3686 ConstantOffset += SL->getElementOffset(Idx);
3688 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
3689 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3690 ConstantOffset += CI->getSExtValue() * TypeSize;
3691 } else if (TypeSize) { // Scales of zero don't do anything.
3692 // We only allow one variable index at the moment.
3693 if (VariableOperand != -1)
3696 // Remember the variable index.
3697 VariableOperand = i;
3698 VariableScale = TypeSize;
3703 // A common case is for the GEP to only do a constant offset. In this case,
3704 // just add it to the disp field and check validity.
3705 if (VariableOperand == -1) {
3706 AddrMode.BaseOffs += ConstantOffset;
3707 if (ConstantOffset == 0 ||
3708 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
3709 // Check to see if we can fold the base pointer in too.
3710 if (matchAddr(AddrInst->getOperand(0), Depth+1))
3713 AddrMode.BaseOffs -= ConstantOffset;
3717 // Save the valid addressing mode in case we can't match.
3718 ExtAddrMode BackupAddrMode = AddrMode;
3719 unsigned OldSize = AddrModeInsts.size();
3721 // See if the scale and offset amount is valid for this target.
3722 AddrMode.BaseOffs += ConstantOffset;
3724 // Match the base operand of the GEP.
3725 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
3726 // If it couldn't be matched, just stuff the value in a register.
3727 if (AddrMode.HasBaseReg) {
3728 AddrMode = BackupAddrMode;
3729 AddrModeInsts.resize(OldSize);
3732 AddrMode.HasBaseReg = true;
3733 AddrMode.BaseReg = AddrInst->getOperand(0);
3736 // Match the remaining variable portion of the GEP.
3737 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
3739 // If it couldn't be matched, try stuffing the base into a register
3740 // instead of matching it, and retrying the match of the scale.
3741 AddrMode = BackupAddrMode;
3742 AddrModeInsts.resize(OldSize);
3743 if (AddrMode.HasBaseReg)
3745 AddrMode.HasBaseReg = true;
3746 AddrMode.BaseReg = AddrInst->getOperand(0);
3747 AddrMode.BaseOffs += ConstantOffset;
3748 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
3749 VariableScale, Depth)) {
3750 // If even that didn't work, bail.
3751 AddrMode = BackupAddrMode;
3752 AddrModeInsts.resize(OldSize);
3759 case Instruction::SExt:
3760 case Instruction::ZExt: {
3761 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3765 // Try to move this ext out of the way of the addressing mode.
3766 // Ask for a method for doing so.
3767 TypePromotionHelper::Action TPH =
3768 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
3772 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3773 TPT.getRestorationPoint();
3774 unsigned CreatedInstsCost = 0;
3775 unsigned ExtCost = !TLI.isExtFree(Ext);
3776 Value *PromotedOperand =
3777 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
3778 // SExt has been moved away.
3779 // Thus either it will be rematched later in the recursive calls or it is
3780 // gone. Anyway, we must not fold it into the addressing mode at this point.
3784 // addr = gep base, idx
3786 // promotedOpnd = ext opnd <- no match here
3787 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3788 // addr = gep base, op <- match
3792 assert(PromotedOperand &&
3793 "TypePromotionHelper should have filtered out those cases");
3795 ExtAddrMode BackupAddrMode = AddrMode;
3796 unsigned OldSize = AddrModeInsts.size();
3798 if (!matchAddr(PromotedOperand, Depth) ||
3799 // The total of the new cost is equal to the cost of the created
3801 // The total of the old cost is equal to the cost of the extension plus
3802 // what we have saved in the addressing mode.
3803 !isPromotionProfitable(CreatedInstsCost,
3804 ExtCost + (AddrModeInsts.size() - OldSize),
3806 AddrMode = BackupAddrMode;
3807 AddrModeInsts.resize(OldSize);
3808 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3809 TPT.rollback(LastKnownGood);
3818 /// If we can, try to add the value of 'Addr' into the current addressing mode.
3819 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3820 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
3823 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
3824 // Start a transaction at this point that we will rollback if the matching
3826 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3827 TPT.getRestorationPoint();
3828 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3829 // Fold in immediates if legal for the target.
3830 AddrMode.BaseOffs += CI->getSExtValue();
3831 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3833 AddrMode.BaseOffs -= CI->getSExtValue();
3834 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3835 // If this is a global variable, try to fold it into the addressing mode.
3836 if (!AddrMode.BaseGV) {
3837 AddrMode.BaseGV = GV;
3838 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3840 AddrMode.BaseGV = nullptr;
3842 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3843 ExtAddrMode BackupAddrMode = AddrMode;
3844 unsigned OldSize = AddrModeInsts.size();
3846 // Check to see if it is possible to fold this operation.
3847 bool MovedAway = false;
3848 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
3849 // This instruction may have been moved away. If so, there is nothing
3853 // Okay, it's possible to fold this. Check to see if it is actually
3854 // *profitable* to do so. We use a simple cost model to avoid increasing
3855 // register pressure too much.
3856 if (I->hasOneUse() ||
3857 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
3858 AddrModeInsts.push_back(I);
3862 // It isn't profitable to do this, roll back.
3863 //cerr << "NOT FOLDING: " << *I;
3864 AddrMode = BackupAddrMode;
3865 AddrModeInsts.resize(OldSize);
3866 TPT.rollback(LastKnownGood);
3868 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
3869 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
3871 TPT.rollback(LastKnownGood);
3872 } else if (isa<ConstantPointerNull>(Addr)) {
3873 // Null pointer gets folded without affecting the addressing mode.
3877 // Worse case, the target should support [reg] addressing modes. :)
3878 if (!AddrMode.HasBaseReg) {
3879 AddrMode.HasBaseReg = true;
3880 AddrMode.BaseReg = Addr;
3881 // Still check for legality in case the target supports [imm] but not [i+r].
3882 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3884 AddrMode.HasBaseReg = false;
3885 AddrMode.BaseReg = nullptr;
3888 // If the base register is already taken, see if we can do [r+r].
3889 if (AddrMode.Scale == 0) {
3891 AddrMode.ScaledReg = Addr;
3892 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3895 AddrMode.ScaledReg = nullptr;
3898 TPT.rollback(LastKnownGood);
3902 /// Check to see if all uses of OpVal by the specified inline asm call are due
3903 /// to memory operands. If so, return true, otherwise return false.
3904 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
3905 const TargetLowering &TLI,
3906 const TargetRegisterInfo &TRI) {
3907 const Function *F = CI->getFunction();
3908 TargetLowering::AsmOperandInfoVector TargetConstraints =
3909 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
3910 ImmutableCallSite(CI));
3912 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3913 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3915 // Compute the constraint code and ConstraintType to use.
3916 TLI.ComputeConstraintToUse(OpInfo, SDValue());
3918 // If this asm operand is our Value*, and if it isn't an indirect memory
3919 // operand, we can't fold it!
3920 if (OpInfo.CallOperandVal == OpVal &&
3921 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3922 !OpInfo.isIndirect))
3929 // Max number of memory uses to look at before aborting the search to conserve
3931 static constexpr int MaxMemoryUsesToScan = 20;
3933 /// Recursively walk all the uses of I until we find a memory use.
3934 /// If we find an obviously non-foldable instruction, return true.
3935 /// Add the ultimately found memory instructions to MemoryUses.
3936 static bool FindAllMemoryUses(
3938 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3939 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
3940 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
3941 // If we already considered this instruction, we're done.
3942 if (!ConsideredInsts.insert(I).second)
3945 // If this is an obviously unfoldable instruction, bail out.
3946 if (!MightBeFoldableInst(I))
3949 const bool OptSize = I->getFunction()->optForSize();
3951 // Loop over all the uses, recursively processing them.
3952 for (Use &U : I->uses()) {
3953 // Conservatively return true if we're seeing a large number or a deep chain
3954 // of users. This avoids excessive compilation times in pathological cases.
3955 if (SeenInsts++ >= MaxMemoryUsesToScan)
3958 Instruction *UserI = cast<Instruction>(U.getUser());
3959 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3960 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
3964 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3965 unsigned opNo = U.getOperandNo();
3966 if (opNo != StoreInst::getPointerOperandIndex())
3967 return true; // Storing addr, not into addr.
3968 MemoryUses.push_back(std::make_pair(SI, opNo));
3972 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
3973 unsigned opNo = U.getOperandNo();
3974 if (opNo != AtomicRMWInst::getPointerOperandIndex())
3975 return true; // Storing addr, not into addr.
3976 MemoryUses.push_back(std::make_pair(RMW, opNo));
3980 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
3981 unsigned opNo = U.getOperandNo();
3982 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
3983 return true; // Storing addr, not into addr.
3984 MemoryUses.push_back(std::make_pair(CmpX, opNo));
3988 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
3989 // If this is a cold call, we can sink the addressing calculation into
3990 // the cold path. See optimizeCallInst
3991 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3994 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3995 if (!IA) return true;
3997 // If this is a memory operand, we're cool, otherwise bail out.
3998 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
4003 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4011 /// Return true if Val is already known to be live at the use site that we're
4012 /// folding it into. If so, there is no cost to include it in the addressing
4013 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4014 /// instruction already.
4015 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4016 Value *KnownLive2) {
4017 // If Val is either of the known-live values, we know it is live!
4018 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4021 // All values other than instructions and arguments (e.g. constants) are live.
4022 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4024 // If Val is a constant sized alloca in the entry block, it is live, this is
4025 // true because it is just a reference to the stack/frame pointer, which is
4026 // live for the whole function.
4027 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4028 if (AI->isStaticAlloca())
4031 // Check to see if this value is already used in the memory instruction's
4032 // block. If so, it's already live into the block at the very least, so we
4033 // can reasonably fold it.
4034 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4037 /// It is possible for the addressing mode of the machine to fold the specified
4038 /// instruction into a load or store that ultimately uses it.
4039 /// However, the specified instruction has multiple uses.
4040 /// Given this, it may actually increase register pressure to fold it
4041 /// into the load. For example, consider this code:
4045 /// use(Y) -> nonload/store
4049 /// In this case, Y has multiple uses, and can be folded into the load of Z
4050 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4051 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4052 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4053 /// number of computations either.
4055 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4056 /// X was live across 'load Z' for other reasons, we actually *would* want to
4057 /// fold the addressing mode in the Z case. This would make Y die earlier.
4058 bool AddressingModeMatcher::
4059 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4060 ExtAddrMode &AMAfter) {
4061 if (IgnoreProfitability) return true;
4063 // AMBefore is the addressing mode before this instruction was folded into it,
4064 // and AMAfter is the addressing mode after the instruction was folded. Get
4065 // the set of registers referenced by AMAfter and subtract out those
4066 // referenced by AMBefore: this is the set of values which folding in this
4067 // address extends the lifetime of.
4069 // Note that there are only two potential values being referenced here,
4070 // BaseReg and ScaleReg (global addresses are always available, as are any
4071 // folded immediates).
4072 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4074 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4075 // lifetime wasn't extended by adding this instruction.
4076 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4078 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4079 ScaledReg = nullptr;
4081 // If folding this instruction (and it's subexprs) didn't extend any live
4082 // ranges, we're ok with it.
4083 if (!BaseReg && !ScaledReg)
4086 // If all uses of this instruction can have the address mode sunk into them,
4087 // we can remove the addressing mode and effectively trade one live register
4088 // for another (at worst.) In this context, folding an addressing mode into
4089 // the use is just a particularly nice way of sinking it.
4090 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4091 SmallPtrSet<Instruction*, 16> ConsideredInsts;
4092 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
4093 return false; // Has a non-memory, non-foldable use!
4095 // Now that we know that all uses of this instruction are part of a chain of
4096 // computation involving only operations that could theoretically be folded
4097 // into a memory use, loop over each of these memory operation uses and see
4098 // if they could *actually* fold the instruction. The assumption is that
4099 // addressing modes are cheap and that duplicating the computation involved
4100 // many times is worthwhile, even on a fastpath. For sinking candidates
4101 // (i.e. cold call sites), this serves as a way to prevent excessive code
4102 // growth since most architectures have some reasonable small and fast way to
4103 // compute an effective address. (i.e LEA on x86)
4104 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4105 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4106 Instruction *User = MemoryUses[i].first;
4107 unsigned OpNo = MemoryUses[i].second;
4109 // Get the access type of this use. If the use isn't a pointer, we don't
4110 // know what it accesses.
4111 Value *Address = User->getOperand(OpNo);
4112 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4115 Type *AddressAccessTy = AddrTy->getElementType();
4116 unsigned AS = AddrTy->getAddressSpace();
4118 // Do a match against the root of this address, ignoring profitability. This
4119 // will tell us if the addressing mode for the memory operation will
4120 // *actually* cover the shared instruction.
4122 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4123 TPT.getRestorationPoint();
4124 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4125 AddressAccessTy, AS,
4126 MemoryInst, Result, InsertedInsts,
4127 PromotedInsts, TPT);
4128 Matcher.IgnoreProfitability = true;
4129 bool Success = Matcher.matchAddr(Address, 0);
4130 (void)Success; assert(Success && "Couldn't select *anything*?");
4132 // The match was to check the profitability, the changes made are not
4133 // part of the original matcher. Therefore, they should be dropped
4134 // otherwise the original matcher will not present the right state.
4135 TPT.rollback(LastKnownGood);
4137 // If the match didn't cover I, then it won't be shared by it.
4138 if (!is_contained(MatchedAddrModeInsts, I))
4141 MatchedAddrModeInsts.clear();
4147 /// Return true if the specified values are defined in a
4148 /// different basic block than BB.
4149 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4150 if (Instruction *I = dyn_cast<Instruction>(V))
4151 return I->getParent() != BB;
4155 /// Sink addressing mode computation immediate before MemoryInst if doing so
4156 /// can be done without increasing register pressure. The need for the
4157 /// register pressure constraint means this can end up being an all or nothing
4158 /// decision for all uses of the same addressing computation.
4160 /// Load and Store Instructions often have addressing modes that can do
4161 /// significant amounts of computation. As such, instruction selection will try
4162 /// to get the load or store to do as much computation as possible for the
4163 /// program. The problem is that isel can only see within a single block. As
4164 /// such, we sink as much legal addressing mode work into the block as possible.
4166 /// This method is used to optimize both load/store and inline asms with memory
4167 /// operands. It's also used to sink addressing computations feeding into cold
4168 /// call sites into their (cold) basic block.
4170 /// The motivation for handling sinking into cold blocks is that doing so can
4171 /// both enable other address mode sinking (by satisfying the register pressure
4172 /// constraint above), and reduce register pressure globally (by removing the
4173 /// addressing mode computation from the fast path entirely.).
4174 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4175 Type *AccessTy, unsigned AddrSpace) {
4178 // Try to collapse single-value PHI nodes. This is necessary to undo
4179 // unprofitable PRE transformations.
4180 SmallVector<Value*, 8> worklist;
4181 SmallPtrSet<Value*, 16> Visited;
4182 worklist.push_back(Addr);
4184 // Use a worklist to iteratively look through PHI and select nodes, and
4185 // ensure that the addressing mode obtained from the non-PHI/select roots of
4186 // the graph are compatible.
4187 bool PhiOrSelectSeen = false;
4188 SmallVector<Instruction*, 16> AddrModeInsts;
4189 const SimplifyQuery SQ(*DL, TLInfo);
4190 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
4191 TypePromotionTransaction TPT(RemovedInsts);
4192 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4193 TPT.getRestorationPoint();
4194 while (!worklist.empty()) {
4195 Value *V = worklist.back();
4196 worklist.pop_back();
4198 // We allow traversing cyclic Phi nodes.
4199 // In case of success after this loop we ensure that traversing through
4200 // Phi nodes ends up with all cases to compute address of the form
4201 // BaseGV + Base + Scale * Index + Offset
4202 // where Scale and Offset are constans and BaseGV, Base and Index
4203 // are exactly the same Values in all cases.
4204 // It means that BaseGV, Scale and Offset dominate our memory instruction
4205 // and have the same value as they had in address computation represented
4206 // as Phi. So we can safely sink address computation to memory instruction.
4207 if (!Visited.insert(V).second)
4210 // For a PHI node, push all of its incoming values.
4211 if (PHINode *P = dyn_cast<PHINode>(V)) {
4212 for (Value *IncValue : P->incoming_values())
4213 worklist.push_back(IncValue);
4214 PhiOrSelectSeen = true;
4217 // Similar for select.
4218 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4219 worklist.push_back(SI->getFalseValue());
4220 worklist.push_back(SI->getTrueValue());
4221 PhiOrSelectSeen = true;
4225 // For non-PHIs, determine the addressing mode being computed. Note that
4226 // the result may differ depending on what other uses our candidate
4227 // addressing instructions might have.
4228 AddrModeInsts.clear();
4229 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4230 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4231 InsertedInsts, PromotedInsts, TPT);
4232 NewAddrMode.OriginalValue = V;
4234 if (!AddrModes.addNewAddrMode(NewAddrMode))
4238 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4239 // or we have multiple but either couldn't combine them or combining them
4240 // wouldn't do anything useful, bail out now.
4241 if (!AddrModes.combineAddrModes()) {
4242 TPT.rollback(LastKnownGood);
4247 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4248 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4250 // If all the instructions matched are already in this BB, don't do anything.
4251 // If we saw a Phi node then it is not local definitely, and if we saw a select
4252 // then we want to push the address calculation past it even if it's already
4254 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
4255 return IsNonLocalValue(V, MemoryInst->getParent());
4257 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
4261 // Insert this computation right after this user. Since our caller is
4262 // scanning from the top of the BB to the bottom, reuse of the expr are
4263 // guaranteed to happen later.
4264 IRBuilder<> Builder(MemoryInst);
4266 // Now that we determined the addressing expression we want to use and know
4267 // that we have to sink it into this block. Check to see if we have already
4268 // done this for some other load/store instr in this block. If so, reuse
4269 // the computation. Before attempting reuse, check if the address is valid
4270 // as it may have been erased.
4272 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4274 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
4276 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
4277 << *MemoryInst << "\n");
4278 if (SunkAddr->getType() != Addr->getType())
4279 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4280 } else if (AddrSinkUsingGEPs ||
4281 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
4282 SubtargetInfo->useAA())) {
4283 // By default, we use the GEP-based method when AA is used later. This
4284 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4285 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4286 << *MemoryInst << "\n");
4287 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4288 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4290 // First, find the pointer.
4291 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4292 ResultPtr = AddrMode.BaseReg;
4293 AddrMode.BaseReg = nullptr;
4296 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4297 // We can't add more than one pointer together, nor can we scale a
4298 // pointer (both of which seem meaningless).
4299 if (ResultPtr || AddrMode.Scale != 1)
4302 ResultPtr = AddrMode.ScaledReg;
4306 // It is only safe to sign extend the BaseReg if we know that the math
4307 // required to create it did not overflow before we extend it. Since
4308 // the original IR value was tossed in favor of a constant back when
4309 // the AddrMode was created we need to bail out gracefully if widths
4310 // do not match instead of extending it.
4312 // (See below for code to add the scale.)
4313 if (AddrMode.Scale) {
4314 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4315 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4316 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4320 if (AddrMode.BaseGV) {
4324 ResultPtr = AddrMode.BaseGV;
4327 // If the real base value actually came from an inttoptr, then the matcher
4328 // will look through it and provide only the integer value. In that case,
4330 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4331 if (!ResultPtr && AddrMode.BaseReg) {
4332 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4334 AddrMode.BaseReg = nullptr;
4335 } else if (!ResultPtr && AddrMode.Scale == 1) {
4336 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4343 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4344 SunkAddr = Constant::getNullValue(Addr->getType());
4345 } else if (!ResultPtr) {
4349 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4350 Type *I8Ty = Builder.getInt8Ty();
4352 // Start with the base register. Do this first so that subsequent address
4353 // matching finds it last, which will prevent it from trying to match it
4354 // as the scaled value in case it happens to be a mul. That would be
4355 // problematic if we've sunk a different mul for the scale, because then
4356 // we'd end up sinking both muls.
4357 if (AddrMode.BaseReg) {
4358 Value *V = AddrMode.BaseReg;
4359 if (V->getType() != IntPtrTy)
4360 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4365 // Add the scale value.
4366 if (AddrMode.Scale) {
4367 Value *V = AddrMode.ScaledReg;
4368 if (V->getType() == IntPtrTy) {
4371 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4372 cast<IntegerType>(V->getType())->getBitWidth() &&
4373 "We can't transform if ScaledReg is too narrow");
4374 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4377 if (AddrMode.Scale != 1)
4378 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4381 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4386 // Add in the Base Offset if present.
4387 if (AddrMode.BaseOffs) {
4388 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4390 // We need to add this separately from the scale above to help with
4391 // SDAG consecutive load/store merging.
4392 if (ResultPtr->getType() != I8PtrTy)
4393 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4394 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4401 SunkAddr = ResultPtr;
4403 if (ResultPtr->getType() != I8PtrTy)
4404 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4405 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4408 if (SunkAddr->getType() != Addr->getType())
4409 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4412 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4413 // non-integral pointers, so in that case bail out now.
4414 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4415 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4416 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4417 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4418 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4419 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4420 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4422 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4425 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4426 << *MemoryInst << "\n");
4427 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4428 Value *Result = nullptr;
4430 // Start with the base register. Do this first so that subsequent address
4431 // matching finds it last, which will prevent it from trying to match it
4432 // as the scaled value in case it happens to be a mul. That would be
4433 // problematic if we've sunk a different mul for the scale, because then
4434 // we'd end up sinking both muls.
4435 if (AddrMode.BaseReg) {
4436 Value *V = AddrMode.BaseReg;
4437 if (V->getType()->isPointerTy())
4438 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4439 if (V->getType() != IntPtrTy)
4440 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4444 // Add the scale value.
4445 if (AddrMode.Scale) {
4446 Value *V = AddrMode.ScaledReg;
4447 if (V->getType() == IntPtrTy) {
4449 } else if (V->getType()->isPointerTy()) {
4450 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4451 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4452 cast<IntegerType>(V->getType())->getBitWidth()) {
4453 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4455 // It is only safe to sign extend the BaseReg if we know that the math
4456 // required to create it did not overflow before we extend it. Since
4457 // the original IR value was tossed in favor of a constant back when
4458 // the AddrMode was created we need to bail out gracefully if widths
4459 // do not match instead of extending it.
4460 Instruction *I = dyn_cast_or_null<Instruction>(Result);
4461 if (I && (Result != AddrMode.BaseReg))
4462 I->eraseFromParent();
4465 if (AddrMode.Scale != 1)
4466 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4469 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4474 // Add in the BaseGV if present.
4475 if (AddrMode.BaseGV) {
4476 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4478 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4483 // Add in the Base Offset if present.
4484 if (AddrMode.BaseOffs) {
4485 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4487 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4493 SunkAddr = Constant::getNullValue(Addr->getType());
4495 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
4498 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
4499 // Store the newly computed address into the cache. In the case we reused a
4500 // value, this should be idempotent.
4501 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
4503 // If we have no uses, recursively delete the value and all dead instructions
4505 if (Repl->use_empty()) {
4506 // This can cause recursive deletion, which can invalidate our iterator.
4507 // Use a WeakTrackingVH to hold onto it in case this happens.
4508 Value *CurValue = &*CurInstIterator;
4509 WeakTrackingVH IterHandle(CurValue);
4510 BasicBlock *BB = CurInstIterator->getParent();
4512 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
4514 if (IterHandle != CurValue) {
4515 // If the iterator instruction was recursively deleted, start over at the
4516 // start of the block.
4517 CurInstIterator = BB->begin();
4525 /// If there are any memory operands, use OptimizeMemoryInst to sink their
4526 /// address computing into the block when possible / profitable.
4527 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
4528 bool MadeChange = false;
4530 const TargetRegisterInfo *TRI =
4531 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
4532 TargetLowering::AsmOperandInfoVector TargetConstraints =
4533 TLI->ParseConstraints(*DL, TRI, CS);
4535 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4536 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4538 // Compute the constraint code and ConstraintType to use.
4539 TLI->ComputeConstraintToUse(OpInfo, SDValue());
4541 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4542 OpInfo.isIndirect) {
4543 Value *OpVal = CS->getArgOperand(ArgNo++);
4544 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
4545 } else if (OpInfo.Type == InlineAsm::isInput)
4552 /// \brief Check if all the uses of \p Val are equivalent (or free) zero or
4553 /// sign extensions.
4554 static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4555 assert(!Val->use_empty() && "Input must have at least one use");
4556 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
4557 bool IsSExt = isa<SExtInst>(FirstUser);
4558 Type *ExtTy = FirstUser->getType();
4559 for (const User *U : Val->users()) {
4560 const Instruction *UI = cast<Instruction>(U);
4561 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4563 Type *CurTy = UI->getType();
4564 // Same input and output types: Same instruction after CSE.
4568 // If IsSExt is true, we are in this situation:
4570 // b = sext ty1 a to ty2
4571 // c = sext ty1 a to ty3
4572 // Assuming ty2 is shorter than ty3, this could be turned into:
4574 // b = sext ty1 a to ty2
4575 // c = sext ty2 b to ty3
4576 // However, the last sext is not free.
4580 // This is a ZExt, maybe this is free to extend from one type to another.
4581 // In that case, we would not account for a different use.
4584 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4585 CurTy->getScalarType()->getIntegerBitWidth()) {
4593 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4596 // All uses are the same or can be derived from one another for free.
4600 /// \brief Try to speculatively promote extensions in \p Exts and continue
4601 /// promoting through newly promoted operands recursively as far as doing so is
4602 /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4603 /// When some promotion happened, \p TPT contains the proper state to revert
4606 /// \return true if some promotion happened, false otherwise.
4607 bool CodeGenPrepare::tryToPromoteExts(
4608 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4609 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4610 unsigned CreatedInstsCost) {
4611 bool Promoted = false;
4613 // Iterate over all the extensions to try to promote them.
4614 for (auto I : Exts) {
4615 // Early check if we directly have ext(load).
4616 if (isa<LoadInst>(I->getOperand(0))) {
4617 ProfitablyMovedExts.push_back(I);
4621 // Check whether or not we want to do any promotion. The reason we have
4622 // this check inside the for loop is to catch the case where an extension
4623 // is directly fed by a load because in such case the extension can be moved
4624 // up without any promotion on its operands.
4625 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4628 // Get the action to perform the promotion.
4629 TypePromotionHelper::Action TPH =
4630 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
4631 // Check if we can promote.
4633 // Save the current extension as we cannot move up through its operand.
4634 ProfitablyMovedExts.push_back(I);
4638 // Save the current state.
4639 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4640 TPT.getRestorationPoint();
4641 SmallVector<Instruction *, 4> NewExts;
4642 unsigned NewCreatedInstsCost = 0;
4643 unsigned ExtCost = !TLI->isExtFree(I);
4645 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4646 &NewExts, nullptr, *TLI);
4647 assert(PromotedVal &&
4648 "TypePromotionHelper should have filtered out those cases");
4650 // We would be able to merge only one extension in a load.
4651 // Therefore, if we have more than 1 new extension we heuristically
4652 // cut this search path, because it means we degrade the code quality.
4653 // With exactly 2, the transformation is neutral, because we will merge
4654 // one extension but leave one. However, we optimistically keep going,
4655 // because the new extension may be removed too.
4656 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4657 // FIXME: It would be possible to propagate a negative value instead of
4658 // conservatively ceiling it to 0.
4659 TotalCreatedInstsCost =
4660 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
4661 if (!StressExtLdPromotion &&
4662 (TotalCreatedInstsCost > 1 ||
4663 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
4664 // This promotion is not profitable, rollback to the previous state, and
4665 // save the current extension in ProfitablyMovedExts as the latest
4666 // speculative promotion turned out to be unprofitable.
4667 TPT.rollback(LastKnownGood);
4668 ProfitablyMovedExts.push_back(I);
4671 // Continue promoting NewExts as far as doing so is profitable.
4672 SmallVector<Instruction *, 2> NewlyMovedExts;
4673 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4674 bool NewPromoted = false;
4675 for (auto ExtInst : NewlyMovedExts) {
4676 Instruction *MovedExt = cast<Instruction>(ExtInst);
4677 Value *ExtOperand = MovedExt->getOperand(0);
4678 // If we have reached to a load, we need this extra profitability check
4679 // as it could potentially be merged into an ext(load).
4680 if (isa<LoadInst>(ExtOperand) &&
4681 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4682 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4685 ProfitablyMovedExts.push_back(MovedExt);
4689 // If none of speculative promotions for NewExts is profitable, rollback
4690 // and save the current extension (I) as the last profitable extension.
4692 TPT.rollback(LastKnownGood);
4693 ProfitablyMovedExts.push_back(I);
4696 // The promotion is profitable.
4702 /// Merging redundant sexts when one is dominating the other.
4703 bool CodeGenPrepare::mergeSExts(Function &F) {
4704 DominatorTree DT(F);
4705 bool Changed = false;
4706 for (auto &Entry : ValToSExtendedUses) {
4707 SExts &Insts = Entry.second;
4709 for (Instruction *Inst : Insts) {
4710 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4711 Inst->getOperand(0) != Entry.first)
4713 bool inserted = false;
4714 for (auto &Pt : CurPts) {
4715 if (DT.dominates(Inst, Pt)) {
4716 Pt->replaceAllUsesWith(Inst);
4717 RemovedInsts.insert(Pt);
4718 Pt->removeFromParent();
4724 if (!DT.dominates(Pt, Inst))
4725 // Give up if we need to merge in a common dominator as the
4726 // expermients show it is not profitable.
4728 Inst->replaceAllUsesWith(Pt);
4729 RemovedInsts.insert(Inst);
4730 Inst->removeFromParent();
4736 CurPts.push_back(Inst);
4742 /// Return true, if an ext(load) can be formed from an extension in
4744 bool CodeGenPrepare::canFormExtLd(
4745 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4746 Instruction *&Inst, bool HasPromoted) {
4747 for (auto *MovedExtInst : MovedExts) {
4748 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4749 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4750 Inst = MovedExtInst;
4757 // If they're already in the same block, there's nothing to do.
4758 // Make the cheap checks first if we did not promote.
4759 // If we promoted, we need to check if it is indeed profitable.
4760 if (!HasPromoted && LI->getParent() == Inst->getParent())
4763 return TLI->isExtLoad(LI, Inst, *DL);
4766 /// Move a zext or sext fed by a load into the same basic block as the load,
4767 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
4768 /// extend into the load.
4772 /// %ld = load i32* %addr
4773 /// %add = add nuw i32 %ld, 4
4774 /// %zext = zext i32 %add to i64
4778 /// %ld = load i32* %addr
4779 /// %zext = zext i32 %ld to i64
4780 /// %add = add nuw i64 %zext, 4
4782 /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4783 /// allow us to match zext(load i32*) to i64.
4785 /// Also, try to promote the computations used to obtain a sign extended
4786 /// value used into memory accesses.
4789 /// a = add nsw i32 b, 3
4790 /// d = sext i32 a to i64
4791 /// e = getelementptr ..., i64 d
4795 /// f = sext i32 b to i64
4796 /// a = add nsw i64 f, 3
4797 /// e = getelementptr ..., i64 a
4800 /// \p Inst[in/out] the extension may be modified during the process if some
4801 /// promotions apply.
4802 bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4803 // ExtLoad formation and address type promotion infrastructure requires TLI to
4808 bool AllowPromotionWithoutCommonHeader = false;
4809 /// See if it is an interesting sext operations for the address type
4810 /// promotion before trying to promote it, e.g., the ones with the right
4811 /// type and used in memory accesses.
4812 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4813 *Inst, AllowPromotionWithoutCommonHeader);
4814 TypePromotionTransaction TPT(RemovedInsts);
4815 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4816 TPT.getRestorationPoint();
4817 SmallVector<Instruction *, 1> Exts;
4818 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4819 Exts.push_back(Inst);
4821 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
4823 // Look for a load being extended.
4824 LoadInst *LI = nullptr;
4825 Instruction *ExtFedByLoad;
4827 // Try to promote a chain of computation if it allows to form an extended
4829 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4830 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4832 // Move the extend into the same block as the load
4833 ExtFedByLoad->moveAfter(LI);
4834 // CGP does not check if the zext would be speculatively executed when moved
4835 // to the same basic block as the load. Preserving its original location
4836 // would pessimize the debugging experience, as well as negatively impact
4837 // the quality of sample pgo. We don't want to use "line 0" as that has a
4838 // size cost in the line-table section and logically the zext can be seen as
4839 // part of the load. Therefore we conservatively reuse the same debug
4840 // location for the load and the zext.
4841 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4843 Inst = ExtFedByLoad;
4847 // Continue promoting SExts if known as considerable depending on targets.
4848 if (ATPConsiderable &&
4849 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4850 HasPromoted, TPT, SpeculativelyMovedExts))
4853 TPT.rollback(LastKnownGood);
4857 // Perform address type promotion if doing so is profitable.
4858 // If AllowPromotionWithoutCommonHeader == false, we should find other sext
4859 // instructions that sign extended the same initial value. However, if
4860 // AllowPromotionWithoutCommonHeader == true, we expect promoting the
4861 // extension is just profitable.
4862 bool CodeGenPrepare::performAddressTypePromotion(
4863 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4864 bool HasPromoted, TypePromotionTransaction &TPT,
4865 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4866 bool Promoted = false;
4867 SmallPtrSet<Instruction *, 1> UnhandledExts;
4868 bool AllSeenFirst = true;
4869 for (auto I : SpeculativelyMovedExts) {
4870 Value *HeadOfChain = I->getOperand(0);
4871 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4872 SeenChainsForSExt.find(HeadOfChain);
4873 // If there is an unhandled SExt which has the same header, try to promote
4875 if (AlreadySeen != SeenChainsForSExt.end()) {
4876 if (AlreadySeen->second != nullptr)
4877 UnhandledExts.insert(AlreadySeen->second);
4878 AllSeenFirst = false;
4882 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4883 SpeculativelyMovedExts.size() == 1)) {
4887 for (auto I : SpeculativelyMovedExts) {
4888 Value *HeadOfChain = I->getOperand(0);
4889 SeenChainsForSExt[HeadOfChain] = nullptr;
4890 ValToSExtendedUses[HeadOfChain].push_back(I);
4892 // Update Inst as promotion happen.
4893 Inst = SpeculativelyMovedExts.pop_back_val();
4895 // This is the first chain visited from the header, keep the current chain
4896 // as unhandled. Defer to promote this until we encounter another SExt
4897 // chain derived from the same header.
4898 for (auto I : SpeculativelyMovedExts) {
4899 Value *HeadOfChain = I->getOperand(0);
4900 SeenChainsForSExt[HeadOfChain] = Inst;
4905 if (!AllSeenFirst && !UnhandledExts.empty())
4906 for (auto VisitedSExt : UnhandledExts) {
4907 if (RemovedInsts.count(VisitedSExt))
4909 TypePromotionTransaction TPT(RemovedInsts);
4910 SmallVector<Instruction *, 1> Exts;
4911 SmallVector<Instruction *, 2> Chains;
4912 Exts.push_back(VisitedSExt);
4913 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4917 for (auto I : Chains) {
4918 Value *HeadOfChain = I->getOperand(0);
4919 // Mark this as handled.
4920 SeenChainsForSExt[HeadOfChain] = nullptr;
4921 ValToSExtendedUses[HeadOfChain].push_back(I);
4927 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
4928 BasicBlock *DefBB = I->getParent();
4930 // If the result of a {s|z}ext and its source are both live out, rewrite all
4931 // other uses of the source with result of extension.
4932 Value *Src = I->getOperand(0);
4933 if (Src->hasOneUse())
4936 // Only do this xform if truncating is free.
4937 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
4940 // Only safe to perform the optimization if the source is also defined in
4942 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
4945 bool DefIsLiveOut = false;
4946 for (User *U : I->users()) {
4947 Instruction *UI = cast<Instruction>(U);
4949 // Figure out which BB this ext is used in.
4950 BasicBlock *UserBB = UI->getParent();
4951 if (UserBB == DefBB) continue;
4952 DefIsLiveOut = true;
4958 // Make sure none of the uses are PHI nodes.
4959 for (User *U : Src->users()) {
4960 Instruction *UI = cast<Instruction>(U);
4961 BasicBlock *UserBB = UI->getParent();
4962 if (UserBB == DefBB) continue;
4963 // Be conservative. We don't want this xform to end up introducing
4964 // reloads just before load / store instructions.
4965 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
4969 // InsertedTruncs - Only insert one trunc in each block once.
4970 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4972 bool MadeChange = false;
4973 for (Use &U : Src->uses()) {
4974 Instruction *User = cast<Instruction>(U.getUser());
4976 // Figure out which BB this ext is used in.
4977 BasicBlock *UserBB = User->getParent();
4978 if (UserBB == DefBB) continue;
4980 // Both src and def are live in this block. Rewrite the use.
4981 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4983 if (!InsertedTrunc) {
4984 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
4985 assert(InsertPt != UserBB->end());
4986 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
4987 InsertedInsts.insert(InsertedTrunc);
4990 // Replace a use of the {s|z}ext source with a use of the result.
4999 // Find loads whose uses only use some of the loaded value's bits. Add an "and"
5000 // just after the load if the target can fold this into one extload instruction,
5001 // with the hope of eliminating some of the other later "and" instructions using
5002 // the loaded value. "and"s that are made trivially redundant by the insertion
5003 // of the new "and" are removed by this function, while others (e.g. those whose
5004 // path from the load goes through a phi) are left for isel to potentially
5037 // becomes (after a call to optimizeLoadExt for each load):
5041 // x1' = and x1, 0xff
5045 // x2' = and x2, 0xff
5050 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5051 if (!Load->isSimple() ||
5052 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5055 // Skip loads we've already transformed.
5056 if (Load->hasOneUse() &&
5057 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5060 // Look at all uses of Load, looking through phis, to determine how many bits
5061 // of the loaded value are needed.
5062 SmallVector<Instruction *, 8> WorkList;
5063 SmallPtrSet<Instruction *, 16> Visited;
5064 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5065 for (auto *U : Load->users())
5066 WorkList.push_back(cast<Instruction>(U));
5068 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5069 unsigned BitWidth = LoadResultVT.getSizeInBits();
5070 APInt DemandBits(BitWidth, 0);
5071 APInt WidestAndBits(BitWidth, 0);
5073 while (!WorkList.empty()) {
5074 Instruction *I = WorkList.back();
5075 WorkList.pop_back();
5077 // Break use-def graph loops.
5078 if (!Visited.insert(I).second)
5081 // For a PHI node, push all of its users.
5082 if (auto *Phi = dyn_cast<PHINode>(I)) {
5083 for (auto *U : Phi->users())
5084 WorkList.push_back(cast<Instruction>(U));
5088 switch (I->getOpcode()) {
5089 case Instruction::And: {
5090 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5093 APInt AndBits = AndC->getValue();
5094 DemandBits |= AndBits;
5095 // Keep track of the widest and mask we see.
5096 if (AndBits.ugt(WidestAndBits))
5097 WidestAndBits = AndBits;
5098 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5099 AndsToMaybeRemove.push_back(I);
5103 case Instruction::Shl: {
5104 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5107 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5108 DemandBits.setLowBits(BitWidth - ShiftAmt);
5112 case Instruction::Trunc: {
5113 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5114 unsigned TruncBitWidth = TruncVT.getSizeInBits();
5115 DemandBits.setLowBits(TruncBitWidth);
5124 uint32_t ActiveBits = DemandBits.getActiveBits();
5125 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5126 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5127 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5128 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5129 // followed by an AND.
5130 // TODO: Look into removing this restriction by fixing backends to either
5131 // return false for isLoadExtLegal for i1 or have them select this pattern to
5132 // a single instruction.
5134 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5135 // mask, since these are the only ands that will be removed by isel.
5136 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
5137 WidestAndBits != DemandBits)
5140 LLVMContext &Ctx = Load->getType()->getContext();
5141 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5142 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5144 // Reject cases that won't be matched as extloads.
5145 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5146 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5149 IRBuilder<> Builder(Load->getNextNode());
5150 auto *NewAnd = dyn_cast<Instruction>(
5151 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5152 // Mark this instruction as "inserted by CGP", so that other
5153 // optimizations don't touch it.
5154 InsertedInsts.insert(NewAnd);
5156 // Replace all uses of load with new and (except for the use of load in the
5158 Load->replaceAllUsesWith(NewAnd);
5159 NewAnd->setOperand(0, Load);
5161 // Remove any and instructions that are now redundant.
5162 for (auto *And : AndsToMaybeRemove)
5163 // Check that the and mask is the same as the one we decided to put on the
5165 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5166 And->replaceAllUsesWith(NewAnd);
5167 if (&*CurInstIterator == And)
5168 CurInstIterator = std::next(And->getIterator());
5169 And->eraseFromParent();
5177 /// Check if V (an operand of a select instruction) is an expensive instruction
5178 /// that is only used once.
5179 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5180 auto *I = dyn_cast<Instruction>(V);
5181 // If it's safe to speculatively execute, then it should not have side
5182 // effects; therefore, it's safe to sink and possibly *not* execute.
5183 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5184 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5187 /// Returns true if a SelectInst should be turned into an explicit branch.
5188 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5189 const TargetLowering *TLI,
5191 // If even a predictable select is cheap, then a branch can't be cheaper.
5192 if (!TLI->isPredictableSelectExpensive())
5195 // FIXME: This should use the same heuristics as IfConversion to determine
5196 // whether a select is better represented as a branch.
5198 // If metadata tells us that the select condition is obviously predictable,
5199 // then we want to replace the select with a branch.
5200 uint64_t TrueWeight, FalseWeight;
5201 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5202 uint64_t Max = std::max(TrueWeight, FalseWeight);
5203 uint64_t Sum = TrueWeight + FalseWeight;
5205 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5206 if (Probability > TLI->getPredictableBranchThreshold())
5211 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5213 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5214 // comparison condition. If the compare has more than one use, there's
5215 // probably another cmov or setcc around, so it's not worth emitting a branch.
5216 if (!Cmp || !Cmp->hasOneUse())
5219 // If either operand of the select is expensive and only needed on one side
5220 // of the select, we should form a branch.
5221 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5222 sinkSelectOperand(TTI, SI->getFalseValue()))
5228 /// If \p isTrue is true, return the true value of \p SI, otherwise return
5229 /// false value of \p SI. If the true/false value of \p SI is defined by any
5230 /// select instructions in \p Selects, look through the defining select
5231 /// instruction until the true/false value is not defined in \p Selects.
5232 static Value *getTrueOrFalseValue(
5233 SelectInst *SI, bool isTrue,
5234 const SmallPtrSet<const Instruction *, 2> &Selects) {
5237 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5238 DefSI = dyn_cast<SelectInst>(V)) {
5239 assert(DefSI->getCondition() == SI->getCondition() &&
5240 "The condition of DefSI does not match with SI");
5241 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5246 /// If we have a SelectInst that will likely profit from branch prediction,
5247 /// turn it into a branch.
5248 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5249 // Find all consecutive select instructions that share the same condition.
5250 SmallVector<SelectInst *, 2> ASI;
5252 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5253 It != SI->getParent()->end(); ++It) {
5254 SelectInst *I = dyn_cast<SelectInst>(&*It);
5255 if (I && SI->getCondition() == I->getCondition()) {
5262 SelectInst *LastSI = ASI.back();
5263 // Increment the current iterator to skip all the rest of select instructions
5264 // because they will be either "not lowered" or "all lowered" to branch.
5265 CurInstIterator = std::next(LastSI->getIterator());
5267 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5269 // Can we convert the 'select' to CF ?
5270 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5271 SI->getMetadata(LLVMContext::MD_unpredictable))
5274 TargetLowering::SelectSupportKind SelectKind;
5276 SelectKind = TargetLowering::VectorMaskSelect;
5277 else if (SI->getType()->isVectorTy())
5278 SelectKind = TargetLowering::ScalarCondVectorVal;
5280 SelectKind = TargetLowering::ScalarValSelect;
5282 if (TLI->isSelectSupported(SelectKind) &&
5283 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5288 // Transform a sequence like this:
5290 // %cmp = cmp uge i32 %a, %b
5291 // %sel = select i1 %cmp, i32 %c, i32 %d
5295 // %cmp = cmp uge i32 %a, %b
5296 // br i1 %cmp, label %select.true, label %select.false
5298 // br label %select.end
5300 // br label %select.end
5302 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5304 // In addition, we may sink instructions that produce %c or %d from
5305 // the entry block into the destination(s) of the new branch.
5306 // If the true or false blocks do not contain a sunken instruction, that
5307 // block and its branch may be optimized away. In that case, one side of the
5308 // first branch will point directly to select.end, and the corresponding PHI
5309 // predecessor block will be the start block.
5311 // First, we split the block containing the select into 2 blocks.
5312 BasicBlock *StartBlock = SI->getParent();
5313 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
5314 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5316 // Delete the unconditional branch that was just created by the split.
5317 StartBlock->getTerminator()->eraseFromParent();
5319 // These are the new basic blocks for the conditional branch.
5320 // At least one will become an actual new basic block.
5321 BasicBlock *TrueBlock = nullptr;
5322 BasicBlock *FalseBlock = nullptr;
5323 BranchInst *TrueBranch = nullptr;
5324 BranchInst *FalseBranch = nullptr;
5326 // Sink expensive instructions into the conditional blocks to avoid executing
5327 // them speculatively.
5328 for (SelectInst *SI : ASI) {
5329 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5330 if (TrueBlock == nullptr) {
5331 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5332 EndBlock->getParent(), EndBlock);
5333 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5335 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5336 TrueInst->moveBefore(TrueBranch);
5338 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5339 if (FalseBlock == nullptr) {
5340 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5341 EndBlock->getParent(), EndBlock);
5342 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5344 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5345 FalseInst->moveBefore(FalseBranch);
5349 // If there was nothing to sink, then arbitrarily choose the 'false' side
5350 // for a new input value to the PHI.
5351 if (TrueBlock == FalseBlock) {
5352 assert(TrueBlock == nullptr &&
5353 "Unexpected basic block transform while optimizing select");
5355 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5356 EndBlock->getParent(), EndBlock);
5357 BranchInst::Create(EndBlock, FalseBlock);
5360 // Insert the real conditional branch based on the original condition.
5361 // If we did not create a new block for one of the 'true' or 'false' paths
5362 // of the condition, it means that side of the branch goes to the end block
5363 // directly and the path originates from the start block from the point of
5364 // view of the new PHI.
5365 BasicBlock *TT, *FT;
5366 if (TrueBlock == nullptr) {
5369 TrueBlock = StartBlock;
5370 } else if (FalseBlock == nullptr) {
5373 FalseBlock = StartBlock;
5378 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
5380 SmallPtrSet<const Instruction *, 2> INS;
5381 INS.insert(ASI.begin(), ASI.end());
5382 // Use reverse iterator because later select may use the value of the
5383 // earlier select, and we need to propagate value through earlier select
5384 // to get the PHI operand.
5385 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5386 SelectInst *SI = *It;
5387 // The select itself is replaced with a PHI Node.
5388 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5390 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5391 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
5393 SI->replaceAllUsesWith(PN);
5394 SI->eraseFromParent();
5396 ++NumSelectsExpanded;
5399 // Instruct OptimizeBlock to skip to the next block.
5400 CurInstIterator = StartBlock->end();
5404 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5405 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5407 for (unsigned i = 0; i < Mask.size(); ++i) {
5408 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5410 SplatElem = Mask[i];
5416 /// Some targets have expensive vector shifts if the lanes aren't all the same
5417 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5418 /// it's often worth sinking a shufflevector splat down to its use so that
5419 /// codegen can spot all lanes are identical.
5420 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5421 BasicBlock *DefBB = SVI->getParent();
5423 // Only do this xform if variable vector shifts are particularly expensive.
5424 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5427 // We only expect better codegen by sinking a shuffle if we can recognise a
5429 if (!isBroadcastShuffle(SVI))
5432 // InsertedShuffles - Only insert a shuffle in each block once.
5433 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5435 bool MadeChange = false;
5436 for (User *U : SVI->users()) {
5437 Instruction *UI = cast<Instruction>(U);
5439 // Figure out which BB this ext is used in.
5440 BasicBlock *UserBB = UI->getParent();
5441 if (UserBB == DefBB) continue;
5443 // For now only apply this when the splat is used by a shift instruction.
5444 if (!UI->isShift()) continue;
5446 // Everything checks out, sink the shuffle if the user's block doesn't
5447 // already have a copy.
5448 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5450 if (!InsertedShuffle) {
5451 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5452 assert(InsertPt != UserBB->end());
5454 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5455 SVI->getOperand(2), "", &*InsertPt);
5458 UI->replaceUsesOfWith(SVI, InsertedShuffle);
5462 // If we removed all uses, nuke the shuffle.
5463 if (SVI->use_empty()) {
5464 SVI->eraseFromParent();
5471 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5475 Value *Cond = SI->getCondition();
5476 Type *OldType = Cond->getType();
5477 LLVMContext &Context = Cond->getContext();
5478 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5479 unsigned RegWidth = RegType.getSizeInBits();
5481 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5484 // If the register width is greater than the type width, expand the condition
5485 // of the switch instruction and each case constant to the width of the
5486 // register. By widening the type of the switch condition, subsequent
5487 // comparisons (for case comparisons) will not need to be extended to the
5488 // preferred register width, so we will potentially eliminate N-1 extends,
5489 // where N is the number of cases in the switch.
5490 auto *NewType = Type::getIntNTy(Context, RegWidth);
5492 // Zero-extend the switch condition and case constants unless the switch
5493 // condition is a function argument that is already being sign-extended.
5494 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5495 // everything instead.
5496 Instruction::CastOps ExtType = Instruction::ZExt;
5497 if (auto *Arg = dyn_cast<Argument>(Cond))
5498 if (Arg->hasSExtAttr())
5499 ExtType = Instruction::SExt;
5501 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5502 ExtInst->insertBefore(SI);
5503 SI->setCondition(ExtInst);
5504 for (auto Case : SI->cases()) {
5505 APInt NarrowConst = Case.getCaseValue()->getValue();
5506 APInt WideConst = (ExtType == Instruction::ZExt) ?
5507 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5508 Case.setValue(ConstantInt::get(Context, WideConst));
5517 /// \brief Helper class to promote a scalar operation to a vector one.
5518 /// This class is used to move downward extractelement transition.
5520 /// a = vector_op <2 x i32>
5521 /// b = extractelement <2 x i32> a, i32 0
5526 /// a = vector_op <2 x i32>
5527 /// c = vector_op a (equivalent to scalar_op on the related lane)
5528 /// * d = extractelement <2 x i32> c, i32 0
5530 /// Assuming both extractelement and store can be combine, we get rid of the
5532 class VectorPromoteHelper {
5533 /// DataLayout associated with the current module.
5534 const DataLayout &DL;
5536 /// Used to perform some checks on the legality of vector operations.
5537 const TargetLowering &TLI;
5539 /// Used to estimated the cost of the promoted chain.
5540 const TargetTransformInfo &TTI;
5542 /// The transition being moved downwards.
5543 Instruction *Transition;
5545 /// The sequence of instructions to be promoted.
5546 SmallVector<Instruction *, 4> InstsToBePromoted;
5548 /// Cost of combining a store and an extract.
5549 unsigned StoreExtractCombineCost;
5551 /// Instruction that will be combined with the transition.
5552 Instruction *CombineInst = nullptr;
5554 /// \brief The instruction that represents the current end of the transition.
5555 /// Since we are faking the promotion until we reach the end of the chain
5556 /// of computation, we need a way to get the current end of the transition.
5557 Instruction *getEndOfTransition() const {
5558 if (InstsToBePromoted.empty())
5560 return InstsToBePromoted.back();
5563 /// \brief Return the index of the original value in the transition.
5564 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5565 /// c, is at index 0.
5566 unsigned getTransitionOriginalValueIdx() const {
5567 assert(isa<ExtractElementInst>(Transition) &&
5568 "Other kind of transitions are not supported yet");
5572 /// \brief Return the index of the index in the transition.
5573 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5575 unsigned getTransitionIdx() const {
5576 assert(isa<ExtractElementInst>(Transition) &&
5577 "Other kind of transitions are not supported yet");
5581 /// \brief Get the type of the transition.
5582 /// This is the type of the original value.
5583 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5584 /// transition is <2 x i32>.
5585 Type *getTransitionType() const {
5586 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5589 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5590 /// I.e., we have the following sequence:
5591 /// Def = Transition <ty1> a to <ty2>
5592 /// b = ToBePromoted <ty2> Def, ...
5594 /// b = ToBePromoted <ty1> a, ...
5595 /// Def = Transition <ty1> ToBePromoted to <ty2>
5596 void promoteImpl(Instruction *ToBePromoted);
5598 /// \brief Check whether or not it is profitable to promote all the
5599 /// instructions enqueued to be promoted.
5600 bool isProfitableToPromote() {
5601 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5602 unsigned Index = isa<ConstantInt>(ValIdx)
5603 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5605 Type *PromotedType = getTransitionType();
5607 StoreInst *ST = cast<StoreInst>(CombineInst);
5608 unsigned AS = ST->getPointerAddressSpace();
5609 unsigned Align = ST->getAlignment();
5610 // Check if this store is supported.
5611 if (!TLI.allowsMisalignedMemoryAccesses(
5612 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5614 // If this is not supported, there is no way we can combine
5615 // the extract with the store.
5619 // The scalar chain of computation has to pay for the transition
5620 // scalar to vector.
5621 // The vector chain has to account for the combining cost.
5622 uint64_t ScalarCost =
5623 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5624 uint64_t VectorCost = StoreExtractCombineCost;
5625 for (const auto &Inst : InstsToBePromoted) {
5626 // Compute the cost.
5627 // By construction, all instructions being promoted are arithmetic ones.
5628 // Moreover, one argument is a constant that can be viewed as a splat
5630 Value *Arg0 = Inst->getOperand(0);
5631 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5632 isa<ConstantFP>(Arg0);
5633 TargetTransformInfo::OperandValueKind Arg0OVK =
5634 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5635 : TargetTransformInfo::OK_AnyValue;
5636 TargetTransformInfo::OperandValueKind Arg1OVK =
5637 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5638 : TargetTransformInfo::OK_AnyValue;
5639 ScalarCost += TTI.getArithmeticInstrCost(
5640 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5641 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5644 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5645 << ScalarCost << "\nVector: " << VectorCost << '\n');
5646 return ScalarCost > VectorCost;
5649 /// \brief Generate a constant vector with \p Val with the same
5650 /// number of elements as the transition.
5651 /// \p UseSplat defines whether or not \p Val should be replicated
5652 /// across the whole vector.
5653 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5654 /// otherwise we generate a vector with as many undef as possible:
5655 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5656 /// used at the index of the extract.
5657 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5658 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
5660 // If we cannot determine where the constant must be, we have to
5661 // use a splat constant.
5662 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5663 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5664 ExtractIdx = CstVal->getSExtValue();
5669 unsigned End = getTransitionType()->getVectorNumElements();
5671 return ConstantVector::getSplat(End, Val);
5673 SmallVector<Constant *, 4> ConstVec;
5674 UndefValue *UndefVal = UndefValue::get(Val->getType());
5675 for (unsigned Idx = 0; Idx != End; ++Idx) {
5676 if (Idx == ExtractIdx)
5677 ConstVec.push_back(Val);
5679 ConstVec.push_back(UndefVal);
5681 return ConstantVector::get(ConstVec);
5684 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5685 /// in \p Use can trigger undefined behavior.
5686 static bool canCauseUndefinedBehavior(const Instruction *Use,
5687 unsigned OperandIdx) {
5688 // This is not safe to introduce undef when the operand is on
5689 // the right hand side of a division-like instruction.
5690 if (OperandIdx != 1)
5692 switch (Use->getOpcode()) {
5695 case Instruction::SDiv:
5696 case Instruction::UDiv:
5697 case Instruction::SRem:
5698 case Instruction::URem:
5700 case Instruction::FDiv:
5701 case Instruction::FRem:
5702 return !Use->hasNoNaNs();
5704 llvm_unreachable(nullptr);
5708 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5709 const TargetTransformInfo &TTI, Instruction *Transition,
5710 unsigned CombineCost)
5711 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5712 StoreExtractCombineCost(CombineCost) {
5713 assert(Transition && "Do not know how to promote null");
5716 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5717 bool canPromote(const Instruction *ToBePromoted) const {
5718 // We could support CastInst too.
5719 return isa<BinaryOperator>(ToBePromoted);
5722 /// \brief Check if it is profitable to promote \p ToBePromoted
5723 /// by moving downward the transition through.
5724 bool shouldPromote(const Instruction *ToBePromoted) const {
5725 // Promote only if all the operands can be statically expanded.
5726 // Indeed, we do not want to introduce any new kind of transitions.
5727 for (const Use &U : ToBePromoted->operands()) {
5728 const Value *Val = U.get();
5729 if (Val == getEndOfTransition()) {
5730 // If the use is a division and the transition is on the rhs,
5731 // we cannot promote the operation, otherwise we may create a
5732 // division by zero.
5733 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5737 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5738 !isa<ConstantFP>(Val))
5741 // Check that the resulting operation is legal.
5742 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5745 return StressStoreExtract ||
5746 TLI.isOperationLegalOrCustom(
5747 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
5750 /// \brief Check whether or not \p Use can be combined
5751 /// with the transition.
5752 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5753 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5755 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5756 void enqueueForPromotion(Instruction *ToBePromoted) {
5757 InstsToBePromoted.push_back(ToBePromoted);
5760 /// \brief Set the instruction that will be combined with the transition.
5761 void recordCombineInstruction(Instruction *ToBeCombined) {
5762 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5763 CombineInst = ToBeCombined;
5766 /// \brief Promote all the instructions enqueued for promotion if it is
5768 /// \return True if the promotion happened, false otherwise.
5770 // Check if there is something to promote.
5771 // Right now, if we do not have anything to combine with,
5772 // we assume the promotion is not profitable.
5773 if (InstsToBePromoted.empty() || !CombineInst)
5777 if (!StressStoreExtract && !isProfitableToPromote())
5781 for (auto &ToBePromoted : InstsToBePromoted)
5782 promoteImpl(ToBePromoted);
5783 InstsToBePromoted.clear();
5788 } // end anonymous namespace
5790 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5791 // At this point, we know that all the operands of ToBePromoted but Def
5792 // can be statically promoted.
5793 // For Def, we need to use its parameter in ToBePromoted:
5794 // b = ToBePromoted ty1 a
5795 // Def = Transition ty1 b to ty2
5796 // Move the transition down.
5797 // 1. Replace all uses of the promoted operation by the transition.
5798 // = ... b => = ... Def.
5799 assert(ToBePromoted->getType() == Transition->getType() &&
5800 "The type of the result of the transition does not match "
5802 ToBePromoted->replaceAllUsesWith(Transition);
5803 // 2. Update the type of the uses.
5804 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5805 Type *TransitionTy = getTransitionType();
5806 ToBePromoted->mutateType(TransitionTy);
5807 // 3. Update all the operands of the promoted operation with promoted
5809 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5810 for (Use &U : ToBePromoted->operands()) {
5811 Value *Val = U.get();
5812 Value *NewVal = nullptr;
5813 if (Val == Transition)
5814 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5815 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5816 isa<ConstantFP>(Val)) {
5817 // Use a splat constant if it is not safe to use undef.
5818 NewVal = getConstantVector(
5819 cast<Constant>(Val),
5820 isa<UndefValue>(Val) ||
5821 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5823 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5825 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5827 Transition->moveAfter(ToBePromoted);
5828 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5831 /// Some targets can do store(extractelement) with one instruction.
5832 /// Try to push the extractelement towards the stores when the target
5833 /// has this feature and this is profitable.
5834 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
5835 unsigned CombineCost = std::numeric_limits<unsigned>::max();
5836 if (DisableStoreExtract || !TLI ||
5837 (!StressStoreExtract &&
5838 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5839 Inst->getOperand(1), CombineCost)))
5842 // At this point we know that Inst is a vector to scalar transition.
5843 // Try to move it down the def-use chain, until:
5844 // - We can combine the transition with its single use
5845 // => we got rid of the transition.
5846 // - We escape the current basic block
5847 // => we would need to check that we are moving it at a cheaper place and
5848 // we do not do that for now.
5849 BasicBlock *Parent = Inst->getParent();
5850 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
5851 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
5852 // If the transition has more than one use, assume this is not going to be
5854 while (Inst->hasOneUse()) {
5855 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5856 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5858 if (ToBePromoted->getParent() != Parent) {
5859 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5860 << ToBePromoted->getParent()->getName()
5861 << ") than the transition (" << Parent->getName() << ").\n");
5865 if (VPH.canCombine(ToBePromoted)) {
5866 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5867 << "will be combined with: " << *ToBePromoted << '\n');
5868 VPH.recordCombineInstruction(ToBePromoted);
5869 bool Changed = VPH.promote();
5870 NumStoreExtractExposed += Changed;
5874 DEBUG(dbgs() << "Try promoting.\n");
5875 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5878 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5880 VPH.enqueueForPromotion(ToBePromoted);
5881 Inst = ToBePromoted;
5886 /// For the instruction sequence of store below, F and I values
5887 /// are bundled together as an i64 value before being stored into memory.
5888 /// Sometimes it is more efficent to generate separate stores for F and I,
5889 /// which can remove the bitwise instructions or sink them to colder places.
5891 /// (store (or (zext (bitcast F to i32) to i64),
5892 /// (shl (zext I to i64), 32)), addr) -->
5893 /// (store F, addr) and (store I, addr+4)
5895 /// Similarly, splitting for other merged store can also be beneficial, like:
5896 /// For pair of {i32, i32}, i64 store --> two i32 stores.
5897 /// For pair of {i32, i16}, i64 store --> two i32 stores.
5898 /// For pair of {i16, i16}, i32 store --> two i16 stores.
5899 /// For pair of {i16, i8}, i32 store --> two i16 stores.
5900 /// For pair of {i8, i8}, i16 store --> two i8 stores.
5902 /// We allow each target to determine specifically which kind of splitting is
5905 /// The store patterns are commonly seen from the simple code snippet below
5906 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5907 /// void goo(const std::pair<int, float> &);
5910 /// goo(std::make_pair(tmp, ftmp));
5914 /// Although we already have similar splitting in DAG Combine, we duplicate
5915 /// it in CodeGenPrepare to catch the case in which pattern is across
5916 /// multiple BBs. The logic in DAG Combine is kept to catch case generated
5917 /// during code expansion.
5918 static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5919 const TargetLowering &TLI) {
5920 // Handle simple but common cases only.
5921 Type *StoreType = SI.getValueOperand()->getType();
5922 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5923 DL.getTypeSizeInBits(StoreType) == 0)
5926 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5927 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5928 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5929 DL.getTypeSizeInBits(SplitStoreType))
5932 // Match the following patterns:
5933 // (store (or (zext LValue to i64),
5934 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5936 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5937 // (zext LValue to i64),
5938 // Expect both operands of OR and the first operand of SHL have only
5940 Value *LValue, *HValue;
5941 if (!match(SI.getValueOperand(),
5942 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5943 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5944 m_SpecificInt(HalfValBitSize))))))
5947 // Check LValue and HValue are int with size less or equal than 32.
5948 if (!LValue->getType()->isIntegerTy() ||
5949 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5950 !HValue->getType()->isIntegerTy() ||
5951 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5954 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5955 // as the input of target query.
5956 auto *LBC = dyn_cast<BitCastInst>(LValue);
5957 auto *HBC = dyn_cast<BitCastInst>(HValue);
5958 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5959 : EVT::getEVT(LValue->getType());
5960 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5961 : EVT::getEVT(HValue->getType());
5962 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5965 // Start to split store.
5966 IRBuilder<> Builder(SI.getContext());
5967 Builder.SetInsertPoint(&SI);
5969 // If LValue/HValue is a bitcast in another BB, create a new one in current
5970 // BB so it may be merged with the splitted stores by dag combiner.
5971 if (LBC && LBC->getParent() != SI.getParent())
5972 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5973 if (HBC && HBC->getParent() != SI.getParent())
5974 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5976 auto CreateSplitStore = [&](Value *V, bool Upper) {
5977 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5978 Value *Addr = Builder.CreateBitCast(
5980 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5982 Addr = Builder.CreateGEP(
5983 SplitStoreType, Addr,
5984 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5985 Builder.CreateAlignedStore(
5986 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5989 CreateSplitStore(LValue, false);
5990 CreateSplitStore(HValue, true);
5992 // Delete the old store.
5993 SI.eraseFromParent();
5997 // Return true if the GEP has two operands, the first operand is of a sequential
5998 // type, and the second operand is a constant.
5999 static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6000 gep_type_iterator I = gep_type_begin(*GEP);
6001 return GEP->getNumOperands() == 2 &&
6003 isa<ConstantInt>(GEP->getOperand(1));
6006 // Try unmerging GEPs to reduce liveness interference (register pressure) across
6007 // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6008 // reducing liveness interference across those edges benefits global register
6009 // allocation. Currently handles only certain cases.
6011 // For example, unmerge %GEPI and %UGEPI as below.
6013 // ---------- BEFORE ----------
6018 // %GEPI = gep %GEPIOp, Idx
6020 // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6021 // (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6022 // (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6025 // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6026 // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6031 // %UGEPI = gep %GEPIOp, UIdx
6033 // ---------------------------
6035 // ---------- AFTER ----------
6037 // ... (same as above)
6038 // (* %GEPI is still alive on the indirectbr edges)
6039 // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6045 // %UGEPI = gep %GEPI, (UIdx-Idx)
6047 // ---------------------------
6049 // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6050 // no longer alive on them.
6052 // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6053 // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6054 // not to disable further simplications and optimizations as a result of GEP
6057 // Note this unmerging may increase the length of the data flow critical path
6058 // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6059 // between the register pressure and the length of data-flow critical
6060 // path. Restricting this to the uncommon IndirectBr case would minimize the
6061 // impact of potentially longer critical path, if any, and the impact on compile
6063 static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6064 const TargetTransformInfo *TTI) {
6065 BasicBlock *SrcBlock = GEPI->getParent();
6066 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6067 // (non-IndirectBr) cases exit early here.
6068 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6070 // Check that GEPI is a simple gep with a single constant index.
6071 if (!GEPSequentialConstIndexed(GEPI))
6073 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6074 // Check that GEPI is a cheap one.
6075 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6076 > TargetTransformInfo::TCC_Basic)
6078 Value *GEPIOp = GEPI->getOperand(0);
6079 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6080 if (!isa<Instruction>(GEPIOp))
6082 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6083 if (GEPIOpI->getParent() != SrcBlock)
6085 // Check that GEP is used outside the block, meaning it's alive on the
6086 // IndirectBr edge(s).
6087 if (find_if(GEPI->users(), [&](User *Usr) {
6088 if (auto *I = dyn_cast<Instruction>(Usr)) {
6089 if (I->getParent() != SrcBlock) {
6094 }) == GEPI->users().end())
6096 // The second elements of the GEP chains to be unmerged.
6097 std::vector<GetElementPtrInst *> UGEPIs;
6098 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6099 // on IndirectBr edges.
6100 for (User *Usr : GEPIOp->users()) {
6101 if (Usr == GEPI) continue;
6102 // Check if Usr is an Instruction. If not, give up.
6103 if (!isa<Instruction>(Usr))
6105 auto *UI = cast<Instruction>(Usr);
6106 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6107 if (UI->getParent() == SrcBlock)
6109 // Check if Usr is a GEP. If not, give up.
6110 if (!isa<GetElementPtrInst>(Usr))
6112 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6113 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6114 // the pointer operand to it. If so, record it in the vector. If not, give
6116 if (!GEPSequentialConstIndexed(UGEPI))
6118 if (UGEPI->getOperand(0) != GEPIOp)
6120 if (GEPIIdx->getType() !=
6121 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6123 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6124 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6125 > TargetTransformInfo::TCC_Basic)
6127 UGEPIs.push_back(UGEPI);
6129 if (UGEPIs.size() == 0)
6131 // Check the materializing cost of (Uidx-Idx).
6132 for (GetElementPtrInst *UGEPI : UGEPIs) {
6133 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6134 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6135 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6136 if (ImmCost > TargetTransformInfo::TCC_Basic)
6139 // Now unmerge between GEPI and UGEPIs.
6140 for (GetElementPtrInst *UGEPI : UGEPIs) {
6141 UGEPI->setOperand(0, GEPI);
6142 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6143 Constant *NewUGEPIIdx =
6144 ConstantInt::get(GEPIIdx->getType(),
6145 UGEPIIdx->getValue() - GEPIIdx->getValue());
6146 UGEPI->setOperand(1, NewUGEPIIdx);
6147 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6148 // inbounds to avoid UB.
6149 if (!GEPI->isInBounds()) {
6150 UGEPI->setIsInBounds(false);
6153 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6154 // alive on IndirectBr edges).
6155 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6156 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6157 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6161 bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
6162 // Bail out if we inserted the instruction to prevent optimizations from
6163 // stepping on each other's toes.
6164 if (InsertedInsts.count(I))
6167 if (PHINode *P = dyn_cast<PHINode>(I)) {
6168 // It is possible for very late stage optimizations (such as SimplifyCFG)
6169 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6170 // trivial PHI, go ahead and zap it here.
6171 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
6172 P->replaceAllUsesWith(V);
6173 P->eraseFromParent();
6180 if (CastInst *CI = dyn_cast<CastInst>(I)) {
6181 // If the source of the cast is a constant, then this should have
6182 // already been constant folded. The only reason NOT to constant fold
6183 // it is if something (e.g. LSR) was careful to place the constant
6184 // evaluation in a block other than then one that uses it (e.g. to hoist
6185 // the address of globals out of a loop). If this is the case, we don't
6186 // want to forward-subst the cast.
6187 if (isa<Constant>(CI->getOperand(0)))
6190 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
6193 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6194 /// Sink a zext or sext into its user blocks if the target type doesn't
6195 /// fit in one register
6197 TLI->getTypeAction(CI->getContext(),
6198 TLI->getValueType(*DL, CI->getType())) ==
6199 TargetLowering::TypeExpandInteger) {
6200 return SinkCast(CI);
6202 bool MadeChange = optimizeExt(I);
6203 return MadeChange | optimizeExtUses(I);
6209 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6210 if (!TLI || !TLI->hasMultipleConditionRegisters())
6211 return OptimizeCmpExpression(CI, TLI);
6213 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6214 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6216 bool Modified = optimizeLoadExt(LI);
6217 unsigned AS = LI->getPointerAddressSpace();
6218 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6224 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6225 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6227 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6229 unsigned AS = SI->getPointerAddressSpace();
6230 return optimizeMemoryInst(I, SI->getOperand(1),
6231 SI->getOperand(0)->getType(), AS);
6236 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6237 unsigned AS = RMW->getPointerAddressSpace();
6238 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6239 RMW->getType(), AS);
6242 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6243 unsigned AS = CmpX->getPointerAddressSpace();
6244 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6245 CmpX->getCompareOperand()->getType(), AS);
6248 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6250 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6251 EnableAndCmpSinking && TLI)
6252 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6254 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6255 BinOp->getOpcode() == Instruction::LShr)) {
6256 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6257 if (TLI && CI && TLI->hasExtractBitsInsn())
6258 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6263 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6264 if (GEPI->hasAllZeroIndices()) {
6265 /// The GEP operand must be a pointer, so must its result -> BitCast
6266 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6267 GEPI->getName(), GEPI);
6268 GEPI->replaceAllUsesWith(NC);
6269 GEPI->eraseFromParent();
6271 optimizeInst(NC, ModifiedDT);
6274 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6280 if (CallInst *CI = dyn_cast<CallInst>(I))
6281 return optimizeCallInst(CI, ModifiedDT);
6283 if (SelectInst *SI = dyn_cast<SelectInst>(I))
6284 return optimizeSelectInst(SI);
6286 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6287 return optimizeShuffleVectorInst(SVI);
6289 if (auto *Switch = dyn_cast<SwitchInst>(I))
6290 return optimizeSwitchInst(Switch);
6292 if (isa<ExtractElementInst>(I))
6293 return optimizeExtractElementInst(I);
6298 /// Given an OR instruction, check to see if this is a bitreverse
6299 /// idiom. If so, insert the new intrinsic and return true.
6300 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6301 const TargetLowering &TLI) {
6302 if (!I.getType()->isIntegerTy() ||
6303 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6304 TLI.getValueType(DL, I.getType(), true)))
6307 SmallVector<Instruction*, 4> Insts;
6308 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
6310 Instruction *LastInst = Insts.back();
6311 I.replaceAllUsesWith(LastInst);
6312 RecursivelyDeleteTriviallyDeadInstructions(&I);
6316 // In this pass we look for GEP and cast instructions that are used
6317 // across basic blocks and rewrite them to improve basic-block-at-a-time
6319 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
6321 bool MadeChange = false;
6323 CurInstIterator = BB.begin();
6324 while (CurInstIterator != BB.end()) {
6325 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6330 bool MadeBitReverse = true;
6331 while (TLI && MadeBitReverse) {
6332 MadeBitReverse = false;
6333 for (auto &I : reverse(BB)) {
6334 if (makeBitReverse(I, *DL, *TLI)) {
6335 MadeBitReverse = MadeChange = true;
6341 MadeChange |= dupRetToEnableTailCallOpts(&BB);
6346 // llvm.dbg.value is far away from the value then iSel may not be able
6347 // handle it properly. iSel will drop llvm.dbg.value if it can not
6348 // find a node corresponding to the value.
6349 bool CodeGenPrepare::placeDbgValues(Function &F) {
6350 bool MadeChange = false;
6351 for (BasicBlock &BB : F) {
6352 Instruction *PrevNonDbgInst = nullptr;
6353 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6354 Instruction *Insn = &*BI++;
6355 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6356 // Leave dbg.values that refer to an alloca alone. These
6357 // intrinsics describe the address of a variable (= the alloca)
6358 // being taken. They should not be moved next to the alloca
6359 // (and to the beginning of the scope), but rather stay close to
6360 // where said address is used.
6361 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6362 PrevNonDbgInst = Insn;
6366 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6367 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6368 // If VI is a phi in a block with an EHPad terminator, we can't insert
6370 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6372 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6373 DVI->removeFromParent();
6374 if (isa<PHINode>(VI))
6375 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6377 DVI->insertAfter(VI);
6386 /// \brief Scale down both weights to fit into uint32_t.
6387 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6388 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6389 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
6390 NewTrue = NewTrue / Scale;
6391 NewFalse = NewFalse / Scale;
6394 /// \brief Some targets prefer to split a conditional branch like:
6396 /// %0 = icmp ne i32 %a, 0
6397 /// %1 = icmp ne i32 %b, 0
6398 /// %or.cond = or i1 %0, %1
6399 /// br i1 %or.cond, label %TrueBB, label %FalseBB
6401 /// into multiple branch instructions like:
6404 /// %0 = icmp ne i32 %a, 0
6405 /// br i1 %0, label %TrueBB, label %bb2
6407 /// %1 = icmp ne i32 %b, 0
6408 /// br i1 %1, label %TrueBB, label %FalseBB
6410 /// This usually allows instruction selection to do even further optimizations
6411 /// and combine the compare with the branch instruction. Currently this is
6412 /// applied for targets which have "cheap" jump instructions.
6414 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6416 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6417 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6420 bool MadeChange = false;
6421 for (auto &BB : F) {
6422 // Does this BB end with the following?
6423 // %cond1 = icmp|fcmp|binary instruction ...
6424 // %cond2 = icmp|fcmp|binary instruction ...
6425 // %cond.or = or|and i1 %cond1, cond2
6426 // br i1 %cond.or label %dest1, label %dest2"
6427 BinaryOperator *LogicOp;
6428 BasicBlock *TBB, *FBB;
6429 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6432 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6433 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6437 Value *Cond1, *Cond2;
6438 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6439 m_OneUse(m_Value(Cond2)))))
6440 Opc = Instruction::And;
6441 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6442 m_OneUse(m_Value(Cond2)))))
6443 Opc = Instruction::Or;
6447 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6448 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6451 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6455 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6456 BB.getParent(), BB.getNextNode());
6458 // Update original basic block by using the first condition directly by the
6459 // branch instruction and removing the no longer needed and/or instruction.
6460 Br1->setCondition(Cond1);
6461 LogicOp->eraseFromParent();
6463 // Depending on the conditon we have to either replace the true or the false
6464 // successor of the original branch instruction.
6465 if (Opc == Instruction::And)
6466 Br1->setSuccessor(0, TmpBB);
6468 Br1->setSuccessor(1, TmpBB);
6470 // Fill in the new basic block.
6471 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6472 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6473 I->removeFromParent();
6474 I->insertBefore(Br2);
6477 // Update PHI nodes in both successors. The original BB needs to be
6478 // replaced in one successor's PHI nodes, because the branch comes now from
6479 // the newly generated BB (NewBB). In the other successor we need to add one
6480 // incoming edge to the PHI nodes, because both branch instructions target
6481 // now the same successor. Depending on the original branch condition
6482 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6483 // we perform the correct update for the PHI nodes.
6484 // This doesn't change the successor order of the just created branch
6485 // instruction (or any other instruction).
6486 if (Opc == Instruction::Or)
6487 std::swap(TBB, FBB);
6489 // Replace the old BB with the new BB.
6490 for (PHINode &PN : TBB->phis()) {
6492 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6493 PN.setIncomingBlock(i, TmpBB);
6496 // Add another incoming edge form the new BB.
6497 for (PHINode &PN : FBB->phis()) {
6498 auto *Val = PN.getIncomingValueForBlock(&BB);
6499 PN.addIncoming(Val, TmpBB);
6502 // Update the branch weights (from SelectionDAGBuilder::
6503 // FindMergedConditions).
6504 if (Opc == Instruction::Or) {
6505 // Codegen X | Y as:
6514 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6515 // The requirement is that
6516 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6517 // = TrueProb for orignal BB.
6518 // Assuming the orignal weights are A and B, one choice is to set BB1's
6519 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6521 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6522 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6523 // TmpBB, but the math is more complicated.
6524 uint64_t TrueWeight, FalseWeight;
6525 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6526 uint64_t NewTrueWeight = TrueWeight;
6527 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6528 scaleWeights(NewTrueWeight, NewFalseWeight);
6529 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6530 .createBranchWeights(TrueWeight, FalseWeight));
6532 NewTrueWeight = TrueWeight;
6533 NewFalseWeight = 2 * FalseWeight;
6534 scaleWeights(NewTrueWeight, NewFalseWeight);
6535 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6536 .createBranchWeights(TrueWeight, FalseWeight));
6539 // Codegen X & Y as:
6547 // This requires creation of TmpBB after CurBB.
6549 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6550 // The requirement is that
6551 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6552 // = FalseProb for orignal BB.
6553 // Assuming the orignal weights are A and B, one choice is to set BB1's
6554 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6556 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6557 uint64_t TrueWeight, FalseWeight;
6558 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6559 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6560 uint64_t NewFalseWeight = FalseWeight;
6561 scaleWeights(NewTrueWeight, NewFalseWeight);
6562 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6563 .createBranchWeights(TrueWeight, FalseWeight));
6565 NewTrueWeight = 2 * TrueWeight;
6566 NewFalseWeight = FalseWeight;
6567 scaleWeights(NewTrueWeight, NewFalseWeight);
6568 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6569 .createBranchWeights(TrueWeight, FalseWeight));
6573 // Note: No point in getting fancy here, since the DT info is never
6574 // available to CodeGenPrepare.
6579 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();