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