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