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