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