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