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