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