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