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