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