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