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