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