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