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