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