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