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