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