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