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