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