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