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