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