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