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