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