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