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