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