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