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