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