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