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