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