191bc56edSDimitry Andric //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
291bc56edSDimitry Andric //
391bc56edSDimitry Andric //                     The LLVM Compiler Infrastructure
491bc56edSDimitry Andric //
591bc56edSDimitry Andric // This file is distributed under the University of Illinois Open Source
691bc56edSDimitry Andric // License. See LICENSE.TXT for details.
791bc56edSDimitry Andric //
891bc56edSDimitry Andric //===----------------------------------------------------------------------===//
991bc56edSDimitry Andric //
1091bc56edSDimitry Andric // This pass munges the code in the input function to better prepare it for
1191bc56edSDimitry Andric // SelectionDAG-based code generation. This works around limitations in it's
1291bc56edSDimitry Andric // basic-block-at-a-time approach. It should eventually be removed.
1391bc56edSDimitry Andric //
1491bc56edSDimitry Andric //===----------------------------------------------------------------------===//
1591bc56edSDimitry Andric 
162cab237bSDimitry Andric #include "llvm/ADT/APInt.h"
172cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
1891bc56edSDimitry Andric #include "llvm/ADT/DenseMap.h"
192cab237bSDimitry Andric #include "llvm/ADT/PointerIntPair.h"
202cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
212cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
222cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
2391bc56edSDimitry Andric #include "llvm/ADT/Statistic.h"
24d88c1a5aSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
25d88c1a5aSDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
262cab237bSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
2791bc56edSDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
283ca95b02SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
29f9448bf3SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
30d88c1a5aSDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
31ff0cc061SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
3239d628a0SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
334ba319b5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
347d523365SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
35d88c1a5aSDimitry Andric #include "llvm/CodeGen/Analysis.h"
362cab237bSDimitry Andric #include "llvm/CodeGen/ISDOpcodes.h"
372cab237bSDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
382cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
39db17bf38SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
402cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
412cab237bSDimitry Andric #include "llvm/CodeGen/ValueTypes.h"
424ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
432cab237bSDimitry Andric #include "llvm/IR/Argument.h"
442cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
452cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
4691bc56edSDimitry Andric #include "llvm/IR/CallSite.h"
472cab237bSDimitry Andric #include "llvm/IR/Constant.h"
4891bc56edSDimitry Andric #include "llvm/IR/Constants.h"
4991bc56edSDimitry Andric #include "llvm/IR/DataLayout.h"
5091bc56edSDimitry Andric #include "llvm/IR/DerivedTypes.h"
5191bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
5291bc56edSDimitry Andric #include "llvm/IR/Function.h"
5391bc56edSDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
542cab237bSDimitry Andric #include "llvm/IR/GlobalValue.h"
552cab237bSDimitry Andric #include "llvm/IR/GlobalVariable.h"
5691bc56edSDimitry Andric #include "llvm/IR/IRBuilder.h"
5791bc56edSDimitry Andric #include "llvm/IR/InlineAsm.h"
582cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
592cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
6091bc56edSDimitry Andric #include "llvm/IR/Instructions.h"
6191bc56edSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
622cab237bSDimitry Andric #include "llvm/IR/Intrinsics.h"
632cab237bSDimitry Andric #include "llvm/IR/LLVMContext.h"
6439d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
652cab237bSDimitry Andric #include "llvm/IR/Module.h"
662cab237bSDimitry Andric #include "llvm/IR/Operator.h"
6791bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h"
68ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
692cab237bSDimitry Andric #include "llvm/IR/Type.h"
702cab237bSDimitry Andric #include "llvm/IR/Use.h"
712cab237bSDimitry Andric #include "llvm/IR/User.h"
722cab237bSDimitry Andric #include "llvm/IR/Value.h"
7391bc56edSDimitry Andric #include "llvm/IR/ValueHandle.h"
7491bc56edSDimitry Andric #include "llvm/IR/ValueMap.h"
7591bc56edSDimitry Andric #include "llvm/Pass.h"
762cab237bSDimitry Andric #include "llvm/Support/BlockFrequency.h"
773ca95b02SDimitry Andric #include "llvm/Support/BranchProbability.h"
782cab237bSDimitry Andric #include "llvm/Support/Casting.h"
7991bc56edSDimitry Andric #include "llvm/Support/CommandLine.h"
802cab237bSDimitry Andric #include "llvm/Support/Compiler.h"
8191bc56edSDimitry Andric #include "llvm/Support/Debug.h"
822cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
834ba319b5SDimitry Andric #include "llvm/Support/MachineValueType.h"
842cab237bSDimitry Andric #include "llvm/Support/MathExtras.h"
8591bc56edSDimitry Andric #include "llvm/Support/raw_ostream.h"
862cab237bSDimitry Andric #include "llvm/Target/TargetMachine.h"
872cab237bSDimitry Andric #include "llvm/Target/TargetOptions.h"
8891bc56edSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
8991bc56edSDimitry Andric #include "llvm/Transforms/Utils/BypassSlowDivision.h"
9039d628a0SDimitry Andric #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
912cab237bSDimitry Andric #include <algorithm>
922cab237bSDimitry Andric #include <cassert>
932cab237bSDimitry Andric #include <cstdint>
942cab237bSDimitry Andric #include <iterator>
952cab237bSDimitry Andric #include <limits>
962cab237bSDimitry Andric #include <memory>
972cab237bSDimitry Andric #include <utility>
982cab237bSDimitry Andric #include <vector>
99f9448bf3SDimitry Andric 
10091bc56edSDimitry Andric using namespace llvm;
10191bc56edSDimitry Andric using namespace llvm::PatternMatch;
10291bc56edSDimitry Andric 
10391bc56edSDimitry Andric #define DEBUG_TYPE "codegenprepare"
10491bc56edSDimitry Andric 
10591bc56edSDimitry Andric STATISTIC(NumBlocksElim, "Number of blocks eliminated");
10691bc56edSDimitry Andric STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
10791bc56edSDimitry Andric STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
10891bc56edSDimitry Andric STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
10991bc56edSDimitry Andric                       "sunken Cmps");
11091bc56edSDimitry Andric STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
11191bc56edSDimitry Andric                        "of sunken Casts");
11291bc56edSDimitry Andric STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
11391bc56edSDimitry Andric                           "computations were sunk");
1142cab237bSDimitry Andric STATISTIC(NumMemoryInstsPhiCreated,
1152cab237bSDimitry Andric           "Number of phis created when address "
1162cab237bSDimitry Andric           "computations were sunk to memory instructions");
1172cab237bSDimitry Andric STATISTIC(NumMemoryInstsSelectCreated,
1182cab237bSDimitry Andric           "Number of select created when address "
1192cab237bSDimitry Andric           "computations were sunk to memory instructions");
12091bc56edSDimitry Andric STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
12191bc56edSDimitry Andric STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
1227d523365SDimitry Andric STATISTIC(NumAndsAdded,
1237d523365SDimitry Andric           "Number of and mask instructions added to form ext loads");
1247d523365SDimitry Andric STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
12591bc56edSDimitry Andric STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
12691bc56edSDimitry Andric STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
12791bc56edSDimitry Andric STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
12839d628a0SDimitry Andric STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
12991bc56edSDimitry Andric 
13091bc56edSDimitry Andric static cl::opt<bool> DisableBranchOpts(
13191bc56edSDimitry Andric   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
13291bc56edSDimitry Andric   cl::desc("Disable branch optimizations in CodeGenPrepare"));
13391bc56edSDimitry Andric 
134ff0cc061SDimitry Andric static cl::opt<bool>
135ff0cc061SDimitry Andric     DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
136ff0cc061SDimitry Andric                   cl::desc("Disable GC optimizations in CodeGenPrepare"));
137ff0cc061SDimitry Andric 
13891bc56edSDimitry Andric static cl::opt<bool> DisableSelectToBranch(
13991bc56edSDimitry Andric   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
14091bc56edSDimitry Andric   cl::desc("Disable select to branch conversion."));
14191bc56edSDimitry Andric 
14291bc56edSDimitry Andric static cl::opt<bool> AddrSinkUsingGEPs(
1437a7e6055SDimitry Andric   "addr-sink-using-gep", cl::Hidden, cl::init(true),
14491bc56edSDimitry Andric   cl::desc("Address sinking in CGP using GEPs."));
14591bc56edSDimitry Andric 
14691bc56edSDimitry Andric static cl::opt<bool> EnableAndCmpSinking(
14791bc56edSDimitry Andric    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
14891bc56edSDimitry Andric    cl::desc("Enable sinkinig and/cmp into branches."));
14991bc56edSDimitry Andric 
15039d628a0SDimitry Andric static cl::opt<bool> DisableStoreExtract(
15139d628a0SDimitry Andric     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
15239d628a0SDimitry Andric     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
15339d628a0SDimitry Andric 
15439d628a0SDimitry Andric static cl::opt<bool> StressStoreExtract(
15539d628a0SDimitry Andric     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
15639d628a0SDimitry Andric     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
15739d628a0SDimitry Andric 
15839d628a0SDimitry Andric static cl::opt<bool> DisableExtLdPromotion(
15939d628a0SDimitry Andric     "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
16039d628a0SDimitry Andric     cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
16139d628a0SDimitry Andric              "CodeGenPrepare"));
16239d628a0SDimitry Andric 
16339d628a0SDimitry Andric static cl::opt<bool> StressExtLdPromotion(
16439d628a0SDimitry Andric     "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
16539d628a0SDimitry Andric     cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
16639d628a0SDimitry Andric              "optimization in CodeGenPrepare"));
16739d628a0SDimitry Andric 
1683ca95b02SDimitry Andric static cl::opt<bool> DisablePreheaderProtect(
1693ca95b02SDimitry Andric     "disable-preheader-prot", cl::Hidden, cl::init(false),
1703ca95b02SDimitry Andric     cl::desc("Disable protection against removing loop preheaders"));
1713ca95b02SDimitry Andric 
172d88c1a5aSDimitry Andric static cl::opt<bool> ProfileGuidedSectionPrefix(
17324d58133SDimitry Andric     "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
174d88c1a5aSDimitry Andric     cl::desc("Use profile info to add section prefix for hot/cold functions"));
175d88c1a5aSDimitry Andric 
176d88c1a5aSDimitry Andric static cl::opt<unsigned> FreqRatioToSkipMerge(
177d88c1a5aSDimitry Andric     "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
178d88c1a5aSDimitry Andric     cl::desc("Skip merging empty blocks if (frequency of empty block) / "
179d88c1a5aSDimitry Andric              "(frequency of destination block) is greater than this ratio"));
180d88c1a5aSDimitry Andric 
181d88c1a5aSDimitry Andric static cl::opt<bool> ForceSplitStore(
182d88c1a5aSDimitry Andric     "force-split-store", cl::Hidden, cl::init(false),
183d88c1a5aSDimitry Andric     cl::desc("Force store splitting no matter what the target query says."));
184d88c1a5aSDimitry Andric 
1857a7e6055SDimitry Andric static cl::opt<bool>
1867a7e6055SDimitry Andric EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
1877a7e6055SDimitry Andric     cl::desc("Enable merging of redundant sexts when one is dominating"
1887a7e6055SDimitry Andric     " the other."), cl::init(true));
1897a7e6055SDimitry Andric 
1902cab237bSDimitry Andric static cl::opt<bool> DisableComplexAddrModes(
1912cab237bSDimitry Andric     "disable-complex-addr-modes", cl::Hidden, cl::init(false),
1922cab237bSDimitry Andric     cl::desc("Disables combining addressing modes with different parts "
1932cab237bSDimitry Andric              "in optimizeMemoryInst."));
1942cab237bSDimitry Andric 
1952cab237bSDimitry Andric static cl::opt<bool>
1962cab237bSDimitry Andric AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
1972cab237bSDimitry Andric                 cl::desc("Allow creation of Phis in Address sinking."));
1982cab237bSDimitry Andric 
1992cab237bSDimitry Andric static cl::opt<bool>
2004ba319b5SDimitry Andric AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
2012cab237bSDimitry Andric                    cl::desc("Allow creation of selects in Address sinking."));
2022cab237bSDimitry Andric 
2032cab237bSDimitry Andric static cl::opt<bool> AddrSinkCombineBaseReg(
2042cab237bSDimitry Andric     "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
2052cab237bSDimitry Andric     cl::desc("Allow combining of BaseReg field in Address sinking."));
2062cab237bSDimitry Andric 
2072cab237bSDimitry Andric static cl::opt<bool> AddrSinkCombineBaseGV(
2082cab237bSDimitry Andric     "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
2092cab237bSDimitry Andric     cl::desc("Allow combining of BaseGV field in Address sinking."));
2102cab237bSDimitry Andric 
2112cab237bSDimitry Andric static cl::opt<bool> AddrSinkCombineBaseOffs(
2122cab237bSDimitry Andric     "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
2132cab237bSDimitry Andric     cl::desc("Allow combining of BaseOffs field in Address sinking."));
2142cab237bSDimitry Andric 
2152cab237bSDimitry Andric static cl::opt<bool> AddrSinkCombineScaledReg(
2162cab237bSDimitry Andric     "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
2172cab237bSDimitry Andric     cl::desc("Allow combining of ScaledReg field in Address sinking."));
218f9448bf3SDimitry Andric 
2194ba319b5SDimitry Andric static cl::opt<bool>
2204ba319b5SDimitry Andric     EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
2214ba319b5SDimitry Andric                          cl::init(true),
2224ba319b5SDimitry Andric                          cl::desc("Enable splitting large offset of GEP."));
2234ba319b5SDimitry Andric 
22491bc56edSDimitry Andric namespace {
2252cab237bSDimitry Andric 
2264ba319b5SDimitry Andric enum ExtType {
2274ba319b5SDimitry Andric   ZeroExtension,   // Zero extension has been seen.
2284ba319b5SDimitry Andric   SignExtension,   // Sign extension has been seen.
2294ba319b5SDimitry Andric   BothExtension    // This extension type is used if we saw sext after
2304ba319b5SDimitry Andric                    // ZeroExtension had been set, or if we saw zext after
2314ba319b5SDimitry Andric                    // SignExtension had been set. It makes the type
2324ba319b5SDimitry Andric                    // information of a promoted instruction invalid.
2334ba319b5SDimitry Andric };
2344ba319b5SDimitry Andric 
2352cab237bSDimitry Andric using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
2364ba319b5SDimitry Andric using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
2372cab237bSDimitry Andric using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
2382cab237bSDimitry Andric using SExts = SmallVector<Instruction *, 16>;
2392cab237bSDimitry Andric using ValueToSExts = DenseMap<Value *, SExts>;
2402cab237bSDimitry Andric 
24139d628a0SDimitry Andric class TypePromotionTransaction;
24291bc56edSDimitry Andric 
24391bc56edSDimitry Andric   class CodeGenPrepare : public FunctionPass {
2442cab237bSDimitry Andric     const TargetMachine *TM = nullptr;
2457a7e6055SDimitry Andric     const TargetSubtargetInfo *SubtargetInfo;
2462cab237bSDimitry Andric     const TargetLowering *TLI = nullptr;
2477a7e6055SDimitry Andric     const TargetRegisterInfo *TRI;
2482cab237bSDimitry Andric     const TargetTransformInfo *TTI = nullptr;
24991bc56edSDimitry Andric     const TargetLibraryInfo *TLInfo;
2503ca95b02SDimitry Andric     const LoopInfo *LI;
251d88c1a5aSDimitry Andric     std::unique_ptr<BlockFrequencyInfo> BFI;
252d88c1a5aSDimitry Andric     std::unique_ptr<BranchProbabilityInfo> BPI;
25391bc56edSDimitry Andric 
2547d523365SDimitry Andric     /// As we scan instructions optimizing them, this is the next instruction
2557d523365SDimitry Andric     /// to optimize. Transforms that can invalidate this should update it.
25691bc56edSDimitry Andric     BasicBlock::iterator CurInstIterator;
25791bc56edSDimitry Andric 
25891bc56edSDimitry Andric     /// Keeps track of non-local addresses that have been sunk into a block.
25991bc56edSDimitry Andric     /// This allows us to avoid inserting duplicate code for blocks with
2602cab237bSDimitry Andric     /// multiple load/stores of the same address. The usage of WeakTrackingVH
2612cab237bSDimitry Andric     /// enables SunkAddrs to be treated as a cache whose entries can be
2622cab237bSDimitry Andric     /// invalidated if a sunken address computation has been erased.
2632cab237bSDimitry Andric     ValueMap<Value*, WeakTrackingVH> SunkAddrs;
26491bc56edSDimitry Andric 
2658f0fd8f6SDimitry Andric     /// Keeps track of all instructions inserted for the current function.
2668f0fd8f6SDimitry Andric     SetOfInstrs InsertedInsts;
2672cab237bSDimitry Andric 
26891bc56edSDimitry Andric     /// Keeps track of the type of the related instruction before their
26991bc56edSDimitry Andric     /// promotion for the current function.
27091bc56edSDimitry Andric     InstrToOrigTy PromotedInsts;
27191bc56edSDimitry Andric 
2727a7e6055SDimitry Andric     /// Keep track of instructions removed during promotion.
2737a7e6055SDimitry Andric     SetOfInstrs RemovedInsts;
2747a7e6055SDimitry Andric 
2757a7e6055SDimitry Andric     /// Keep track of sext chains based on their initial value.
2767a7e6055SDimitry Andric     DenseMap<Value *, Instruction *> SeenChainsForSExt;
2777a7e6055SDimitry Andric 
2784ba319b5SDimitry Andric     /// Keep track of GEPs accessing the same data structures such as structs or
2794ba319b5SDimitry Andric     /// arrays that are candidates to be split later because of their large
2804ba319b5SDimitry Andric     /// size.
281*b5893f02SDimitry Andric     MapVector<
2824ba319b5SDimitry Andric         AssertingVH<Value>,
2834ba319b5SDimitry Andric         SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
2844ba319b5SDimitry Andric         LargeOffsetGEPMap;
2854ba319b5SDimitry Andric 
2864ba319b5SDimitry Andric     /// Keep track of new GEP base after splitting the GEPs having large offset.
2874ba319b5SDimitry Andric     SmallSet<AssertingVH<Value>, 2> NewGEPBases;
2884ba319b5SDimitry Andric 
2894ba319b5SDimitry Andric     /// Map serial numbers to Large offset GEPs.
2904ba319b5SDimitry Andric     DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
2914ba319b5SDimitry Andric 
2927a7e6055SDimitry Andric     /// Keep track of SExt promoted.
2937a7e6055SDimitry Andric     ValueToSExts ValToSExtendedUses;
2947a7e6055SDimitry Andric 
2957d523365SDimitry Andric     /// True if CFG is modified in any way.
29691bc56edSDimitry Andric     bool ModifiedDT;
29791bc56edSDimitry Andric 
2987d523365SDimitry Andric     /// True if optimizing for size.
29991bc56edSDimitry Andric     bool OptSize;
30091bc56edSDimitry Andric 
301875ed548SDimitry Andric     /// DataLayout for the Function being processed.
3022cab237bSDimitry Andric     const DataLayout *DL = nullptr;
303875ed548SDimitry Andric 
30491bc56edSDimitry Andric   public:
30591bc56edSDimitry Andric     static char ID; // Pass identification, replacement for typeid
3062cab237bSDimitry Andric 
CodeGenPrepare()3072cab237bSDimitry Andric     CodeGenPrepare() : FunctionPass(ID) {
30891bc56edSDimitry Andric       initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
30991bc56edSDimitry Andric     }
3102cab237bSDimitry Andric 
31191bc56edSDimitry Andric     bool runOnFunction(Function &F) override;
31291bc56edSDimitry Andric 
getPassName() const313d88c1a5aSDimitry Andric     StringRef getPassName() const override { return "CodeGen Prepare"; }
31491bc56edSDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const31591bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
3163ca95b02SDimitry Andric       // FIXME: When we can selectively preserve passes, preserve the domtree.
317d88c1a5aSDimitry Andric       AU.addRequired<ProfileSummaryInfoWrapperPass>();
318ff0cc061SDimitry Andric       AU.addRequired<TargetLibraryInfoWrapperPass>();
319ff0cc061SDimitry Andric       AU.addRequired<TargetTransformInfoWrapperPass>();
3203ca95b02SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
32191bc56edSDimitry Andric     }
32291bc56edSDimitry Andric 
32391bc56edSDimitry Andric   private:
324*b5893f02SDimitry Andric     template <typename F>
resetIteratorIfInvalidatedWhileCalling(BasicBlock * BB,F f)325*b5893f02SDimitry Andric     void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
326*b5893f02SDimitry Andric       // Substituting can cause recursive simplifications, which can invalidate
327*b5893f02SDimitry Andric       // our iterator.  Use a WeakTrackingVH to hold onto it in case this
328*b5893f02SDimitry Andric       // happens.
329*b5893f02SDimitry Andric       Value *CurValue = &*CurInstIterator;
330*b5893f02SDimitry Andric       WeakTrackingVH IterHandle(CurValue);
331*b5893f02SDimitry Andric 
332*b5893f02SDimitry Andric       f();
333*b5893f02SDimitry Andric 
334*b5893f02SDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
335*b5893f02SDimitry Andric       // start of the block.
336*b5893f02SDimitry Andric       if (IterHandle != CurValue) {
337*b5893f02SDimitry Andric         CurInstIterator = BB->begin();
338*b5893f02SDimitry Andric         SunkAddrs.clear();
339*b5893f02SDimitry Andric       }
340*b5893f02SDimitry Andric     }
341*b5893f02SDimitry Andric 
3427d523365SDimitry Andric     bool eliminateFallThrough(Function &F);
3437d523365SDimitry Andric     bool eliminateMostlyEmptyBlocks(Function &F);
344d88c1a5aSDimitry Andric     BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
3457d523365SDimitry Andric     bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
3467d523365SDimitry Andric     void eliminateMostlyEmptyBlock(BasicBlock *BB);
347d88c1a5aSDimitry Andric     bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
348d88c1a5aSDimitry Andric                                        bool isPreheader);
3497d523365SDimitry Andric     bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
3507d523365SDimitry Andric     bool optimizeInst(Instruction *I, bool &ModifiedDT);
3514ba319b5SDimitry Andric     bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
3524ba319b5SDimitry Andric                             Type *AccessTy, unsigned AddrSpace);
3537d523365SDimitry Andric     bool optimizeInlineAsmInst(CallInst *CS);
3547d523365SDimitry Andric     bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
3557a7e6055SDimitry Andric     bool optimizeExt(Instruction *&I);
3567d523365SDimitry Andric     bool optimizeExtUses(Instruction *I);
3574ba319b5SDimitry Andric     bool optimizeLoadExt(LoadInst *Load);
3587d523365SDimitry Andric     bool optimizeSelectInst(SelectInst *SI);
3594ba319b5SDimitry Andric     bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
3604ba319b5SDimitry Andric     bool optimizeSwitchInst(SwitchInst *SI);
3617d523365SDimitry Andric     bool optimizeExtractElementInst(Instruction *Inst);
3627d523365SDimitry Andric     bool dupRetToEnableTailCallOpts(BasicBlock *BB);
3637d523365SDimitry Andric     bool placeDbgValues(Function &F);
3647a7e6055SDimitry Andric     bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
3657a7e6055SDimitry Andric                       LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
3667a7e6055SDimitry Andric     bool tryToPromoteExts(TypePromotionTransaction &TPT,
36739d628a0SDimitry Andric                           const SmallVectorImpl<Instruction *> &Exts,
3687a7e6055SDimitry Andric                           SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
3697a7e6055SDimitry Andric                           unsigned CreatedInstsCost = 0);
3707a7e6055SDimitry Andric     bool mergeSExts(Function &F);
3714ba319b5SDimitry Andric     bool splitLargeGEPOffsets();
3727a7e6055SDimitry Andric     bool performAddressTypePromotion(
3737a7e6055SDimitry Andric         Instruction *&Inst,
3747a7e6055SDimitry Andric         bool AllowPromotionWithoutCommonHeader,
3757a7e6055SDimitry Andric         bool HasPromoted, TypePromotionTransaction &TPT,
3767a7e6055SDimitry Andric         SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
37739d628a0SDimitry Andric     bool splitBranchCondition(Function &F);
378ff0cc061SDimitry Andric     bool simplifyOffsetableRelocate(Instruction &I);
37991bc56edSDimitry Andric   };
3802cab237bSDimitry Andric 
3812cab237bSDimitry Andric } // end anonymous namespace
38291bc56edSDimitry Andric 
38391bc56edSDimitry Andric char CodeGenPrepare::ID = 0;
3842cab237bSDimitry Andric 
385302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
386d88c1a5aSDimitry Andric                       "Optimize for code generation", false, false)
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)387d88c1a5aSDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
388302affcbSDimitry Andric INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
38991bc56edSDimitry Andric                     "Optimize for code generation", false, false)
39091bc56edSDimitry Andric 
391d8866befSDimitry Andric FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
39291bc56edSDimitry Andric 
runOnFunction(Function & F)39391bc56edSDimitry Andric bool CodeGenPrepare::runOnFunction(Function &F) {
3943ca95b02SDimitry Andric   if (skipFunction(F))
39591bc56edSDimitry Andric     return false;
39691bc56edSDimitry Andric 
397875ed548SDimitry Andric   DL = &F.getParent()->getDataLayout();
398875ed548SDimitry Andric 
39991bc56edSDimitry Andric   bool EverMadeChange = false;
40091bc56edSDimitry Andric   // Clear per function information.
4018f0fd8f6SDimitry Andric   InsertedInsts.clear();
40291bc56edSDimitry Andric   PromotedInsts.clear();
40391bc56edSDimitry Andric 
40491bc56edSDimitry Andric   ModifiedDT = false;
405d8866befSDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
406d8866befSDimitry Andric     TM = &TPC->getTM<TargetMachine>();
4077a7e6055SDimitry Andric     SubtargetInfo = TM->getSubtargetImpl(F);
4087a7e6055SDimitry Andric     TLI = SubtargetInfo->getTargetLowering();
4097a7e6055SDimitry Andric     TRI = SubtargetInfo->getRegisterInfo();
4107a7e6055SDimitry Andric   }
411ff0cc061SDimitry Andric   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
412ff0cc061SDimitry Andric   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4133ca95b02SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
414da09e106SDimitry Andric   BPI.reset(new BranchProbabilityInfo(F, *LI));
415da09e106SDimitry Andric   BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
4167d523365SDimitry Andric   OptSize = F.optForSize();
41791bc56edSDimitry Andric 
418d88c1a5aSDimitry Andric   ProfileSummaryInfo *PSI =
419*b5893f02SDimitry Andric       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
4202cab237bSDimitry Andric   if (ProfileGuidedSectionPrefix) {
421da09e106SDimitry Andric     if (PSI->isFunctionHotInCallGraph(&F, *BFI))
422d88c1a5aSDimitry Andric       F.setSectionPrefix(".hot");
423da09e106SDimitry Andric     else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
4245517e702SDimitry Andric       F.setSectionPrefix(".unlikely");
425d88c1a5aSDimitry Andric   }
426d88c1a5aSDimitry Andric 
42791bc56edSDimitry Andric   /// This optimization identifies DIV instructions that can be
42891bc56edSDimitry Andric   /// profitably bypassed and carried out with a shorter, faster divide.
4292cab237bSDimitry Andric   if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
4302cab237bSDimitry Andric       TLI->isSlowDivBypassed()) {
43191bc56edSDimitry Andric     const DenseMap<unsigned int, unsigned int> &BypassWidths =
43291bc56edSDimitry Andric        TLI->getBypassSlowDivWidths();
4334d0b32cdSDimitry Andric     BasicBlock* BB = &*F.begin();
4344d0b32cdSDimitry Andric     while (BB != nullptr) {
4354d0b32cdSDimitry Andric       // bypassSlowDivision may create new BBs, but we don't want to reapply the
4364d0b32cdSDimitry Andric       // optimization to those blocks.
4374d0b32cdSDimitry Andric       BasicBlock* Next = BB->getNextNode();
4384d0b32cdSDimitry Andric       EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
4394d0b32cdSDimitry Andric       BB = Next;
4404d0b32cdSDimitry Andric     }
44191bc56edSDimitry Andric   }
44291bc56edSDimitry Andric 
44391bc56edSDimitry Andric   // Eliminate blocks that contain only PHI nodes and an
44491bc56edSDimitry Andric   // unconditional branch.
4457d523365SDimitry Andric   EverMadeChange |= eliminateMostlyEmptyBlocks(F);
44691bc56edSDimitry Andric 
4477a7e6055SDimitry Andric   if (!DisableBranchOpts)
44839d628a0SDimitry Andric     EverMadeChange |= splitBranchCondition(F);
4497a7e6055SDimitry Andric 
4507a7e6055SDimitry Andric   // Split some critical edges where one of the sources is an indirect branch,
4517a7e6055SDimitry Andric   // to help generate sane code for PHIs involving such edges.
4522cab237bSDimitry Andric   EverMadeChange |= SplitIndirectBrCriticalEdges(F);
45391bc56edSDimitry Andric 
45491bc56edSDimitry Andric   bool MadeChange = true;
45591bc56edSDimitry Andric   while (MadeChange) {
45691bc56edSDimitry Andric     MadeChange = false;
45791bc56edSDimitry Andric     for (Function::iterator I = F.begin(); I != F.end(); ) {
4587d523365SDimitry Andric       BasicBlock *BB = &*I++;
45939d628a0SDimitry Andric       bool ModifiedDTOnIteration = false;
4607d523365SDimitry Andric       MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
46139d628a0SDimitry Andric 
46239d628a0SDimitry Andric       // Restart BB iteration if the dominator tree of the Function was changed
46339d628a0SDimitry Andric       if (ModifiedDTOnIteration)
46439d628a0SDimitry Andric         break;
46591bc56edSDimitry Andric     }
4667a7e6055SDimitry Andric     if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
4677a7e6055SDimitry Andric       MadeChange |= mergeSExts(F);
4684ba319b5SDimitry Andric     if (!LargeOffsetGEPMap.empty())
4694ba319b5SDimitry Andric       MadeChange |= splitLargeGEPOffsets();
4707a7e6055SDimitry Andric 
4717a7e6055SDimitry Andric     // Really free removed instructions during promotion.
4727a7e6055SDimitry Andric     for (Instruction *I : RemovedInsts)
473d8866befSDimitry Andric       I->deleteValue();
4747a7e6055SDimitry Andric 
47591bc56edSDimitry Andric     EverMadeChange |= MadeChange;
476*b5893f02SDimitry Andric     SeenChainsForSExt.clear();
477*b5893f02SDimitry Andric     ValToSExtendedUses.clear();
478*b5893f02SDimitry Andric     RemovedInsts.clear();
479*b5893f02SDimitry Andric     LargeOffsetGEPMap.clear();
480*b5893f02SDimitry Andric     LargeOffsetGEPID.clear();
48191bc56edSDimitry Andric   }
48291bc56edSDimitry Andric 
48391bc56edSDimitry Andric   SunkAddrs.clear();
48491bc56edSDimitry Andric 
48591bc56edSDimitry Andric   if (!DisableBranchOpts) {
48691bc56edSDimitry Andric     MadeChange = false;
4874ba319b5SDimitry Andric     // Use a set vector to get deterministic iteration order. The order the
4884ba319b5SDimitry Andric     // blocks are removed may affect whether or not PHI nodes in successors
4894ba319b5SDimitry Andric     // are removed.
4904ba319b5SDimitry Andric     SmallSetVector<BasicBlock*, 8> WorkList;
49139d628a0SDimitry Andric     for (BasicBlock &BB : F) {
49239d628a0SDimitry Andric       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
49339d628a0SDimitry Andric       MadeChange |= ConstantFoldTerminator(&BB, true);
49491bc56edSDimitry Andric       if (!MadeChange) continue;
49591bc56edSDimitry Andric 
49691bc56edSDimitry Andric       for (SmallVectorImpl<BasicBlock*>::iterator
49791bc56edSDimitry Andric              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
49891bc56edSDimitry Andric         if (pred_begin(*II) == pred_end(*II))
49991bc56edSDimitry Andric           WorkList.insert(*II);
50091bc56edSDimitry Andric     }
50191bc56edSDimitry Andric 
50291bc56edSDimitry Andric     // Delete the dead blocks and any of their dead successors.
50391bc56edSDimitry Andric     MadeChange |= !WorkList.empty();
50491bc56edSDimitry Andric     while (!WorkList.empty()) {
5054ba319b5SDimitry Andric       BasicBlock *BB = WorkList.pop_back_val();
50691bc56edSDimitry Andric       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
50791bc56edSDimitry Andric 
50891bc56edSDimitry Andric       DeleteDeadBlock(BB);
50991bc56edSDimitry Andric 
51091bc56edSDimitry Andric       for (SmallVectorImpl<BasicBlock*>::iterator
51191bc56edSDimitry Andric              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
51291bc56edSDimitry Andric         if (pred_begin(*II) == pred_end(*II))
51391bc56edSDimitry Andric           WorkList.insert(*II);
51491bc56edSDimitry Andric     }
51591bc56edSDimitry Andric 
51691bc56edSDimitry Andric     // Merge pairs of basic blocks with unconditional branches, connected by
51791bc56edSDimitry Andric     // a single edge.
51891bc56edSDimitry Andric     if (EverMadeChange || MadeChange)
5197d523365SDimitry Andric       MadeChange |= eliminateFallThrough(F);
52091bc56edSDimitry Andric 
52191bc56edSDimitry Andric     EverMadeChange |= MadeChange;
52291bc56edSDimitry Andric   }
52391bc56edSDimitry Andric 
524ff0cc061SDimitry Andric   if (!DisableGCOpts) {
525ff0cc061SDimitry Andric     SmallVector<Instruction *, 2> Statepoints;
526ff0cc061SDimitry Andric     for (BasicBlock &BB : F)
527ff0cc061SDimitry Andric       for (Instruction &I : BB)
528ff0cc061SDimitry Andric         if (isStatepoint(I))
529ff0cc061SDimitry Andric           Statepoints.push_back(&I);
530ff0cc061SDimitry Andric     for (auto &I : Statepoints)
531ff0cc061SDimitry Andric       EverMadeChange |= simplifyOffsetableRelocate(*I);
532ff0cc061SDimitry Andric   }
53391bc56edSDimitry Andric 
534*b5893f02SDimitry Andric   // Do this last to clean up use-before-def scenarios introduced by other
535*b5893f02SDimitry Andric   // preparatory transforms.
536*b5893f02SDimitry Andric   EverMadeChange |= placeDbgValues(F);
537*b5893f02SDimitry Andric 
53891bc56edSDimitry Andric   return EverMadeChange;
53991bc56edSDimitry Andric }
54091bc56edSDimitry Andric 
5417d523365SDimitry Andric /// Merge basic blocks which are connected by a single edge, where one of the
5427d523365SDimitry Andric /// basic blocks has a single successor pointing to the other basic block,
5437d523365SDimitry Andric /// which has a single predecessor.
eliminateFallThrough(Function & F)5447d523365SDimitry Andric bool CodeGenPrepare::eliminateFallThrough(Function &F) {
54591bc56edSDimitry Andric   bool Changed = false;
54691bc56edSDimitry Andric   // Scan all of the blocks in the function, except for the entry block.
5474ba319b5SDimitry Andric   // Use a temporary array to avoid iterator being invalidated when
5484ba319b5SDimitry Andric   // deleting blocks.
5494ba319b5SDimitry Andric   SmallVector<WeakTrackingVH, 16> Blocks;
5504ba319b5SDimitry Andric   for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
5514ba319b5SDimitry Andric     Blocks.push_back(&Block);
5524ba319b5SDimitry Andric 
5534ba319b5SDimitry Andric   for (auto &Block : Blocks) {
5544ba319b5SDimitry Andric     auto *BB = cast_or_null<BasicBlock>(Block);
5554ba319b5SDimitry Andric     if (!BB)
5564ba319b5SDimitry Andric       continue;
55791bc56edSDimitry Andric     // If the destination block has a single pred, then this is a trivial
55891bc56edSDimitry Andric     // edge, just collapse it.
55991bc56edSDimitry Andric     BasicBlock *SinglePred = BB->getSinglePredecessor();
56091bc56edSDimitry Andric 
56191bc56edSDimitry Andric     // Don't merge if BB's address is taken.
56291bc56edSDimitry Andric     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
56391bc56edSDimitry Andric 
56491bc56edSDimitry Andric     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
56591bc56edSDimitry Andric     if (Term && !Term->isConditional()) {
56691bc56edSDimitry Andric       Changed = true;
5674ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
56891bc56edSDimitry Andric 
5694ba319b5SDimitry Andric       // Merge BB into SinglePred and delete it.
5704ba319b5SDimitry Andric       MergeBlockIntoPredecessor(BB);
57191bc56edSDimitry Andric     }
57291bc56edSDimitry Andric   }
57391bc56edSDimitry Andric   return Changed;
57491bc56edSDimitry Andric }
57591bc56edSDimitry Andric 
576d88c1a5aSDimitry Andric /// Find a destination block from BB if BB is mergeable empty block.
findDestBlockOfMergeableEmptyBlock(BasicBlock * BB)577d88c1a5aSDimitry Andric BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
578d88c1a5aSDimitry Andric   // If this block doesn't end with an uncond branch, ignore it.
579d88c1a5aSDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
580d88c1a5aSDimitry Andric   if (!BI || !BI->isUnconditional())
581d88c1a5aSDimitry Andric     return nullptr;
582d88c1a5aSDimitry Andric 
583d88c1a5aSDimitry Andric   // If the instruction before the branch (skipping debug info) isn't a phi
584d88c1a5aSDimitry Andric   // node, then other stuff is happening here.
585d88c1a5aSDimitry Andric   BasicBlock::iterator BBI = BI->getIterator();
586d88c1a5aSDimitry Andric   if (BBI != BB->begin()) {
587d88c1a5aSDimitry Andric     --BBI;
588d88c1a5aSDimitry Andric     while (isa<DbgInfoIntrinsic>(BBI)) {
589d88c1a5aSDimitry Andric       if (BBI == BB->begin())
590d88c1a5aSDimitry Andric         break;
591d88c1a5aSDimitry Andric       --BBI;
592d88c1a5aSDimitry Andric     }
593d88c1a5aSDimitry Andric     if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
594d88c1a5aSDimitry Andric       return nullptr;
595d88c1a5aSDimitry Andric   }
596d88c1a5aSDimitry Andric 
597d88c1a5aSDimitry Andric   // Do not break infinite loops.
598d88c1a5aSDimitry Andric   BasicBlock *DestBB = BI->getSuccessor(0);
599d88c1a5aSDimitry Andric   if (DestBB == BB)
600d88c1a5aSDimitry Andric     return nullptr;
601d88c1a5aSDimitry Andric 
602d88c1a5aSDimitry Andric   if (!canMergeBlocks(BB, DestBB))
603d88c1a5aSDimitry Andric     DestBB = nullptr;
604d88c1a5aSDimitry Andric 
605d88c1a5aSDimitry Andric   return DestBB;
606d88c1a5aSDimitry Andric }
607d88c1a5aSDimitry Andric 
6087d523365SDimitry Andric /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
6097d523365SDimitry Andric /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
6107d523365SDimitry Andric /// edges in ways that are non-optimal for isel. Start by eliminating these
6117d523365SDimitry Andric /// blocks so we can split them the way we want them.
eliminateMostlyEmptyBlocks(Function & F)6127d523365SDimitry Andric bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
6133ca95b02SDimitry Andric   SmallPtrSet<BasicBlock *, 16> Preheaders;
6143ca95b02SDimitry Andric   SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
6153ca95b02SDimitry Andric   while (!LoopList.empty()) {
6163ca95b02SDimitry Andric     Loop *L = LoopList.pop_back_val();
6173ca95b02SDimitry Andric     LoopList.insert(LoopList.end(), L->begin(), L->end());
6183ca95b02SDimitry Andric     if (BasicBlock *Preheader = L->getLoopPreheader())
6193ca95b02SDimitry Andric       Preheaders.insert(Preheader);
6203ca95b02SDimitry Andric   }
6213ca95b02SDimitry Andric 
62291bc56edSDimitry Andric   bool MadeChange = false;
6234ba319b5SDimitry Andric   // Copy blocks into a temporary array to avoid iterator invalidation issues
6244ba319b5SDimitry Andric   // as we remove them.
62591bc56edSDimitry Andric   // Note that this intentionally skips the entry block.
6264ba319b5SDimitry Andric   SmallVector<WeakTrackingVH, 16> Blocks;
6274ba319b5SDimitry Andric   for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
6284ba319b5SDimitry Andric     Blocks.push_back(&Block);
6294ba319b5SDimitry Andric 
6304ba319b5SDimitry Andric   for (auto &Block : Blocks) {
6314ba319b5SDimitry Andric     BasicBlock *BB = cast_or_null<BasicBlock>(Block);
6324ba319b5SDimitry Andric     if (!BB)
6334ba319b5SDimitry Andric       continue;
634d88c1a5aSDimitry Andric     BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
635d88c1a5aSDimitry Andric     if (!DestBB ||
636d88c1a5aSDimitry Andric         !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
6373ca95b02SDimitry Andric       continue;
6383ca95b02SDimitry Andric 
6397d523365SDimitry Andric     eliminateMostlyEmptyBlock(BB);
64091bc56edSDimitry Andric     MadeChange = true;
64191bc56edSDimitry Andric   }
64291bc56edSDimitry Andric   return MadeChange;
64391bc56edSDimitry Andric }
64491bc56edSDimitry Andric 
isMergingEmptyBlockProfitable(BasicBlock * BB,BasicBlock * DestBB,bool isPreheader)645d88c1a5aSDimitry Andric bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
646d88c1a5aSDimitry Andric                                                    BasicBlock *DestBB,
647d88c1a5aSDimitry Andric                                                    bool isPreheader) {
648d88c1a5aSDimitry Andric   // Do not delete loop preheaders if doing so would create a critical edge.
649d88c1a5aSDimitry Andric   // Loop preheaders can be good locations to spill registers. If the
650d88c1a5aSDimitry Andric   // preheader is deleted and we create a critical edge, registers may be
651d88c1a5aSDimitry Andric   // spilled in the loop body instead.
652d88c1a5aSDimitry Andric   if (!DisablePreheaderProtect && isPreheader &&
653d88c1a5aSDimitry Andric       !(BB->getSinglePredecessor() &&
654d88c1a5aSDimitry Andric         BB->getSinglePredecessor()->getSingleSuccessor()))
655d88c1a5aSDimitry Andric     return false;
656d88c1a5aSDimitry Andric 
657d88c1a5aSDimitry Andric   // Try to skip merging if the unique predecessor of BB is terminated by a
658d88c1a5aSDimitry Andric   // switch or indirect branch instruction, and BB is used as an incoming block
659d88c1a5aSDimitry Andric   // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
660d88c1a5aSDimitry Andric   // add COPY instructions in the predecessor of BB instead of BB (if it is not
661d88c1a5aSDimitry Andric   // merged). Note that the critical edge created by merging such blocks wont be
662d88c1a5aSDimitry Andric   // split in MachineSink because the jump table is not analyzable. By keeping
663d88c1a5aSDimitry Andric   // such empty block (BB), ISel will place COPY instructions in BB, not in the
664d88c1a5aSDimitry Andric   // predecessor of BB.
665d88c1a5aSDimitry Andric   BasicBlock *Pred = BB->getUniquePredecessor();
666d88c1a5aSDimitry Andric   if (!Pred ||
667d88c1a5aSDimitry Andric       !(isa<SwitchInst>(Pred->getTerminator()) ||
668d88c1a5aSDimitry Andric         isa<IndirectBrInst>(Pred->getTerminator())))
669d88c1a5aSDimitry Andric     return true;
670d88c1a5aSDimitry Andric 
671*b5893f02SDimitry Andric   if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
672d88c1a5aSDimitry Andric     return true;
673d88c1a5aSDimitry Andric 
674d88c1a5aSDimitry Andric   // We use a simple cost heuristic which determine skipping merging is
675d88c1a5aSDimitry Andric   // profitable if the cost of skipping merging is less than the cost of
676d88c1a5aSDimitry Andric   // merging : Cost(skipping merging) < Cost(merging BB), where the
677d88c1a5aSDimitry Andric   // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
678d88c1a5aSDimitry Andric   // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
679d88c1a5aSDimitry Andric   // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
680d88c1a5aSDimitry Andric   //   Freq(Pred) / Freq(BB) > 2.
681d88c1a5aSDimitry Andric   // Note that if there are multiple empty blocks sharing the same incoming
682d88c1a5aSDimitry Andric   // value for the PHIs in the DestBB, we consider them together. In such
683d88c1a5aSDimitry Andric   // case, Cost(merging BB) will be the sum of their frequencies.
684d88c1a5aSDimitry Andric 
685d88c1a5aSDimitry Andric   if (!isa<PHINode>(DestBB->begin()))
686d88c1a5aSDimitry Andric     return true;
687d88c1a5aSDimitry Andric 
688d88c1a5aSDimitry Andric   SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
689d88c1a5aSDimitry Andric 
690d88c1a5aSDimitry Andric   // Find all other incoming blocks from which incoming values of all PHIs in
691d88c1a5aSDimitry Andric   // DestBB are the same as the ones from BB.
692d88c1a5aSDimitry Andric   for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
693d88c1a5aSDimitry Andric        ++PI) {
694d88c1a5aSDimitry Andric     BasicBlock *DestBBPred = *PI;
695d88c1a5aSDimitry Andric     if (DestBBPred == BB)
696d88c1a5aSDimitry Andric       continue;
697d88c1a5aSDimitry Andric 
69830785c0eSDimitry Andric     if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
69930785c0eSDimitry Andric           return DestPN.getIncomingValueForBlock(BB) ==
70030785c0eSDimitry Andric                  DestPN.getIncomingValueForBlock(DestBBPred);
70130785c0eSDimitry Andric         }))
702d88c1a5aSDimitry Andric       SameIncomingValueBBs.insert(DestBBPred);
703d88c1a5aSDimitry Andric   }
704d88c1a5aSDimitry Andric 
705d88c1a5aSDimitry Andric   // See if all BB's incoming values are same as the value from Pred. In this
706d88c1a5aSDimitry Andric   // case, no reason to skip merging because COPYs are expected to be place in
707d88c1a5aSDimitry Andric   // Pred already.
708d88c1a5aSDimitry Andric   if (SameIncomingValueBBs.count(Pred))
709d88c1a5aSDimitry Andric     return true;
710d88c1a5aSDimitry Andric 
711d88c1a5aSDimitry Andric   BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
712d88c1a5aSDimitry Andric   BlockFrequency BBFreq = BFI->getBlockFreq(BB);
713d88c1a5aSDimitry Andric 
714d88c1a5aSDimitry Andric   for (auto SameValueBB : SameIncomingValueBBs)
715d88c1a5aSDimitry Andric     if (SameValueBB->getUniquePredecessor() == Pred &&
716d88c1a5aSDimitry Andric         DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
717d88c1a5aSDimitry Andric       BBFreq += BFI->getBlockFreq(SameValueBB);
718d88c1a5aSDimitry Andric 
719d88c1a5aSDimitry Andric   return PredFreq.getFrequency() <=
720d88c1a5aSDimitry Andric          BBFreq.getFrequency() * FreqRatioToSkipMerge;
721d88c1a5aSDimitry Andric }
722d88c1a5aSDimitry Andric 
7237d523365SDimitry Andric /// Return true if we can merge BB into DestBB if there is a single
7247d523365SDimitry Andric /// unconditional branch between them, and BB contains no other non-phi
72591bc56edSDimitry Andric /// instructions.
canMergeBlocks(const BasicBlock * BB,const BasicBlock * DestBB) const7267d523365SDimitry Andric bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
72791bc56edSDimitry Andric                                     const BasicBlock *DestBB) const {
72891bc56edSDimitry Andric   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
72991bc56edSDimitry Andric   // the successor.  If there are more complex condition (e.g. preheaders),
73091bc56edSDimitry Andric   // don't mess around with them.
73130785c0eSDimitry Andric   for (const PHINode &PN : BB->phis()) {
73230785c0eSDimitry Andric     for (const User *U : PN.users()) {
73391bc56edSDimitry Andric       const Instruction *UI = cast<Instruction>(U);
73491bc56edSDimitry Andric       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
73591bc56edSDimitry Andric         return false;
73691bc56edSDimitry Andric       // If User is inside DestBB block and it is a PHINode then check
73791bc56edSDimitry Andric       // incoming value. If incoming value is not from BB then this is
73891bc56edSDimitry Andric       // a complex condition (e.g. preheaders) we want to avoid here.
73991bc56edSDimitry Andric       if (UI->getParent() == DestBB) {
74091bc56edSDimitry Andric         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
74191bc56edSDimitry Andric           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
74291bc56edSDimitry Andric             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
74391bc56edSDimitry Andric             if (Insn && Insn->getParent() == BB &&
74491bc56edSDimitry Andric                 Insn->getParent() != UPN->getIncomingBlock(I))
74591bc56edSDimitry Andric               return false;
74691bc56edSDimitry Andric           }
74791bc56edSDimitry Andric       }
74891bc56edSDimitry Andric     }
74991bc56edSDimitry Andric   }
75091bc56edSDimitry Andric 
75191bc56edSDimitry Andric   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
75291bc56edSDimitry Andric   // and DestBB may have conflicting incoming values for the block.  If so, we
75391bc56edSDimitry Andric   // can't merge the block.
75491bc56edSDimitry Andric   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
75591bc56edSDimitry Andric   if (!DestBBPN) return true;  // no conflict.
75691bc56edSDimitry Andric 
75791bc56edSDimitry Andric   // Collect the preds of BB.
75891bc56edSDimitry Andric   SmallPtrSet<const BasicBlock*, 16> BBPreds;
75991bc56edSDimitry Andric   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
76091bc56edSDimitry Andric     // It is faster to get preds from a PHI than with pred_iterator.
76191bc56edSDimitry Andric     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
76291bc56edSDimitry Andric       BBPreds.insert(BBPN->getIncomingBlock(i));
76391bc56edSDimitry Andric   } else {
76491bc56edSDimitry Andric     BBPreds.insert(pred_begin(BB), pred_end(BB));
76591bc56edSDimitry Andric   }
76691bc56edSDimitry Andric 
76791bc56edSDimitry Andric   // Walk the preds of DestBB.
76891bc56edSDimitry Andric   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
76991bc56edSDimitry Andric     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
77091bc56edSDimitry Andric     if (BBPreds.count(Pred)) {   // Common predecessor?
77130785c0eSDimitry Andric       for (const PHINode &PN : DestBB->phis()) {
77230785c0eSDimitry Andric         const Value *V1 = PN.getIncomingValueForBlock(Pred);
77330785c0eSDimitry Andric         const Value *V2 = PN.getIncomingValueForBlock(BB);
77491bc56edSDimitry Andric 
77591bc56edSDimitry Andric         // If V2 is a phi node in BB, look up what the mapped value will be.
77691bc56edSDimitry Andric         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
77791bc56edSDimitry Andric           if (V2PN->getParent() == BB)
77891bc56edSDimitry Andric             V2 = V2PN->getIncomingValueForBlock(Pred);
77991bc56edSDimitry Andric 
78091bc56edSDimitry Andric         // If there is a conflict, bail out.
78191bc56edSDimitry Andric         if (V1 != V2) return false;
78291bc56edSDimitry Andric       }
78391bc56edSDimitry Andric     }
78491bc56edSDimitry Andric   }
78591bc56edSDimitry Andric 
78691bc56edSDimitry Andric   return true;
78791bc56edSDimitry Andric }
78891bc56edSDimitry Andric 
7897d523365SDimitry Andric /// Eliminate a basic block that has only phi's and an unconditional branch in
7907d523365SDimitry Andric /// it.
eliminateMostlyEmptyBlock(BasicBlock * BB)7917d523365SDimitry Andric void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
79291bc56edSDimitry Andric   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
79391bc56edSDimitry Andric   BasicBlock *DestBB = BI->getSuccessor(0);
79491bc56edSDimitry Andric 
7954ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
7964ba319b5SDimitry Andric                     << *BB << *DestBB);
79791bc56edSDimitry Andric 
79891bc56edSDimitry Andric   // If the destination block has a single pred, then this is a trivial edge,
79991bc56edSDimitry Andric   // just collapse it.
80091bc56edSDimitry Andric   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
80191bc56edSDimitry Andric     if (SinglePred != DestBB) {
8024ba319b5SDimitry Andric       assert(SinglePred == BB &&
8034ba319b5SDimitry Andric              "Single predecessor not the same as predecessor");
8044ba319b5SDimitry Andric       // Merge DestBB into SinglePred/BB and delete it.
8054ba319b5SDimitry Andric       MergeBlockIntoPredecessor(DestBB);
8064ba319b5SDimitry Andric       // Note: BB(=SinglePred) will not be deleted on this path.
8074ba319b5SDimitry Andric       // DestBB(=its single successor) is the one that was deleted.
8084ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
80991bc56edSDimitry Andric       return;
81091bc56edSDimitry Andric     }
81191bc56edSDimitry Andric   }
81291bc56edSDimitry Andric 
81391bc56edSDimitry Andric   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
81491bc56edSDimitry Andric   // to handle the new incoming edges it is about to have.
81530785c0eSDimitry Andric   for (PHINode &PN : DestBB->phis()) {
81691bc56edSDimitry Andric     // Remove the incoming value for BB, and remember it.
81730785c0eSDimitry Andric     Value *InVal = PN.removeIncomingValue(BB, false);
81891bc56edSDimitry Andric 
81991bc56edSDimitry Andric     // Two options: either the InVal is a phi node defined in BB or it is some
82091bc56edSDimitry Andric     // value that dominates BB.
82191bc56edSDimitry Andric     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
82291bc56edSDimitry Andric     if (InValPhi && InValPhi->getParent() == BB) {
82391bc56edSDimitry Andric       // Add all of the input values of the input PHI as inputs of this phi.
82491bc56edSDimitry Andric       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
82530785c0eSDimitry Andric         PN.addIncoming(InValPhi->getIncomingValue(i),
82691bc56edSDimitry Andric                        InValPhi->getIncomingBlock(i));
82791bc56edSDimitry Andric     } else {
82891bc56edSDimitry Andric       // Otherwise, add one instance of the dominating value for each edge that
82991bc56edSDimitry Andric       // we will be adding.
83091bc56edSDimitry Andric       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
83191bc56edSDimitry Andric         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
83230785c0eSDimitry Andric           PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
83391bc56edSDimitry Andric       } else {
83491bc56edSDimitry Andric         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
83530785c0eSDimitry Andric           PN.addIncoming(InVal, *PI);
83691bc56edSDimitry Andric       }
83791bc56edSDimitry Andric     }
83891bc56edSDimitry Andric   }
83991bc56edSDimitry Andric 
84091bc56edSDimitry Andric   // The PHIs are now updated, change everything that refers to BB to use
84191bc56edSDimitry Andric   // DestBB and remove BB.
84291bc56edSDimitry Andric   BB->replaceAllUsesWith(DestBB);
84391bc56edSDimitry Andric   BB->eraseFromParent();
84491bc56edSDimitry Andric   ++NumBlocksElim;
84591bc56edSDimitry Andric 
8464ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
84791bc56edSDimitry Andric }
84891bc56edSDimitry Andric 
849ff0cc061SDimitry Andric // Computes a map of base pointer relocation instructions to corresponding
850ff0cc061SDimitry Andric // derived pointer relocation instructions given a vector of all relocate calls
computeBaseDerivedRelocateMap(const SmallVectorImpl<GCRelocateInst * > & AllRelocateCalls,DenseMap<GCRelocateInst *,SmallVector<GCRelocateInst *,2>> & RelocateInstMap)851ff0cc061SDimitry Andric static void computeBaseDerivedRelocateMap(
8524d0b32cdSDimitry Andric     const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
8534d0b32cdSDimitry Andric     DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
8544d0b32cdSDimitry Andric         &RelocateInstMap) {
855ff0cc061SDimitry Andric   // Collect information in two maps: one primarily for locating the base object
856ff0cc061SDimitry Andric   // while filling the second map; the second map is the final structure holding
857ff0cc061SDimitry Andric   // a mapping between Base and corresponding Derived relocate calls
8584d0b32cdSDimitry Andric   DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
8594d0b32cdSDimitry Andric   for (auto *ThisRelocate : AllRelocateCalls) {
8604d0b32cdSDimitry Andric     auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
8614d0b32cdSDimitry Andric                             ThisRelocate->getDerivedPtrIndex());
8624d0b32cdSDimitry Andric     RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
863ff0cc061SDimitry Andric   }
864ff0cc061SDimitry Andric   for (auto &Item : RelocateIdxMap) {
865ff0cc061SDimitry Andric     std::pair<unsigned, unsigned> Key = Item.first;
866ff0cc061SDimitry Andric     if (Key.first == Key.second)
867ff0cc061SDimitry Andric       // Base relocation: nothing to insert
868ff0cc061SDimitry Andric       continue;
869ff0cc061SDimitry Andric 
8704d0b32cdSDimitry Andric     GCRelocateInst *I = Item.second;
871ff0cc061SDimitry Andric     auto BaseKey = std::make_pair(Key.first, Key.first);
872ff0cc061SDimitry Andric 
873ff0cc061SDimitry Andric     // We're iterating over RelocateIdxMap so we cannot modify it.
874ff0cc061SDimitry Andric     auto MaybeBase = RelocateIdxMap.find(BaseKey);
875ff0cc061SDimitry Andric     if (MaybeBase == RelocateIdxMap.end())
876ff0cc061SDimitry Andric       // TODO: We might want to insert a new base object relocate and gep off
877ff0cc061SDimitry Andric       // that, if there are enough derived object relocates.
878ff0cc061SDimitry Andric       continue;
879ff0cc061SDimitry Andric 
880ff0cc061SDimitry Andric     RelocateInstMap[MaybeBase->second].push_back(I);
881ff0cc061SDimitry Andric   }
882ff0cc061SDimitry Andric }
883ff0cc061SDimitry Andric 
884ff0cc061SDimitry Andric // Accepts a GEP and extracts the operands into a vector provided they're all
885ff0cc061SDimitry Andric // small integer constants
getGEPSmallConstantIntOffsetV(GetElementPtrInst * GEP,SmallVectorImpl<Value * > & OffsetV)886ff0cc061SDimitry Andric static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
887ff0cc061SDimitry Andric                                           SmallVectorImpl<Value *> &OffsetV) {
888ff0cc061SDimitry Andric   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
889ff0cc061SDimitry Andric     // Only accept small constant integer operands
890ff0cc061SDimitry Andric     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
891ff0cc061SDimitry Andric     if (!Op || Op->getZExtValue() > 20)
892ff0cc061SDimitry Andric       return false;
893ff0cc061SDimitry Andric   }
894ff0cc061SDimitry Andric 
895ff0cc061SDimitry Andric   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
896ff0cc061SDimitry Andric     OffsetV.push_back(GEP->getOperand(i));
897ff0cc061SDimitry Andric   return true;
898ff0cc061SDimitry Andric }
899ff0cc061SDimitry Andric 
900ff0cc061SDimitry Andric // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
901ff0cc061SDimitry Andric // replace, computes a replacement, and affects it.
902ff0cc061SDimitry Andric static bool
simplifyRelocatesOffABase(GCRelocateInst * RelocatedBase,const SmallVectorImpl<GCRelocateInst * > & Targets)9034d0b32cdSDimitry Andric simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
9044d0b32cdSDimitry Andric                           const SmallVectorImpl<GCRelocateInst *> &Targets) {
905ff0cc061SDimitry Andric   bool MadeChange = false;
9062cab237bSDimitry Andric   // We must ensure the relocation of derived pointer is defined after
9072cab237bSDimitry Andric   // relocation of base pointer. If we find a relocation corresponding to base
9082cab237bSDimitry Andric   // defined earlier than relocation of base then we move relocation of base
9092cab237bSDimitry Andric   // right before found relocation. We consider only relocation in the same
9102cab237bSDimitry Andric   // basic block as relocation of base. Relocations from other basic block will
9112cab237bSDimitry Andric   // be skipped by optimization and we do not care about them.
9122cab237bSDimitry Andric   for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
9132cab237bSDimitry Andric        &*R != RelocatedBase; ++R)
9142cab237bSDimitry Andric     if (auto RI = dyn_cast<GCRelocateInst>(R))
9152cab237bSDimitry Andric       if (RI->getStatepoint() == RelocatedBase->getStatepoint())
9162cab237bSDimitry Andric         if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
9172cab237bSDimitry Andric           RelocatedBase->moveBefore(RI);
9182cab237bSDimitry Andric           break;
9192cab237bSDimitry Andric         }
9202cab237bSDimitry Andric 
9214d0b32cdSDimitry Andric   for (GCRelocateInst *ToReplace : Targets) {
9224d0b32cdSDimitry Andric     assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
923ff0cc061SDimitry Andric            "Not relocating a derived object of the original base object");
9244d0b32cdSDimitry Andric     if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
925ff0cc061SDimitry Andric       // A duplicate relocate call. TODO: coalesce duplicates.
926ff0cc061SDimitry Andric       continue;
927ff0cc061SDimitry Andric     }
928ff0cc061SDimitry Andric 
9297d523365SDimitry Andric     if (RelocatedBase->getParent() != ToReplace->getParent()) {
9307d523365SDimitry Andric       // Base and derived relocates are in different basic blocks.
9317d523365SDimitry Andric       // In this case transform is only valid when base dominates derived
9327d523365SDimitry Andric       // relocate. However it would be too expensive to check dominance
9337d523365SDimitry Andric       // for each such relocate, so we skip the whole transformation.
9347d523365SDimitry Andric       continue;
9357d523365SDimitry Andric     }
9367d523365SDimitry Andric 
9374d0b32cdSDimitry Andric     Value *Base = ToReplace->getBasePtr();
9384d0b32cdSDimitry Andric     auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
939ff0cc061SDimitry Andric     if (!Derived || Derived->getPointerOperand() != Base)
940ff0cc061SDimitry Andric       continue;
941ff0cc061SDimitry Andric 
942ff0cc061SDimitry Andric     SmallVector<Value *, 2> OffsetV;
943ff0cc061SDimitry Andric     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
944ff0cc061SDimitry Andric       continue;
945ff0cc061SDimitry Andric 
946ff0cc061SDimitry Andric     // Create a Builder and replace the target callsite with a gep
9473ca95b02SDimitry Andric     assert(RelocatedBase->getNextNode() &&
9483ca95b02SDimitry Andric            "Should always have one since it's not a terminator");
949ff0cc061SDimitry Andric 
950ff0cc061SDimitry Andric     // Insert after RelocatedBase
951ff0cc061SDimitry Andric     IRBuilder<> Builder(RelocatedBase->getNextNode());
952ff0cc061SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
953ff0cc061SDimitry Andric 
954ff0cc061SDimitry Andric     // If gc_relocate does not match the actual type, cast it to the right type.
955ff0cc061SDimitry Andric     // In theory, there must be a bitcast after gc_relocate if the type does not
956ff0cc061SDimitry Andric     // match, and we should reuse it to get the derived pointer. But it could be
957ff0cc061SDimitry Andric     // cases like this:
958ff0cc061SDimitry Andric     // bb1:
959ff0cc061SDimitry Andric     //  ...
960ff0cc061SDimitry Andric     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
961ff0cc061SDimitry Andric     //  br label %merge
962ff0cc061SDimitry Andric     //
963ff0cc061SDimitry Andric     // bb2:
964ff0cc061SDimitry Andric     //  ...
965ff0cc061SDimitry Andric     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
966ff0cc061SDimitry Andric     //  br label %merge
967ff0cc061SDimitry Andric     //
968ff0cc061SDimitry Andric     // merge:
969ff0cc061SDimitry Andric     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
970ff0cc061SDimitry Andric     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
971ff0cc061SDimitry Andric     //
972ff0cc061SDimitry Andric     // In this case, we can not find the bitcast any more. So we insert a new bitcast
973ff0cc061SDimitry Andric     // no matter there is already one or not. In this way, we can handle all cases, and
974ff0cc061SDimitry Andric     // the extra bitcast should be optimized away in later passes.
9757d523365SDimitry Andric     Value *ActualRelocatedBase = RelocatedBase;
976ff0cc061SDimitry Andric     if (RelocatedBase->getType() != Base->getType()) {
977ff0cc061SDimitry Andric       ActualRelocatedBase =
9787d523365SDimitry Andric           Builder.CreateBitCast(RelocatedBase, Base->getType());
979ff0cc061SDimitry Andric     }
980ff0cc061SDimitry Andric     Value *Replacement = Builder.CreateGEP(
981ff0cc061SDimitry Andric         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
982ff0cc061SDimitry Andric     Replacement->takeName(ToReplace);
983ff0cc061SDimitry Andric     // If the newly generated derived pointer's type does not match the original derived
984ff0cc061SDimitry Andric     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
9857d523365SDimitry Andric     Value *ActualReplacement = Replacement;
9867d523365SDimitry Andric     if (Replacement->getType() != ToReplace->getType()) {
987ff0cc061SDimitry Andric       ActualReplacement =
9887d523365SDimitry Andric           Builder.CreateBitCast(Replacement, ToReplace->getType());
989ff0cc061SDimitry Andric     }
990ff0cc061SDimitry Andric     ToReplace->replaceAllUsesWith(ActualReplacement);
991ff0cc061SDimitry Andric     ToReplace->eraseFromParent();
992ff0cc061SDimitry Andric 
993ff0cc061SDimitry Andric     MadeChange = true;
994ff0cc061SDimitry Andric   }
995ff0cc061SDimitry Andric   return MadeChange;
996ff0cc061SDimitry Andric }
997ff0cc061SDimitry Andric 
998ff0cc061SDimitry Andric // Turns this:
999ff0cc061SDimitry Andric //
1000ff0cc061SDimitry Andric // %base = ...
1001ff0cc061SDimitry Andric // %ptr = gep %base + 15
1002ff0cc061SDimitry Andric // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1003ff0cc061SDimitry Andric // %base' = relocate(%tok, i32 4, i32 4)
1004ff0cc061SDimitry Andric // %ptr' = relocate(%tok, i32 4, i32 5)
1005ff0cc061SDimitry Andric // %val = load %ptr'
1006ff0cc061SDimitry Andric //
1007ff0cc061SDimitry Andric // into this:
1008ff0cc061SDimitry Andric //
1009ff0cc061SDimitry Andric // %base = ...
1010ff0cc061SDimitry Andric // %ptr = gep %base + 15
1011ff0cc061SDimitry Andric // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1012ff0cc061SDimitry Andric // %base' = gc.relocate(%tok, i32 4, i32 4)
1013ff0cc061SDimitry Andric // %ptr' = gep %base' + 15
1014ff0cc061SDimitry Andric // %val = load %ptr'
simplifyOffsetableRelocate(Instruction & I)1015ff0cc061SDimitry Andric bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1016ff0cc061SDimitry Andric   bool MadeChange = false;
10174d0b32cdSDimitry Andric   SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1018ff0cc061SDimitry Andric 
1019ff0cc061SDimitry Andric   for (auto *U : I.users())
10204d0b32cdSDimitry Andric     if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1021ff0cc061SDimitry Andric       // Collect all the relocate calls associated with a statepoint
10224d0b32cdSDimitry Andric       AllRelocateCalls.push_back(Relocate);
1023ff0cc061SDimitry Andric 
1024ff0cc061SDimitry Andric   // We need atleast one base pointer relocation + one derived pointer
1025ff0cc061SDimitry Andric   // relocation to mangle
1026ff0cc061SDimitry Andric   if (AllRelocateCalls.size() < 2)
1027ff0cc061SDimitry Andric     return false;
1028ff0cc061SDimitry Andric 
1029ff0cc061SDimitry Andric   // RelocateInstMap is a mapping from the base relocate instruction to the
1030ff0cc061SDimitry Andric   // corresponding derived relocate instructions
10314d0b32cdSDimitry Andric   DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1032ff0cc061SDimitry Andric   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1033ff0cc061SDimitry Andric   if (RelocateInstMap.empty())
1034ff0cc061SDimitry Andric     return false;
1035ff0cc061SDimitry Andric 
1036ff0cc061SDimitry Andric   for (auto &Item : RelocateInstMap)
1037ff0cc061SDimitry Andric     // Item.first is the RelocatedBase to offset against
1038ff0cc061SDimitry Andric     // Item.second is the vector of Targets to replace
1039ff0cc061SDimitry Andric     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1040ff0cc061SDimitry Andric   return MadeChange;
1041ff0cc061SDimitry Andric }
1042ff0cc061SDimitry Andric 
104391bc56edSDimitry Andric /// SinkCast - Sink the specified cast instruction into its user blocks
SinkCast(CastInst * CI)104491bc56edSDimitry Andric static bool SinkCast(CastInst *CI) {
104591bc56edSDimitry Andric   BasicBlock *DefBB = CI->getParent();
104691bc56edSDimitry Andric 
104791bc56edSDimitry Andric   /// InsertedCasts - Only insert a cast in each block once.
104891bc56edSDimitry Andric   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
104991bc56edSDimitry Andric 
105091bc56edSDimitry Andric   bool MadeChange = false;
105191bc56edSDimitry Andric   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
105291bc56edSDimitry Andric        UI != E; ) {
105391bc56edSDimitry Andric     Use &TheUse = UI.getUse();
105491bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
105591bc56edSDimitry Andric 
105691bc56edSDimitry Andric     // Figure out which BB this cast is used in.  For PHI's this is the
105791bc56edSDimitry Andric     // appropriate predecessor block.
105891bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
105991bc56edSDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(User)) {
106091bc56edSDimitry Andric       UserBB = PN->getIncomingBlock(TheUse);
106191bc56edSDimitry Andric     }
106291bc56edSDimitry Andric 
106391bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
106491bc56edSDimitry Andric     ++UI;
106591bc56edSDimitry Andric 
10663ca95b02SDimitry Andric     // The first insertion point of a block containing an EH pad is after the
10673ca95b02SDimitry Andric     // pad.  If the pad is the user, we cannot sink the cast past the pad.
10683ca95b02SDimitry Andric     if (User->isEHPad())
10693ca95b02SDimitry Andric       continue;
10703ca95b02SDimitry Andric 
10717d523365SDimitry Andric     // If the block selected to receive the cast is an EH pad that does not
10727d523365SDimitry Andric     // allow non-PHI instructions before the terminator, we can't sink the
10737d523365SDimitry Andric     // cast.
10747d523365SDimitry Andric     if (UserBB->getTerminator()->isEHPad())
10757d523365SDimitry Andric       continue;
10767d523365SDimitry Andric 
107791bc56edSDimitry Andric     // If this user is in the same block as the cast, don't change the cast.
107891bc56edSDimitry Andric     if (UserBB == DefBB) continue;
107991bc56edSDimitry Andric 
108091bc56edSDimitry Andric     // If we have already inserted a cast into this block, use it.
108191bc56edSDimitry Andric     CastInst *&InsertedCast = InsertedCasts[UserBB];
108291bc56edSDimitry Andric 
108391bc56edSDimitry Andric     if (!InsertedCast) {
108491bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
10857d523365SDimitry Andric       assert(InsertPt != UserBB->end());
10867d523365SDimitry Andric       InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
10877d523365SDimitry Andric                                       CI->getType(), "", &*InsertPt);
10884ba319b5SDimitry Andric       InsertedCast->setDebugLoc(CI->getDebugLoc());
108991bc56edSDimitry Andric     }
109091bc56edSDimitry Andric 
109191bc56edSDimitry Andric     // Replace a use of the cast with a use of the new cast.
109291bc56edSDimitry Andric     TheUse = InsertedCast;
1093ff0cc061SDimitry Andric     MadeChange = true;
109491bc56edSDimitry Andric     ++NumCastUses;
109591bc56edSDimitry Andric   }
109691bc56edSDimitry Andric 
109791bc56edSDimitry Andric   // If we removed all uses, nuke the cast.
109891bc56edSDimitry Andric   if (CI->use_empty()) {
10992cab237bSDimitry Andric     salvageDebugInfo(*CI);
110091bc56edSDimitry Andric     CI->eraseFromParent();
110191bc56edSDimitry Andric     MadeChange = true;
110291bc56edSDimitry Andric   }
110391bc56edSDimitry Andric 
110491bc56edSDimitry Andric   return MadeChange;
110591bc56edSDimitry Andric }
110691bc56edSDimitry Andric 
11077d523365SDimitry Andric /// If the specified cast instruction is a noop copy (e.g. it's casting from
11087d523365SDimitry Andric /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
11097d523365SDimitry Andric /// reduce the number of virtual registers that must be created and coalesced.
111091bc56edSDimitry Andric ///
111191bc56edSDimitry Andric /// Return true if any changes are made.
OptimizeNoopCopyExpression(CastInst * CI,const TargetLowering & TLI,const DataLayout & DL)1112875ed548SDimitry Andric static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1113875ed548SDimitry Andric                                        const DataLayout &DL) {
1114d88c1a5aSDimitry Andric   // Sink only "cheap" (or nop) address-space casts.  This is a weaker condition
1115d88c1a5aSDimitry Andric   // than sinking only nop casts, but is helpful on some platforms.
1116d88c1a5aSDimitry Andric   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1117d88c1a5aSDimitry Andric     if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1118d88c1a5aSDimitry Andric                                   ASC->getDestAddressSpace()))
1119d88c1a5aSDimitry Andric       return false;
1120d88c1a5aSDimitry Andric   }
1121d88c1a5aSDimitry Andric 
112291bc56edSDimitry Andric   // If this is a noop copy,
1123875ed548SDimitry Andric   EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1124875ed548SDimitry Andric   EVT DstVT = TLI.getValueType(DL, CI->getType());
112591bc56edSDimitry Andric 
112691bc56edSDimitry Andric   // This is an fp<->int conversion?
112791bc56edSDimitry Andric   if (SrcVT.isInteger() != DstVT.isInteger())
112891bc56edSDimitry Andric     return false;
112991bc56edSDimitry Andric 
113091bc56edSDimitry Andric   // If this is an extension, it will be a zero or sign extension, which
113191bc56edSDimitry Andric   // isn't a noop.
113291bc56edSDimitry Andric   if (SrcVT.bitsLT(DstVT)) return false;
113391bc56edSDimitry Andric 
113491bc56edSDimitry Andric   // If these values will be promoted, find out what they will be promoted
113591bc56edSDimitry Andric   // to.  This helps us consider truncates on PPC as noop copies when they
113691bc56edSDimitry Andric   // are.
113791bc56edSDimitry Andric   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
113891bc56edSDimitry Andric       TargetLowering::TypePromoteInteger)
113991bc56edSDimitry Andric     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
114091bc56edSDimitry Andric   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
114191bc56edSDimitry Andric       TargetLowering::TypePromoteInteger)
114291bc56edSDimitry Andric     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
114391bc56edSDimitry Andric 
114491bc56edSDimitry Andric   // If, after promotion, these are the same types, this is a noop copy.
114591bc56edSDimitry Andric   if (SrcVT != DstVT)
114691bc56edSDimitry Andric     return false;
114791bc56edSDimitry Andric 
114891bc56edSDimitry Andric   return SinkCast(CI);
114991bc56edSDimitry Andric }
115091bc56edSDimitry Andric 
11517d523365SDimitry Andric /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
11527d523365SDimitry Andric /// possible.
1153ff0cc061SDimitry Andric ///
1154ff0cc061SDimitry Andric /// Return true if any changes were made.
CombineUAddWithOverflow(CmpInst * CI)1155ff0cc061SDimitry Andric static bool CombineUAddWithOverflow(CmpInst *CI) {
1156ff0cc061SDimitry Andric   Value *A, *B;
1157ff0cc061SDimitry Andric   Instruction *AddI;
1158ff0cc061SDimitry Andric   if (!match(CI,
1159ff0cc061SDimitry Andric              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1160ff0cc061SDimitry Andric     return false;
1161ff0cc061SDimitry Andric 
1162ff0cc061SDimitry Andric   Type *Ty = AddI->getType();
1163ff0cc061SDimitry Andric   if (!isa<IntegerType>(Ty))
1164ff0cc061SDimitry Andric     return false;
1165ff0cc061SDimitry Andric 
1166ff0cc061SDimitry Andric   // We don't want to move around uses of condition values this late, so we we
1167ff0cc061SDimitry Andric   // check if it is legal to create the call to the intrinsic in the basic
1168ff0cc061SDimitry Andric   // block containing the icmp:
1169ff0cc061SDimitry Andric 
1170ff0cc061SDimitry Andric   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1171ff0cc061SDimitry Andric     return false;
1172ff0cc061SDimitry Andric 
1173ff0cc061SDimitry Andric #ifndef NDEBUG
1174ff0cc061SDimitry Andric   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1175ff0cc061SDimitry Andric   // for now:
1176ff0cc061SDimitry Andric   if (AddI->hasOneUse())
1177ff0cc061SDimitry Andric     assert(*AddI->user_begin() == CI && "expected!");
1178ff0cc061SDimitry Andric #endif
1179ff0cc061SDimitry Andric 
11807d523365SDimitry Andric   Module *M = CI->getModule();
1181ff0cc061SDimitry Andric   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1182ff0cc061SDimitry Andric 
1183ff0cc061SDimitry Andric   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1184ff0cc061SDimitry Andric 
1185*b5893f02SDimitry Andric   DebugLoc Loc = CI->getDebugLoc();
1186ff0cc061SDimitry Andric   auto *UAddWithOverflow =
1187ff0cc061SDimitry Andric       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1188*b5893f02SDimitry Andric   UAddWithOverflow->setDebugLoc(Loc);
1189ff0cc061SDimitry Andric   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1190*b5893f02SDimitry Andric   UAdd->setDebugLoc(Loc);
1191ff0cc061SDimitry Andric   auto *Overflow =
1192ff0cc061SDimitry Andric       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1193*b5893f02SDimitry Andric   Overflow->setDebugLoc(Loc);
1194ff0cc061SDimitry Andric 
1195ff0cc061SDimitry Andric   CI->replaceAllUsesWith(Overflow);
1196ff0cc061SDimitry Andric   AddI->replaceAllUsesWith(UAdd);
1197ff0cc061SDimitry Andric   CI->eraseFromParent();
1198ff0cc061SDimitry Andric   AddI->eraseFromParent();
1199ff0cc061SDimitry Andric   return true;
1200ff0cc061SDimitry Andric }
1201ff0cc061SDimitry Andric 
12027d523365SDimitry Andric /// Sink the given CmpInst into user blocks to reduce the number of virtual
12037d523365SDimitry Andric /// registers that must be created and coalesced. This is a clear win except on
12047d523365SDimitry Andric /// targets with multiple condition code registers (PowerPC), where it might
12057d523365SDimitry Andric /// lose; some adjustment may be wanted there.
120691bc56edSDimitry Andric ///
120791bc56edSDimitry Andric /// Return true if any changes are made.
SinkCmpExpression(CmpInst * CI,const TargetLowering * TLI)12083ca95b02SDimitry Andric static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
120991bc56edSDimitry Andric   BasicBlock *DefBB = CI->getParent();
121091bc56edSDimitry Andric 
12113ca95b02SDimitry Andric   // Avoid sinking soft-FP comparisons, since this can move them into a loop.
12123ca95b02SDimitry Andric   if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
12133ca95b02SDimitry Andric     return false;
12143ca95b02SDimitry Andric 
12153ca95b02SDimitry Andric   // Only insert a cmp in each block once.
121691bc56edSDimitry Andric   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
121791bc56edSDimitry Andric 
121891bc56edSDimitry Andric   bool MadeChange = false;
121991bc56edSDimitry Andric   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
122091bc56edSDimitry Andric        UI != E; ) {
122191bc56edSDimitry Andric     Use &TheUse = UI.getUse();
122291bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
122391bc56edSDimitry Andric 
122491bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
122591bc56edSDimitry Andric     ++UI;
122691bc56edSDimitry Andric 
122791bc56edSDimitry Andric     // Don't bother for PHI nodes.
122891bc56edSDimitry Andric     if (isa<PHINode>(User))
122991bc56edSDimitry Andric       continue;
123091bc56edSDimitry Andric 
123191bc56edSDimitry Andric     // Figure out which BB this cmp is used in.
123291bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
123391bc56edSDimitry Andric 
123491bc56edSDimitry Andric     // If this user is in the same block as the cmp, don't change the cmp.
123591bc56edSDimitry Andric     if (UserBB == DefBB) continue;
123691bc56edSDimitry Andric 
123791bc56edSDimitry Andric     // If we have already inserted a cmp into this block, use it.
123891bc56edSDimitry Andric     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
123991bc56edSDimitry Andric 
124091bc56edSDimitry Andric     if (!InsertedCmp) {
124191bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
12427d523365SDimitry Andric       assert(InsertPt != UserBB->end());
124391bc56edSDimitry Andric       InsertedCmp =
12447d523365SDimitry Andric           CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
12457d523365SDimitry Andric                           CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1246d88c1a5aSDimitry Andric       // Propagate the debug info.
1247d88c1a5aSDimitry Andric       InsertedCmp->setDebugLoc(CI->getDebugLoc());
124891bc56edSDimitry Andric     }
124991bc56edSDimitry Andric 
125091bc56edSDimitry Andric     // Replace a use of the cmp with a use of the new cmp.
125191bc56edSDimitry Andric     TheUse = InsertedCmp;
1252ff0cc061SDimitry Andric     MadeChange = true;
125391bc56edSDimitry Andric     ++NumCmpUses;
125491bc56edSDimitry Andric   }
125591bc56edSDimitry Andric 
125691bc56edSDimitry Andric   // If we removed all uses, nuke the cmp.
1257ff0cc061SDimitry Andric   if (CI->use_empty()) {
125891bc56edSDimitry Andric     CI->eraseFromParent();
1259ff0cc061SDimitry Andric     MadeChange = true;
1260ff0cc061SDimitry Andric   }
126191bc56edSDimitry Andric 
126291bc56edSDimitry Andric   return MadeChange;
126391bc56edSDimitry Andric }
126491bc56edSDimitry Andric 
OptimizeCmpExpression(CmpInst * CI,const TargetLowering * TLI)12653ca95b02SDimitry Andric static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
12663ca95b02SDimitry Andric   if (SinkCmpExpression(CI, TLI))
1267ff0cc061SDimitry Andric     return true;
1268ff0cc061SDimitry Andric 
1269ff0cc061SDimitry Andric   if (CombineUAddWithOverflow(CI))
1270ff0cc061SDimitry Andric     return true;
1271ff0cc061SDimitry Andric 
1272ff0cc061SDimitry Andric   return false;
1273ff0cc061SDimitry Andric }
1274ff0cc061SDimitry Andric 
12757a7e6055SDimitry Andric /// Duplicate and sink the given 'and' instruction into user blocks where it is
12767a7e6055SDimitry Andric /// used in a compare to allow isel to generate better code for targets where
12777a7e6055SDimitry Andric /// this operation can be combined.
12787a7e6055SDimitry Andric ///
12797a7e6055SDimitry Andric /// Return true if any changes are made.
sinkAndCmp0Expression(Instruction * AndI,const TargetLowering & TLI,SetOfInstrs & InsertedInsts)12807a7e6055SDimitry Andric static bool sinkAndCmp0Expression(Instruction *AndI,
12817a7e6055SDimitry Andric                                   const TargetLowering &TLI,
12827a7e6055SDimitry Andric                                   SetOfInstrs &InsertedInsts) {
12837a7e6055SDimitry Andric   // Double-check that we're not trying to optimize an instruction that was
12847a7e6055SDimitry Andric   // already optimized by some other part of this pass.
12857a7e6055SDimitry Andric   assert(!InsertedInsts.count(AndI) &&
12867a7e6055SDimitry Andric          "Attempting to optimize already optimized and instruction");
12877a7e6055SDimitry Andric   (void) InsertedInsts;
12887a7e6055SDimitry Andric 
12897a7e6055SDimitry Andric   // Nothing to do for single use in same basic block.
12907a7e6055SDimitry Andric   if (AndI->hasOneUse() &&
12917a7e6055SDimitry Andric       AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
12927a7e6055SDimitry Andric     return false;
12937a7e6055SDimitry Andric 
12947a7e6055SDimitry Andric   // Try to avoid cases where sinking/duplicating is likely to increase register
12957a7e6055SDimitry Andric   // pressure.
12967a7e6055SDimitry Andric   if (!isa<ConstantInt>(AndI->getOperand(0)) &&
12977a7e6055SDimitry Andric       !isa<ConstantInt>(AndI->getOperand(1)) &&
12987a7e6055SDimitry Andric       AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
12997a7e6055SDimitry Andric     return false;
13007a7e6055SDimitry Andric 
13017a7e6055SDimitry Andric   for (auto *U : AndI->users()) {
13027a7e6055SDimitry Andric     Instruction *User = cast<Instruction>(U);
13037a7e6055SDimitry Andric 
13047a7e6055SDimitry Andric     // Only sink for and mask feeding icmp with 0.
13057a7e6055SDimitry Andric     if (!isa<ICmpInst>(User))
13067a7e6055SDimitry Andric       return false;
13077a7e6055SDimitry Andric 
13087a7e6055SDimitry Andric     auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
13097a7e6055SDimitry Andric     if (!CmpC || !CmpC->isZero())
13107a7e6055SDimitry Andric       return false;
13117a7e6055SDimitry Andric   }
13127a7e6055SDimitry Andric 
13137a7e6055SDimitry Andric   if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
13147a7e6055SDimitry Andric     return false;
13157a7e6055SDimitry Andric 
13164ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
13174ba319b5SDimitry Andric   LLVM_DEBUG(AndI->getParent()->dump());
13187a7e6055SDimitry Andric 
13197a7e6055SDimitry Andric   // Push the 'and' into the same block as the icmp 0.  There should only be
13207a7e6055SDimitry Andric   // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
13217a7e6055SDimitry Andric   // others, so we don't need to keep track of which BBs we insert into.
13227a7e6055SDimitry Andric   for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
13237a7e6055SDimitry Andric        UI != E; ) {
13247a7e6055SDimitry Andric     Use &TheUse = UI.getUse();
13257a7e6055SDimitry Andric     Instruction *User = cast<Instruction>(*UI);
13267a7e6055SDimitry Andric 
13277a7e6055SDimitry Andric     // Preincrement use iterator so we don't invalidate it.
13287a7e6055SDimitry Andric     ++UI;
13297a7e6055SDimitry Andric 
13304ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
13317a7e6055SDimitry Andric 
13327a7e6055SDimitry Andric     // Keep the 'and' in the same place if the use is already in the same block.
13337a7e6055SDimitry Andric     Instruction *InsertPt =
13347a7e6055SDimitry Andric         User->getParent() == AndI->getParent() ? AndI : User;
13357a7e6055SDimitry Andric     Instruction *InsertedAnd =
13367a7e6055SDimitry Andric         BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
13377a7e6055SDimitry Andric                                AndI->getOperand(1), "", InsertPt);
13387a7e6055SDimitry Andric     // Propagate the debug info.
13397a7e6055SDimitry Andric     InsertedAnd->setDebugLoc(AndI->getDebugLoc());
13407a7e6055SDimitry Andric 
13417a7e6055SDimitry Andric     // Replace a use of the 'and' with a use of the new 'and'.
13427a7e6055SDimitry Andric     TheUse = InsertedAnd;
13437a7e6055SDimitry Andric     ++NumAndUses;
13444ba319b5SDimitry Andric     LLVM_DEBUG(User->getParent()->dump());
13457a7e6055SDimitry Andric   }
13467a7e6055SDimitry Andric 
13477a7e6055SDimitry Andric   // We removed all uses, nuke the and.
13487a7e6055SDimitry Andric   AndI->eraseFromParent();
13497a7e6055SDimitry Andric   return true;
13507a7e6055SDimitry Andric }
13517a7e6055SDimitry Andric 
13527d523365SDimitry Andric /// Check if the candidates could be combined with a shift instruction, which
13537d523365SDimitry Andric /// includes:
135491bc56edSDimitry Andric /// 1. Truncate instruction
135591bc56edSDimitry Andric /// 2. And instruction and the imm is a mask of the low bits:
135691bc56edSDimitry Andric /// imm & (imm+1) == 0
isExtractBitsCandidateUse(Instruction * User)135791bc56edSDimitry Andric static bool isExtractBitsCandidateUse(Instruction *User) {
135891bc56edSDimitry Andric   if (!isa<TruncInst>(User)) {
135991bc56edSDimitry Andric     if (User->getOpcode() != Instruction::And ||
136091bc56edSDimitry Andric         !isa<ConstantInt>(User->getOperand(1)))
136191bc56edSDimitry Andric       return false;
136291bc56edSDimitry Andric 
136391bc56edSDimitry Andric     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
136491bc56edSDimitry Andric 
136591bc56edSDimitry Andric     if ((Cimm & (Cimm + 1)).getBoolValue())
136691bc56edSDimitry Andric       return false;
136791bc56edSDimitry Andric   }
136891bc56edSDimitry Andric   return true;
136991bc56edSDimitry Andric }
137091bc56edSDimitry Andric 
13717d523365SDimitry Andric /// Sink both shift and truncate instruction to the use of truncate's BB.
137291bc56edSDimitry Andric static bool
SinkShiftAndTruncate(BinaryOperator * ShiftI,Instruction * User,ConstantInt * CI,DenseMap<BasicBlock *,BinaryOperator * > & InsertedShifts,const TargetLowering & TLI,const DataLayout & DL)137391bc56edSDimitry Andric SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
137491bc56edSDimitry Andric                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1375875ed548SDimitry Andric                      const TargetLowering &TLI, const DataLayout &DL) {
137691bc56edSDimitry Andric   BasicBlock *UserBB = User->getParent();
137791bc56edSDimitry Andric   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
137891bc56edSDimitry Andric   TruncInst *TruncI = dyn_cast<TruncInst>(User);
137991bc56edSDimitry Andric   bool MadeChange = false;
138091bc56edSDimitry Andric 
138191bc56edSDimitry Andric   for (Value::user_iterator TruncUI = TruncI->user_begin(),
138291bc56edSDimitry Andric                             TruncE = TruncI->user_end();
138391bc56edSDimitry Andric        TruncUI != TruncE;) {
138491bc56edSDimitry Andric 
138591bc56edSDimitry Andric     Use &TruncTheUse = TruncUI.getUse();
138691bc56edSDimitry Andric     Instruction *TruncUser = cast<Instruction>(*TruncUI);
138791bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
138891bc56edSDimitry Andric 
138991bc56edSDimitry Andric     ++TruncUI;
139091bc56edSDimitry Andric 
139191bc56edSDimitry Andric     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
139291bc56edSDimitry Andric     if (!ISDOpcode)
139391bc56edSDimitry Andric       continue;
139491bc56edSDimitry Andric 
139539d628a0SDimitry Andric     // If the use is actually a legal node, there will not be an
139639d628a0SDimitry Andric     // implicit truncate.
139739d628a0SDimitry Andric     // FIXME: always querying the result type is just an
139839d628a0SDimitry Andric     // approximation; some nodes' legality is determined by the
139939d628a0SDimitry Andric     // operand or other means. There's no good way to find out though.
140039d628a0SDimitry Andric     if (TLI.isOperationLegalOrCustom(
1401875ed548SDimitry Andric             ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
140291bc56edSDimitry Andric       continue;
140391bc56edSDimitry Andric 
140491bc56edSDimitry Andric     // Don't bother for PHI nodes.
140591bc56edSDimitry Andric     if (isa<PHINode>(TruncUser))
140691bc56edSDimitry Andric       continue;
140791bc56edSDimitry Andric 
140891bc56edSDimitry Andric     BasicBlock *TruncUserBB = TruncUser->getParent();
140991bc56edSDimitry Andric 
141091bc56edSDimitry Andric     if (UserBB == TruncUserBB)
141191bc56edSDimitry Andric       continue;
141291bc56edSDimitry Andric 
141391bc56edSDimitry Andric     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
141491bc56edSDimitry Andric     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
141591bc56edSDimitry Andric 
141691bc56edSDimitry Andric     if (!InsertedShift && !InsertedTrunc) {
141791bc56edSDimitry Andric       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
14187d523365SDimitry Andric       assert(InsertPt != TruncUserBB->end());
141991bc56edSDimitry Andric       // Sink the shift
142091bc56edSDimitry Andric       if (ShiftI->getOpcode() == Instruction::AShr)
14217d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
14227d523365SDimitry Andric                                                    "", &*InsertPt);
142391bc56edSDimitry Andric       else
14247d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
14257d523365SDimitry Andric                                                    "", &*InsertPt);
1426*b5893f02SDimitry Andric       InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
142791bc56edSDimitry Andric 
142891bc56edSDimitry Andric       // Sink the trunc
142991bc56edSDimitry Andric       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
143091bc56edSDimitry Andric       TruncInsertPt++;
14317d523365SDimitry Andric       assert(TruncInsertPt != TruncUserBB->end());
143291bc56edSDimitry Andric 
143391bc56edSDimitry Andric       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
14347d523365SDimitry Andric                                        TruncI->getType(), "", &*TruncInsertPt);
1435*b5893f02SDimitry Andric       InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
143691bc56edSDimitry Andric 
143791bc56edSDimitry Andric       MadeChange = true;
143891bc56edSDimitry Andric 
143991bc56edSDimitry Andric       TruncTheUse = InsertedTrunc;
144091bc56edSDimitry Andric     }
144191bc56edSDimitry Andric   }
144291bc56edSDimitry Andric   return MadeChange;
144391bc56edSDimitry Andric }
144491bc56edSDimitry Andric 
14457d523365SDimitry Andric /// Sink the shift *right* instruction into user blocks if the uses could
14467d523365SDimitry Andric /// potentially be combined with this shift instruction and generate BitExtract
14477d523365SDimitry Andric /// instruction. It will only be applied if the architecture supports BitExtract
14487d523365SDimitry Andric /// instruction. Here is an example:
144991bc56edSDimitry Andric /// BB1:
145091bc56edSDimitry Andric ///   %x.extract.shift = lshr i64 %arg1, 32
145191bc56edSDimitry Andric /// BB2:
145291bc56edSDimitry Andric ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
145391bc56edSDimitry Andric /// ==>
145491bc56edSDimitry Andric ///
145591bc56edSDimitry Andric /// BB2:
145691bc56edSDimitry Andric ///   %x.extract.shift.1 = lshr i64 %arg1, 32
145791bc56edSDimitry Andric ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
145891bc56edSDimitry Andric ///
14594ba319b5SDimitry Andric /// CodeGen will recognize the pattern in BB2 and generate BitExtract
146091bc56edSDimitry Andric /// instruction.
146191bc56edSDimitry Andric /// Return true if any changes are made.
OptimizeExtractBits(BinaryOperator * ShiftI,ConstantInt * CI,const TargetLowering & TLI,const DataLayout & DL)146291bc56edSDimitry Andric static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1463875ed548SDimitry Andric                                 const TargetLowering &TLI,
1464875ed548SDimitry Andric                                 const DataLayout &DL) {
146591bc56edSDimitry Andric   BasicBlock *DefBB = ShiftI->getParent();
146691bc56edSDimitry Andric 
146791bc56edSDimitry Andric   /// Only insert instructions in each block once.
146891bc56edSDimitry Andric   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
146991bc56edSDimitry Andric 
1470875ed548SDimitry Andric   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
147191bc56edSDimitry Andric 
147291bc56edSDimitry Andric   bool MadeChange = false;
147391bc56edSDimitry Andric   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
147491bc56edSDimitry Andric        UI != E;) {
147591bc56edSDimitry Andric     Use &TheUse = UI.getUse();
147691bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
147791bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
147891bc56edSDimitry Andric     ++UI;
147991bc56edSDimitry Andric 
148091bc56edSDimitry Andric     // Don't bother for PHI nodes.
148191bc56edSDimitry Andric     if (isa<PHINode>(User))
148291bc56edSDimitry Andric       continue;
148391bc56edSDimitry Andric 
148491bc56edSDimitry Andric     if (!isExtractBitsCandidateUse(User))
148591bc56edSDimitry Andric       continue;
148691bc56edSDimitry Andric 
148791bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
148891bc56edSDimitry Andric 
148991bc56edSDimitry Andric     if (UserBB == DefBB) {
149091bc56edSDimitry Andric       // If the shift and truncate instruction are in the same BB. The use of
149191bc56edSDimitry Andric       // the truncate(TruncUse) may still introduce another truncate if not
149291bc56edSDimitry Andric       // legal. In this case, we would like to sink both shift and truncate
149391bc56edSDimitry Andric       // instruction to the BB of TruncUse.
149491bc56edSDimitry Andric       // for example:
149591bc56edSDimitry Andric       // BB1:
149691bc56edSDimitry Andric       // i64 shift.result = lshr i64 opnd, imm
149791bc56edSDimitry Andric       // trunc.result = trunc shift.result to i16
149891bc56edSDimitry Andric       //
149991bc56edSDimitry Andric       // BB2:
150091bc56edSDimitry Andric       //   ----> We will have an implicit truncate here if the architecture does
150191bc56edSDimitry Andric       //   not have i16 compare.
150291bc56edSDimitry Andric       // cmp i16 trunc.result, opnd2
150391bc56edSDimitry Andric       //
150491bc56edSDimitry Andric       if (isa<TruncInst>(User) && shiftIsLegal
15054ba319b5SDimitry Andric           // If the type of the truncate is legal, no truncate will be
150691bc56edSDimitry Andric           // introduced in other basic blocks.
1507875ed548SDimitry Andric           &&
1508875ed548SDimitry Andric           (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
150991bc56edSDimitry Andric         MadeChange =
1510875ed548SDimitry Andric             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
151191bc56edSDimitry Andric 
151291bc56edSDimitry Andric       continue;
151391bc56edSDimitry Andric     }
151491bc56edSDimitry Andric     // If we have already inserted a shift into this block, use it.
151591bc56edSDimitry Andric     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
151691bc56edSDimitry Andric 
151791bc56edSDimitry Andric     if (!InsertedShift) {
151891bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
15197d523365SDimitry Andric       assert(InsertPt != UserBB->end());
152091bc56edSDimitry Andric 
152191bc56edSDimitry Andric       if (ShiftI->getOpcode() == Instruction::AShr)
15227d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
15237d523365SDimitry Andric                                                    "", &*InsertPt);
152491bc56edSDimitry Andric       else
15257d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
15267d523365SDimitry Andric                                                    "", &*InsertPt);
1527*b5893f02SDimitry Andric       InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
152891bc56edSDimitry Andric 
152991bc56edSDimitry Andric       MadeChange = true;
153091bc56edSDimitry Andric     }
153191bc56edSDimitry Andric 
153291bc56edSDimitry Andric     // Replace a use of the shift with a use of the new shift.
153391bc56edSDimitry Andric     TheUse = InsertedShift;
153491bc56edSDimitry Andric   }
153591bc56edSDimitry Andric 
153691bc56edSDimitry Andric   // If we removed all uses, nuke the shift.
1537*b5893f02SDimitry Andric   if (ShiftI->use_empty()) {
1538*b5893f02SDimitry Andric     salvageDebugInfo(*ShiftI);
153991bc56edSDimitry Andric     ShiftI->eraseFromParent();
1540*b5893f02SDimitry Andric   }
154191bc56edSDimitry Andric 
154291bc56edSDimitry Andric   return MadeChange;
154391bc56edSDimitry Andric }
154491bc56edSDimitry Andric 
15457d523365SDimitry Andric /// If counting leading or trailing zeros is an expensive operation and a zero
15467d523365SDimitry Andric /// input is defined, add a check for zero to avoid calling the intrinsic.
15477d523365SDimitry Andric ///
15487d523365SDimitry Andric /// We want to transform:
15497d523365SDimitry Andric ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
15507d523365SDimitry Andric ///
15517d523365SDimitry Andric /// into:
15527d523365SDimitry Andric ///   entry:
15537d523365SDimitry Andric ///     %cmpz = icmp eq i64 %A, 0
15547d523365SDimitry Andric ///     br i1 %cmpz, label %cond.end, label %cond.false
15557d523365SDimitry Andric ///   cond.false:
15567d523365SDimitry Andric ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
15577d523365SDimitry Andric ///     br label %cond.end
15587d523365SDimitry Andric ///   cond.end:
15597d523365SDimitry Andric ///     %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
15607d523365SDimitry Andric ///
15617d523365SDimitry Andric /// If the transform is performed, return true and set ModifiedDT to true.
despeculateCountZeros(IntrinsicInst * CountZeros,const TargetLowering * TLI,const DataLayout * DL,bool & ModifiedDT)15627d523365SDimitry Andric static bool despeculateCountZeros(IntrinsicInst *CountZeros,
15637d523365SDimitry Andric                                   const TargetLowering *TLI,
15647d523365SDimitry Andric                                   const DataLayout *DL,
15657d523365SDimitry Andric                                   bool &ModifiedDT) {
15667d523365SDimitry Andric   if (!TLI || !DL)
15677d523365SDimitry Andric     return false;
15687d523365SDimitry Andric 
15697d523365SDimitry Andric   // If a zero input is undefined, it doesn't make sense to despeculate that.
15707d523365SDimitry Andric   if (match(CountZeros->getOperand(1), m_One()))
15717d523365SDimitry Andric     return false;
15727d523365SDimitry Andric 
15737d523365SDimitry Andric   // If it's cheap to speculate, there's nothing to do.
15747d523365SDimitry Andric   auto IntrinsicID = CountZeros->getIntrinsicID();
15757d523365SDimitry Andric   if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
15767d523365SDimitry Andric       (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
15777d523365SDimitry Andric     return false;
15787d523365SDimitry Andric 
15797d523365SDimitry Andric   // Only handle legal scalar cases. Anything else requires too much work.
15807d523365SDimitry Andric   Type *Ty = CountZeros->getType();
15817d523365SDimitry Andric   unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
15823ca95b02SDimitry Andric   if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
15837d523365SDimitry Andric     return false;
15847d523365SDimitry Andric 
15857d523365SDimitry Andric   // The intrinsic will be sunk behind a compare against zero and branch.
15867d523365SDimitry Andric   BasicBlock *StartBlock = CountZeros->getParent();
15877d523365SDimitry Andric   BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
15887d523365SDimitry Andric 
15897d523365SDimitry Andric   // Create another block after the count zero intrinsic. A PHI will be added
15907d523365SDimitry Andric   // in this block to select the result of the intrinsic or the bit-width
15917d523365SDimitry Andric   // constant if the input to the intrinsic is zero.
15927d523365SDimitry Andric   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
15937d523365SDimitry Andric   BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
15947d523365SDimitry Andric 
15957d523365SDimitry Andric   // Set up a builder to create a compare, conditional branch, and PHI.
15967d523365SDimitry Andric   IRBuilder<> Builder(CountZeros->getContext());
15977d523365SDimitry Andric   Builder.SetInsertPoint(StartBlock->getTerminator());
15987d523365SDimitry Andric   Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
15997d523365SDimitry Andric 
16007d523365SDimitry Andric   // Replace the unconditional branch that was created by the first split with
16017d523365SDimitry Andric   // a compare against zero and a conditional branch.
16027d523365SDimitry Andric   Value *Zero = Constant::getNullValue(Ty);
16037d523365SDimitry Andric   Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
16047d523365SDimitry Andric   Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
16057d523365SDimitry Andric   StartBlock->getTerminator()->eraseFromParent();
16067d523365SDimitry Andric 
16077d523365SDimitry Andric   // Create a PHI in the end block to select either the output of the intrinsic
16087d523365SDimitry Andric   // or the bit width of the operand.
16097d523365SDimitry Andric   Builder.SetInsertPoint(&EndBlock->front());
16107d523365SDimitry Andric   PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
16117d523365SDimitry Andric   CountZeros->replaceAllUsesWith(PN);
16127d523365SDimitry Andric   Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
16137d523365SDimitry Andric   PN->addIncoming(BitWidth, StartBlock);
16147d523365SDimitry Andric   PN->addIncoming(CountZeros, CallBlock);
16157d523365SDimitry Andric 
16167d523365SDimitry Andric   // We are explicitly handling the zero case, so we can set the intrinsic's
16177d523365SDimitry Andric   // undefined zero argument to 'true'. This will also prevent reprocessing the
16187d523365SDimitry Andric   // intrinsic; we only despeculate when a zero input is defined.
16197d523365SDimitry Andric   CountZeros->setArgOperand(1, Builder.getTrue());
16207d523365SDimitry Andric   ModifiedDT = true;
16217d523365SDimitry Andric   return true;
16227d523365SDimitry Andric }
16237d523365SDimitry Andric 
optimizeCallInst(CallInst * CI,bool & ModifiedDT)16247d523365SDimitry Andric bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
162591bc56edSDimitry Andric   BasicBlock *BB = CI->getParent();
162691bc56edSDimitry Andric 
162791bc56edSDimitry Andric   // Lower inline assembly if we can.
162891bc56edSDimitry Andric   // If we found an inline asm expession, and if the target knows how to
162991bc56edSDimitry Andric   // lower it to normal LLVM code, do so now.
163091bc56edSDimitry Andric   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
163191bc56edSDimitry Andric     if (TLI->ExpandInlineAsm(CI)) {
163291bc56edSDimitry Andric       // Avoid invalidating the iterator.
163391bc56edSDimitry Andric       CurInstIterator = BB->begin();
163491bc56edSDimitry Andric       // Avoid processing instructions out of order, which could cause
163591bc56edSDimitry Andric       // reuse before a value is defined.
163691bc56edSDimitry Andric       SunkAddrs.clear();
163791bc56edSDimitry Andric       return true;
163891bc56edSDimitry Andric     }
163991bc56edSDimitry Andric     // Sink address computing for memory operands into the block.
16407d523365SDimitry Andric     if (optimizeInlineAsmInst(CI))
164191bc56edSDimitry Andric       return true;
164291bc56edSDimitry Andric   }
164391bc56edSDimitry Andric 
1644ff0cc061SDimitry Andric   // Align the pointer arguments to this call if the target thinks it's a good
1645ff0cc061SDimitry Andric   // idea
1646ff0cc061SDimitry Andric   unsigned MinSize, PrefAlign;
1647875ed548SDimitry Andric   if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1648ff0cc061SDimitry Andric     for (auto &Arg : CI->arg_operands()) {
1649ff0cc061SDimitry Andric       // We want to align both objects whose address is used directly and
1650ff0cc061SDimitry Andric       // objects whose address is used in casts and GEPs, though it only makes
1651ff0cc061SDimitry Andric       // sense for GEPs if the offset is a multiple of the desired alignment and
1652ff0cc061SDimitry Andric       // if size - offset meets the size threshold.
1653ff0cc061SDimitry Andric       if (!Arg->getType()->isPointerTy())
1654ff0cc061SDimitry Andric         continue;
16554ba319b5SDimitry Andric       APInt Offset(DL->getIndexSizeInBits(
1656875ed548SDimitry Andric                        cast<PointerType>(Arg->getType())->getAddressSpace()),
1657875ed548SDimitry Andric                    0);
1658875ed548SDimitry Andric       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
1659ff0cc061SDimitry Andric       uint64_t Offset2 = Offset.getLimitedValue();
1660ff0cc061SDimitry Andric       if ((Offset2 & (PrefAlign-1)) != 0)
1661ff0cc061SDimitry Andric         continue;
1662ff0cc061SDimitry Andric       AllocaInst *AI;
1663875ed548SDimitry Andric       if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1664875ed548SDimitry Andric           DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
1665ff0cc061SDimitry Andric         AI->setAlignment(PrefAlign);
1666ff0cc061SDimitry Andric       // Global variables can only be aligned if they are defined in this
1667ff0cc061SDimitry Andric       // object (i.e. they are uniquely initialized in this object), and
1668ff0cc061SDimitry Andric       // over-aligning global variables that have an explicit section is
1669ff0cc061SDimitry Andric       // forbidden.
1670ff0cc061SDimitry Andric       GlobalVariable *GV;
1671cdd9644cSDimitry Andric       if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
16723ca95b02SDimitry Andric           GV->getPointerAlignment(*DL) < PrefAlign &&
16733ca95b02SDimitry Andric           DL->getTypeAllocSize(GV->getValueType()) >=
1674875ed548SDimitry Andric               MinSize + Offset2)
1675ff0cc061SDimitry Andric         GV->setAlignment(PrefAlign);
1676ff0cc061SDimitry Andric     }
1677ff0cc061SDimitry Andric     // If this is a memcpy (or similar) then we may be able to improve the
1678ff0cc061SDimitry Andric     // alignment
1679ff0cc061SDimitry Andric     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
16804ba319b5SDimitry Andric       unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
16814ba319b5SDimitry Andric       if (DestAlign > MI->getDestAlignment())
16824ba319b5SDimitry Andric         MI->setDestAlignment(DestAlign);
16834ba319b5SDimitry Andric       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
16844ba319b5SDimitry Andric         unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
16854ba319b5SDimitry Andric         if (SrcAlign > MTI->getSourceAlignment())
16864ba319b5SDimitry Andric           MTI->setSourceAlignment(SrcAlign);
16874ba319b5SDimitry Andric       }
1688ff0cc061SDimitry Andric     }
1689ff0cc061SDimitry Andric   }
1690ff0cc061SDimitry Andric 
16913ca95b02SDimitry Andric   // If we have a cold call site, try to sink addressing computation into the
16923ca95b02SDimitry Andric   // cold block.  This interacts with our handling for loads and stores to
16933ca95b02SDimitry Andric   // ensure that we can fold all uses of a potential addressing computation
16943ca95b02SDimitry Andric   // into their uses.  TODO: generalize this to work over profiling data
16953ca95b02SDimitry Andric   if (!OptSize && CI->hasFnAttr(Attribute::Cold))
16963ca95b02SDimitry Andric     for (auto &Arg : CI->arg_operands()) {
16973ca95b02SDimitry Andric       if (!Arg->getType()->isPointerTy())
16983ca95b02SDimitry Andric         continue;
16993ca95b02SDimitry Andric       unsigned AS = Arg->getType()->getPointerAddressSpace();
17003ca95b02SDimitry Andric       return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
17013ca95b02SDimitry Andric     }
17023ca95b02SDimitry Andric 
170391bc56edSDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
170439d628a0SDimitry Andric   if (II) {
170539d628a0SDimitry Andric     switch (II->getIntrinsicID()) {
170639d628a0SDimitry Andric     default: break;
170739d628a0SDimitry Andric     case Intrinsic::objectsize: {
170839d628a0SDimitry Andric       // Lower all uses of llvm.objectsize.*
1709d88c1a5aSDimitry Andric       ConstantInt *RetVal =
1710d88c1a5aSDimitry Andric           lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
171191bc56edSDimitry Andric 
1712*b5893f02SDimitry Andric       resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
17133ca95b02SDimitry Andric         replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1714*b5893f02SDimitry Andric       });
1715*b5893f02SDimitry Andric       return true;
171691bc56edSDimitry Andric     }
1717*b5893f02SDimitry Andric     case Intrinsic::is_constant: {
1718*b5893f02SDimitry Andric       // If is_constant hasn't folded away yet, lower it to false now.
1719*b5893f02SDimitry Andric       Constant *RetVal = ConstantInt::get(II->getType(), 0);
1720*b5893f02SDimitry Andric       resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1721*b5893f02SDimitry Andric         replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1722*b5893f02SDimitry Andric       });
172391bc56edSDimitry Andric       return true;
172491bc56edSDimitry Andric     }
1725ff0cc061SDimitry Andric     case Intrinsic::aarch64_stlxr:
1726ff0cc061SDimitry Andric     case Intrinsic::aarch64_stxr: {
1727ff0cc061SDimitry Andric       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1728ff0cc061SDimitry Andric       if (!ExtVal || !ExtVal->hasOneUse() ||
1729ff0cc061SDimitry Andric           ExtVal->getParent() == CI->getParent())
1730ff0cc061SDimitry Andric         return false;
1731ff0cc061SDimitry Andric       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1732ff0cc061SDimitry Andric       ExtVal->moveBefore(CI);
17338f0fd8f6SDimitry Andric       // Mark this instruction as "inserted by CGP", so that other
17348f0fd8f6SDimitry Andric       // optimizations don't touch it.
17358f0fd8f6SDimitry Andric       InsertedInsts.insert(ExtVal);
1736ff0cc061SDimitry Andric       return true;
1737ff0cc061SDimitry Andric     }
17384ba319b5SDimitry Andric     case Intrinsic::launder_invariant_group:
1739*b5893f02SDimitry Andric     case Intrinsic::strip_invariant_group: {
1740*b5893f02SDimitry Andric       Value *ArgVal = II->getArgOperand(0);
1741*b5893f02SDimitry Andric       auto it = LargeOffsetGEPMap.find(II);
1742*b5893f02SDimitry Andric       if (it != LargeOffsetGEPMap.end()) {
1743*b5893f02SDimitry Andric           // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
1744*b5893f02SDimitry Andric           // Make sure not to have to deal with iterator invalidation
1745*b5893f02SDimitry Andric           // after possibly adding ArgVal to LargeOffsetGEPMap.
1746*b5893f02SDimitry Andric           auto GEPs = std::move(it->second);
1747*b5893f02SDimitry Andric           LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
1748*b5893f02SDimitry Andric           LargeOffsetGEPMap.erase(II);
1749*b5893f02SDimitry Andric       }
1750*b5893f02SDimitry Andric 
1751*b5893f02SDimitry Andric       II->replaceAllUsesWith(ArgVal);
17527d523365SDimitry Andric       II->eraseFromParent();
17537d523365SDimitry Andric       return true;
1754*b5893f02SDimitry Andric     }
17557d523365SDimitry Andric     case Intrinsic::cttz:
17567d523365SDimitry Andric     case Intrinsic::ctlz:
17577d523365SDimitry Andric       // If counting zeros is expensive, try to avoid it.
17587d523365SDimitry Andric       return despeculateCountZeros(II, TLI, DL, ModifiedDT);
175939d628a0SDimitry Andric     }
176091bc56edSDimitry Andric 
176139d628a0SDimitry Andric     if (TLI) {
176291bc56edSDimitry Andric       SmallVector<Value*, 2> PtrOps;
176391bc56edSDimitry Andric       Type *AccessTy;
17647a7e6055SDimitry Andric       if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
17657a7e6055SDimitry Andric         while (!PtrOps.empty()) {
17667a7e6055SDimitry Andric           Value *PtrVal = PtrOps.pop_back_val();
17677a7e6055SDimitry Andric           unsigned AS = PtrVal->getType()->getPointerAddressSpace();
17687a7e6055SDimitry Andric           if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
176991bc56edSDimitry Andric             return true;
177091bc56edSDimitry Andric         }
177139d628a0SDimitry Andric     }
17727a7e6055SDimitry Andric   }
177391bc56edSDimitry Andric 
177491bc56edSDimitry Andric   // From here on out we're working with named functions.
177591bc56edSDimitry Andric   if (!CI->getCalledFunction()) return false;
177691bc56edSDimitry Andric 
177791bc56edSDimitry Andric   // Lower all default uses of _chk calls.  This is very similar
177891bc56edSDimitry Andric   // to what InstCombineCalls does, but here we are only lowering calls
177939d628a0SDimitry Andric   // to fortified library functions (e.g. __memcpy_chk) that have the default
178039d628a0SDimitry Andric   // "don't know" as the objectsize.  Anything else should be left alone.
1781ff0cc061SDimitry Andric   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
178239d628a0SDimitry Andric   if (Value *V = Simplifier.optimizeCall(CI)) {
178339d628a0SDimitry Andric     CI->replaceAllUsesWith(V);
178439d628a0SDimitry Andric     CI->eraseFromParent();
178539d628a0SDimitry Andric     return true;
178639d628a0SDimitry Andric   }
1787f9448bf3SDimitry Andric 
178839d628a0SDimitry Andric   return false;
178991bc56edSDimitry Andric }
179091bc56edSDimitry Andric 
17917d523365SDimitry Andric /// Look for opportunities to duplicate return instructions to the predecessor
17927d523365SDimitry Andric /// to enable tail call optimizations. The case it is currently looking for is:
179391bc56edSDimitry Andric /// @code
179491bc56edSDimitry Andric /// bb0:
179591bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
179691bc56edSDimitry Andric ///   br label %return
179791bc56edSDimitry Andric /// bb1:
179891bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
179991bc56edSDimitry Andric ///   br label %return
180091bc56edSDimitry Andric /// bb2:
180191bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
180291bc56edSDimitry Andric ///   br label %return
180391bc56edSDimitry Andric /// return:
180491bc56edSDimitry Andric ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
180591bc56edSDimitry Andric ///   ret i32 %retval
180691bc56edSDimitry Andric /// @endcode
180791bc56edSDimitry Andric ///
180891bc56edSDimitry Andric /// =>
180991bc56edSDimitry Andric ///
181091bc56edSDimitry Andric /// @code
181191bc56edSDimitry Andric /// bb0:
181291bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
181391bc56edSDimitry Andric ///   ret i32 %tmp0
181491bc56edSDimitry Andric /// bb1:
181591bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
181691bc56edSDimitry Andric ///   ret i32 %tmp1
181791bc56edSDimitry Andric /// bb2:
181891bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
181991bc56edSDimitry Andric ///   ret i32 %tmp2
182091bc56edSDimitry Andric /// @endcode
dupRetToEnableTailCallOpts(BasicBlock * BB)18217d523365SDimitry Andric bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
182291bc56edSDimitry Andric   if (!TLI)
182391bc56edSDimitry Andric     return false;
182491bc56edSDimitry Andric 
1825d88c1a5aSDimitry Andric   ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1826d88c1a5aSDimitry Andric   if (!RetI)
182791bc56edSDimitry Andric     return false;
182891bc56edSDimitry Andric 
182991bc56edSDimitry Andric   PHINode *PN = nullptr;
183091bc56edSDimitry Andric   BitCastInst *BCI = nullptr;
1831d88c1a5aSDimitry Andric   Value *V = RetI->getReturnValue();
183291bc56edSDimitry Andric   if (V) {
183391bc56edSDimitry Andric     BCI = dyn_cast<BitCastInst>(V);
183491bc56edSDimitry Andric     if (BCI)
183591bc56edSDimitry Andric       V = BCI->getOperand(0);
183691bc56edSDimitry Andric 
183791bc56edSDimitry Andric     PN = dyn_cast<PHINode>(V);
183891bc56edSDimitry Andric     if (!PN)
183991bc56edSDimitry Andric       return false;
184091bc56edSDimitry Andric   }
184191bc56edSDimitry Andric 
184291bc56edSDimitry Andric   if (PN && PN->getParent() != BB)
184391bc56edSDimitry Andric     return false;
184491bc56edSDimitry Andric 
184591bc56edSDimitry Andric   // Make sure there are no instructions between the PHI and return, or that the
184691bc56edSDimitry Andric   // return is the first instruction in the block.
184791bc56edSDimitry Andric   if (PN) {
184891bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
184991bc56edSDimitry Andric     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
185091bc56edSDimitry Andric     if (&*BI == BCI)
185191bc56edSDimitry Andric       // Also skip over the bitcast.
185291bc56edSDimitry Andric       ++BI;
1853d88c1a5aSDimitry Andric     if (&*BI != RetI)
185491bc56edSDimitry Andric       return false;
185591bc56edSDimitry Andric   } else {
185691bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
185791bc56edSDimitry Andric     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1858d88c1a5aSDimitry Andric     if (&*BI != RetI)
185991bc56edSDimitry Andric       return false;
186091bc56edSDimitry Andric   }
186191bc56edSDimitry Andric 
186291bc56edSDimitry Andric   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
186391bc56edSDimitry Andric   /// call.
1864d88c1a5aSDimitry Andric   const Function *F = BB->getParent();
186591bc56edSDimitry Andric   SmallVector<CallInst*, 4> TailCalls;
186691bc56edSDimitry Andric   if (PN) {
186791bc56edSDimitry Andric     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
186891bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
186991bc56edSDimitry Andric       // Make sure the phi value is indeed produced by the tail call.
187091bc56edSDimitry Andric       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1871d88c1a5aSDimitry Andric           TLI->mayBeEmittedAsTailCall(CI) &&
1872d88c1a5aSDimitry Andric           attributesPermitTailCall(F, CI, RetI, *TLI))
187391bc56edSDimitry Andric         TailCalls.push_back(CI);
187491bc56edSDimitry Andric     }
187591bc56edSDimitry Andric   } else {
187691bc56edSDimitry Andric     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
187791bc56edSDimitry Andric     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
187839d628a0SDimitry Andric       if (!VisitedBBs.insert(*PI).second)
187991bc56edSDimitry Andric         continue;
188091bc56edSDimitry Andric 
188191bc56edSDimitry Andric       BasicBlock::InstListType &InstList = (*PI)->getInstList();
188291bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
188391bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
188491bc56edSDimitry Andric       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
188591bc56edSDimitry Andric       if (RI == RE)
188691bc56edSDimitry Andric         continue;
188791bc56edSDimitry Andric 
188891bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(&*RI);
1889d88c1a5aSDimitry Andric       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1890d88c1a5aSDimitry Andric           attributesPermitTailCall(F, CI, RetI, *TLI))
189191bc56edSDimitry Andric         TailCalls.push_back(CI);
189291bc56edSDimitry Andric     }
189391bc56edSDimitry Andric   }
189491bc56edSDimitry Andric 
189591bc56edSDimitry Andric   bool Changed = false;
189691bc56edSDimitry Andric   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
189791bc56edSDimitry Andric     CallInst *CI = TailCalls[i];
189891bc56edSDimitry Andric     CallSite CS(CI);
189991bc56edSDimitry Andric 
190091bc56edSDimitry Andric     // Make sure the call instruction is followed by an unconditional branch to
190191bc56edSDimitry Andric     // the return block.
190291bc56edSDimitry Andric     BasicBlock *CallBB = CI->getParent();
190391bc56edSDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
190491bc56edSDimitry Andric     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
190591bc56edSDimitry Andric       continue;
190691bc56edSDimitry Andric 
190791bc56edSDimitry Andric     // Duplicate the return into CallBB.
1908d88c1a5aSDimitry Andric     (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
190991bc56edSDimitry Andric     ModifiedDT = Changed = true;
191091bc56edSDimitry Andric     ++NumRetsDup;
191191bc56edSDimitry Andric   }
191291bc56edSDimitry Andric 
191391bc56edSDimitry Andric   // If we eliminated all predecessors of the block, delete the block now.
191491bc56edSDimitry Andric   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
191591bc56edSDimitry Andric     BB->eraseFromParent();
191691bc56edSDimitry Andric 
191791bc56edSDimitry Andric   return Changed;
191891bc56edSDimitry Andric }
191991bc56edSDimitry Andric 
192091bc56edSDimitry Andric //===----------------------------------------------------------------------===//
192191bc56edSDimitry Andric // Memory Optimization
192291bc56edSDimitry Andric //===----------------------------------------------------------------------===//
192391bc56edSDimitry Andric 
192491bc56edSDimitry Andric namespace {
192591bc56edSDimitry Andric 
19267d523365SDimitry Andric /// This is an extended version of TargetLowering::AddrMode
192791bc56edSDimitry Andric /// which holds actual Value*'s for register values.
192891bc56edSDimitry Andric struct ExtAddrMode : public TargetLowering::AddrMode {
19292cab237bSDimitry Andric   Value *BaseReg = nullptr;
19302cab237bSDimitry Andric   Value *ScaledReg = nullptr;
19312cab237bSDimitry Andric   Value *OriginalValue = nullptr;
19322cab237bSDimitry Andric 
19332cab237bSDimitry Andric   enum FieldName {
19342cab237bSDimitry Andric     NoField        = 0x00,
19352cab237bSDimitry Andric     BaseRegField   = 0x01,
19362cab237bSDimitry Andric     BaseGVField    = 0x02,
19372cab237bSDimitry Andric     BaseOffsField  = 0x04,
19382cab237bSDimitry Andric     ScaledRegField = 0x08,
19392cab237bSDimitry Andric     ScaleField     = 0x10,
19402cab237bSDimitry Andric     MultipleFields = 0xff
19412cab237bSDimitry Andric   };
19422cab237bSDimitry Andric 
19432cab237bSDimitry Andric   ExtAddrMode() = default;
19442cab237bSDimitry Andric 
194591bc56edSDimitry Andric   void print(raw_ostream &OS) const;
194691bc56edSDimitry Andric   void dump() const;
194791bc56edSDimitry Andric 
compare__anon6227213d0511::ExtAddrMode19482cab237bSDimitry Andric   FieldName compare(const ExtAddrMode &other) {
19492cab237bSDimitry Andric     // First check that the types are the same on each field, as differing types
19502cab237bSDimitry Andric     // is something we can't cope with later on.
19512cab237bSDimitry Andric     if (BaseReg && other.BaseReg &&
19522cab237bSDimitry Andric         BaseReg->getType() != other.BaseReg->getType())
19532cab237bSDimitry Andric       return MultipleFields;
19542cab237bSDimitry Andric     if (BaseGV && other.BaseGV &&
19552cab237bSDimitry Andric         BaseGV->getType() != other.BaseGV->getType())
19562cab237bSDimitry Andric       return MultipleFields;
19572cab237bSDimitry Andric     if (ScaledReg && other.ScaledReg &&
19582cab237bSDimitry Andric         ScaledReg->getType() != other.ScaledReg->getType())
19592cab237bSDimitry Andric       return MultipleFields;
19602cab237bSDimitry Andric 
19612cab237bSDimitry Andric     // Check each field to see if it differs.
19622cab237bSDimitry Andric     unsigned Result = NoField;
19632cab237bSDimitry Andric     if (BaseReg != other.BaseReg)
19642cab237bSDimitry Andric       Result |= BaseRegField;
19652cab237bSDimitry Andric     if (BaseGV != other.BaseGV)
19662cab237bSDimitry Andric       Result |= BaseGVField;
19672cab237bSDimitry Andric     if (BaseOffs != other.BaseOffs)
19682cab237bSDimitry Andric       Result |= BaseOffsField;
19692cab237bSDimitry Andric     if (ScaledReg != other.ScaledReg)
19702cab237bSDimitry Andric       Result |= ScaledRegField;
19712cab237bSDimitry Andric     // Don't count 0 as being a different scale, because that actually means
19722cab237bSDimitry Andric     // unscaled (which will already be counted by having no ScaledReg).
19732cab237bSDimitry Andric     if (Scale && other.Scale && Scale != other.Scale)
19742cab237bSDimitry Andric       Result |= ScaleField;
19752cab237bSDimitry Andric 
19762cab237bSDimitry Andric     if (countPopulation(Result) > 1)
19772cab237bSDimitry Andric       return MultipleFields;
19782cab237bSDimitry Andric     else
19792cab237bSDimitry Andric       return static_cast<FieldName>(Result);
19802cab237bSDimitry Andric   }
19812cab237bSDimitry Andric 
19822cab237bSDimitry Andric   // An AddrMode is trivial if it involves no calculation i.e. it is just a base
19832cab237bSDimitry Andric   // with no offset.
isTrivial__anon6227213d0511::ExtAddrMode19842cab237bSDimitry Andric   bool isTrivial() {
19852cab237bSDimitry Andric     // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
19862cab237bSDimitry Andric     // trivial if at most one of these terms is nonzero, except that BaseGV and
19872cab237bSDimitry Andric     // BaseReg both being zero actually means a null pointer value, which we
19882cab237bSDimitry Andric     // consider to be 'non-zero' here.
19892cab237bSDimitry Andric     return !BaseOffs && !Scale && !(BaseGV && BaseReg);
19902cab237bSDimitry Andric   }
19912cab237bSDimitry Andric 
GetFieldAsValue__anon6227213d0511::ExtAddrMode19922cab237bSDimitry Andric   Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
19932cab237bSDimitry Andric     switch (Field) {
19942cab237bSDimitry Andric     default:
19952cab237bSDimitry Andric       return nullptr;
19962cab237bSDimitry Andric     case BaseRegField:
19972cab237bSDimitry Andric       return BaseReg;
19982cab237bSDimitry Andric     case BaseGVField:
19992cab237bSDimitry Andric       return BaseGV;
20002cab237bSDimitry Andric     case ScaledRegField:
20012cab237bSDimitry Andric       return ScaledReg;
20022cab237bSDimitry Andric     case BaseOffsField:
20032cab237bSDimitry Andric       return ConstantInt::get(IntPtrTy, BaseOffs);
20042cab237bSDimitry Andric     }
20052cab237bSDimitry Andric   }
20062cab237bSDimitry Andric 
SetCombinedField__anon6227213d0511::ExtAddrMode20072cab237bSDimitry Andric   void SetCombinedField(FieldName Field, Value *V,
20082cab237bSDimitry Andric                         const SmallVectorImpl<ExtAddrMode> &AddrModes) {
20092cab237bSDimitry Andric     switch (Field) {
20102cab237bSDimitry Andric     default:
20112cab237bSDimitry Andric       llvm_unreachable("Unhandled fields are expected to be rejected earlier");
20122cab237bSDimitry Andric       break;
20132cab237bSDimitry Andric     case ExtAddrMode::BaseRegField:
20142cab237bSDimitry Andric       BaseReg = V;
20152cab237bSDimitry Andric       break;
20162cab237bSDimitry Andric     case ExtAddrMode::BaseGVField:
20172cab237bSDimitry Andric       // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
20182cab237bSDimitry Andric       // in the BaseReg field.
20192cab237bSDimitry Andric       assert(BaseReg == nullptr);
20202cab237bSDimitry Andric       BaseReg = V;
20212cab237bSDimitry Andric       BaseGV = nullptr;
20222cab237bSDimitry Andric       break;
20232cab237bSDimitry Andric     case ExtAddrMode::ScaledRegField:
20242cab237bSDimitry Andric       ScaledReg = V;
20252cab237bSDimitry Andric       // If we have a mix of scaled and unscaled addrmodes then we want scale
20262cab237bSDimitry Andric       // to be the scale and not zero.
20272cab237bSDimitry Andric       if (!Scale)
20282cab237bSDimitry Andric         for (const ExtAddrMode &AM : AddrModes)
20292cab237bSDimitry Andric           if (AM.Scale) {
20302cab237bSDimitry Andric             Scale = AM.Scale;
20312cab237bSDimitry Andric             break;
20322cab237bSDimitry Andric           }
20332cab237bSDimitry Andric       break;
20342cab237bSDimitry Andric     case ExtAddrMode::BaseOffsField:
20352cab237bSDimitry Andric       // The offset is no longer a constant, so it goes in ScaledReg with a
20362cab237bSDimitry Andric       // scale of 1.
20372cab237bSDimitry Andric       assert(ScaledReg == nullptr);
20382cab237bSDimitry Andric       ScaledReg = V;
20392cab237bSDimitry Andric       Scale = 1;
20402cab237bSDimitry Andric       BaseOffs = 0;
20412cab237bSDimitry Andric       break;
20422cab237bSDimitry Andric     }
204391bc56edSDimitry Andric   }
204491bc56edSDimitry Andric };
204591bc56edSDimitry Andric 
20462cab237bSDimitry Andric } // end anonymous namespace
20472cab237bSDimitry Andric 
204891bc56edSDimitry Andric #ifndef NDEBUG
operator <<(raw_ostream & OS,const ExtAddrMode & AM)204991bc56edSDimitry Andric static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
205091bc56edSDimitry Andric   AM.print(OS);
205191bc56edSDimitry Andric   return OS;
205291bc56edSDimitry Andric }
205391bc56edSDimitry Andric #endif
205491bc56edSDimitry Andric 
20552cab237bSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
print(raw_ostream & OS) const205691bc56edSDimitry Andric void ExtAddrMode::print(raw_ostream &OS) const {
205791bc56edSDimitry Andric   bool NeedPlus = false;
205891bc56edSDimitry Andric   OS << "[";
205991bc56edSDimitry Andric   if (BaseGV) {
206091bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
206191bc56edSDimitry Andric        << "GV:";
206291bc56edSDimitry Andric     BaseGV->printAsOperand(OS, /*PrintType=*/false);
206391bc56edSDimitry Andric     NeedPlus = true;
206491bc56edSDimitry Andric   }
206591bc56edSDimitry Andric 
206691bc56edSDimitry Andric   if (BaseOffs) {
206791bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
206891bc56edSDimitry Andric        << BaseOffs;
206991bc56edSDimitry Andric     NeedPlus = true;
207091bc56edSDimitry Andric   }
207191bc56edSDimitry Andric 
207291bc56edSDimitry Andric   if (BaseReg) {
207391bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
207491bc56edSDimitry Andric        << "Base:";
207591bc56edSDimitry Andric     BaseReg->printAsOperand(OS, /*PrintType=*/false);
207691bc56edSDimitry Andric     NeedPlus = true;
207791bc56edSDimitry Andric   }
207891bc56edSDimitry Andric   if (Scale) {
207991bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
208091bc56edSDimitry Andric        << Scale << "*";
208191bc56edSDimitry Andric     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
208291bc56edSDimitry Andric   }
208391bc56edSDimitry Andric 
208491bc56edSDimitry Andric   OS << ']';
208591bc56edSDimitry Andric }
208691bc56edSDimitry Andric 
dump() const20873ca95b02SDimitry Andric LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
208891bc56edSDimitry Andric   print(dbgs());
208991bc56edSDimitry Andric   dbgs() << '\n';
209091bc56edSDimitry Andric }
209191bc56edSDimitry Andric #endif
209291bc56edSDimitry Andric 
20932cab237bSDimitry Andric namespace {
20942cab237bSDimitry Andric 
20954ba319b5SDimitry Andric /// This class provides transaction based operation on the IR.
209691bc56edSDimitry Andric /// Every change made through this class is recorded in the internal state and
209791bc56edSDimitry Andric /// can be undone (rollback) until commit is called.
209891bc56edSDimitry Andric class TypePromotionTransaction {
20994ba319b5SDimitry Andric   /// This represents the common interface of the individual transaction.
210091bc56edSDimitry Andric   /// Each class implements the logic for doing one specific modification on
210191bc56edSDimitry Andric   /// the IR via the TypePromotionTransaction.
210291bc56edSDimitry Andric   class TypePromotionAction {
210391bc56edSDimitry Andric   protected:
210491bc56edSDimitry Andric     /// The Instruction modified.
210591bc56edSDimitry Andric     Instruction *Inst;
210691bc56edSDimitry Andric 
210791bc56edSDimitry Andric   public:
21084ba319b5SDimitry Andric     /// Constructor of the action.
210991bc56edSDimitry Andric     /// The constructor performs the related action on the IR.
TypePromotionAction(Instruction * Inst)211091bc56edSDimitry Andric     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
211191bc56edSDimitry Andric 
21122cab237bSDimitry Andric     virtual ~TypePromotionAction() = default;
211391bc56edSDimitry Andric 
21144ba319b5SDimitry Andric     /// Undo the modification done by this action.
211591bc56edSDimitry Andric     /// When this method is called, the IR must be in the same state as it was
211691bc56edSDimitry Andric     /// before this action was applied.
211791bc56edSDimitry Andric     /// \pre Undoing the action works if and only if the IR is in the exact same
211891bc56edSDimitry Andric     /// state as it was directly after this action was applied.
211991bc56edSDimitry Andric     virtual void undo() = 0;
212091bc56edSDimitry Andric 
21214ba319b5SDimitry Andric     /// Advocate every change made by this action.
212291bc56edSDimitry Andric     /// When the results on the IR of the action are to be kept, it is important
212391bc56edSDimitry Andric     /// to call this function, otherwise hidden information may be kept forever.
commit()212491bc56edSDimitry Andric     virtual void commit() {
212591bc56edSDimitry Andric       // Nothing to be done, this action is not doing anything.
212691bc56edSDimitry Andric     }
212791bc56edSDimitry Andric   };
212891bc56edSDimitry Andric 
21294ba319b5SDimitry Andric   /// Utility to remember the position of an instruction.
213091bc56edSDimitry Andric   class InsertionHandler {
213191bc56edSDimitry Andric     /// Position of an instruction.
213291bc56edSDimitry Andric     /// Either an instruction:
213391bc56edSDimitry Andric     /// - Is the first in a basic block: BB is used.
21344ba319b5SDimitry Andric     /// - Has a previous instruction: PrevInst is used.
213591bc56edSDimitry Andric     union {
213691bc56edSDimitry Andric       Instruction *PrevInst;
213791bc56edSDimitry Andric       BasicBlock *BB;
213891bc56edSDimitry Andric     } Point;
21392cab237bSDimitry Andric 
214091bc56edSDimitry Andric     /// Remember whether or not the instruction had a previous instruction.
214191bc56edSDimitry Andric     bool HasPrevInstruction;
214291bc56edSDimitry Andric 
214391bc56edSDimitry Andric   public:
21444ba319b5SDimitry Andric     /// Record the position of \p Inst.
InsertionHandler(Instruction * Inst)214591bc56edSDimitry Andric     InsertionHandler(Instruction *Inst) {
21467d523365SDimitry Andric       BasicBlock::iterator It = Inst->getIterator();
214791bc56edSDimitry Andric       HasPrevInstruction = (It != (Inst->getParent()->begin()));
214891bc56edSDimitry Andric       if (HasPrevInstruction)
21497d523365SDimitry Andric         Point.PrevInst = &*--It;
215091bc56edSDimitry Andric       else
215191bc56edSDimitry Andric         Point.BB = Inst->getParent();
215291bc56edSDimitry Andric     }
215391bc56edSDimitry Andric 
21544ba319b5SDimitry Andric     /// Insert \p Inst at the recorded position.
insert(Instruction * Inst)215591bc56edSDimitry Andric     void insert(Instruction *Inst) {
215691bc56edSDimitry Andric       if (HasPrevInstruction) {
215791bc56edSDimitry Andric         if (Inst->getParent())
215891bc56edSDimitry Andric           Inst->removeFromParent();
215991bc56edSDimitry Andric         Inst->insertAfter(Point.PrevInst);
216091bc56edSDimitry Andric       } else {
21617d523365SDimitry Andric         Instruction *Position = &*Point.BB->getFirstInsertionPt();
216291bc56edSDimitry Andric         if (Inst->getParent())
216391bc56edSDimitry Andric           Inst->moveBefore(Position);
216491bc56edSDimitry Andric         else
216591bc56edSDimitry Andric           Inst->insertBefore(Position);
216691bc56edSDimitry Andric       }
216791bc56edSDimitry Andric     }
216891bc56edSDimitry Andric   };
216991bc56edSDimitry Andric 
21704ba319b5SDimitry Andric   /// Move an instruction before another.
217191bc56edSDimitry Andric   class InstructionMoveBefore : public TypePromotionAction {
217291bc56edSDimitry Andric     /// Original position of the instruction.
217391bc56edSDimitry Andric     InsertionHandler Position;
217491bc56edSDimitry Andric 
217591bc56edSDimitry Andric   public:
21764ba319b5SDimitry Andric     /// Move \p Inst before \p Before.
InstructionMoveBefore(Instruction * Inst,Instruction * Before)217791bc56edSDimitry Andric     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
217891bc56edSDimitry Andric         : TypePromotionAction(Inst), Position(Inst) {
21794ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
21804ba319b5SDimitry Andric                         << "\n");
218191bc56edSDimitry Andric       Inst->moveBefore(Before);
218291bc56edSDimitry Andric     }
218391bc56edSDimitry Andric 
21844ba319b5SDimitry Andric     /// Move the instruction back to its original position.
undo()218591bc56edSDimitry Andric     void undo() override {
21864ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
218791bc56edSDimitry Andric       Position.insert(Inst);
218891bc56edSDimitry Andric     }
218991bc56edSDimitry Andric   };
219091bc56edSDimitry Andric 
21914ba319b5SDimitry Andric   /// Set the operand of an instruction with a new value.
219291bc56edSDimitry Andric   class OperandSetter : public TypePromotionAction {
219391bc56edSDimitry Andric     /// Original operand of the instruction.
219491bc56edSDimitry Andric     Value *Origin;
21952cab237bSDimitry Andric 
219691bc56edSDimitry Andric     /// Index of the modified instruction.
219791bc56edSDimitry Andric     unsigned Idx;
219891bc56edSDimitry Andric 
219991bc56edSDimitry Andric   public:
22004ba319b5SDimitry Andric     /// Set \p Idx operand of \p Inst with \p NewVal.
OperandSetter(Instruction * Inst,unsigned Idx,Value * NewVal)220191bc56edSDimitry Andric     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
220291bc56edSDimitry Andric         : TypePromotionAction(Inst), Idx(Idx) {
22034ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
220491bc56edSDimitry Andric                         << "for:" << *Inst << "\n"
220591bc56edSDimitry Andric                         << "with:" << *NewVal << "\n");
220691bc56edSDimitry Andric       Origin = Inst->getOperand(Idx);
220791bc56edSDimitry Andric       Inst->setOperand(Idx, NewVal);
220891bc56edSDimitry Andric     }
220991bc56edSDimitry Andric 
22104ba319b5SDimitry Andric     /// Restore the original value of the instruction.
undo()221191bc56edSDimitry Andric     void undo() override {
22124ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
221391bc56edSDimitry Andric                         << "for: " << *Inst << "\n"
221491bc56edSDimitry Andric                         << "with: " << *Origin << "\n");
221591bc56edSDimitry Andric       Inst->setOperand(Idx, Origin);
221691bc56edSDimitry Andric     }
221791bc56edSDimitry Andric   };
221891bc56edSDimitry Andric 
22194ba319b5SDimitry Andric   /// Hide the operands of an instruction.
222091bc56edSDimitry Andric   /// Do as if this instruction was not using any of its operands.
222191bc56edSDimitry Andric   class OperandsHider : public TypePromotionAction {
222291bc56edSDimitry Andric     /// The list of original operands.
222391bc56edSDimitry Andric     SmallVector<Value *, 4> OriginalValues;
222491bc56edSDimitry Andric 
222591bc56edSDimitry Andric   public:
22264ba319b5SDimitry Andric     /// Remove \p Inst from the uses of the operands of \p Inst.
OperandsHider(Instruction * Inst)222791bc56edSDimitry Andric     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
22284ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
222991bc56edSDimitry Andric       unsigned NumOpnds = Inst->getNumOperands();
223091bc56edSDimitry Andric       OriginalValues.reserve(NumOpnds);
223191bc56edSDimitry Andric       for (unsigned It = 0; It < NumOpnds; ++It) {
223291bc56edSDimitry Andric         // Save the current operand.
223391bc56edSDimitry Andric         Value *Val = Inst->getOperand(It);
223491bc56edSDimitry Andric         OriginalValues.push_back(Val);
223591bc56edSDimitry Andric         // Set a dummy one.
22367d523365SDimitry Andric         // We could use OperandSetter here, but that would imply an overhead
223791bc56edSDimitry Andric         // that we are not willing to pay.
223891bc56edSDimitry Andric         Inst->setOperand(It, UndefValue::get(Val->getType()));
223991bc56edSDimitry Andric       }
224091bc56edSDimitry Andric     }
224191bc56edSDimitry Andric 
22424ba319b5SDimitry Andric     /// Restore the original list of uses.
undo()224391bc56edSDimitry Andric     void undo() override {
22444ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
224591bc56edSDimitry Andric       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
224691bc56edSDimitry Andric         Inst->setOperand(It, OriginalValues[It]);
224791bc56edSDimitry Andric     }
224891bc56edSDimitry Andric   };
224991bc56edSDimitry Andric 
22504ba319b5SDimitry Andric   /// Build a truncate instruction.
225191bc56edSDimitry Andric   class TruncBuilder : public TypePromotionAction {
225239d628a0SDimitry Andric     Value *Val;
22532cab237bSDimitry Andric 
225491bc56edSDimitry Andric   public:
22554ba319b5SDimitry Andric     /// Build a truncate instruction of \p Opnd producing a \p Ty
225691bc56edSDimitry Andric     /// result.
225791bc56edSDimitry Andric     /// trunc Opnd to Ty.
TruncBuilder(Instruction * Opnd,Type * Ty)225891bc56edSDimitry Andric     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
225991bc56edSDimitry Andric       IRBuilder<> Builder(Opnd);
226039d628a0SDimitry Andric       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
22614ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
226291bc56edSDimitry Andric     }
226391bc56edSDimitry Andric 
22644ba319b5SDimitry Andric     /// Get the built value.
getBuiltValue()226539d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
226691bc56edSDimitry Andric 
22674ba319b5SDimitry Andric     /// Remove the built instruction.
undo()226891bc56edSDimitry Andric     void undo() override {
22694ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
227039d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
227139d628a0SDimitry Andric         IVal->eraseFromParent();
227291bc56edSDimitry Andric     }
227391bc56edSDimitry Andric   };
227491bc56edSDimitry Andric 
22754ba319b5SDimitry Andric   /// Build a sign extension instruction.
227691bc56edSDimitry Andric   class SExtBuilder : public TypePromotionAction {
227739d628a0SDimitry Andric     Value *Val;
22782cab237bSDimitry Andric 
227991bc56edSDimitry Andric   public:
22804ba319b5SDimitry Andric     /// Build a sign extension instruction of \p Opnd producing a \p Ty
228191bc56edSDimitry Andric     /// result.
228291bc56edSDimitry Andric     /// sext Opnd to Ty.
SExtBuilder(Instruction * InsertPt,Value * Opnd,Type * Ty)228391bc56edSDimitry Andric     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
228439d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
228591bc56edSDimitry Andric       IRBuilder<> Builder(InsertPt);
228639d628a0SDimitry Andric       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
22874ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
228891bc56edSDimitry Andric     }
228991bc56edSDimitry Andric 
22904ba319b5SDimitry Andric     /// Get the built value.
getBuiltValue()229139d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
229291bc56edSDimitry Andric 
22934ba319b5SDimitry Andric     /// Remove the built instruction.
undo()229491bc56edSDimitry Andric     void undo() override {
22954ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
229639d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
229739d628a0SDimitry Andric         IVal->eraseFromParent();
229839d628a0SDimitry Andric     }
229939d628a0SDimitry Andric   };
230039d628a0SDimitry Andric 
23014ba319b5SDimitry Andric   /// Build a zero extension instruction.
230239d628a0SDimitry Andric   class ZExtBuilder : public TypePromotionAction {
230339d628a0SDimitry Andric     Value *Val;
23042cab237bSDimitry Andric 
230539d628a0SDimitry Andric   public:
23064ba319b5SDimitry Andric     /// Build a zero extension instruction of \p Opnd producing a \p Ty
230739d628a0SDimitry Andric     /// result.
230839d628a0SDimitry Andric     /// zext Opnd to Ty.
ZExtBuilder(Instruction * InsertPt,Value * Opnd,Type * Ty)230939d628a0SDimitry Andric     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
231039d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
231139d628a0SDimitry Andric       IRBuilder<> Builder(InsertPt);
231239d628a0SDimitry Andric       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
23134ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
231439d628a0SDimitry Andric     }
231539d628a0SDimitry Andric 
23164ba319b5SDimitry Andric     /// Get the built value.
getBuiltValue()231739d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
231839d628a0SDimitry Andric 
23194ba319b5SDimitry Andric     /// Remove the built instruction.
undo()232039d628a0SDimitry Andric     void undo() override {
23214ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
232239d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
232339d628a0SDimitry Andric         IVal->eraseFromParent();
232491bc56edSDimitry Andric     }
232591bc56edSDimitry Andric   };
232691bc56edSDimitry Andric 
23274ba319b5SDimitry Andric   /// Mutate an instruction to another type.
232891bc56edSDimitry Andric   class TypeMutator : public TypePromotionAction {
232991bc56edSDimitry Andric     /// Record the original type.
233091bc56edSDimitry Andric     Type *OrigTy;
233191bc56edSDimitry Andric 
233291bc56edSDimitry Andric   public:
23334ba319b5SDimitry Andric     /// Mutate the type of \p Inst into \p NewTy.
TypeMutator(Instruction * Inst,Type * NewTy)233491bc56edSDimitry Andric     TypeMutator(Instruction *Inst, Type *NewTy)
233591bc56edSDimitry Andric         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
23364ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
233791bc56edSDimitry Andric                         << "\n");
233891bc56edSDimitry Andric       Inst->mutateType(NewTy);
233991bc56edSDimitry Andric     }
234091bc56edSDimitry Andric 
23414ba319b5SDimitry Andric     /// Mutate the instruction back to its original type.
undo()234291bc56edSDimitry Andric     void undo() override {
23434ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
234491bc56edSDimitry Andric                         << "\n");
234591bc56edSDimitry Andric       Inst->mutateType(OrigTy);
234691bc56edSDimitry Andric     }
234791bc56edSDimitry Andric   };
234891bc56edSDimitry Andric 
23494ba319b5SDimitry Andric   /// Replace the uses of an instruction by another instruction.
235091bc56edSDimitry Andric   class UsesReplacer : public TypePromotionAction {
235191bc56edSDimitry Andric     /// Helper structure to keep track of the replaced uses.
235291bc56edSDimitry Andric     struct InstructionAndIdx {
235391bc56edSDimitry Andric       /// The instruction using the instruction.
235491bc56edSDimitry Andric       Instruction *Inst;
23552cab237bSDimitry Andric 
235691bc56edSDimitry Andric       /// The index where this instruction is used for Inst.
235791bc56edSDimitry Andric       unsigned Idx;
23582cab237bSDimitry Andric 
InstructionAndIdx__anon6227213d0611::TypePromotionTransaction::UsesReplacer::InstructionAndIdx235991bc56edSDimitry Andric       InstructionAndIdx(Instruction *Inst, unsigned Idx)
236091bc56edSDimitry Andric           : Inst(Inst), Idx(Idx) {}
236191bc56edSDimitry Andric     };
236291bc56edSDimitry Andric 
236391bc56edSDimitry Andric     /// Keep track of the original uses (pair Instruction, Index).
236491bc56edSDimitry Andric     SmallVector<InstructionAndIdx, 4> OriginalUses;
2365*b5893f02SDimitry Andric     /// Keep track of the debug users.
2366*b5893f02SDimitry Andric     SmallVector<DbgValueInst *, 1> DbgValues;
23672cab237bSDimitry Andric 
23682cab237bSDimitry Andric     using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
236991bc56edSDimitry Andric 
237091bc56edSDimitry Andric   public:
23714ba319b5SDimitry Andric     /// Replace all the use of \p Inst by \p New.
UsesReplacer(Instruction * Inst,Value * New)237291bc56edSDimitry Andric     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
23734ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
237491bc56edSDimitry Andric                         << "\n");
237591bc56edSDimitry Andric       // Record the original uses.
237691bc56edSDimitry Andric       for (Use &U : Inst->uses()) {
237791bc56edSDimitry Andric         Instruction *UserI = cast<Instruction>(U.getUser());
237891bc56edSDimitry Andric         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
237991bc56edSDimitry Andric       }
2380*b5893f02SDimitry Andric       // Record the debug uses separately. They are not in the instruction's
2381*b5893f02SDimitry Andric       // use list, but they are replaced by RAUW.
2382*b5893f02SDimitry Andric       findDbgValues(DbgValues, Inst);
2383*b5893f02SDimitry Andric 
238491bc56edSDimitry Andric       // Now, we can replace the uses.
238591bc56edSDimitry Andric       Inst->replaceAllUsesWith(New);
238691bc56edSDimitry Andric     }
238791bc56edSDimitry Andric 
23884ba319b5SDimitry Andric     /// Reassign the original uses of Inst to Inst.
undo()238991bc56edSDimitry Andric     void undo() override {
23904ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
239191bc56edSDimitry Andric       for (use_iterator UseIt = OriginalUses.begin(),
239291bc56edSDimitry Andric                         EndIt = OriginalUses.end();
239391bc56edSDimitry Andric            UseIt != EndIt; ++UseIt) {
239491bc56edSDimitry Andric         UseIt->Inst->setOperand(UseIt->Idx, Inst);
239591bc56edSDimitry Andric       }
2396*b5893f02SDimitry Andric       // RAUW has replaced all original uses with references to the new value,
2397*b5893f02SDimitry Andric       // including the debug uses. Since we are undoing the replacements,
2398*b5893f02SDimitry Andric       // the original debug uses must also be reinstated to maintain the
2399*b5893f02SDimitry Andric       // correctness and utility of debug value instructions.
2400*b5893f02SDimitry Andric       for (auto *DVI: DbgValues) {
2401*b5893f02SDimitry Andric         LLVMContext &Ctx = Inst->getType()->getContext();
2402*b5893f02SDimitry Andric         auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
2403*b5893f02SDimitry Andric         DVI->setOperand(0, MV);
2404*b5893f02SDimitry Andric       }
240591bc56edSDimitry Andric     }
240691bc56edSDimitry Andric   };
240791bc56edSDimitry Andric 
24084ba319b5SDimitry Andric   /// Remove an instruction from the IR.
240991bc56edSDimitry Andric   class InstructionRemover : public TypePromotionAction {
241091bc56edSDimitry Andric     /// Original position of the instruction.
241191bc56edSDimitry Andric     InsertionHandler Inserter;
24122cab237bSDimitry Andric 
241391bc56edSDimitry Andric     /// Helper structure to hide all the link to the instruction. In other
241491bc56edSDimitry Andric     /// words, this helps to do as if the instruction was removed.
241591bc56edSDimitry Andric     OperandsHider Hider;
24162cab237bSDimitry Andric 
241791bc56edSDimitry Andric     /// Keep track of the uses replaced, if any.
24182cab237bSDimitry Andric     UsesReplacer *Replacer = nullptr;
24192cab237bSDimitry Andric 
24207a7e6055SDimitry Andric     /// Keep track of instructions removed.
24217a7e6055SDimitry Andric     SetOfInstrs &RemovedInsts;
242291bc56edSDimitry Andric 
242391bc56edSDimitry Andric   public:
24244ba319b5SDimitry Andric     /// Remove all reference of \p Inst and optionally replace all its
242591bc56edSDimitry Andric     /// uses with New.
24267a7e6055SDimitry Andric     /// \p RemovedInsts Keep track of the instructions removed by this Action.
242791bc56edSDimitry Andric     /// \pre If !Inst->use_empty(), then New != nullptr
InstructionRemover(Instruction * Inst,SetOfInstrs & RemovedInsts,Value * New=nullptr)24287a7e6055SDimitry Andric     InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
24297a7e6055SDimitry Andric                        Value *New = nullptr)
243091bc56edSDimitry Andric         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
24312cab237bSDimitry Andric           RemovedInsts(RemovedInsts) {
243291bc56edSDimitry Andric       if (New)
243391bc56edSDimitry Andric         Replacer = new UsesReplacer(Inst, New);
24344ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
24357a7e6055SDimitry Andric       RemovedInsts.insert(Inst);
24367a7e6055SDimitry Andric       /// The instructions removed here will be freed after completing
24377a7e6055SDimitry Andric       /// optimizeBlock() for all blocks as we need to keep track of the
24387a7e6055SDimitry Andric       /// removed instructions during promotion.
243991bc56edSDimitry Andric       Inst->removeFromParent();
244091bc56edSDimitry Andric     }
244191bc56edSDimitry Andric 
~InstructionRemover()2442ff0cc061SDimitry Andric     ~InstructionRemover() override { delete Replacer; }
244391bc56edSDimitry Andric 
24444ba319b5SDimitry Andric     /// Resurrect the instruction and reassign it to the proper uses if
244591bc56edSDimitry Andric     /// new value was provided when build this action.
undo()244691bc56edSDimitry Andric     void undo() override {
24474ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
244891bc56edSDimitry Andric       Inserter.insert(Inst);
244991bc56edSDimitry Andric       if (Replacer)
245091bc56edSDimitry Andric         Replacer->undo();
245191bc56edSDimitry Andric       Hider.undo();
24527a7e6055SDimitry Andric       RemovedInsts.erase(Inst);
245391bc56edSDimitry Andric     }
245491bc56edSDimitry Andric   };
245591bc56edSDimitry Andric 
245691bc56edSDimitry Andric public:
245791bc56edSDimitry Andric   /// Restoration point.
245891bc56edSDimitry Andric   /// The restoration point is a pointer to an action instead of an iterator
245991bc56edSDimitry Andric   /// because the iterator may be invalidated but not the pointer.
24602cab237bSDimitry Andric   using ConstRestorationPt = const TypePromotionAction *;
24617a7e6055SDimitry Andric 
TypePromotionTransaction(SetOfInstrs & RemovedInsts)24627a7e6055SDimitry Andric   TypePromotionTransaction(SetOfInstrs &RemovedInsts)
24637a7e6055SDimitry Andric       : RemovedInsts(RemovedInsts) {}
24647a7e6055SDimitry Andric 
246591bc56edSDimitry Andric   /// Advocate every changes made in that transaction.
246691bc56edSDimitry Andric   void commit();
24672cab237bSDimitry Andric 
246891bc56edSDimitry Andric   /// Undo all the changes made after the given point.
246991bc56edSDimitry Andric   void rollback(ConstRestorationPt Point);
24702cab237bSDimitry Andric 
247191bc56edSDimitry Andric   /// Get the current restoration point.
247291bc56edSDimitry Andric   ConstRestorationPt getRestorationPoint() const;
247391bc56edSDimitry Andric 
247491bc56edSDimitry Andric   /// \name API for IR modification with state keeping to support rollback.
247591bc56edSDimitry Andric   /// @{
247691bc56edSDimitry Andric   /// Same as Instruction::setOperand.
247791bc56edSDimitry Andric   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
24782cab237bSDimitry Andric 
247991bc56edSDimitry Andric   /// Same as Instruction::eraseFromParent.
248091bc56edSDimitry Andric   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
24812cab237bSDimitry Andric 
248291bc56edSDimitry Andric   /// Same as Value::replaceAllUsesWith.
248391bc56edSDimitry Andric   void replaceAllUsesWith(Instruction *Inst, Value *New);
24842cab237bSDimitry Andric 
248591bc56edSDimitry Andric   /// Same as Value::mutateType.
248691bc56edSDimitry Andric   void mutateType(Instruction *Inst, Type *NewTy);
24872cab237bSDimitry Andric 
248891bc56edSDimitry Andric   /// Same as IRBuilder::createTrunc.
248939d628a0SDimitry Andric   Value *createTrunc(Instruction *Opnd, Type *Ty);
24902cab237bSDimitry Andric 
249191bc56edSDimitry Andric   /// Same as IRBuilder::createSExt.
249239d628a0SDimitry Andric   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
24932cab237bSDimitry Andric 
249439d628a0SDimitry Andric   /// Same as IRBuilder::createZExt.
249539d628a0SDimitry Andric   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
24962cab237bSDimitry Andric 
249791bc56edSDimitry Andric   /// Same as Instruction::moveBefore.
249891bc56edSDimitry Andric   void moveBefore(Instruction *Inst, Instruction *Before);
249991bc56edSDimitry Andric   /// @}
250091bc56edSDimitry Andric 
250191bc56edSDimitry Andric private:
250291bc56edSDimitry Andric   /// The ordered list of actions made so far.
250391bc56edSDimitry Andric   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
25042cab237bSDimitry Andric 
25052cab237bSDimitry Andric   using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
25062cab237bSDimitry Andric 
25077a7e6055SDimitry Andric   SetOfInstrs &RemovedInsts;
250891bc56edSDimitry Andric };
250991bc56edSDimitry Andric 
25102cab237bSDimitry Andric } // end anonymous namespace
25112cab237bSDimitry Andric 
setOperand(Instruction * Inst,unsigned Idx,Value * NewVal)251291bc56edSDimitry Andric void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
251391bc56edSDimitry Andric                                           Value *NewVal) {
25142cab237bSDimitry Andric   Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
25152cab237bSDimitry Andric       Inst, Idx, NewVal));
251691bc56edSDimitry Andric }
251791bc56edSDimitry Andric 
eraseInstruction(Instruction * Inst,Value * NewVal)251891bc56edSDimitry Andric void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
251991bc56edSDimitry Andric                                                 Value *NewVal) {
252091bc56edSDimitry Andric   Actions.push_back(
25212cab237bSDimitry Andric       llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
25222cab237bSDimitry Andric           Inst, RemovedInsts, NewVal));
252391bc56edSDimitry Andric }
252491bc56edSDimitry Andric 
replaceAllUsesWith(Instruction * Inst,Value * New)252591bc56edSDimitry Andric void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
252691bc56edSDimitry Andric                                                   Value *New) {
25272cab237bSDimitry Andric   Actions.push_back(
25282cab237bSDimitry Andric       llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
252991bc56edSDimitry Andric }
253091bc56edSDimitry Andric 
mutateType(Instruction * Inst,Type * NewTy)253191bc56edSDimitry Andric void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
25322cab237bSDimitry Andric   Actions.push_back(
25332cab237bSDimitry Andric       llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
253491bc56edSDimitry Andric }
253591bc56edSDimitry Andric 
createTrunc(Instruction * Opnd,Type * Ty)253639d628a0SDimitry Andric Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
253791bc56edSDimitry Andric                                              Type *Ty) {
253891bc56edSDimitry Andric   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
253939d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
254091bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
254139d628a0SDimitry Andric   return Val;
254291bc56edSDimitry Andric }
254391bc56edSDimitry Andric 
createSExt(Instruction * Inst,Value * Opnd,Type * Ty)254439d628a0SDimitry Andric Value *TypePromotionTransaction::createSExt(Instruction *Inst,
254591bc56edSDimitry Andric                                             Value *Opnd, Type *Ty) {
254691bc56edSDimitry Andric   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
254739d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
254891bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
254939d628a0SDimitry Andric   return Val;
255039d628a0SDimitry Andric }
255139d628a0SDimitry Andric 
createZExt(Instruction * Inst,Value * Opnd,Type * Ty)255239d628a0SDimitry Andric Value *TypePromotionTransaction::createZExt(Instruction *Inst,
255339d628a0SDimitry Andric                                             Value *Opnd, Type *Ty) {
255439d628a0SDimitry Andric   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
255539d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
255639d628a0SDimitry Andric   Actions.push_back(std::move(Ptr));
255739d628a0SDimitry Andric   return Val;
255891bc56edSDimitry Andric }
255991bc56edSDimitry Andric 
moveBefore(Instruction * Inst,Instruction * Before)256091bc56edSDimitry Andric void TypePromotionTransaction::moveBefore(Instruction *Inst,
256191bc56edSDimitry Andric                                           Instruction *Before) {
256291bc56edSDimitry Andric   Actions.push_back(
25632cab237bSDimitry Andric       llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
25642cab237bSDimitry Andric           Inst, Before));
256591bc56edSDimitry Andric }
256691bc56edSDimitry Andric 
256791bc56edSDimitry Andric TypePromotionTransaction::ConstRestorationPt
getRestorationPoint() const256891bc56edSDimitry Andric TypePromotionTransaction::getRestorationPoint() const {
256991bc56edSDimitry Andric   return !Actions.empty() ? Actions.back().get() : nullptr;
257091bc56edSDimitry Andric }
257191bc56edSDimitry Andric 
commit()257291bc56edSDimitry Andric void TypePromotionTransaction::commit() {
257391bc56edSDimitry Andric   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
257491bc56edSDimitry Andric        ++It)
257591bc56edSDimitry Andric     (*It)->commit();
257691bc56edSDimitry Andric   Actions.clear();
257791bc56edSDimitry Andric }
257891bc56edSDimitry Andric 
rollback(TypePromotionTransaction::ConstRestorationPt Point)257991bc56edSDimitry Andric void TypePromotionTransaction::rollback(
258091bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt Point) {
258191bc56edSDimitry Andric   while (!Actions.empty() && Point != Actions.back().get()) {
258291bc56edSDimitry Andric     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
258391bc56edSDimitry Andric     Curr->undo();
258491bc56edSDimitry Andric   }
258591bc56edSDimitry Andric }
258691bc56edSDimitry Andric 
25872cab237bSDimitry Andric namespace {
25882cab237bSDimitry Andric 
25894ba319b5SDimitry Andric /// A helper class for matching addressing modes.
259091bc56edSDimitry Andric ///
259191bc56edSDimitry Andric /// This encapsulates the logic for matching the target-legal addressing modes.
259291bc56edSDimitry Andric class AddressingModeMatcher {
259391bc56edSDimitry Andric   SmallVectorImpl<Instruction*> &AddrModeInsts;
259491bc56edSDimitry Andric   const TargetLowering &TLI;
25957a7e6055SDimitry Andric   const TargetRegisterInfo &TRI;
2596875ed548SDimitry Andric   const DataLayout &DL;
259791bc56edSDimitry Andric 
259891bc56edSDimitry Andric   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
259991bc56edSDimitry Andric   /// the memory instruction that we're computing this address for.
260091bc56edSDimitry Andric   Type *AccessTy;
260197bc6c73SDimitry Andric   unsigned AddrSpace;
260291bc56edSDimitry Andric   Instruction *MemoryInst;
260391bc56edSDimitry Andric 
26047d523365SDimitry Andric   /// This is the addressing mode that we're building up. This is
260591bc56edSDimitry Andric   /// part of the return value of this addressing mode matching stuff.
260691bc56edSDimitry Andric   ExtAddrMode &AddrMode;
260791bc56edSDimitry Andric 
26088f0fd8f6SDimitry Andric   /// The instructions inserted by other CodeGenPrepare optimizations.
26098f0fd8f6SDimitry Andric   const SetOfInstrs &InsertedInsts;
26102cab237bSDimitry Andric 
261191bc56edSDimitry Andric   /// A map from the instructions to their type before promotion.
261291bc56edSDimitry Andric   InstrToOrigTy &PromotedInsts;
26132cab237bSDimitry Andric 
261491bc56edSDimitry Andric   /// The ongoing transaction where every action should be registered.
261591bc56edSDimitry Andric   TypePromotionTransaction &TPT;
261691bc56edSDimitry Andric 
26174ba319b5SDimitry Andric   // A GEP which has too large offset to be folded into the addressing mode.
26184ba319b5SDimitry Andric   std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
26194ba319b5SDimitry Andric 
26207d523365SDimitry Andric   /// This is set to true when we should not do profitability checks.
26217d523365SDimitry Andric   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
262291bc56edSDimitry Andric   bool IgnoreProfitability;
262391bc56edSDimitry Andric 
AddressingModeMatcher(SmallVectorImpl<Instruction * > & AMI,const TargetLowering & TLI,const TargetRegisterInfo & TRI,Type * AT,unsigned AS,Instruction * MI,ExtAddrMode & AM,const SetOfInstrs & InsertedInsts,InstrToOrigTy & PromotedInsts,TypePromotionTransaction & TPT,std::pair<AssertingVH<GetElementPtrInst>,int64_t> & LargeOffsetGEP)26244ba319b5SDimitry Andric   AddressingModeMatcher(
26254ba319b5SDimitry Andric       SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
26264ba319b5SDimitry Andric       const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
26274ba319b5SDimitry Andric       ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
26284ba319b5SDimitry Andric       InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
26294ba319b5SDimitry Andric       std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
26307a7e6055SDimitry Andric       : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
2631875ed548SDimitry Andric         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2632875ed548SDimitry Andric         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
26334ba319b5SDimitry Andric         PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
263491bc56edSDimitry Andric     IgnoreProfitability = false;
263591bc56edSDimitry Andric   }
263691bc56edSDimitry Andric 
26372cab237bSDimitry Andric public:
26387d523365SDimitry Andric   /// Find the maximal addressing mode that a load/store of V can fold,
263991bc56edSDimitry Andric   /// give an access type of AccessTy.  This returns a list of involved
264091bc56edSDimitry Andric   /// instructions in AddrModeInsts.
26418f0fd8f6SDimitry Andric   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
264291bc56edSDimitry Andric   /// optimizations.
264391bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
264491bc56edSDimitry Andric   /// \p The ongoing transaction where every action should be registered.
26454ba319b5SDimitry Andric   static ExtAddrMode
Match(Value * V,Type * AccessTy,unsigned AS,Instruction * MemoryInst,SmallVectorImpl<Instruction * > & AddrModeInsts,const TargetLowering & TLI,const TargetRegisterInfo & TRI,const SetOfInstrs & InsertedInsts,InstrToOrigTy & PromotedInsts,TypePromotionTransaction & TPT,std::pair<AssertingVH<GetElementPtrInst>,int64_t> & LargeOffsetGEP)26464ba319b5SDimitry Andric   Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
264791bc56edSDimitry Andric         SmallVectorImpl<Instruction *> &AddrModeInsts,
26484ba319b5SDimitry Andric         const TargetLowering &TLI, const TargetRegisterInfo &TRI,
26494ba319b5SDimitry Andric         const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
26504ba319b5SDimitry Andric         TypePromotionTransaction &TPT,
26514ba319b5SDimitry Andric         std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
265291bc56edSDimitry Andric     ExtAddrMode Result;
265391bc56edSDimitry Andric 
26544ba319b5SDimitry Andric     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
26558f0fd8f6SDimitry Andric                                          MemoryInst, Result, InsertedInsts,
26564ba319b5SDimitry Andric                                          PromotedInsts, TPT, LargeOffsetGEP)
26574ba319b5SDimitry Andric                        .matchAddr(V, 0);
265891bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
265991bc56edSDimitry Andric     return Result;
266091bc56edSDimitry Andric   }
26612cab237bSDimitry Andric 
266291bc56edSDimitry Andric private:
26637d523365SDimitry Andric   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
26644ba319b5SDimitry Andric   bool matchAddr(Value *Addr, unsigned Depth);
26654ba319b5SDimitry Andric   bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
266691bc56edSDimitry Andric                           bool *MovedAway = nullptr);
26677d523365SDimitry Andric   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
266891bc56edSDimitry Andric                                             ExtAddrMode &AMBefore,
266991bc56edSDimitry Andric                                             ExtAddrMode &AMAfter);
26707d523365SDimitry Andric   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
26717d523365SDimitry Andric   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
267291bc56edSDimitry Andric                              Value *PromotedOperand) const;
267391bc56edSDimitry Andric };
267491bc56edSDimitry Andric 
2675*b5893f02SDimitry Andric class PhiNodeSet;
2676*b5893f02SDimitry Andric 
2677*b5893f02SDimitry Andric /// An iterator for PhiNodeSet.
2678*b5893f02SDimitry Andric class PhiNodeSetIterator {
2679*b5893f02SDimitry Andric   PhiNodeSet * const Set;
2680*b5893f02SDimitry Andric   size_t CurrentIndex = 0;
2681*b5893f02SDimitry Andric 
2682*b5893f02SDimitry Andric public:
2683*b5893f02SDimitry Andric   /// The constructor. Start should point to either a valid element, or be equal
2684*b5893f02SDimitry Andric   /// to the size of the underlying SmallVector of the PhiNodeSet.
2685*b5893f02SDimitry Andric   PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
2686*b5893f02SDimitry Andric   PHINode * operator*() const;
2687*b5893f02SDimitry Andric   PhiNodeSetIterator& operator++();
2688*b5893f02SDimitry Andric   bool operator==(const PhiNodeSetIterator &RHS) const;
2689*b5893f02SDimitry Andric   bool operator!=(const PhiNodeSetIterator &RHS) const;
2690*b5893f02SDimitry Andric };
2691*b5893f02SDimitry Andric 
2692*b5893f02SDimitry Andric /// Keeps a set of PHINodes.
2693*b5893f02SDimitry Andric ///
2694*b5893f02SDimitry Andric /// This is a minimal set implementation for a specific use case:
2695*b5893f02SDimitry Andric /// It is very fast when there are very few elements, but also provides good
2696*b5893f02SDimitry Andric /// performance when there are many. It is similar to SmallPtrSet, but also
2697*b5893f02SDimitry Andric /// provides iteration by insertion order, which is deterministic and stable
2698*b5893f02SDimitry Andric /// across runs. It is also similar to SmallSetVector, but provides removing
2699*b5893f02SDimitry Andric /// elements in O(1) time. This is achieved by not actually removing the element
2700*b5893f02SDimitry Andric /// from the underlying vector, so comes at the cost of using more memory, but
2701*b5893f02SDimitry Andric /// that is fine, since PhiNodeSets are used as short lived objects.
2702*b5893f02SDimitry Andric class PhiNodeSet {
2703*b5893f02SDimitry Andric   friend class PhiNodeSetIterator;
2704*b5893f02SDimitry Andric 
2705*b5893f02SDimitry Andric   using MapType = SmallDenseMap<PHINode *, size_t, 32>;
2706*b5893f02SDimitry Andric   using iterator =  PhiNodeSetIterator;
2707*b5893f02SDimitry Andric 
2708*b5893f02SDimitry Andric   /// Keeps the elements in the order of their insertion in the underlying
2709*b5893f02SDimitry Andric   /// vector. To achieve constant time removal, it never deletes any element.
2710*b5893f02SDimitry Andric   SmallVector<PHINode *, 32> NodeList;
2711*b5893f02SDimitry Andric 
2712*b5893f02SDimitry Andric   /// Keeps the elements in the underlying set implementation. This (and not the
2713*b5893f02SDimitry Andric   /// NodeList defined above) is the source of truth on whether an element
2714*b5893f02SDimitry Andric   /// is actually in the collection.
2715*b5893f02SDimitry Andric   MapType NodeMap;
2716*b5893f02SDimitry Andric 
2717*b5893f02SDimitry Andric   /// Points to the first valid (not deleted) element when the set is not empty
2718*b5893f02SDimitry Andric   /// and the value is not zero. Equals to the size of the underlying vector
2719*b5893f02SDimitry Andric   /// when the set is empty. When the value is 0, as in the beginning, the
2720*b5893f02SDimitry Andric   /// first element may or may not be valid.
2721*b5893f02SDimitry Andric   size_t FirstValidElement = 0;
2722*b5893f02SDimitry Andric 
2723*b5893f02SDimitry Andric public:
2724*b5893f02SDimitry Andric   /// Inserts a new element to the collection.
2725*b5893f02SDimitry Andric   /// \returns true if the element is actually added, i.e. was not in the
2726*b5893f02SDimitry Andric   /// collection before the operation.
insert(PHINode * Ptr)2727*b5893f02SDimitry Andric   bool insert(PHINode *Ptr) {
2728*b5893f02SDimitry Andric     if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
2729*b5893f02SDimitry Andric       NodeList.push_back(Ptr);
2730*b5893f02SDimitry Andric       return true;
2731*b5893f02SDimitry Andric     }
2732*b5893f02SDimitry Andric     return false;
2733*b5893f02SDimitry Andric   }
2734*b5893f02SDimitry Andric 
2735*b5893f02SDimitry Andric   /// Removes the element from the collection.
2736*b5893f02SDimitry Andric   /// \returns whether the element is actually removed, i.e. was in the
2737*b5893f02SDimitry Andric   /// collection before the operation.
erase(PHINode * Ptr)2738*b5893f02SDimitry Andric   bool erase(PHINode *Ptr) {
2739*b5893f02SDimitry Andric     auto it = NodeMap.find(Ptr);
2740*b5893f02SDimitry Andric     if (it != NodeMap.end()) {
2741*b5893f02SDimitry Andric       NodeMap.erase(Ptr);
2742*b5893f02SDimitry Andric       SkipRemovedElements(FirstValidElement);
2743*b5893f02SDimitry Andric       return true;
2744*b5893f02SDimitry Andric     }
2745*b5893f02SDimitry Andric     return false;
2746*b5893f02SDimitry Andric   }
2747*b5893f02SDimitry Andric 
2748*b5893f02SDimitry Andric   /// Removes all elements and clears the collection.
clear()2749*b5893f02SDimitry Andric   void clear() {
2750*b5893f02SDimitry Andric     NodeMap.clear();
2751*b5893f02SDimitry Andric     NodeList.clear();
2752*b5893f02SDimitry Andric     FirstValidElement = 0;
2753*b5893f02SDimitry Andric   }
2754*b5893f02SDimitry Andric 
2755*b5893f02SDimitry Andric   /// \returns an iterator that will iterate the elements in the order of
2756*b5893f02SDimitry Andric   /// insertion.
begin()2757*b5893f02SDimitry Andric   iterator begin() {
2758*b5893f02SDimitry Andric     if (FirstValidElement == 0)
2759*b5893f02SDimitry Andric       SkipRemovedElements(FirstValidElement);
2760*b5893f02SDimitry Andric     return PhiNodeSetIterator(this, FirstValidElement);
2761*b5893f02SDimitry Andric   }
2762*b5893f02SDimitry Andric 
2763*b5893f02SDimitry Andric   /// \returns an iterator that points to the end of the collection.
end()2764*b5893f02SDimitry Andric   iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
2765*b5893f02SDimitry Andric 
2766*b5893f02SDimitry Andric   /// Returns the number of elements in the collection.
size() const2767*b5893f02SDimitry Andric   size_t size() const {
2768*b5893f02SDimitry Andric     return NodeMap.size();
2769*b5893f02SDimitry Andric   }
2770*b5893f02SDimitry Andric 
2771*b5893f02SDimitry Andric   /// \returns 1 if the given element is in the collection, and 0 if otherwise.
count(PHINode * Ptr) const2772*b5893f02SDimitry Andric   size_t count(PHINode *Ptr) const {
2773*b5893f02SDimitry Andric     return NodeMap.count(Ptr);
2774*b5893f02SDimitry Andric   }
2775*b5893f02SDimitry Andric 
2776*b5893f02SDimitry Andric private:
2777*b5893f02SDimitry Andric   /// Updates the CurrentIndex so that it will point to a valid element.
2778*b5893f02SDimitry Andric   ///
2779*b5893f02SDimitry Andric   /// If the element of NodeList at CurrentIndex is valid, it does not
2780*b5893f02SDimitry Andric   /// change it. If there are no more valid elements, it updates CurrentIndex
2781*b5893f02SDimitry Andric   /// to point to the end of the NodeList.
SkipRemovedElements(size_t & CurrentIndex)2782*b5893f02SDimitry Andric   void SkipRemovedElements(size_t &CurrentIndex) {
2783*b5893f02SDimitry Andric     while (CurrentIndex < NodeList.size()) {
2784*b5893f02SDimitry Andric       auto it = NodeMap.find(NodeList[CurrentIndex]);
2785*b5893f02SDimitry Andric       // If the element has been deleted and added again later, NodeMap will
2786*b5893f02SDimitry Andric       // point to a different index, so CurrentIndex will still be invalid.
2787*b5893f02SDimitry Andric       if (it != NodeMap.end() && it->second == CurrentIndex)
2788*b5893f02SDimitry Andric         break;
2789*b5893f02SDimitry Andric       ++CurrentIndex;
2790*b5893f02SDimitry Andric     }
2791*b5893f02SDimitry Andric   }
2792*b5893f02SDimitry Andric };
2793*b5893f02SDimitry Andric 
PhiNodeSetIterator(PhiNodeSet * const Set,size_t Start)2794*b5893f02SDimitry Andric PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
2795*b5893f02SDimitry Andric     : Set(Set), CurrentIndex(Start) {}
2796*b5893f02SDimitry Andric 
operator *() const2797*b5893f02SDimitry Andric PHINode * PhiNodeSetIterator::operator*() const {
2798*b5893f02SDimitry Andric   assert(CurrentIndex < Set->NodeList.size() &&
2799*b5893f02SDimitry Andric          "PhiNodeSet access out of range");
2800*b5893f02SDimitry Andric   return Set->NodeList[CurrentIndex];
2801*b5893f02SDimitry Andric }
2802*b5893f02SDimitry Andric 
operator ++()2803*b5893f02SDimitry Andric PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
2804*b5893f02SDimitry Andric   assert(CurrentIndex < Set->NodeList.size() &&
2805*b5893f02SDimitry Andric          "PhiNodeSet access out of range");
2806*b5893f02SDimitry Andric   ++CurrentIndex;
2807*b5893f02SDimitry Andric   Set->SkipRemovedElements(CurrentIndex);
2808*b5893f02SDimitry Andric   return *this;
2809*b5893f02SDimitry Andric }
2810*b5893f02SDimitry Andric 
operator ==(const PhiNodeSetIterator & RHS) const2811*b5893f02SDimitry Andric bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
2812*b5893f02SDimitry Andric   return CurrentIndex == RHS.CurrentIndex;
2813*b5893f02SDimitry Andric }
2814*b5893f02SDimitry Andric 
operator !=(const PhiNodeSetIterator & RHS) const2815*b5893f02SDimitry Andric bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
2816*b5893f02SDimitry Andric   return !((*this) == RHS);
2817*b5893f02SDimitry Andric }
2818*b5893f02SDimitry Andric 
28194ba319b5SDimitry Andric /// Keep track of simplification of Phi nodes.
28202cab237bSDimitry Andric /// Accept the set of all phi nodes and erase phi node from this set
28212cab237bSDimitry Andric /// if it is simplified.
28222cab237bSDimitry Andric class SimplificationTracker {
28232cab237bSDimitry Andric   DenseMap<Value *, Value *> Storage;
28242cab237bSDimitry Andric   const SimplifyQuery &SQ;
2825*b5893f02SDimitry Andric   // Tracks newly created Phi nodes. The elements are iterated by insertion
2826*b5893f02SDimitry Andric   // order.
2827*b5893f02SDimitry Andric   PhiNodeSet AllPhiNodes;
28284ba319b5SDimitry Andric   // Tracks newly created Select nodes.
28294ba319b5SDimitry Andric   SmallPtrSet<SelectInst *, 32> AllSelectNodes;
28302cab237bSDimitry Andric 
28312cab237bSDimitry Andric public:
SimplificationTracker(const SimplifyQuery & sq)28324ba319b5SDimitry Andric   SimplificationTracker(const SimplifyQuery &sq)
28334ba319b5SDimitry Andric       : SQ(sq) {}
28342cab237bSDimitry Andric 
Get(Value * V)28352cab237bSDimitry Andric   Value *Get(Value *V) {
28362cab237bSDimitry Andric     do {
28372cab237bSDimitry Andric       auto SV = Storage.find(V);
28382cab237bSDimitry Andric       if (SV == Storage.end())
28392cab237bSDimitry Andric         return V;
28402cab237bSDimitry Andric       V = SV->second;
28412cab237bSDimitry Andric     } while (true);
28422cab237bSDimitry Andric   }
28432cab237bSDimitry Andric 
Simplify(Value * Val)28442cab237bSDimitry Andric   Value *Simplify(Value *Val) {
28452cab237bSDimitry Andric     SmallVector<Value *, 32> WorkList;
28462cab237bSDimitry Andric     SmallPtrSet<Value *, 32> Visited;
28472cab237bSDimitry Andric     WorkList.push_back(Val);
28482cab237bSDimitry Andric     while (!WorkList.empty()) {
28492cab237bSDimitry Andric       auto P = WorkList.pop_back_val();
28502cab237bSDimitry Andric       if (!Visited.insert(P).second)
28512cab237bSDimitry Andric         continue;
28522cab237bSDimitry Andric       if (auto *PI = dyn_cast<Instruction>(P))
28532cab237bSDimitry Andric         if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
28542cab237bSDimitry Andric           for (auto *U : PI->users())
28552cab237bSDimitry Andric             WorkList.push_back(cast<Value>(U));
28562cab237bSDimitry Andric           Put(PI, V);
28572cab237bSDimitry Andric           PI->replaceAllUsesWith(V);
28582cab237bSDimitry Andric           if (auto *PHI = dyn_cast<PHINode>(PI))
2859*b5893f02SDimitry Andric             AllPhiNodes.erase(PHI);
28602cab237bSDimitry Andric           if (auto *Select = dyn_cast<SelectInst>(PI))
28612cab237bSDimitry Andric             AllSelectNodes.erase(Select);
28622cab237bSDimitry Andric           PI->eraseFromParent();
28632cab237bSDimitry Andric         }
28642cab237bSDimitry Andric     }
28652cab237bSDimitry Andric     return Get(Val);
28662cab237bSDimitry Andric   }
28672cab237bSDimitry Andric 
Put(Value * From,Value * To)28682cab237bSDimitry Andric   void Put(Value *From, Value *To) {
28692cab237bSDimitry Andric     Storage.insert({ From, To });
28702cab237bSDimitry Andric   }
28714ba319b5SDimitry Andric 
ReplacePhi(PHINode * From,PHINode * To)28724ba319b5SDimitry Andric   void ReplacePhi(PHINode *From, PHINode *To) {
28734ba319b5SDimitry Andric     Value* OldReplacement = Get(From);
28744ba319b5SDimitry Andric     while (OldReplacement != From) {
28754ba319b5SDimitry Andric       From = To;
28764ba319b5SDimitry Andric       To = dyn_cast<PHINode>(OldReplacement);
28774ba319b5SDimitry Andric       OldReplacement = Get(From);
28784ba319b5SDimitry Andric     }
28794ba319b5SDimitry Andric     assert(Get(To) == To && "Replacement PHI node is already replaced.");
28804ba319b5SDimitry Andric     Put(From, To);
28814ba319b5SDimitry Andric     From->replaceAllUsesWith(To);
2882*b5893f02SDimitry Andric     AllPhiNodes.erase(From);
28834ba319b5SDimitry Andric     From->eraseFromParent();
28844ba319b5SDimitry Andric   }
28854ba319b5SDimitry Andric 
newPhiNodes()2886*b5893f02SDimitry Andric   PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
28874ba319b5SDimitry Andric 
insertNewPhi(PHINode * PN)28884ba319b5SDimitry Andric   void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
28894ba319b5SDimitry Andric 
insertNewSelect(SelectInst * SI)28904ba319b5SDimitry Andric   void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
28914ba319b5SDimitry Andric 
countNewPhiNodes() const28924ba319b5SDimitry Andric   unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
28934ba319b5SDimitry Andric 
countNewSelectNodes() const28944ba319b5SDimitry Andric   unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
28954ba319b5SDimitry Andric 
destroyNewNodes(Type * CommonType)28964ba319b5SDimitry Andric   void destroyNewNodes(Type *CommonType) {
28974ba319b5SDimitry Andric     // For safe erasing, replace the uses with dummy value first.
28984ba319b5SDimitry Andric     auto Dummy = UndefValue::get(CommonType);
28994ba319b5SDimitry Andric     for (auto I : AllPhiNodes) {
29004ba319b5SDimitry Andric       I->replaceAllUsesWith(Dummy);
29014ba319b5SDimitry Andric       I->eraseFromParent();
29024ba319b5SDimitry Andric     }
29034ba319b5SDimitry Andric     AllPhiNodes.clear();
29044ba319b5SDimitry Andric     for (auto I : AllSelectNodes) {
29054ba319b5SDimitry Andric       I->replaceAllUsesWith(Dummy);
29064ba319b5SDimitry Andric       I->eraseFromParent();
29074ba319b5SDimitry Andric     }
29084ba319b5SDimitry Andric     AllSelectNodes.clear();
29094ba319b5SDimitry Andric   }
29102cab237bSDimitry Andric };
29112cab237bSDimitry Andric 
29124ba319b5SDimitry Andric /// A helper class for combining addressing modes.
29132cab237bSDimitry Andric class AddressingModeCombiner {
2914*b5893f02SDimitry Andric   typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
29152cab237bSDimitry Andric   typedef std::pair<PHINode *, PHINode *> PHIPair;
29162cab237bSDimitry Andric 
29172cab237bSDimitry Andric private:
29182cab237bSDimitry Andric   /// The addressing modes we've collected.
29192cab237bSDimitry Andric   SmallVector<ExtAddrMode, 16> AddrModes;
29202cab237bSDimitry Andric 
29212cab237bSDimitry Andric   /// The field in which the AddrModes differ, when we have more than one.
29222cab237bSDimitry Andric   ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
29232cab237bSDimitry Andric 
29242cab237bSDimitry Andric   /// Are the AddrModes that we have all just equal to their original values?
29252cab237bSDimitry Andric   bool AllAddrModesTrivial = true;
29262cab237bSDimitry Andric 
29272cab237bSDimitry Andric   /// Common Type for all different fields in addressing modes.
29282cab237bSDimitry Andric   Type *CommonType;
29292cab237bSDimitry Andric 
29302cab237bSDimitry Andric   /// SimplifyQuery for simplifyInstruction utility.
29312cab237bSDimitry Andric   const SimplifyQuery &SQ;
29322cab237bSDimitry Andric 
29332cab237bSDimitry Andric   /// Original Address.
2934*b5893f02SDimitry Andric   Value *Original;
29352cab237bSDimitry Andric 
29362cab237bSDimitry Andric public:
AddressingModeCombiner(const SimplifyQuery & _SQ,Value * OriginalValue)2937*b5893f02SDimitry Andric   AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
29382cab237bSDimitry Andric       : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
29392cab237bSDimitry Andric 
29404ba319b5SDimitry Andric   /// Get the combined AddrMode
getAddrMode() const29412cab237bSDimitry Andric   const ExtAddrMode &getAddrMode() const {
29422cab237bSDimitry Andric     return AddrModes[0];
29432cab237bSDimitry Andric   }
29442cab237bSDimitry Andric 
29454ba319b5SDimitry Andric   /// Add a new AddrMode if it's compatible with the AddrModes we already
29462cab237bSDimitry Andric   /// have.
29472cab237bSDimitry Andric   /// \return True iff we succeeded in doing so.
addNewAddrMode(ExtAddrMode & NewAddrMode)29482cab237bSDimitry Andric   bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
29492cab237bSDimitry Andric     // Take note of if we have any non-trivial AddrModes, as we need to detect
29502cab237bSDimitry Andric     // when all AddrModes are trivial as then we would introduce a phi or select
29512cab237bSDimitry Andric     // which just duplicates what's already there.
29522cab237bSDimitry Andric     AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
29532cab237bSDimitry Andric 
29542cab237bSDimitry Andric     // If this is the first addrmode then everything is fine.
29552cab237bSDimitry Andric     if (AddrModes.empty()) {
29562cab237bSDimitry Andric       AddrModes.emplace_back(NewAddrMode);
29572cab237bSDimitry Andric       return true;
29582cab237bSDimitry Andric     }
29592cab237bSDimitry Andric 
29602cab237bSDimitry Andric     // Figure out how different this is from the other address modes, which we
29612cab237bSDimitry Andric     // can do just by comparing against the first one given that we only care
29622cab237bSDimitry Andric     // about the cumulative difference.
29632cab237bSDimitry Andric     ExtAddrMode::FieldName ThisDifferentField =
29642cab237bSDimitry Andric       AddrModes[0].compare(NewAddrMode);
29652cab237bSDimitry Andric     if (DifferentField == ExtAddrMode::NoField)
29662cab237bSDimitry Andric       DifferentField = ThisDifferentField;
29672cab237bSDimitry Andric     else if (DifferentField != ThisDifferentField)
29682cab237bSDimitry Andric       DifferentField = ExtAddrMode::MultipleFields;
29692cab237bSDimitry Andric 
29704ba319b5SDimitry Andric     // If NewAddrMode differs in more than one dimension we cannot handle it.
29714ba319b5SDimitry Andric     bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
29724ba319b5SDimitry Andric 
29734ba319b5SDimitry Andric     // If Scale Field is different then we reject.
29744ba319b5SDimitry Andric     CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
29754ba319b5SDimitry Andric 
297666f8bb86SDimitry Andric     // We also must reject the case when base offset is different and
297766f8bb86SDimitry Andric     // scale reg is not null, we cannot handle this case due to merge of
297866f8bb86SDimitry Andric     // different offsets will be used as ScaleReg.
29794ba319b5SDimitry Andric     CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
29804ba319b5SDimitry Andric                               !NewAddrMode.ScaledReg);
29814ba319b5SDimitry Andric 
29824ba319b5SDimitry Andric     // We also must reject the case when GV is different and BaseReg installed
29834ba319b5SDimitry Andric     // due to we want to use base reg as a merge of GV values.
29844ba319b5SDimitry Andric     CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
29854ba319b5SDimitry Andric                               !NewAddrMode.HasBaseReg);
29864ba319b5SDimitry Andric 
29874ba319b5SDimitry Andric     // Even if NewAddMode is the same we still need to collect it due to
29884ba319b5SDimitry Andric     // original value is different. And later we will need all original values
29894ba319b5SDimitry Andric     // as anchors during finding the common Phi node.
29904ba319b5SDimitry Andric     if (CanHandle)
29912cab237bSDimitry Andric       AddrModes.emplace_back(NewAddrMode);
29924ba319b5SDimitry Andric     else
29932cab237bSDimitry Andric       AddrModes.clear();
29944ba319b5SDimitry Andric 
29954ba319b5SDimitry Andric     return CanHandle;
29962cab237bSDimitry Andric   }
29972cab237bSDimitry Andric 
29984ba319b5SDimitry Andric   /// Combine the addressing modes we've collected into a single
29992cab237bSDimitry Andric   /// addressing mode.
30002cab237bSDimitry Andric   /// \return True iff we successfully combined them or we only had one so
30012cab237bSDimitry Andric   /// didn't need to combine them anyway.
combineAddrModes()30022cab237bSDimitry Andric   bool combineAddrModes() {
30032cab237bSDimitry Andric     // If we have no AddrModes then they can't be combined.
30042cab237bSDimitry Andric     if (AddrModes.size() == 0)
30052cab237bSDimitry Andric       return false;
30062cab237bSDimitry Andric 
30072cab237bSDimitry Andric     // A single AddrMode can trivially be combined.
30082cab237bSDimitry Andric     if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
30092cab237bSDimitry Andric       return true;
30102cab237bSDimitry Andric 
30112cab237bSDimitry Andric     // If the AddrModes we collected are all just equal to the value they are
30122cab237bSDimitry Andric     // derived from then combining them wouldn't do anything useful.
30132cab237bSDimitry Andric     if (AllAddrModesTrivial)
30142cab237bSDimitry Andric       return false;
30152cab237bSDimitry Andric 
30162cab237bSDimitry Andric     if (!addrModeCombiningAllowed())
30172cab237bSDimitry Andric       return false;
30182cab237bSDimitry Andric 
30192cab237bSDimitry Andric     // Build a map between <original value, basic block where we saw it> to
30202cab237bSDimitry Andric     // value of base register.
30212cab237bSDimitry Andric     // Bail out if there is no common type.
30222cab237bSDimitry Andric     FoldAddrToValueMapping Map;
30232cab237bSDimitry Andric     if (!initializeMap(Map))
30242cab237bSDimitry Andric       return false;
30252cab237bSDimitry Andric 
30262cab237bSDimitry Andric     Value *CommonValue = findCommon(Map);
30272cab237bSDimitry Andric     if (CommonValue)
30282cab237bSDimitry Andric       AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
30292cab237bSDimitry Andric     return CommonValue != nullptr;
30302cab237bSDimitry Andric   }
30312cab237bSDimitry Andric 
30322cab237bSDimitry Andric private:
3033*b5893f02SDimitry Andric   /// Initialize Map with anchor values. For address seen
30342cab237bSDimitry Andric   /// we set the value of different field saw in this address.
30352cab237bSDimitry Andric   /// At the same time we find a common type for different field we will
30362cab237bSDimitry Andric   /// use to create new Phi/Select nodes. Keep it in CommonType field.
30372cab237bSDimitry Andric   /// Return false if there is no common type found.
initializeMap(FoldAddrToValueMapping & Map)30382cab237bSDimitry Andric   bool initializeMap(FoldAddrToValueMapping &Map) {
30392cab237bSDimitry Andric     // Keep track of keys where the value is null. We will need to replace it
30402cab237bSDimitry Andric     // with constant null when we know the common type.
3041*b5893f02SDimitry Andric     SmallVector<Value *, 2> NullValue;
30422cab237bSDimitry Andric     Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
30432cab237bSDimitry Andric     for (auto &AM : AddrModes) {
30442cab237bSDimitry Andric       Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
30452cab237bSDimitry Andric       if (DV) {
30462cab237bSDimitry Andric         auto *Type = DV->getType();
30472cab237bSDimitry Andric         if (CommonType && CommonType != Type)
30482cab237bSDimitry Andric           return false;
30492cab237bSDimitry Andric         CommonType = Type;
3050*b5893f02SDimitry Andric         Map[AM.OriginalValue] = DV;
30512cab237bSDimitry Andric       } else {
3052*b5893f02SDimitry Andric         NullValue.push_back(AM.OriginalValue);
30532cab237bSDimitry Andric       }
30542cab237bSDimitry Andric     }
30552cab237bSDimitry Andric     assert(CommonType && "At least one non-null value must be!");
3056*b5893f02SDimitry Andric     for (auto *V : NullValue)
3057*b5893f02SDimitry Andric       Map[V] = Constant::getNullValue(CommonType);
30582cab237bSDimitry Andric     return true;
30592cab237bSDimitry Andric   }
30602cab237bSDimitry Andric 
3061*b5893f02SDimitry Andric   /// We have mapping between value A and other value B where B was a field in
3062*b5893f02SDimitry Andric   /// addressing mode represented by A. Also we have an original value C
3063*b5893f02SDimitry Andric   /// representing an address we start with. Traversing from C through phi and
3064*b5893f02SDimitry Andric   /// selects we ended up with A's in a map. This utility function tries to find
3065*b5893f02SDimitry Andric   /// a value V which is a field in addressing mode C and traversing through phi
3066*b5893f02SDimitry Andric   /// nodes and selects we will end up in corresponded values B in a map.
30672cab237bSDimitry Andric   /// The utility will create a new Phi/Selects if needed.
30682cab237bSDimitry Andric   // The simple example looks as follows:
30692cab237bSDimitry Andric   // BB1:
30702cab237bSDimitry Andric   //   p1 = b1 + 40
30712cab237bSDimitry Andric   //   br cond BB2, BB3
30722cab237bSDimitry Andric   // BB2:
30732cab237bSDimitry Andric   //   p2 = b2 + 40
30742cab237bSDimitry Andric   //   br BB3
30752cab237bSDimitry Andric   // BB3:
30762cab237bSDimitry Andric   //   p = phi [p1, BB1], [p2, BB2]
30772cab237bSDimitry Andric   //   v = load p
30782cab237bSDimitry Andric   // Map is
3079*b5893f02SDimitry Andric   //   p1 -> b1
3080*b5893f02SDimitry Andric   //   p2 -> b2
30812cab237bSDimitry Andric   // Request is
3082*b5893f02SDimitry Andric   //   p -> ?
3083*b5893f02SDimitry Andric   // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
findCommon(FoldAddrToValueMapping & Map)30842cab237bSDimitry Andric   Value *findCommon(FoldAddrToValueMapping &Map) {
30854ba319b5SDimitry Andric     // Tracks the simplification of newly created phi nodes. The reason we use
30862cab237bSDimitry Andric     // this mapping is because we will add new created Phi nodes in AddrToBase.
30872cab237bSDimitry Andric     // Simplification of Phi nodes is recursive, so some Phi node may
3088*b5893f02SDimitry Andric     // be simplified after we added it to AddrToBase. In reality this
3089*b5893f02SDimitry Andric     // simplification is possible only if original phi/selects were not
3090*b5893f02SDimitry Andric     // simplified yet.
30912cab237bSDimitry Andric     // Using this mapping we can find the current value in AddrToBase.
30924ba319b5SDimitry Andric     SimplificationTracker ST(SQ);
30932cab237bSDimitry Andric 
30942cab237bSDimitry Andric     // First step, DFS to create PHI nodes for all intermediate blocks.
30952cab237bSDimitry Andric     // Also fill traverse order for the second step.
3096*b5893f02SDimitry Andric     SmallVector<Value *, 32> TraverseOrder;
30974ba319b5SDimitry Andric     InsertPlaceholders(Map, TraverseOrder, ST);
30982cab237bSDimitry Andric 
30992cab237bSDimitry Andric     // Second Step, fill new nodes by merged values and simplify if possible.
31002cab237bSDimitry Andric     FillPlaceholders(Map, TraverseOrder, ST);
31012cab237bSDimitry Andric 
31024ba319b5SDimitry Andric     if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
31034ba319b5SDimitry Andric       ST.destroyNewNodes(CommonType);
31042cab237bSDimitry Andric       return nullptr;
31052cab237bSDimitry Andric     }
31062cab237bSDimitry Andric 
31072cab237bSDimitry Andric     // Now we'd like to match New Phi nodes to existed ones.
31082cab237bSDimitry Andric     unsigned PhiNotMatchedCount = 0;
31094ba319b5SDimitry Andric     if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
31104ba319b5SDimitry Andric       ST.destroyNewNodes(CommonType);
31112cab237bSDimitry Andric       return nullptr;
31122cab237bSDimitry Andric     }
31132cab237bSDimitry Andric 
31142cab237bSDimitry Andric     auto *Result = ST.Get(Map.find(Original)->second);
31152cab237bSDimitry Andric     if (Result) {
31164ba319b5SDimitry Andric       NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
31174ba319b5SDimitry Andric       NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
31182cab237bSDimitry Andric     }
31192cab237bSDimitry Andric     return Result;
31202cab237bSDimitry Andric   }
31212cab237bSDimitry Andric 
31224ba319b5SDimitry Andric   /// Try to match PHI node to Candidate.
31232cab237bSDimitry Andric   /// Matcher tracks the matched Phi nodes.
MatchPhiNode(PHINode * PHI,PHINode * Candidate,SmallSetVector<PHIPair,8> & Matcher,PhiNodeSet & PhiNodesToMatch)31242cab237bSDimitry Andric   bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
31254ba319b5SDimitry Andric                     SmallSetVector<PHIPair, 8> &Matcher,
3126*b5893f02SDimitry Andric                     PhiNodeSet &PhiNodesToMatch) {
31272cab237bSDimitry Andric     SmallVector<PHIPair, 8> WorkList;
31282cab237bSDimitry Andric     Matcher.insert({ PHI, Candidate });
31292cab237bSDimitry Andric     WorkList.push_back({ PHI, Candidate });
31302cab237bSDimitry Andric     SmallSet<PHIPair, 8> Visited;
31312cab237bSDimitry Andric     while (!WorkList.empty()) {
31322cab237bSDimitry Andric       auto Item = WorkList.pop_back_val();
31332cab237bSDimitry Andric       if (!Visited.insert(Item).second)
31342cab237bSDimitry Andric         continue;
31352cab237bSDimitry Andric       // We iterate over all incoming values to Phi to compare them.
31362cab237bSDimitry Andric       // If values are different and both of them Phi and the first one is a
31372cab237bSDimitry Andric       // Phi we added (subject to match) and both of them is in the same basic
31382cab237bSDimitry Andric       // block then we can match our pair if values match. So we state that
31392cab237bSDimitry Andric       // these values match and add it to work list to verify that.
31402cab237bSDimitry Andric       for (auto B : Item.first->blocks()) {
31412cab237bSDimitry Andric         Value *FirstValue = Item.first->getIncomingValueForBlock(B);
31422cab237bSDimitry Andric         Value *SecondValue = Item.second->getIncomingValueForBlock(B);
31432cab237bSDimitry Andric         if (FirstValue == SecondValue)
31442cab237bSDimitry Andric           continue;
31452cab237bSDimitry Andric 
31462cab237bSDimitry Andric         PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
31472cab237bSDimitry Andric         PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
31482cab237bSDimitry Andric 
31492cab237bSDimitry Andric         // One of them is not Phi or
31502cab237bSDimitry Andric         // The first one is not Phi node from the set we'd like to match or
31512cab237bSDimitry Andric         // Phi nodes from different basic blocks then
31522cab237bSDimitry Andric         // we will not be able to match.
31532cab237bSDimitry Andric         if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
31542cab237bSDimitry Andric             FirstPhi->getParent() != SecondPhi->getParent())
31552cab237bSDimitry Andric           return false;
31562cab237bSDimitry Andric 
31572cab237bSDimitry Andric         // If we already matched them then continue.
31582cab237bSDimitry Andric         if (Matcher.count({ FirstPhi, SecondPhi }))
31592cab237bSDimitry Andric           continue;
31602cab237bSDimitry Andric         // So the values are different and does not match. So we need them to
31612cab237bSDimitry Andric         // match.
31622cab237bSDimitry Andric         Matcher.insert({ FirstPhi, SecondPhi });
31632cab237bSDimitry Andric         // But me must check it.
31642cab237bSDimitry Andric         WorkList.push_back({ FirstPhi, SecondPhi });
31652cab237bSDimitry Andric       }
31662cab237bSDimitry Andric     }
31672cab237bSDimitry Andric     return true;
31682cab237bSDimitry Andric   }
31692cab237bSDimitry Andric 
31704ba319b5SDimitry Andric   /// For the given set of PHI nodes (in the SimplificationTracker) try
31714ba319b5SDimitry Andric   /// to find their equivalents.
31722cab237bSDimitry Andric   /// Returns false if this matching fails and creation of new Phi is disabled.
MatchPhiSet(SimplificationTracker & ST,bool AllowNewPhiNodes,unsigned & PhiNotMatchedCount)31734ba319b5SDimitry Andric   bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
31742cab237bSDimitry Andric                    unsigned &PhiNotMatchedCount) {
3175*b5893f02SDimitry Andric     // Matched and PhiNodesToMatch iterate their elements in a deterministic
3176*b5893f02SDimitry Andric     // order, so the replacements (ReplacePhi) are also done in a deterministic
3177*b5893f02SDimitry Andric     // order.
31784ba319b5SDimitry Andric     SmallSetVector<PHIPair, 8> Matched;
31792cab237bSDimitry Andric     SmallPtrSet<PHINode *, 8> WillNotMatch;
3180*b5893f02SDimitry Andric     PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
31812cab237bSDimitry Andric     while (PhiNodesToMatch.size()) {
31822cab237bSDimitry Andric       PHINode *PHI = *PhiNodesToMatch.begin();
31832cab237bSDimitry Andric 
31842cab237bSDimitry Andric       // Add us, if no Phi nodes in the basic block we do not match.
31852cab237bSDimitry Andric       WillNotMatch.clear();
31862cab237bSDimitry Andric       WillNotMatch.insert(PHI);
31872cab237bSDimitry Andric 
31882cab237bSDimitry Andric       // Traverse all Phis until we found equivalent or fail to do that.
31892cab237bSDimitry Andric       bool IsMatched = false;
31902cab237bSDimitry Andric       for (auto &P : PHI->getParent()->phis()) {
31912cab237bSDimitry Andric         if (&P == PHI)
31922cab237bSDimitry Andric           continue;
31932cab237bSDimitry Andric         if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
31942cab237bSDimitry Andric           break;
31952cab237bSDimitry Andric         // If it does not match, collect all Phi nodes from matcher.
31962cab237bSDimitry Andric         // if we end up with no match, them all these Phi nodes will not match
31972cab237bSDimitry Andric         // later.
31982cab237bSDimitry Andric         for (auto M : Matched)
31992cab237bSDimitry Andric           WillNotMatch.insert(M.first);
32002cab237bSDimitry Andric         Matched.clear();
32012cab237bSDimitry Andric       }
32022cab237bSDimitry Andric       if (IsMatched) {
32032cab237bSDimitry Andric         // Replace all matched values and erase them.
32044ba319b5SDimitry Andric         for (auto MV : Matched)
32054ba319b5SDimitry Andric           ST.ReplacePhi(MV.first, MV.second);
32062cab237bSDimitry Andric         Matched.clear();
32072cab237bSDimitry Andric         continue;
32082cab237bSDimitry Andric       }
32092cab237bSDimitry Andric       // If we are not allowed to create new nodes then bail out.
32102cab237bSDimitry Andric       if (!AllowNewPhiNodes)
32112cab237bSDimitry Andric         return false;
32122cab237bSDimitry Andric       // Just remove all seen values in matcher. They will not match anything.
32132cab237bSDimitry Andric       PhiNotMatchedCount += WillNotMatch.size();
32142cab237bSDimitry Andric       for (auto *P : WillNotMatch)
3215*b5893f02SDimitry Andric         PhiNodesToMatch.erase(P);
32162cab237bSDimitry Andric     }
32172cab237bSDimitry Andric     return true;
32182cab237bSDimitry Andric   }
3219*b5893f02SDimitry Andric   /// Fill the placeholders with values from predecessors and simplify them.
FillPlaceholders(FoldAddrToValueMapping & Map,SmallVectorImpl<Value * > & TraverseOrder,SimplificationTracker & ST)32202cab237bSDimitry Andric   void FillPlaceholders(FoldAddrToValueMapping &Map,
3221*b5893f02SDimitry Andric                         SmallVectorImpl<Value *> &TraverseOrder,
32222cab237bSDimitry Andric                         SimplificationTracker &ST) {
32232cab237bSDimitry Andric     while (!TraverseOrder.empty()) {
3224*b5893f02SDimitry Andric       Value *Current = TraverseOrder.pop_back_val();
32252cab237bSDimitry Andric       assert(Map.find(Current) != Map.end() && "No node to fill!!!");
32262cab237bSDimitry Andric       Value *V = Map[Current];
32272cab237bSDimitry Andric 
32282cab237bSDimitry Andric       if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
32292cab237bSDimitry Andric         // CurrentValue also must be Select.
3230*b5893f02SDimitry Andric         auto *CurrentSelect = cast<SelectInst>(Current);
32312cab237bSDimitry Andric         auto *TrueValue = CurrentSelect->getTrueValue();
3232*b5893f02SDimitry Andric         assert(Map.find(TrueValue) != Map.end() && "No True Value!");
3233*b5893f02SDimitry Andric         Select->setTrueValue(ST.Get(Map[TrueValue]));
32342cab237bSDimitry Andric         auto *FalseValue = CurrentSelect->getFalseValue();
3235*b5893f02SDimitry Andric         assert(Map.find(FalseValue) != Map.end() && "No False Value!");
3236*b5893f02SDimitry Andric         Select->setFalseValue(ST.Get(Map[FalseValue]));
32372cab237bSDimitry Andric       } else {
32382cab237bSDimitry Andric         // Must be a Phi node then.
32392cab237bSDimitry Andric         PHINode *PHI = cast<PHINode>(V);
3240*b5893f02SDimitry Andric         auto *CurrentPhi = dyn_cast<PHINode>(Current);
32412cab237bSDimitry Andric         // Fill the Phi node with values from predecessors.
3242*b5893f02SDimitry Andric         for (auto B : predecessors(PHI->getParent())) {
3243*b5893f02SDimitry Andric           Value *PV = CurrentPhi->getIncomingValueForBlock(B);
3244*b5893f02SDimitry Andric           assert(Map.find(PV) != Map.end() && "No predecessor Value!");
3245*b5893f02SDimitry Andric           PHI->addIncoming(ST.Get(Map[PV]), B);
32462cab237bSDimitry Andric         }
32472cab237bSDimitry Andric       }
32482cab237bSDimitry Andric       Map[Current] = ST.Simplify(V);
32492cab237bSDimitry Andric     }
32502cab237bSDimitry Andric   }
32512cab237bSDimitry Andric 
3252*b5893f02SDimitry Andric   /// Starting from original value recursively iterates over def-use chain up to
3253*b5893f02SDimitry Andric   /// known ending values represented in a map. For each traversed phi/select
3254*b5893f02SDimitry Andric   /// inserts a placeholder Phi or Select.
32552cab237bSDimitry Andric   /// Reports all new created Phi/Select nodes by adding them to set.
3256*b5893f02SDimitry Andric   /// Also reports and order in what values have been traversed.
InsertPlaceholders(FoldAddrToValueMapping & Map,SmallVectorImpl<Value * > & TraverseOrder,SimplificationTracker & ST)32572cab237bSDimitry Andric   void InsertPlaceholders(FoldAddrToValueMapping &Map,
3258*b5893f02SDimitry Andric                           SmallVectorImpl<Value *> &TraverseOrder,
32594ba319b5SDimitry Andric                           SimplificationTracker &ST) {
3260*b5893f02SDimitry Andric     SmallVector<Value *, 32> Worklist;
3261*b5893f02SDimitry Andric     assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
32622cab237bSDimitry Andric            "Address must be a Phi or Select node");
32632cab237bSDimitry Andric     auto *Dummy = UndefValue::get(CommonType);
32642cab237bSDimitry Andric     Worklist.push_back(Original);
32652cab237bSDimitry Andric     while (!Worklist.empty()) {
3266*b5893f02SDimitry Andric       Value *Current = Worklist.pop_back_val();
32672cab237bSDimitry Andric       // if it is already visited or it is an ending value then skip it.
32682cab237bSDimitry Andric       if (Map.find(Current) != Map.end())
32692cab237bSDimitry Andric         continue;
32702cab237bSDimitry Andric       TraverseOrder.push_back(Current);
32712cab237bSDimitry Andric 
32722cab237bSDimitry Andric       // CurrentValue must be a Phi node or select. All others must be covered
32732cab237bSDimitry Andric       // by anchors.
3274*b5893f02SDimitry Andric       if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
32752cab237bSDimitry Andric         // Is it OK to get metadata from OrigSelect?!
32762cab237bSDimitry Andric         // Create a Select placeholder with dummy value.
3277*b5893f02SDimitry Andric         SelectInst *Select = SelectInst::Create(
3278*b5893f02SDimitry Andric             CurrentSelect->getCondition(), Dummy, Dummy,
3279*b5893f02SDimitry Andric             CurrentSelect->getName(), CurrentSelect, CurrentSelect);
32802cab237bSDimitry Andric         Map[Current] = Select;
32814ba319b5SDimitry Andric         ST.insertNewSelect(Select);
3282*b5893f02SDimitry Andric         // We are interested in True and False values.
3283*b5893f02SDimitry Andric         Worklist.push_back(CurrentSelect->getTrueValue());
3284*b5893f02SDimitry Andric         Worklist.push_back(CurrentSelect->getFalseValue());
32852cab237bSDimitry Andric       } else {
32862cab237bSDimitry Andric         // It must be a Phi node then.
3287*b5893f02SDimitry Andric         PHINode *CurrentPhi = cast<PHINode>(Current);
3288*b5893f02SDimitry Andric         unsigned PredCount = CurrentPhi->getNumIncomingValues();
3289*b5893f02SDimitry Andric         PHINode *PHI =
3290*b5893f02SDimitry Andric             PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
32912cab237bSDimitry Andric         Map[Current] = PHI;
32924ba319b5SDimitry Andric         ST.insertNewPhi(PHI);
3293*b5893f02SDimitry Andric         for (Value *P : CurrentPhi->incoming_values())
3294*b5893f02SDimitry Andric           Worklist.push_back(P);
32952cab237bSDimitry Andric       }
32962cab237bSDimitry Andric     }
32972cab237bSDimitry Andric   }
32982cab237bSDimitry Andric 
addrModeCombiningAllowed()32992cab237bSDimitry Andric   bool addrModeCombiningAllowed() {
33002cab237bSDimitry Andric     if (DisableComplexAddrModes)
33012cab237bSDimitry Andric       return false;
33022cab237bSDimitry Andric     switch (DifferentField) {
33032cab237bSDimitry Andric     default:
33042cab237bSDimitry Andric       return false;
33052cab237bSDimitry Andric     case ExtAddrMode::BaseRegField:
33062cab237bSDimitry Andric       return AddrSinkCombineBaseReg;
33072cab237bSDimitry Andric     case ExtAddrMode::BaseGVField:
33082cab237bSDimitry Andric       return AddrSinkCombineBaseGV;
33092cab237bSDimitry Andric     case ExtAddrMode::BaseOffsField:
33102cab237bSDimitry Andric       return AddrSinkCombineBaseOffs;
33112cab237bSDimitry Andric     case ExtAddrMode::ScaledRegField:
33122cab237bSDimitry Andric       return AddrSinkCombineScaledReg;
33132cab237bSDimitry Andric     }
33142cab237bSDimitry Andric   }
33152cab237bSDimitry Andric };
33162cab237bSDimitry Andric } // end anonymous namespace
33172cab237bSDimitry Andric 
33187d523365SDimitry Andric /// Try adding ScaleReg*Scale to the current addressing mode.
331991bc56edSDimitry Andric /// Return true and update AddrMode if this addr mode is legal for the target,
332091bc56edSDimitry Andric /// false if not.
matchScaledValue(Value * ScaleReg,int64_t Scale,unsigned Depth)33217d523365SDimitry Andric bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
332291bc56edSDimitry Andric                                              unsigned Depth) {
332391bc56edSDimitry Andric   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
332491bc56edSDimitry Andric   // mode.  Just process that directly.
332591bc56edSDimitry Andric   if (Scale == 1)
33267d523365SDimitry Andric     return matchAddr(ScaleReg, Depth);
332791bc56edSDimitry Andric 
332891bc56edSDimitry Andric   // If the scale is 0, it takes nothing to add this.
332991bc56edSDimitry Andric   if (Scale == 0)
333091bc56edSDimitry Andric     return true;
333191bc56edSDimitry Andric 
333291bc56edSDimitry Andric   // If we already have a scale of this value, we can add to it, otherwise, we
333391bc56edSDimitry Andric   // need an available scale field.
333491bc56edSDimitry Andric   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
333591bc56edSDimitry Andric     return false;
333691bc56edSDimitry Andric 
333791bc56edSDimitry Andric   ExtAddrMode TestAddrMode = AddrMode;
333891bc56edSDimitry Andric 
333991bc56edSDimitry Andric   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
334091bc56edSDimitry Andric   // [A+B + A*7] -> [B+A*8].
334191bc56edSDimitry Andric   TestAddrMode.Scale += Scale;
334291bc56edSDimitry Andric   TestAddrMode.ScaledReg = ScaleReg;
334391bc56edSDimitry Andric 
334491bc56edSDimitry Andric   // If the new address isn't legal, bail out.
3345875ed548SDimitry Andric   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
334691bc56edSDimitry Andric     return false;
334791bc56edSDimitry Andric 
334891bc56edSDimitry Andric   // It was legal, so commit it.
334991bc56edSDimitry Andric   AddrMode = TestAddrMode;
335091bc56edSDimitry Andric 
335191bc56edSDimitry Andric   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
335291bc56edSDimitry Andric   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
335391bc56edSDimitry Andric   // X*Scale + C*Scale to addr mode.
335491bc56edSDimitry Andric   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
335591bc56edSDimitry Andric   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
335691bc56edSDimitry Andric       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
335791bc56edSDimitry Andric     TestAddrMode.ScaledReg = AddLHS;
335891bc56edSDimitry Andric     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
335991bc56edSDimitry Andric 
336091bc56edSDimitry Andric     // If this addressing mode is legal, commit it and remember that we folded
336191bc56edSDimitry Andric     // this instruction.
3362875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
336391bc56edSDimitry Andric       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
336491bc56edSDimitry Andric       AddrMode = TestAddrMode;
336591bc56edSDimitry Andric       return true;
336691bc56edSDimitry Andric     }
336791bc56edSDimitry Andric   }
336891bc56edSDimitry Andric 
336991bc56edSDimitry Andric   // Otherwise, not (x+c)*scale, just return what we have.
337091bc56edSDimitry Andric   return true;
337191bc56edSDimitry Andric }
337291bc56edSDimitry Andric 
33737d523365SDimitry Andric /// This is a little filter, which returns true if an addressing computation
33747d523365SDimitry Andric /// involving I might be folded into a load/store accessing it.
33757d523365SDimitry Andric /// This doesn't need to be perfect, but needs to accept at least
337691bc56edSDimitry Andric /// the set of instructions that MatchOperationAddr can.
MightBeFoldableInst(Instruction * I)337791bc56edSDimitry Andric static bool MightBeFoldableInst(Instruction *I) {
337891bc56edSDimitry Andric   switch (I->getOpcode()) {
337991bc56edSDimitry Andric   case Instruction::BitCast:
338091bc56edSDimitry Andric   case Instruction::AddrSpaceCast:
338191bc56edSDimitry Andric     // Don't touch identity bitcasts.
338291bc56edSDimitry Andric     if (I->getType() == I->getOperand(0)->getType())
338391bc56edSDimitry Andric       return false;
33844ba319b5SDimitry Andric     return I->getType()->isIntOrPtrTy();
338591bc56edSDimitry Andric   case Instruction::PtrToInt:
338691bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
338791bc56edSDimitry Andric     return true;
338891bc56edSDimitry Andric   case Instruction::IntToPtr:
338991bc56edSDimitry Andric     // We know the input is intptr_t, so this is foldable.
339091bc56edSDimitry Andric     return true;
339191bc56edSDimitry Andric   case Instruction::Add:
339291bc56edSDimitry Andric     return true;
339391bc56edSDimitry Andric   case Instruction::Mul:
339491bc56edSDimitry Andric   case Instruction::Shl:
339591bc56edSDimitry Andric     // Can only handle X*C and X << C.
339691bc56edSDimitry Andric     return isa<ConstantInt>(I->getOperand(1));
339791bc56edSDimitry Andric   case Instruction::GetElementPtr:
339891bc56edSDimitry Andric     return true;
339991bc56edSDimitry Andric   default:
340091bc56edSDimitry Andric     return false;
340191bc56edSDimitry Andric   }
340291bc56edSDimitry Andric }
340391bc56edSDimitry Andric 
34044ba319b5SDimitry Andric /// Check whether or not \p Val is a legal instruction for \p TLI.
340539d628a0SDimitry Andric /// \note \p Val is assumed to be the product of some type promotion.
340639d628a0SDimitry Andric /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
340739d628a0SDimitry Andric /// to be legal, as the non-promoted value would have had the same state.
isPromotedInstructionLegal(const TargetLowering & TLI,const DataLayout & DL,Value * Val)3408875ed548SDimitry Andric static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3409875ed548SDimitry Andric                                        const DataLayout &DL, Value *Val) {
341039d628a0SDimitry Andric   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
341139d628a0SDimitry Andric   if (!PromotedInst)
341239d628a0SDimitry Andric     return false;
341339d628a0SDimitry Andric   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
341439d628a0SDimitry Andric   // If the ISDOpcode is undefined, it was undefined before the promotion.
341539d628a0SDimitry Andric   if (!ISDOpcode)
341639d628a0SDimitry Andric     return true;
341739d628a0SDimitry Andric   // Otherwise, check if the promoted instruction is legal or not.
341839d628a0SDimitry Andric   return TLI.isOperationLegalOrCustom(
3419875ed548SDimitry Andric       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
342039d628a0SDimitry Andric }
342139d628a0SDimitry Andric 
34222cab237bSDimitry Andric namespace {
34232cab237bSDimitry Andric 
34244ba319b5SDimitry Andric /// Hepler class to perform type promotion.
342591bc56edSDimitry Andric class TypePromotionHelper {
34264ba319b5SDimitry Andric   /// Utility function to add a promoted instruction \p ExtOpnd to
34274ba319b5SDimitry Andric   /// \p PromotedInsts and record the type of extension we have seen.
addPromotedInst(InstrToOrigTy & PromotedInsts,Instruction * ExtOpnd,bool IsSExt)34284ba319b5SDimitry Andric   static void addPromotedInst(InstrToOrigTy &PromotedInsts,
34294ba319b5SDimitry Andric                               Instruction *ExtOpnd,
34304ba319b5SDimitry Andric                               bool IsSExt) {
34314ba319b5SDimitry Andric     ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
34324ba319b5SDimitry Andric     InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
34334ba319b5SDimitry Andric     if (It != PromotedInsts.end()) {
34344ba319b5SDimitry Andric       // If the new extension is same as original, the information in
34354ba319b5SDimitry Andric       // PromotedInsts[ExtOpnd] is still correct.
34364ba319b5SDimitry Andric       if (It->second.getInt() == ExtTy)
34374ba319b5SDimitry Andric         return;
34384ba319b5SDimitry Andric 
34394ba319b5SDimitry Andric       // Now the new extension is different from old extension, we make
34404ba319b5SDimitry Andric       // the type information invalid by setting extension type to
34414ba319b5SDimitry Andric       // BothExtension.
34424ba319b5SDimitry Andric       ExtTy = BothExtension;
34434ba319b5SDimitry Andric     }
34444ba319b5SDimitry Andric     PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
34454ba319b5SDimitry Andric   }
34464ba319b5SDimitry Andric 
34474ba319b5SDimitry Andric   /// Utility function to query the original type of instruction \p Opnd
34484ba319b5SDimitry Andric   /// with a matched extension type. If the extension doesn't match, we
34494ba319b5SDimitry Andric   /// cannot use the information we had on the original type.
34504ba319b5SDimitry Andric   /// BothExtension doesn't match any extension type.
getOrigType(const InstrToOrigTy & PromotedInsts,Instruction * Opnd,bool IsSExt)34514ba319b5SDimitry Andric   static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
34524ba319b5SDimitry Andric                                  Instruction *Opnd,
34534ba319b5SDimitry Andric                                  bool IsSExt) {
34544ba319b5SDimitry Andric     ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
34554ba319b5SDimitry Andric     InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
34564ba319b5SDimitry Andric     if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
34574ba319b5SDimitry Andric       return It->second.getPointer();
34584ba319b5SDimitry Andric     return nullptr;
34594ba319b5SDimitry Andric   }
34604ba319b5SDimitry Andric 
34614ba319b5SDimitry Andric   /// Utility function to check whether or not a sign or zero extension
346239d628a0SDimitry Andric   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
346339d628a0SDimitry Andric   /// either using the operands of \p Inst or promoting \p Inst.
346439d628a0SDimitry Andric   /// The type of the extension is defined by \p IsSExt.
346591bc56edSDimitry Andric   /// In other words, check if:
346639d628a0SDimitry Andric   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
346791bc56edSDimitry Andric   /// #1 Promotion applies:
346839d628a0SDimitry Andric   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
346991bc56edSDimitry Andric   /// #2 Operand reuses:
347039d628a0SDimitry Andric   /// ext opnd1 to ConsideredExtType.
347191bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
347239d628a0SDimitry Andric   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
347339d628a0SDimitry Andric                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
347491bc56edSDimitry Andric 
34754ba319b5SDimitry Andric   /// Utility function to determine if \p OpIdx should be promoted when
347691bc56edSDimitry Andric   /// promoting \p Inst.
shouldExtOperand(const Instruction * Inst,int OpIdx)347739d628a0SDimitry Andric   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
34787d523365SDimitry Andric     return !(isa<SelectInst>(Inst) && OpIdx == 0);
347991bc56edSDimitry Andric   }
348091bc56edSDimitry Andric 
34814ba319b5SDimitry Andric   /// Utility function to promote the operand of \p Ext when this
348239d628a0SDimitry Andric   /// operand is a promotable trunc or sext or zext.
348391bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
3484ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all instructions
348539d628a0SDimitry Andric   /// created to promote the operand of Ext.
348639d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
348739d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
348891bc56edSDimitry Andric   /// Should never be called directly.
348939d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
349039d628a0SDimitry Andric   static Value *promoteOperandForTruncAndAnyExt(
349139d628a0SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3492ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
349339d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3494ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
349591bc56edSDimitry Andric 
34964ba319b5SDimitry Andric   /// Utility function to promote the operand of \p Ext when this
349791bc56edSDimitry Andric   /// operand is promotable and is not a supported trunc or sext.
349891bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
3499ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all the instructions
350039d628a0SDimitry Andric   /// created to promote the operand of Ext.
350139d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
350239d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
350391bc56edSDimitry Andric   /// Should never be called directly.
350439d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
3505ff0cc061SDimitry Andric   static Value *promoteOperandForOther(Instruction *Ext,
3506ff0cc061SDimitry Andric                                        TypePromotionTransaction &TPT,
3507ff0cc061SDimitry Andric                                        InstrToOrigTy &PromotedInsts,
3508ff0cc061SDimitry Andric                                        unsigned &CreatedInstsCost,
350939d628a0SDimitry Andric                                        SmallVectorImpl<Instruction *> *Exts,
3510ff0cc061SDimitry Andric                                        SmallVectorImpl<Instruction *> *Truncs,
3511ff0cc061SDimitry Andric                                        const TargetLowering &TLI, bool IsSExt);
351239d628a0SDimitry Andric 
351339d628a0SDimitry Andric   /// \see promoteOperandForOther.
signExtendOperandForOther(Instruction * Ext,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInstsCost,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs,const TargetLowering & TLI)3514ff0cc061SDimitry Andric   static Value *signExtendOperandForOther(
3515ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3516ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
351739d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3518ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3519ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3520ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, true);
352139d628a0SDimitry Andric   }
352239d628a0SDimitry Andric 
352339d628a0SDimitry Andric   /// \see promoteOperandForOther.
zeroExtendOperandForOther(Instruction * Ext,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInstsCost,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs,const TargetLowering & TLI)3524ff0cc061SDimitry Andric   static Value *zeroExtendOperandForOther(
3525ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3526ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
352739d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3528ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3529ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3530ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, false);
353139d628a0SDimitry Andric   }
353291bc56edSDimitry Andric 
353391bc56edSDimitry Andric public:
353439d628a0SDimitry Andric   /// Type for the utility function that promotes the operand of Ext.
35352cab237bSDimitry Andric   using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3536ff0cc061SDimitry Andric                             InstrToOrigTy &PromotedInsts,
3537ff0cc061SDimitry Andric                             unsigned &CreatedInstsCost,
353839d628a0SDimitry Andric                             SmallVectorImpl<Instruction *> *Exts,
3539ff0cc061SDimitry Andric                             SmallVectorImpl<Instruction *> *Truncs,
3540ff0cc061SDimitry Andric                             const TargetLowering &TLI);
35412cab237bSDimitry Andric 
35424ba319b5SDimitry Andric   /// Given a sign/zero extend instruction \p Ext, return the appropriate
354339d628a0SDimitry Andric   /// action to promote the operand of \p Ext instead of using Ext.
354491bc56edSDimitry Andric   /// \return NULL if no promotable action is possible with the current
354591bc56edSDimitry Andric   /// sign extension.
35468f0fd8f6SDimitry Andric   /// \p InsertedInsts keeps track of all the instructions inserted by the
35478f0fd8f6SDimitry Andric   /// other CodeGenPrepare optimizations. This information is important
354891bc56edSDimitry Andric   /// because we do not want to promote these instructions as CodeGenPrepare
354991bc56edSDimitry Andric   /// will reinsert them later. Thus creating an infinite loop: create/remove.
355091bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
35518f0fd8f6SDimitry Andric   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
355291bc56edSDimitry Andric                           const TargetLowering &TLI,
355391bc56edSDimitry Andric                           const InstrToOrigTy &PromotedInsts);
355491bc56edSDimitry Andric };
355591bc56edSDimitry Andric 
35562cab237bSDimitry Andric } // end anonymous namespace
35572cab237bSDimitry Andric 
canGetThrough(const Instruction * Inst,Type * ConsideredExtType,const InstrToOrigTy & PromotedInsts,bool IsSExt)355891bc56edSDimitry Andric bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
355939d628a0SDimitry Andric                                         Type *ConsideredExtType,
356039d628a0SDimitry Andric                                         const InstrToOrigTy &PromotedInsts,
356139d628a0SDimitry Andric                                         bool IsSExt) {
356239d628a0SDimitry Andric   // The promotion helper does not know how to deal with vector types yet.
356339d628a0SDimitry Andric   // To be able to fix that, we would need to fix the places where we
356439d628a0SDimitry Andric   // statically extend, e.g., constants and such.
356539d628a0SDimitry Andric   if (Inst->getType()->isVectorTy())
356639d628a0SDimitry Andric     return false;
356739d628a0SDimitry Andric 
356839d628a0SDimitry Andric   // We can always get through zext.
356939d628a0SDimitry Andric   if (isa<ZExtInst>(Inst))
357039d628a0SDimitry Andric     return true;
357139d628a0SDimitry Andric 
357239d628a0SDimitry Andric   // sext(sext) is ok too.
357339d628a0SDimitry Andric   if (IsSExt && isa<SExtInst>(Inst))
357491bc56edSDimitry Andric     return true;
357591bc56edSDimitry Andric 
357691bc56edSDimitry Andric   // We can get through binary operator, if it is legal. In other words, the
357791bc56edSDimitry Andric   // binary operator must have a nuw or nsw flag.
357891bc56edSDimitry Andric   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
357991bc56edSDimitry Andric   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
358039d628a0SDimitry Andric       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
358139d628a0SDimitry Andric        (IsSExt && BinOp->hasNoSignedWrap())))
358291bc56edSDimitry Andric     return true;
358391bc56edSDimitry Andric 
35844ba319b5SDimitry Andric   // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
35854ba319b5SDimitry Andric   if ((Inst->getOpcode() == Instruction::And ||
35864ba319b5SDimitry Andric        Inst->getOpcode() == Instruction::Or))
35874ba319b5SDimitry Andric     return true;
35884ba319b5SDimitry Andric 
35894ba319b5SDimitry Andric   // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
35904ba319b5SDimitry Andric   if (Inst->getOpcode() == Instruction::Xor) {
35914ba319b5SDimitry Andric     const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
35924ba319b5SDimitry Andric     // Make sure it is not a NOT.
35934ba319b5SDimitry Andric     if (Cst && !Cst->getValue().isAllOnesValue())
35944ba319b5SDimitry Andric       return true;
35954ba319b5SDimitry Andric   }
35964ba319b5SDimitry Andric 
35974ba319b5SDimitry Andric   // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
35984ba319b5SDimitry Andric   // It may change a poisoned value into a regular value, like
35994ba319b5SDimitry Andric   //     zext i32 (shrl i8 %val, 12)  -->  shrl i32 (zext i8 %val), 12
36004ba319b5SDimitry Andric   //          poisoned value                    regular value
36014ba319b5SDimitry Andric   // It should be OK since undef covers valid value.
36024ba319b5SDimitry Andric   if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
36034ba319b5SDimitry Andric     return true;
36044ba319b5SDimitry Andric 
36054ba319b5SDimitry Andric   // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
36064ba319b5SDimitry Andric   // It may change a poisoned value into a regular value, like
36074ba319b5SDimitry Andric   //     zext i32 (shl i8 %val, 12)  -->  shl i32 (zext i8 %val), 12
36084ba319b5SDimitry Andric   //          poisoned value                    regular value
36094ba319b5SDimitry Andric   // It should be OK since undef covers valid value.
36104ba319b5SDimitry Andric   if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
36114ba319b5SDimitry Andric     const Instruction *ExtInst =
36124ba319b5SDimitry Andric         dyn_cast<const Instruction>(*Inst->user_begin());
36134ba319b5SDimitry Andric     if (ExtInst->hasOneUse()) {
36144ba319b5SDimitry Andric       const Instruction *AndInst =
36154ba319b5SDimitry Andric           dyn_cast<const Instruction>(*ExtInst->user_begin());
36164ba319b5SDimitry Andric       if (AndInst && AndInst->getOpcode() == Instruction::And) {
36174ba319b5SDimitry Andric         const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
36184ba319b5SDimitry Andric         if (Cst &&
36194ba319b5SDimitry Andric             Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
36204ba319b5SDimitry Andric           return true;
36214ba319b5SDimitry Andric       }
36224ba319b5SDimitry Andric     }
36234ba319b5SDimitry Andric   }
36244ba319b5SDimitry Andric 
362591bc56edSDimitry Andric   // Check if we can do the following simplification.
362639d628a0SDimitry Andric   // ext(trunc(opnd)) --> ext(opnd)
362791bc56edSDimitry Andric   if (!isa<TruncInst>(Inst))
362891bc56edSDimitry Andric     return false;
362991bc56edSDimitry Andric 
363091bc56edSDimitry Andric   Value *OpndVal = Inst->getOperand(0);
363139d628a0SDimitry Andric   // Check if we can use this operand in the extension.
36327d523365SDimitry Andric   // If the type is larger than the result type of the extension, we cannot.
363339d628a0SDimitry Andric   if (!OpndVal->getType()->isIntegerTy() ||
363439d628a0SDimitry Andric       OpndVal->getType()->getIntegerBitWidth() >
363539d628a0SDimitry Andric           ConsideredExtType->getIntegerBitWidth())
363691bc56edSDimitry Andric     return false;
363791bc56edSDimitry Andric 
363891bc56edSDimitry Andric   // If the operand of the truncate is not an instruction, we will not have
363991bc56edSDimitry Andric   // any information on the dropped bits.
364091bc56edSDimitry Andric   // (Actually we could for constant but it is not worth the extra logic).
364191bc56edSDimitry Andric   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
364291bc56edSDimitry Andric   if (!Opnd)
364391bc56edSDimitry Andric     return false;
364491bc56edSDimitry Andric 
364591bc56edSDimitry Andric   // Check if the source of the type is narrow enough.
364639d628a0SDimitry Andric   // I.e., check that trunc just drops extended bits of the same kind of
364739d628a0SDimitry Andric   // the extension.
364839d628a0SDimitry Andric   // #1 get the type of the operand and check the kind of the extended bits.
36494ba319b5SDimitry Andric   const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
36504ba319b5SDimitry Andric   if (OpndType)
36514ba319b5SDimitry Andric     ;
365239d628a0SDimitry Andric   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
365339d628a0SDimitry Andric     OpndType = Opnd->getOperand(0)->getType();
365491bc56edSDimitry Andric   else
365591bc56edSDimitry Andric     return false;
365691bc56edSDimitry Andric 
36577d523365SDimitry Andric   // #2 check that the truncate just drops extended bits.
36587d523365SDimitry Andric   return Inst->getType()->getIntegerBitWidth() >=
36597d523365SDimitry Andric          OpndType->getIntegerBitWidth();
366091bc56edSDimitry Andric }
366191bc56edSDimitry Andric 
getAction(Instruction * Ext,const SetOfInstrs & InsertedInsts,const TargetLowering & TLI,const InstrToOrigTy & PromotedInsts)366291bc56edSDimitry Andric TypePromotionHelper::Action TypePromotionHelper::getAction(
36638f0fd8f6SDimitry Andric     Instruction *Ext, const SetOfInstrs &InsertedInsts,
366491bc56edSDimitry Andric     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
366539d628a0SDimitry Andric   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
366639d628a0SDimitry Andric          "Unexpected instruction type");
366739d628a0SDimitry Andric   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
366839d628a0SDimitry Andric   Type *ExtTy = Ext->getType();
366939d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(Ext);
367039d628a0SDimitry Andric   // If the operand of the extension is not an instruction, we cannot
367191bc56edSDimitry Andric   // get through.
367291bc56edSDimitry Andric   // If it, check we can get through.
367339d628a0SDimitry Andric   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
367491bc56edSDimitry Andric     return nullptr;
367591bc56edSDimitry Andric 
367691bc56edSDimitry Andric   // Do not promote if the operand has been added by codegenprepare.
367791bc56edSDimitry Andric   // Otherwise, it means we are undoing an optimization that is likely to be
367891bc56edSDimitry Andric   // redone, thus causing potential infinite loop.
36798f0fd8f6SDimitry Andric   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
368091bc56edSDimitry Andric     return nullptr;
368191bc56edSDimitry Andric 
368291bc56edSDimitry Andric   // SExt or Trunc instructions.
368391bc56edSDimitry Andric   // Return the related handler.
368439d628a0SDimitry Andric   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
368539d628a0SDimitry Andric       isa<ZExtInst>(ExtOpnd))
368639d628a0SDimitry Andric     return promoteOperandForTruncAndAnyExt;
368791bc56edSDimitry Andric 
368891bc56edSDimitry Andric   // Regular instruction.
368991bc56edSDimitry Andric   // Abort early if we will have to insert non-free instructions.
369039d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
369191bc56edSDimitry Andric     return nullptr;
369239d628a0SDimitry Andric   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
369391bc56edSDimitry Andric }
369491bc56edSDimitry Andric 
promoteOperandForTruncAndAnyExt(Instruction * SExt,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInstsCost,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs,const TargetLowering & TLI)369539d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
36962cab237bSDimitry Andric     Instruction *SExt, TypePromotionTransaction &TPT,
3697ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
369839d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
3699ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
370091bc56edSDimitry Andric   // By construction, the operand of SExt is an instruction. Otherwise we cannot
370191bc56edSDimitry Andric   // get through it and this method should not be called.
370291bc56edSDimitry Andric   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
370339d628a0SDimitry Andric   Value *ExtVal = SExt;
3704ff0cc061SDimitry Andric   bool HasMergedNonFreeExt = false;
370539d628a0SDimitry Andric   if (isa<ZExtInst>(SExtOpnd)) {
370639d628a0SDimitry Andric     // Replace s|zext(zext(opnd))
370739d628a0SDimitry Andric     // => zext(opnd).
3708ff0cc061SDimitry Andric     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
370939d628a0SDimitry Andric     Value *ZExt =
371039d628a0SDimitry Andric         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
371139d628a0SDimitry Andric     TPT.replaceAllUsesWith(SExt, ZExt);
371239d628a0SDimitry Andric     TPT.eraseInstruction(SExt);
371339d628a0SDimitry Andric     ExtVal = ZExt;
371439d628a0SDimitry Andric   } else {
371539d628a0SDimitry Andric     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
371639d628a0SDimitry Andric     // => z|sext(opnd).
371791bc56edSDimitry Andric     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
371839d628a0SDimitry Andric   }
3719ff0cc061SDimitry Andric   CreatedInstsCost = 0;
372091bc56edSDimitry Andric 
372191bc56edSDimitry Andric   // Remove dead code.
372291bc56edSDimitry Andric   if (SExtOpnd->use_empty())
372391bc56edSDimitry Andric     TPT.eraseInstruction(SExtOpnd);
372491bc56edSDimitry Andric 
372539d628a0SDimitry Andric   // Check if the extension is still needed.
372639d628a0SDimitry Andric   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
372739d628a0SDimitry Andric   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3728ff0cc061SDimitry Andric     if (ExtInst) {
3729ff0cc061SDimitry Andric       if (Exts)
373039d628a0SDimitry Andric         Exts->push_back(ExtInst);
3731ff0cc061SDimitry Andric       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3732ff0cc061SDimitry Andric     }
373339d628a0SDimitry Andric     return ExtVal;
373439d628a0SDimitry Andric   }
373591bc56edSDimitry Andric 
373639d628a0SDimitry Andric   // At this point we have: ext ty opnd to ty.
373739d628a0SDimitry Andric   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
373839d628a0SDimitry Andric   Value *NextVal = ExtInst->getOperand(0);
373939d628a0SDimitry Andric   TPT.eraseInstruction(ExtInst, NextVal);
374091bc56edSDimitry Andric   return NextVal;
374191bc56edSDimitry Andric }
374291bc56edSDimitry Andric 
promoteOperandForOther(Instruction * Ext,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInstsCost,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs,const TargetLowering & TLI,bool IsSExt)374339d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForOther(
374439d628a0SDimitry Andric     Instruction *Ext, TypePromotionTransaction &TPT,
3745ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
374639d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
3747ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3748ff0cc061SDimitry Andric     bool IsSExt) {
374939d628a0SDimitry Andric   // By construction, the operand of Ext is an instruction. Otherwise we cannot
375091bc56edSDimitry Andric   // get through it and this method should not be called.
375139d628a0SDimitry Andric   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3752ff0cc061SDimitry Andric   CreatedInstsCost = 0;
375339d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse()) {
375439d628a0SDimitry Andric     // ExtOpnd will be promoted.
375539d628a0SDimitry Andric     // All its uses, but Ext, will need to use a truncated value of the
375691bc56edSDimitry Andric     // promoted version.
375791bc56edSDimitry Andric     // Create the truncate now.
375839d628a0SDimitry Andric     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
375939d628a0SDimitry Andric     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
376091bc56edSDimitry Andric       // Insert it just after the definition.
37612cab237bSDimitry Andric       ITrunc->moveAfter(ExtOpnd);
376239d628a0SDimitry Andric       if (Truncs)
376339d628a0SDimitry Andric         Truncs->push_back(ITrunc);
376439d628a0SDimitry Andric     }
376591bc56edSDimitry Andric 
376639d628a0SDimitry Andric     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
37677d523365SDimitry Andric     // Restore the operand of Ext (which has been replaced by the previous call
376891bc56edSDimitry Andric     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
376939d628a0SDimitry Andric     TPT.setOperand(Ext, 0, ExtOpnd);
377091bc56edSDimitry Andric   }
377191bc56edSDimitry Andric 
377291bc56edSDimitry Andric   // Get through the Instruction:
377391bc56edSDimitry Andric   // 1. Update its type.
377439d628a0SDimitry Andric   // 2. Replace the uses of Ext by Inst.
377539d628a0SDimitry Andric   // 3. Extend each operand that needs to be extended.
377691bc56edSDimitry Andric 
377791bc56edSDimitry Andric   // Remember the original type of the instruction before promotion.
377891bc56edSDimitry Andric   // This is useful to know that the high bits are sign extended bits.
37794ba319b5SDimitry Andric   addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
378091bc56edSDimitry Andric   // Step #1.
378139d628a0SDimitry Andric   TPT.mutateType(ExtOpnd, Ext->getType());
378291bc56edSDimitry Andric   // Step #2.
378339d628a0SDimitry Andric   TPT.replaceAllUsesWith(Ext, ExtOpnd);
378491bc56edSDimitry Andric   // Step #3.
378539d628a0SDimitry Andric   Instruction *ExtForOpnd = Ext;
378691bc56edSDimitry Andric 
37874ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
378839d628a0SDimitry Andric   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
378991bc56edSDimitry Andric        ++OpIdx) {
37904ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
379139d628a0SDimitry Andric     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
379239d628a0SDimitry Andric         !shouldExtOperand(ExtOpnd, OpIdx)) {
37934ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "No need to propagate\n");
379491bc56edSDimitry Andric       continue;
379591bc56edSDimitry Andric     }
379639d628a0SDimitry Andric     // Check if we can statically extend the operand.
379739d628a0SDimitry Andric     Value *Opnd = ExtOpnd->getOperand(OpIdx);
379891bc56edSDimitry Andric     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
37994ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Statically extend\n");
380039d628a0SDimitry Andric       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
380139d628a0SDimitry Andric       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
380239d628a0SDimitry Andric                             : Cst->getValue().zext(BitWidth);
380339d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
380491bc56edSDimitry Andric       continue;
380591bc56edSDimitry Andric     }
380691bc56edSDimitry Andric     // UndefValue are typed, so we have to statically sign extend them.
380791bc56edSDimitry Andric     if (isa<UndefValue>(Opnd)) {
38084ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Statically extend\n");
380939d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
381091bc56edSDimitry Andric       continue;
381191bc56edSDimitry Andric     }
381291bc56edSDimitry Andric 
38134ba319b5SDimitry Andric     // Otherwise we have to explicitly sign extend the operand.
381439d628a0SDimitry Andric     // Check if Ext was reused to extend an operand.
381539d628a0SDimitry Andric     if (!ExtForOpnd) {
381691bc56edSDimitry Andric       // If yes, create a new one.
38174ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "More operands to ext\n");
381839d628a0SDimitry Andric       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
381939d628a0SDimitry Andric         : TPT.createZExt(Ext, Opnd, Ext->getType());
382039d628a0SDimitry Andric       if (!isa<Instruction>(ValForExtOpnd)) {
382139d628a0SDimitry Andric         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
382239d628a0SDimitry Andric         continue;
382339d628a0SDimitry Andric       }
382439d628a0SDimitry Andric       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
382591bc56edSDimitry Andric     }
382639d628a0SDimitry Andric     if (Exts)
382739d628a0SDimitry Andric       Exts->push_back(ExtForOpnd);
382839d628a0SDimitry Andric     TPT.setOperand(ExtForOpnd, 0, Opnd);
382991bc56edSDimitry Andric 
383091bc56edSDimitry Andric     // Move the sign extension before the insertion point.
383139d628a0SDimitry Andric     TPT.moveBefore(ExtForOpnd, ExtOpnd);
383239d628a0SDimitry Andric     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3833ff0cc061SDimitry Andric     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
383491bc56edSDimitry Andric     // If more sext are required, new instructions will have to be created.
383539d628a0SDimitry Andric     ExtForOpnd = nullptr;
383691bc56edSDimitry Andric   }
383739d628a0SDimitry Andric   if (ExtForOpnd == Ext) {
38384ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Extension is useless now\n");
383939d628a0SDimitry Andric     TPT.eraseInstruction(Ext);
384091bc56edSDimitry Andric   }
384139d628a0SDimitry Andric   return ExtOpnd;
384291bc56edSDimitry Andric }
384391bc56edSDimitry Andric 
38447d523365SDimitry Andric /// Check whether or not promoting an instruction to a wider type is profitable.
3845ff0cc061SDimitry Andric /// \p NewCost gives the cost of extension instructions created by the
3846ff0cc061SDimitry Andric /// promotion.
3847ff0cc061SDimitry Andric /// \p OldCost gives the cost of extension instructions before the promotion
3848ff0cc061SDimitry Andric /// plus the number of instructions that have been
3849ff0cc061SDimitry Andric /// matched in the addressing mode the promotion.
385091bc56edSDimitry Andric /// \p PromotedOperand is the value that has been promoted.
385191bc56edSDimitry Andric /// \return True if the promotion is profitable, false otherwise.
isPromotionProfitable(unsigned NewCost,unsigned OldCost,Value * PromotedOperand) const38527d523365SDimitry Andric bool AddressingModeMatcher::isPromotionProfitable(
3853ff0cc061SDimitry Andric     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
38544ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
38554ba319b5SDimitry Andric                     << '\n');
3856ff0cc061SDimitry Andric   // The cost of the new extensions is greater than the cost of the
3857ff0cc061SDimitry Andric   // old extension plus what we folded.
385891bc56edSDimitry Andric   // This is not profitable.
3859ff0cc061SDimitry Andric   if (NewCost > OldCost)
386091bc56edSDimitry Andric     return false;
3861ff0cc061SDimitry Andric   if (NewCost < OldCost)
386291bc56edSDimitry Andric     return true;
386391bc56edSDimitry Andric   // The promotion is neutral but it may help folding the sign extension in
386491bc56edSDimitry Andric   // loads for instance.
386591bc56edSDimitry Andric   // Check that we did not create an illegal instruction.
3866875ed548SDimitry Andric   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
386791bc56edSDimitry Andric }
386891bc56edSDimitry Andric 
38697d523365SDimitry Andric /// Given an instruction or constant expr, see if we can fold the operation
38707d523365SDimitry Andric /// into the addressing mode. If so, update the addressing mode and return
38717d523365SDimitry Andric /// true, otherwise return false without modifying AddrMode.
387291bc56edSDimitry Andric /// If \p MovedAway is not NULL, it contains the information of whether or
387391bc56edSDimitry Andric /// not AddrInst has to be folded into the addressing mode on success.
387491bc56edSDimitry Andric /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
387591bc56edSDimitry Andric /// because it has been moved away.
387691bc56edSDimitry Andric /// Thus AddrInst must not be added in the matched instructions.
387791bc56edSDimitry Andric /// This state can happen when AddrInst is a sext, since it may be moved away.
387891bc56edSDimitry Andric /// Therefore, AddrInst may not be valid when MovedAway is true and it must
387991bc56edSDimitry Andric /// not be referenced anymore.
matchOperationAddr(User * AddrInst,unsigned Opcode,unsigned Depth,bool * MovedAway)38807d523365SDimitry Andric bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
388191bc56edSDimitry Andric                                                unsigned Depth,
388291bc56edSDimitry Andric                                                bool *MovedAway) {
388391bc56edSDimitry Andric   // Avoid exponential behavior on extremely deep expression trees.
388491bc56edSDimitry Andric   if (Depth >= 5) return false;
388591bc56edSDimitry Andric 
388691bc56edSDimitry Andric   // By default, all matched instructions stay in place.
388791bc56edSDimitry Andric   if (MovedAway)
388891bc56edSDimitry Andric     *MovedAway = false;
388991bc56edSDimitry Andric 
389091bc56edSDimitry Andric   switch (Opcode) {
389191bc56edSDimitry Andric   case Instruction::PtrToInt:
389291bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
38937d523365SDimitry Andric     return matchAddr(AddrInst->getOperand(0), Depth);
3894875ed548SDimitry Andric   case Instruction::IntToPtr: {
3895875ed548SDimitry Andric     auto AS = AddrInst->getType()->getPointerAddressSpace();
3896875ed548SDimitry Andric     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
389791bc56edSDimitry Andric     // This inttoptr is a no-op if the integer type is pointer sized.
3898875ed548SDimitry Andric     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
38997d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
390091bc56edSDimitry Andric     return false;
3901875ed548SDimitry Andric   }
390291bc56edSDimitry Andric   case Instruction::BitCast:
390391bc56edSDimitry Andric     // BitCast is always a noop, and we can handle it as long as it is
390491bc56edSDimitry Andric     // int->int or pointer->pointer (we don't want int<->fp or something).
39054ba319b5SDimitry Andric     if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
390691bc56edSDimitry Andric         // Don't touch identity bitcasts.  These were probably put here by LSR,
390791bc56edSDimitry Andric         // and we don't want to mess around with them.  Assume it knows what it
390891bc56edSDimitry Andric         // is doing.
390991bc56edSDimitry Andric         AddrInst->getOperand(0)->getType() != AddrInst->getType())
39107d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
391191bc56edSDimitry Andric     return false;
3912ff0cc061SDimitry Andric   case Instruction::AddrSpaceCast: {
3913ff0cc061SDimitry Andric     unsigned SrcAS
3914ff0cc061SDimitry Andric       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3915ff0cc061SDimitry Andric     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3916ff0cc061SDimitry Andric     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
39177d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
3918ff0cc061SDimitry Andric     return false;
3919ff0cc061SDimitry Andric   }
392091bc56edSDimitry Andric   case Instruction::Add: {
392191bc56edSDimitry Andric     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
392291bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
392391bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
392491bc56edSDimitry Andric     // Start a transaction at this point.
392591bc56edSDimitry Andric     // The LHS may match but not the RHS.
392691bc56edSDimitry Andric     // Therefore, we need a higher level restoration point to undo partially
392791bc56edSDimitry Andric     // matched operation.
392891bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
392991bc56edSDimitry Andric         TPT.getRestorationPoint();
393091bc56edSDimitry Andric 
39317d523365SDimitry Andric     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
39327d523365SDimitry Andric         matchAddr(AddrInst->getOperand(0), Depth+1))
393391bc56edSDimitry Andric       return true;
393491bc56edSDimitry Andric 
393591bc56edSDimitry Andric     // Restore the old addr mode info.
393691bc56edSDimitry Andric     AddrMode = BackupAddrMode;
393791bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
393891bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
393991bc56edSDimitry Andric 
394091bc56edSDimitry Andric     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
39417d523365SDimitry Andric     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
39427d523365SDimitry Andric         matchAddr(AddrInst->getOperand(1), Depth+1))
394391bc56edSDimitry Andric       return true;
394491bc56edSDimitry Andric 
394591bc56edSDimitry Andric     // Otherwise we definitely can't merge the ADD in.
394691bc56edSDimitry Andric     AddrMode = BackupAddrMode;
394791bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
394891bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
394991bc56edSDimitry Andric     break;
395091bc56edSDimitry Andric   }
395191bc56edSDimitry Andric   //case Instruction::Or:
395291bc56edSDimitry Andric   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
395391bc56edSDimitry Andric   //break;
395491bc56edSDimitry Andric   case Instruction::Mul:
395591bc56edSDimitry Andric   case Instruction::Shl: {
395691bc56edSDimitry Andric     // Can only handle X*C and X << C.
395791bc56edSDimitry Andric     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
39582cab237bSDimitry Andric     if (!RHS || RHS->getBitWidth() > 64)
395991bc56edSDimitry Andric       return false;
396091bc56edSDimitry Andric     int64_t Scale = RHS->getSExtValue();
396191bc56edSDimitry Andric     if (Opcode == Instruction::Shl)
396291bc56edSDimitry Andric       Scale = 1LL << Scale;
396391bc56edSDimitry Andric 
39647d523365SDimitry Andric     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
396591bc56edSDimitry Andric   }
396691bc56edSDimitry Andric   case Instruction::GetElementPtr: {
396791bc56edSDimitry Andric     // Scan the GEP.  We check it if it contains constant offsets and at most
396891bc56edSDimitry Andric     // one variable offset.
396991bc56edSDimitry Andric     int VariableOperand = -1;
397091bc56edSDimitry Andric     unsigned VariableScale = 0;
397191bc56edSDimitry Andric 
397291bc56edSDimitry Andric     int64_t ConstantOffset = 0;
397391bc56edSDimitry Andric     gep_type_iterator GTI = gep_type_begin(AddrInst);
397491bc56edSDimitry Andric     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3975d88c1a5aSDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
3976875ed548SDimitry Andric         const StructLayout *SL = DL.getStructLayout(STy);
397791bc56edSDimitry Andric         unsigned Idx =
397891bc56edSDimitry Andric           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
397991bc56edSDimitry Andric         ConstantOffset += SL->getElementOffset(Idx);
398091bc56edSDimitry Andric       } else {
3981875ed548SDimitry Andric         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
398291bc56edSDimitry Andric         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3983*b5893f02SDimitry Andric           const APInt &CVal = CI->getValue();
3984*b5893f02SDimitry Andric           if (CVal.getMinSignedBits() <= 64) {
3985*b5893f02SDimitry Andric             ConstantOffset += CVal.getSExtValue() * TypeSize;
3986*b5893f02SDimitry Andric             continue;
3987*b5893f02SDimitry Andric           }
3988*b5893f02SDimitry Andric         }
3989*b5893f02SDimitry Andric         if (TypeSize) {  // Scales of zero don't do anything.
399091bc56edSDimitry Andric           // We only allow one variable index at the moment.
399191bc56edSDimitry Andric           if (VariableOperand != -1)
399291bc56edSDimitry Andric             return false;
399391bc56edSDimitry Andric 
399491bc56edSDimitry Andric           // Remember the variable index.
399591bc56edSDimitry Andric           VariableOperand = i;
399691bc56edSDimitry Andric           VariableScale = TypeSize;
399791bc56edSDimitry Andric         }
399891bc56edSDimitry Andric       }
399991bc56edSDimitry Andric     }
400091bc56edSDimitry Andric 
400191bc56edSDimitry Andric     // A common case is for the GEP to only do a constant offset.  In this case,
400291bc56edSDimitry Andric     // just add it to the disp field and check validity.
400391bc56edSDimitry Andric     if (VariableOperand == -1) {
400491bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
400597bc6c73SDimitry Andric       if (ConstantOffset == 0 ||
4006875ed548SDimitry Andric           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
400791bc56edSDimitry Andric         // Check to see if we can fold the base pointer in too.
40087d523365SDimitry Andric         if (matchAddr(AddrInst->getOperand(0), Depth+1))
400991bc56edSDimitry Andric           return true;
40104ba319b5SDimitry Andric       } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
40114ba319b5SDimitry Andric                  TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
40124ba319b5SDimitry Andric                  ConstantOffset > 0) {
40134ba319b5SDimitry Andric         // Record GEPs with non-zero offsets as candidates for splitting in the
40144ba319b5SDimitry Andric         // event that the offset cannot fit into the r+i addressing mode.
40154ba319b5SDimitry Andric         // Simple and common case that only one GEP is used in calculating the
40164ba319b5SDimitry Andric         // address for the memory access.
40174ba319b5SDimitry Andric         Value *Base = AddrInst->getOperand(0);
40184ba319b5SDimitry Andric         auto *BaseI = dyn_cast<Instruction>(Base);
40194ba319b5SDimitry Andric         auto *GEP = cast<GetElementPtrInst>(AddrInst);
40204ba319b5SDimitry Andric         if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
40214ba319b5SDimitry Andric             (BaseI && !isa<CastInst>(BaseI) &&
40224ba319b5SDimitry Andric              !isa<GetElementPtrInst>(BaseI))) {
40234ba319b5SDimitry Andric           // If the base is an instruction, make sure the GEP is not in the same
40244ba319b5SDimitry Andric           // basic block as the base. If the base is an argument or global
40254ba319b5SDimitry Andric           // value, make sure the GEP is not in the entry block.  Otherwise,
40264ba319b5SDimitry Andric           // instruction selection can undo the split.  Also make sure the
40274ba319b5SDimitry Andric           // parent block allows inserting non-PHI instructions before the
40284ba319b5SDimitry Andric           // terminator.
40294ba319b5SDimitry Andric           BasicBlock *Parent =
40304ba319b5SDimitry Andric               BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
40314ba319b5SDimitry Andric           if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
40324ba319b5SDimitry Andric             LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
40334ba319b5SDimitry Andric         }
403491bc56edSDimitry Andric       }
403591bc56edSDimitry Andric       AddrMode.BaseOffs -= ConstantOffset;
403691bc56edSDimitry Andric       return false;
403791bc56edSDimitry Andric     }
403891bc56edSDimitry Andric 
403991bc56edSDimitry Andric     // Save the valid addressing mode in case we can't match.
404091bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
404191bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
404291bc56edSDimitry Andric 
404391bc56edSDimitry Andric     // See if the scale and offset amount is valid for this target.
404491bc56edSDimitry Andric     AddrMode.BaseOffs += ConstantOffset;
404591bc56edSDimitry Andric 
404691bc56edSDimitry Andric     // Match the base operand of the GEP.
40477d523365SDimitry Andric     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
404891bc56edSDimitry Andric       // If it couldn't be matched, just stuff the value in a register.
404991bc56edSDimitry Andric       if (AddrMode.HasBaseReg) {
405091bc56edSDimitry Andric         AddrMode = BackupAddrMode;
405191bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
405291bc56edSDimitry Andric         return false;
405391bc56edSDimitry Andric       }
405491bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
405591bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
405691bc56edSDimitry Andric     }
405791bc56edSDimitry Andric 
405891bc56edSDimitry Andric     // Match the remaining variable portion of the GEP.
40597d523365SDimitry Andric     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
406091bc56edSDimitry Andric                           Depth)) {
406191bc56edSDimitry Andric       // If it couldn't be matched, try stuffing the base into a register
406291bc56edSDimitry Andric       // instead of matching it, and retrying the match of the scale.
406391bc56edSDimitry Andric       AddrMode = BackupAddrMode;
406491bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
406591bc56edSDimitry Andric       if (AddrMode.HasBaseReg)
406691bc56edSDimitry Andric         return false;
406791bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
406891bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
406991bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
40707d523365SDimitry Andric       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
407191bc56edSDimitry Andric                             VariableScale, Depth)) {
407291bc56edSDimitry Andric         // If even that didn't work, bail.
407391bc56edSDimitry Andric         AddrMode = BackupAddrMode;
407491bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
407591bc56edSDimitry Andric         return false;
407691bc56edSDimitry Andric       }
407791bc56edSDimitry Andric     }
407891bc56edSDimitry Andric 
407991bc56edSDimitry Andric     return true;
408091bc56edSDimitry Andric   }
408139d628a0SDimitry Andric   case Instruction::SExt:
408239d628a0SDimitry Andric   case Instruction::ZExt: {
408339d628a0SDimitry Andric     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
408439d628a0SDimitry Andric     if (!Ext)
408591bc56edSDimitry Andric       return false;
408691bc56edSDimitry Andric 
408739d628a0SDimitry Andric     // Try to move this ext out of the way of the addressing mode.
408891bc56edSDimitry Andric     // Ask for a method for doing so.
408939d628a0SDimitry Andric     TypePromotionHelper::Action TPH =
40908f0fd8f6SDimitry Andric         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
409191bc56edSDimitry Andric     if (!TPH)
409291bc56edSDimitry Andric       return false;
409391bc56edSDimitry Andric 
409491bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
409591bc56edSDimitry Andric         TPT.getRestorationPoint();
4096ff0cc061SDimitry Andric     unsigned CreatedInstsCost = 0;
4097ff0cc061SDimitry Andric     unsigned ExtCost = !TLI.isExtFree(Ext);
409839d628a0SDimitry Andric     Value *PromotedOperand =
4099ff0cc061SDimitry Andric         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
410091bc56edSDimitry Andric     // SExt has been moved away.
410191bc56edSDimitry Andric     // Thus either it will be rematched later in the recursive calls or it is
410291bc56edSDimitry Andric     // gone. Anyway, we must not fold it into the addressing mode at this point.
410391bc56edSDimitry Andric     // E.g.,
410491bc56edSDimitry Andric     // op = add opnd, 1
410539d628a0SDimitry Andric     // idx = ext op
410691bc56edSDimitry Andric     // addr = gep base, idx
410791bc56edSDimitry Andric     // is now:
410839d628a0SDimitry Andric     // promotedOpnd = ext opnd            <- no match here
410991bc56edSDimitry Andric     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
411091bc56edSDimitry Andric     // addr = gep base, op                <- match
411191bc56edSDimitry Andric     if (MovedAway)
411291bc56edSDimitry Andric       *MovedAway = true;
411391bc56edSDimitry Andric 
411491bc56edSDimitry Andric     assert(PromotedOperand &&
411591bc56edSDimitry Andric            "TypePromotionHelper should have filtered out those cases");
411691bc56edSDimitry Andric 
411791bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
411891bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
411991bc56edSDimitry Andric 
41207d523365SDimitry Andric     if (!matchAddr(PromotedOperand, Depth) ||
41217d523365SDimitry Andric         // The total of the new cost is equal to the cost of the created
4122ff0cc061SDimitry Andric         // instructions.
41237d523365SDimitry Andric         // The total of the old cost is equal to the cost of the extension plus
4124ff0cc061SDimitry Andric         // what we have saved in the addressing mode.
41257d523365SDimitry Andric         !isPromotionProfitable(CreatedInstsCost,
4126ff0cc061SDimitry Andric                                ExtCost + (AddrModeInsts.size() - OldSize),
412791bc56edSDimitry Andric                                PromotedOperand)) {
412891bc56edSDimitry Andric       AddrMode = BackupAddrMode;
412991bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
41304ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
413191bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
413291bc56edSDimitry Andric       return false;
413391bc56edSDimitry Andric     }
413491bc56edSDimitry Andric     return true;
413591bc56edSDimitry Andric   }
413691bc56edSDimitry Andric   }
413791bc56edSDimitry Andric   return false;
413891bc56edSDimitry Andric }
413991bc56edSDimitry Andric 
41407d523365SDimitry Andric /// If we can, try to add the value of 'Addr' into the current addressing mode.
41417d523365SDimitry Andric /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
41427d523365SDimitry Andric /// unmodified. This assumes that Addr is either a pointer type or intptr_t
41437d523365SDimitry Andric /// for the target.
414491bc56edSDimitry Andric ///
matchAddr(Value * Addr,unsigned Depth)41457d523365SDimitry Andric bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
414691bc56edSDimitry Andric   // Start a transaction at this point that we will rollback if the matching
414791bc56edSDimitry Andric   // fails.
414891bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
414991bc56edSDimitry Andric       TPT.getRestorationPoint();
415091bc56edSDimitry Andric   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
415191bc56edSDimitry Andric     // Fold in immediates if legal for the target.
415291bc56edSDimitry Andric     AddrMode.BaseOffs += CI->getSExtValue();
4153875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
415491bc56edSDimitry Andric       return true;
415591bc56edSDimitry Andric     AddrMode.BaseOffs -= CI->getSExtValue();
415691bc56edSDimitry Andric   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
415791bc56edSDimitry Andric     // If this is a global variable, try to fold it into the addressing mode.
415891bc56edSDimitry Andric     if (!AddrMode.BaseGV) {
415991bc56edSDimitry Andric       AddrMode.BaseGV = GV;
4160875ed548SDimitry Andric       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
416191bc56edSDimitry Andric         return true;
416291bc56edSDimitry Andric       AddrMode.BaseGV = nullptr;
416391bc56edSDimitry Andric     }
416491bc56edSDimitry Andric   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
416591bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
416691bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
416791bc56edSDimitry Andric 
416891bc56edSDimitry Andric     // Check to see if it is possible to fold this operation.
416991bc56edSDimitry Andric     bool MovedAway = false;
41707d523365SDimitry Andric     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
41717d523365SDimitry Andric       // This instruction may have been moved away. If so, there is nothing
417291bc56edSDimitry Andric       // to check here.
417391bc56edSDimitry Andric       if (MovedAway)
417491bc56edSDimitry Andric         return true;
417591bc56edSDimitry Andric       // Okay, it's possible to fold this.  Check to see if it is actually
417691bc56edSDimitry Andric       // *profitable* to do so.  We use a simple cost model to avoid increasing
417791bc56edSDimitry Andric       // register pressure too much.
417891bc56edSDimitry Andric       if (I->hasOneUse() ||
41797d523365SDimitry Andric           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
418091bc56edSDimitry Andric         AddrModeInsts.push_back(I);
418191bc56edSDimitry Andric         return true;
418291bc56edSDimitry Andric       }
418391bc56edSDimitry Andric 
418491bc56edSDimitry Andric       // It isn't profitable to do this, roll back.
418591bc56edSDimitry Andric       //cerr << "NOT FOLDING: " << *I;
418691bc56edSDimitry Andric       AddrMode = BackupAddrMode;
418791bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
418891bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
418991bc56edSDimitry Andric     }
419091bc56edSDimitry Andric   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
41917d523365SDimitry Andric     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
419291bc56edSDimitry Andric       return true;
419391bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
419491bc56edSDimitry Andric   } else if (isa<ConstantPointerNull>(Addr)) {
419591bc56edSDimitry Andric     // Null pointer gets folded without affecting the addressing mode.
419691bc56edSDimitry Andric     return true;
419791bc56edSDimitry Andric   }
419891bc56edSDimitry Andric 
419991bc56edSDimitry Andric   // Worse case, the target should support [reg] addressing modes. :)
420091bc56edSDimitry Andric   if (!AddrMode.HasBaseReg) {
420191bc56edSDimitry Andric     AddrMode.HasBaseReg = true;
420291bc56edSDimitry Andric     AddrMode.BaseReg = Addr;
420391bc56edSDimitry Andric     // Still check for legality in case the target supports [imm] but not [i+r].
4204875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
420591bc56edSDimitry Andric       return true;
420691bc56edSDimitry Andric     AddrMode.HasBaseReg = false;
420791bc56edSDimitry Andric     AddrMode.BaseReg = nullptr;
420891bc56edSDimitry Andric   }
420991bc56edSDimitry Andric 
421091bc56edSDimitry Andric   // If the base register is already taken, see if we can do [r+r].
421191bc56edSDimitry Andric   if (AddrMode.Scale == 0) {
421291bc56edSDimitry Andric     AddrMode.Scale = 1;
421391bc56edSDimitry Andric     AddrMode.ScaledReg = Addr;
4214875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
421591bc56edSDimitry Andric       return true;
421691bc56edSDimitry Andric     AddrMode.Scale = 0;
421791bc56edSDimitry Andric     AddrMode.ScaledReg = nullptr;
421891bc56edSDimitry Andric   }
421991bc56edSDimitry Andric   // Couldn't match.
422091bc56edSDimitry Andric   TPT.rollback(LastKnownGood);
422191bc56edSDimitry Andric   return false;
422291bc56edSDimitry Andric }
422391bc56edSDimitry Andric 
42247d523365SDimitry Andric /// Check to see if all uses of OpVal by the specified inline asm call are due
42257d523365SDimitry Andric /// to memory operands. If so, return true, otherwise return false.
IsOperandAMemoryOperand(CallInst * CI,InlineAsm * IA,Value * OpVal,const TargetLowering & TLI,const TargetRegisterInfo & TRI)422691bc56edSDimitry Andric static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
42277a7e6055SDimitry Andric                                     const TargetLowering &TLI,
42287a7e6055SDimitry Andric                                     const TargetRegisterInfo &TRI) {
4229db17bf38SDimitry Andric   const Function *F = CI->getFunction();
4230ff0cc061SDimitry Andric   TargetLowering::AsmOperandInfoVector TargetConstraints =
42317a7e6055SDimitry Andric       TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
4232875ed548SDimitry Andric                             ImmutableCallSite(CI));
42337a7e6055SDimitry Andric 
423491bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
423591bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
423691bc56edSDimitry Andric 
423791bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
42387a7e6055SDimitry Andric     TLI.ComputeConstraintToUse(OpInfo, SDValue());
423991bc56edSDimitry Andric 
424091bc56edSDimitry Andric     // If this asm operand is our Value*, and if it isn't an indirect memory
424191bc56edSDimitry Andric     // operand, we can't fold it!
424291bc56edSDimitry Andric     if (OpInfo.CallOperandVal == OpVal &&
424391bc56edSDimitry Andric         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
424491bc56edSDimitry Andric          !OpInfo.isIndirect))
424591bc56edSDimitry Andric       return false;
424691bc56edSDimitry Andric   }
424791bc56edSDimitry Andric 
424891bc56edSDimitry Andric   return true;
424991bc56edSDimitry Andric }
425091bc56edSDimitry Andric 
42514dfab2ebSDimitry Andric // Max number of memory uses to look at before aborting the search to conserve
42524dfab2ebSDimitry Andric // compile time.
42534dfab2ebSDimitry Andric static constexpr int MaxMemoryUsesToScan = 20;
42544dfab2ebSDimitry Andric 
42557d523365SDimitry Andric /// Recursively walk all the uses of I until we find a memory use.
42567d523365SDimitry Andric /// If we find an obviously non-foldable instruction, return true.
425791bc56edSDimitry Andric /// Add the ultimately found memory instructions to MemoryUses.
FindAllMemoryUses(Instruction * I,SmallVectorImpl<std::pair<Instruction *,unsigned>> & MemoryUses,SmallPtrSetImpl<Instruction * > & ConsideredInsts,const TargetLowering & TLI,const TargetRegisterInfo & TRI,int SeenInsts=0)4258ff0cc061SDimitry Andric static bool FindAllMemoryUses(
4259ff0cc061SDimitry Andric     Instruction *I,
426091bc56edSDimitry Andric     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
42614dfab2ebSDimitry Andric     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
42624dfab2ebSDimitry Andric     const TargetRegisterInfo &TRI, int SeenInsts = 0) {
426391bc56edSDimitry Andric   // If we already considered this instruction, we're done.
426439d628a0SDimitry Andric   if (!ConsideredInsts.insert(I).second)
426591bc56edSDimitry Andric     return false;
426691bc56edSDimitry Andric 
426791bc56edSDimitry Andric   // If this is an obviously unfoldable instruction, bail out.
426891bc56edSDimitry Andric   if (!MightBeFoldableInst(I))
426991bc56edSDimitry Andric     return true;
427091bc56edSDimitry Andric 
42713ca95b02SDimitry Andric   const bool OptSize = I->getFunction()->optForSize();
42723ca95b02SDimitry Andric 
427391bc56edSDimitry Andric   // Loop over all the uses, recursively processing them.
427491bc56edSDimitry Andric   for (Use &U : I->uses()) {
42754dfab2ebSDimitry Andric     // Conservatively return true if we're seeing a large number or a deep chain
42764dfab2ebSDimitry Andric     // of users. This avoids excessive compilation times in pathological cases.
42774dfab2ebSDimitry Andric     if (SeenInsts++ >= MaxMemoryUsesToScan)
42784dfab2ebSDimitry Andric       return true;
427991bc56edSDimitry Andric 
42804dfab2ebSDimitry Andric     Instruction *UserI = cast<Instruction>(U.getUser());
428191bc56edSDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
428291bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
428391bc56edSDimitry Andric       continue;
428491bc56edSDimitry Andric     }
428591bc56edSDimitry Andric 
428691bc56edSDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
428791bc56edSDimitry Andric       unsigned opNo = U.getOperandNo();
42887a7e6055SDimitry Andric       if (opNo != StoreInst::getPointerOperandIndex())
42897a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
429091bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(SI, opNo));
429191bc56edSDimitry Andric       continue;
429291bc56edSDimitry Andric     }
429391bc56edSDimitry Andric 
42947a7e6055SDimitry Andric     if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
42957a7e6055SDimitry Andric       unsigned opNo = U.getOperandNo();
42967a7e6055SDimitry Andric       if (opNo != AtomicRMWInst::getPointerOperandIndex())
42977a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
42987a7e6055SDimitry Andric       MemoryUses.push_back(std::make_pair(RMW, opNo));
42997a7e6055SDimitry Andric       continue;
43007a7e6055SDimitry Andric     }
43017a7e6055SDimitry Andric 
43027a7e6055SDimitry Andric     if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
43037a7e6055SDimitry Andric       unsigned opNo = U.getOperandNo();
43047a7e6055SDimitry Andric       if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
43057a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
43067a7e6055SDimitry Andric       MemoryUses.push_back(std::make_pair(CmpX, opNo));
43077a7e6055SDimitry Andric       continue;
43087a7e6055SDimitry Andric     }
43097a7e6055SDimitry Andric 
431091bc56edSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
43113ca95b02SDimitry Andric       // If this is a cold call, we can sink the addressing calculation into
43123ca95b02SDimitry Andric       // the cold path.  See optimizeCallInst
43133ca95b02SDimitry Andric       if (!OptSize && CI->hasFnAttr(Attribute::Cold))
43143ca95b02SDimitry Andric         continue;
43153ca95b02SDimitry Andric 
431691bc56edSDimitry Andric       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
431791bc56edSDimitry Andric       if (!IA) return true;
431891bc56edSDimitry Andric 
431991bc56edSDimitry Andric       // If this is a memory operand, we're cool, otherwise bail out.
43207a7e6055SDimitry Andric       if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
432191bc56edSDimitry Andric         return true;
432291bc56edSDimitry Andric       continue;
432391bc56edSDimitry Andric     }
432491bc56edSDimitry Andric 
43254dfab2ebSDimitry Andric     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
43264dfab2ebSDimitry Andric                           SeenInsts))
432791bc56edSDimitry Andric       return true;
432891bc56edSDimitry Andric   }
432991bc56edSDimitry Andric 
433091bc56edSDimitry Andric   return false;
433191bc56edSDimitry Andric }
433291bc56edSDimitry Andric 
43337d523365SDimitry Andric /// Return true if Val is already known to be live at the use site that we're
43347d523365SDimitry Andric /// folding it into. If so, there is no cost to include it in the addressing
43357d523365SDimitry Andric /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
43367d523365SDimitry Andric /// instruction already.
valueAlreadyLiveAtInst(Value * Val,Value * KnownLive1,Value * KnownLive2)43377d523365SDimitry Andric bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
433891bc56edSDimitry Andric                                                    Value *KnownLive2) {
433991bc56edSDimitry Andric   // If Val is either of the known-live values, we know it is live!
434091bc56edSDimitry Andric   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
434191bc56edSDimitry Andric     return true;
434291bc56edSDimitry Andric 
434391bc56edSDimitry Andric   // All values other than instructions and arguments (e.g. constants) are live.
434491bc56edSDimitry Andric   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
434591bc56edSDimitry Andric 
434691bc56edSDimitry Andric   // If Val is a constant sized alloca in the entry block, it is live, this is
434791bc56edSDimitry Andric   // true because it is just a reference to the stack/frame pointer, which is
434891bc56edSDimitry Andric   // live for the whole function.
434991bc56edSDimitry Andric   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
435091bc56edSDimitry Andric     if (AI->isStaticAlloca())
435191bc56edSDimitry Andric       return true;
435291bc56edSDimitry Andric 
435391bc56edSDimitry Andric   // Check to see if this value is already used in the memory instruction's
435491bc56edSDimitry Andric   // block.  If so, it's already live into the block at the very least, so we
435591bc56edSDimitry Andric   // can reasonably fold it.
435691bc56edSDimitry Andric   return Val->isUsedInBasicBlock(MemoryInst->getParent());
435791bc56edSDimitry Andric }
435891bc56edSDimitry Andric 
43597d523365SDimitry Andric /// It is possible for the addressing mode of the machine to fold the specified
43607d523365SDimitry Andric /// instruction into a load or store that ultimately uses it.
43617d523365SDimitry Andric /// However, the specified instruction has multiple uses.
43627d523365SDimitry Andric /// Given this, it may actually increase register pressure to fold it
436391bc56edSDimitry Andric /// into the load. For example, consider this code:
436491bc56edSDimitry Andric ///
436591bc56edSDimitry Andric ///     X = ...
436691bc56edSDimitry Andric ///     Y = X+1
436791bc56edSDimitry Andric ///     use(Y)   -> nonload/store
436891bc56edSDimitry Andric ///     Z = Y+1
436991bc56edSDimitry Andric ///     load Z
437091bc56edSDimitry Andric ///
437191bc56edSDimitry Andric /// In this case, Y has multiple uses, and can be folded into the load of Z
437291bc56edSDimitry Andric /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
437391bc56edSDimitry Andric /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
437491bc56edSDimitry Andric /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
437591bc56edSDimitry Andric /// number of computations either.
437691bc56edSDimitry Andric ///
437791bc56edSDimitry Andric /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
437891bc56edSDimitry Andric /// X was live across 'load Z' for other reasons, we actually *would* want to
437991bc56edSDimitry Andric /// fold the addressing mode in the Z case.  This would make Y die earlier.
438091bc56edSDimitry Andric bool AddressingModeMatcher::
isProfitableToFoldIntoAddressingMode(Instruction * I,ExtAddrMode & AMBefore,ExtAddrMode & AMAfter)43817d523365SDimitry Andric isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
438291bc56edSDimitry Andric                                      ExtAddrMode &AMAfter) {
438391bc56edSDimitry Andric   if (IgnoreProfitability) return true;
438491bc56edSDimitry Andric 
438591bc56edSDimitry Andric   // AMBefore is the addressing mode before this instruction was folded into it,
438691bc56edSDimitry Andric   // and AMAfter is the addressing mode after the instruction was folded.  Get
438791bc56edSDimitry Andric   // the set of registers referenced by AMAfter and subtract out those
438891bc56edSDimitry Andric   // referenced by AMBefore: this is the set of values which folding in this
438991bc56edSDimitry Andric   // address extends the lifetime of.
439091bc56edSDimitry Andric   //
439191bc56edSDimitry Andric   // Note that there are only two potential values being referenced here,
439291bc56edSDimitry Andric   // BaseReg and ScaleReg (global addresses are always available, as are any
439391bc56edSDimitry Andric   // folded immediates).
439491bc56edSDimitry Andric   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
439591bc56edSDimitry Andric 
439691bc56edSDimitry Andric   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
439791bc56edSDimitry Andric   // lifetime wasn't extended by adding this instruction.
43987d523365SDimitry Andric   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
439991bc56edSDimitry Andric     BaseReg = nullptr;
44007d523365SDimitry Andric   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
440191bc56edSDimitry Andric     ScaledReg = nullptr;
440291bc56edSDimitry Andric 
440391bc56edSDimitry Andric   // If folding this instruction (and it's subexprs) didn't extend any live
440491bc56edSDimitry Andric   // ranges, we're ok with it.
440591bc56edSDimitry Andric   if (!BaseReg && !ScaledReg)
440691bc56edSDimitry Andric     return true;
440791bc56edSDimitry Andric 
44083ca95b02SDimitry Andric   // If all uses of this instruction can have the address mode sunk into them,
44093ca95b02SDimitry Andric   // we can remove the addressing mode and effectively trade one live register
44103ca95b02SDimitry Andric   // for another (at worst.)  In this context, folding an addressing mode into
44113ca95b02SDimitry Andric   // the use is just a particularly nice way of sinking it.
441291bc56edSDimitry Andric   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
441391bc56edSDimitry Andric   SmallPtrSet<Instruction*, 16> ConsideredInsts;
44147a7e6055SDimitry Andric   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
441591bc56edSDimitry Andric     return false;  // Has a non-memory, non-foldable use!
441691bc56edSDimitry Andric 
441791bc56edSDimitry Andric   // Now that we know that all uses of this instruction are part of a chain of
441891bc56edSDimitry Andric   // computation involving only operations that could theoretically be folded
44193ca95b02SDimitry Andric   // into a memory use, loop over each of these memory operation uses and see
44203ca95b02SDimitry Andric   // if they could  *actually* fold the instruction.  The assumption is that
44213ca95b02SDimitry Andric   // addressing modes are cheap and that duplicating the computation involved
44223ca95b02SDimitry Andric   // many times is worthwhile, even on a fastpath. For sinking candidates
44233ca95b02SDimitry Andric   // (i.e. cold call sites), this serves as a way to prevent excessive code
44243ca95b02SDimitry Andric   // growth since most architectures have some reasonable small and fast way to
44253ca95b02SDimitry Andric   // compute an effective address.  (i.e LEA on x86)
442691bc56edSDimitry Andric   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
442791bc56edSDimitry Andric   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
442891bc56edSDimitry Andric     Instruction *User = MemoryUses[i].first;
442991bc56edSDimitry Andric     unsigned OpNo = MemoryUses[i].second;
443091bc56edSDimitry Andric 
443191bc56edSDimitry Andric     // Get the access type of this use.  If the use isn't a pointer, we don't
443291bc56edSDimitry Andric     // know what it accesses.
443391bc56edSDimitry Andric     Value *Address = User->getOperand(OpNo);
443497bc6c73SDimitry Andric     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
443597bc6c73SDimitry Andric     if (!AddrTy)
443691bc56edSDimitry Andric       return false;
443797bc6c73SDimitry Andric     Type *AddressAccessTy = AddrTy->getElementType();
443897bc6c73SDimitry Andric     unsigned AS = AddrTy->getAddressSpace();
443991bc56edSDimitry Andric 
444091bc56edSDimitry Andric     // Do a match against the root of this address, ignoring profitability. This
444191bc56edSDimitry Andric     // will tell us if the addressing mode for the memory operation will
444291bc56edSDimitry Andric     // *actually* cover the shared instruction.
444391bc56edSDimitry Andric     ExtAddrMode Result;
44444ba319b5SDimitry Andric     std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
44454ba319b5SDimitry Andric                                                                       0);
444691bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
444791bc56edSDimitry Andric         TPT.getRestorationPoint();
44484ba319b5SDimitry Andric     AddressingModeMatcher Matcher(
44494ba319b5SDimitry Andric         MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
44504ba319b5SDimitry Andric         InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
445191bc56edSDimitry Andric     Matcher.IgnoreProfitability = true;
44527d523365SDimitry Andric     bool Success = Matcher.matchAddr(Address, 0);
445391bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
445491bc56edSDimitry Andric 
445591bc56edSDimitry Andric     // The match was to check the profitability, the changes made are not
445691bc56edSDimitry Andric     // part of the original matcher. Therefore, they should be dropped
445791bc56edSDimitry Andric     // otherwise the original matcher will not present the right state.
445891bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
445991bc56edSDimitry Andric 
446091bc56edSDimitry Andric     // If the match didn't cover I, then it won't be shared by it.
4461d88c1a5aSDimitry Andric     if (!is_contained(MatchedAddrModeInsts, I))
446291bc56edSDimitry Andric       return false;
446391bc56edSDimitry Andric 
446491bc56edSDimitry Andric     MatchedAddrModeInsts.clear();
446591bc56edSDimitry Andric   }
446691bc56edSDimitry Andric 
446791bc56edSDimitry Andric   return true;
446891bc56edSDimitry Andric }
446991bc56edSDimitry Andric 
44707d523365SDimitry Andric /// Return true if the specified values are defined in a
447191bc56edSDimitry Andric /// different basic block than BB.
IsNonLocalValue(Value * V,BasicBlock * BB)447291bc56edSDimitry Andric static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
447391bc56edSDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V))
447491bc56edSDimitry Andric     return I->getParent() != BB;
447591bc56edSDimitry Andric   return false;
447691bc56edSDimitry Andric }
447791bc56edSDimitry Andric 
44783ca95b02SDimitry Andric /// Sink addressing mode computation immediate before MemoryInst if doing so
44793ca95b02SDimitry Andric /// can be done without increasing register pressure.  The need for the
44803ca95b02SDimitry Andric /// register pressure constraint means this can end up being an all or nothing
44813ca95b02SDimitry Andric /// decision for all uses of the same addressing computation.
44823ca95b02SDimitry Andric ///
44837d523365SDimitry Andric /// Load and Store Instructions often have addressing modes that can do
44847d523365SDimitry Andric /// significant amounts of computation. As such, instruction selection will try
44857d523365SDimitry Andric /// to get the load or store to do as much computation as possible for the
44867d523365SDimitry Andric /// program. The problem is that isel can only see within a single block. As
44877d523365SDimitry Andric /// such, we sink as much legal addressing mode work into the block as possible.
448891bc56edSDimitry Andric ///
448991bc56edSDimitry Andric /// This method is used to optimize both load/store and inline asms with memory
44903ca95b02SDimitry Andric /// operands.  It's also used to sink addressing computations feeding into cold
44913ca95b02SDimitry Andric /// call sites into their (cold) basic block.
44923ca95b02SDimitry Andric ///
44933ca95b02SDimitry Andric /// The motivation for handling sinking into cold blocks is that doing so can
44943ca95b02SDimitry Andric /// both enable other address mode sinking (by satisfying the register pressure
44953ca95b02SDimitry Andric /// constraint above), and reduce register pressure globally (by removing the
44963ca95b02SDimitry Andric /// addressing mode computation from the fast path entirely.).
optimizeMemoryInst(Instruction * MemoryInst,Value * Addr,Type * AccessTy,unsigned AddrSpace)44977d523365SDimitry Andric bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
449897bc6c73SDimitry Andric                                         Type *AccessTy, unsigned AddrSpace) {
449991bc56edSDimitry Andric   Value *Repl = Addr;
450091bc56edSDimitry Andric 
450191bc56edSDimitry Andric   // Try to collapse single-value PHI nodes.  This is necessary to undo
450291bc56edSDimitry Andric   // unprofitable PRE transformations.
450391bc56edSDimitry Andric   SmallVector<Value*, 8> worklist;
450491bc56edSDimitry Andric   SmallPtrSet<Value*, 16> Visited;
450591bc56edSDimitry Andric   worklist.push_back(Addr);
450691bc56edSDimitry Andric 
45072cab237bSDimitry Andric   // Use a worklist to iteratively look through PHI and select nodes, and
45082cab237bSDimitry Andric   // ensure that the addressing mode obtained from the non-PHI/select roots of
45092cab237bSDimitry Andric   // the graph are compatible.
45102cab237bSDimitry Andric   bool PhiOrSelectSeen = false;
451191bc56edSDimitry Andric   SmallVector<Instruction*, 16> AddrModeInsts;
45122cab237bSDimitry Andric   const SimplifyQuery SQ(*DL, TLInfo);
4513*b5893f02SDimitry Andric   AddressingModeCombiner AddrModes(SQ, Addr);
45147a7e6055SDimitry Andric   TypePromotionTransaction TPT(RemovedInsts);
451591bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
451691bc56edSDimitry Andric       TPT.getRestorationPoint();
451791bc56edSDimitry Andric   while (!worklist.empty()) {
451891bc56edSDimitry Andric     Value *V = worklist.back();
451991bc56edSDimitry Andric     worklist.pop_back();
452091bc56edSDimitry Andric 
4521b40b48b8SDimitry Andric     // We allow traversing cyclic Phi nodes.
4522b40b48b8SDimitry Andric     // In case of success after this loop we ensure that traversing through
4523b40b48b8SDimitry Andric     // Phi nodes ends up with all cases to compute address of the form
4524b40b48b8SDimitry Andric     //    BaseGV + Base + Scale * Index + Offset
4525b40b48b8SDimitry Andric     // where Scale and Offset are constans and BaseGV, Base and Index
4526b40b48b8SDimitry Andric     // are exactly the same Values in all cases.
4527b40b48b8SDimitry Andric     // It means that BaseGV, Scale and Offset dominate our memory instruction
4528b40b48b8SDimitry Andric     // and have the same value as they had in address computation represented
4529b40b48b8SDimitry Andric     // as Phi. So we can safely sink address computation to memory instruction.
4530b40b48b8SDimitry Andric     if (!Visited.insert(V).second)
4531b40b48b8SDimitry Andric       continue;
453291bc56edSDimitry Andric 
453391bc56edSDimitry Andric     // For a PHI node, push all of its incoming values.
453491bc56edSDimitry Andric     if (PHINode *P = dyn_cast<PHINode>(V)) {
4535ff0cc061SDimitry Andric       for (Value *IncValue : P->incoming_values())
4536ff0cc061SDimitry Andric         worklist.push_back(IncValue);
45372cab237bSDimitry Andric       PhiOrSelectSeen = true;
45382cab237bSDimitry Andric       continue;
45392cab237bSDimitry Andric     }
45402cab237bSDimitry Andric     // Similar for select.
45412cab237bSDimitry Andric     if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
45422cab237bSDimitry Andric       worklist.push_back(SI->getFalseValue());
45432cab237bSDimitry Andric       worklist.push_back(SI->getTrueValue());
45442cab237bSDimitry Andric       PhiOrSelectSeen = true;
454591bc56edSDimitry Andric       continue;
454691bc56edSDimitry Andric     }
454791bc56edSDimitry Andric 
45483ca95b02SDimitry Andric     // For non-PHIs, determine the addressing mode being computed.  Note that
45493ca95b02SDimitry Andric     // the result may differ depending on what other uses our candidate
45503ca95b02SDimitry Andric     // addressing instructions might have.
4551b40b48b8SDimitry Andric     AddrModeInsts.clear();
45524ba319b5SDimitry Andric     std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
45534ba319b5SDimitry Andric                                                                       0);
455491bc56edSDimitry Andric     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4555b40b48b8SDimitry Andric         V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
45564ba319b5SDimitry Andric         InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
455791bc56edSDimitry Andric 
45584ba319b5SDimitry Andric     GetElementPtrInst *GEP = LargeOffsetGEP.first;
45594ba319b5SDimitry Andric     if (GEP && GEP->getParent() != MemoryInst->getParent() &&
45604ba319b5SDimitry Andric         !NewGEPBases.count(GEP)) {
45614ba319b5SDimitry Andric       // If splitting the underlying data structure can reduce the offset of a
45624ba319b5SDimitry Andric       // GEP, collect the GEP.  Skip the GEPs that are the new bases of
45634ba319b5SDimitry Andric       // previously split data structures.
45644ba319b5SDimitry Andric       LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
45654ba319b5SDimitry Andric       if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
45664ba319b5SDimitry Andric         LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
45674ba319b5SDimitry Andric     }
45684ba319b5SDimitry Andric 
45694ba319b5SDimitry Andric     NewAddrMode.OriginalValue = V;
45702cab237bSDimitry Andric     if (!AddrModes.addNewAddrMode(NewAddrMode))
457191bc56edSDimitry Andric       break;
457291bc56edSDimitry Andric   }
457391bc56edSDimitry Andric 
45742cab237bSDimitry Andric   // Try to combine the AddrModes we've collected. If we couldn't collect any,
45752cab237bSDimitry Andric   // or we have multiple but either couldn't combine them or combining them
45762cab237bSDimitry Andric   // wouldn't do anything useful, bail out now.
45772cab237bSDimitry Andric   if (!AddrModes.combineAddrModes()) {
457891bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
457991bc56edSDimitry Andric     return false;
458091bc56edSDimitry Andric   }
458191bc56edSDimitry Andric   TPT.commit();
458291bc56edSDimitry Andric 
45832cab237bSDimitry Andric   // Get the combined AddrMode (or the only AddrMode, if we only had one).
45842cab237bSDimitry Andric   ExtAddrMode AddrMode = AddrModes.getAddrMode();
45852cab237bSDimitry Andric 
458691bc56edSDimitry Andric   // If all the instructions matched are already in this BB, don't do anything.
45872cab237bSDimitry Andric   // If we saw a Phi node then it is not local definitely, and if we saw a select
45882cab237bSDimitry Andric   // then we want to push the address calculation past it even if it's already
45892cab237bSDimitry Andric   // in this BB.
45902cab237bSDimitry Andric   if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
4591d88c1a5aSDimitry Andric         return IsNonLocalValue(V, MemoryInst->getParent());
4592d88c1a5aSDimitry Andric                   })) {
45934ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode
45944ba319b5SDimitry Andric                       << "\n");
459591bc56edSDimitry Andric     return false;
459691bc56edSDimitry Andric   }
459791bc56edSDimitry Andric 
459891bc56edSDimitry Andric   // Insert this computation right after this user.  Since our caller is
459991bc56edSDimitry Andric   // scanning from the top of the BB to the bottom, reuse of the expr are
460091bc56edSDimitry Andric   // guaranteed to happen later.
460191bc56edSDimitry Andric   IRBuilder<> Builder(MemoryInst);
460291bc56edSDimitry Andric 
460391bc56edSDimitry Andric   // Now that we determined the addressing expression we want to use and know
460491bc56edSDimitry Andric   // that we have to sink it into this block.  Check to see if we have already
46052cab237bSDimitry Andric   // done this for some other load/store instr in this block.  If so, reuse
46062cab237bSDimitry Andric   // the computation.  Before attempting reuse, check if the address is valid
46072cab237bSDimitry Andric   // as it may have been erased.
46082cab237bSDimitry Andric 
46092cab237bSDimitry Andric   WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
46102cab237bSDimitry Andric 
46112cab237bSDimitry Andric   Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
461291bc56edSDimitry Andric   if (SunkAddr) {
46134ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
46144ba319b5SDimitry Andric                       << " for " << *MemoryInst << "\n");
461591bc56edSDimitry Andric     if (SunkAddr->getType() != Addr->getType())
46167a7e6055SDimitry Andric       SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4617ff0cc061SDimitry Andric   } else if (AddrSinkUsingGEPs ||
46184ba319b5SDimitry Andric              (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
461991bc56edSDimitry Andric     // By default, we use the GEP-based method when AA is used later. This
462091bc56edSDimitry Andric     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
46214ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
46224ba319b5SDimitry Andric                       << " for " << *MemoryInst << "\n");
4623875ed548SDimitry Andric     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
462491bc56edSDimitry Andric     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
462591bc56edSDimitry Andric 
462691bc56edSDimitry Andric     // First, find the pointer.
462791bc56edSDimitry Andric     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
462891bc56edSDimitry Andric       ResultPtr = AddrMode.BaseReg;
462991bc56edSDimitry Andric       AddrMode.BaseReg = nullptr;
463091bc56edSDimitry Andric     }
463191bc56edSDimitry Andric 
463291bc56edSDimitry Andric     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
463391bc56edSDimitry Andric       // We can't add more than one pointer together, nor can we scale a
463491bc56edSDimitry Andric       // pointer (both of which seem meaningless).
463591bc56edSDimitry Andric       if (ResultPtr || AddrMode.Scale != 1)
463691bc56edSDimitry Andric         return false;
463791bc56edSDimitry Andric 
463891bc56edSDimitry Andric       ResultPtr = AddrMode.ScaledReg;
463991bc56edSDimitry Andric       AddrMode.Scale = 0;
464091bc56edSDimitry Andric     }
464191bc56edSDimitry Andric 
4642c4394386SDimitry Andric     // It is only safe to sign extend the BaseReg if we know that the math
4643c4394386SDimitry Andric     // required to create it did not overflow before we extend it. Since
4644c4394386SDimitry Andric     // the original IR value was tossed in favor of a constant back when
4645c4394386SDimitry Andric     // the AddrMode was created we need to bail out gracefully if widths
4646c4394386SDimitry Andric     // do not match instead of extending it.
4647c4394386SDimitry Andric     //
4648c4394386SDimitry Andric     // (See below for code to add the scale.)
4649c4394386SDimitry Andric     if (AddrMode.Scale) {
4650c4394386SDimitry Andric       Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4651c4394386SDimitry Andric       if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4652c4394386SDimitry Andric           cast<IntegerType>(ScaledRegTy)->getBitWidth())
4653c4394386SDimitry Andric         return false;
4654c4394386SDimitry Andric     }
4655c4394386SDimitry Andric 
465691bc56edSDimitry Andric     if (AddrMode.BaseGV) {
465791bc56edSDimitry Andric       if (ResultPtr)
465891bc56edSDimitry Andric         return false;
465991bc56edSDimitry Andric 
466091bc56edSDimitry Andric       ResultPtr = AddrMode.BaseGV;
466191bc56edSDimitry Andric     }
466291bc56edSDimitry Andric 
466391bc56edSDimitry Andric     // If the real base value actually came from an inttoptr, then the matcher
466491bc56edSDimitry Andric     // will look through it and provide only the integer value. In that case,
466591bc56edSDimitry Andric     // use it here.
4666a580b014SDimitry Andric     if (!DL->isNonIntegralPointerType(Addr->getType())) {
466791bc56edSDimitry Andric       if (!ResultPtr && AddrMode.BaseReg) {
4668a580b014SDimitry Andric         ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4669a580b014SDimitry Andric                                            "sunkaddr");
467091bc56edSDimitry Andric         AddrMode.BaseReg = nullptr;
467191bc56edSDimitry Andric       } else if (!ResultPtr && AddrMode.Scale == 1) {
4672a580b014SDimitry Andric         ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4673a580b014SDimitry Andric                                            "sunkaddr");
467491bc56edSDimitry Andric         AddrMode.Scale = 0;
467591bc56edSDimitry Andric       }
4676a580b014SDimitry Andric     }
467791bc56edSDimitry Andric 
467891bc56edSDimitry Andric     if (!ResultPtr &&
467991bc56edSDimitry Andric         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
468091bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
468191bc56edSDimitry Andric     } else if (!ResultPtr) {
468291bc56edSDimitry Andric       return false;
468391bc56edSDimitry Andric     } else {
468491bc56edSDimitry Andric       Type *I8PtrTy =
468591bc56edSDimitry Andric           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4686ff0cc061SDimitry Andric       Type *I8Ty = Builder.getInt8Ty();
468791bc56edSDimitry Andric 
468891bc56edSDimitry Andric       // Start with the base register. Do this first so that subsequent address
468991bc56edSDimitry Andric       // matching finds it last, which will prevent it from trying to match it
469091bc56edSDimitry Andric       // as the scaled value in case it happens to be a mul. That would be
469191bc56edSDimitry Andric       // problematic if we've sunk a different mul for the scale, because then
469291bc56edSDimitry Andric       // we'd end up sinking both muls.
469391bc56edSDimitry Andric       if (AddrMode.BaseReg) {
469491bc56edSDimitry Andric         Value *V = AddrMode.BaseReg;
469591bc56edSDimitry Andric         if (V->getType() != IntPtrTy)
469691bc56edSDimitry Andric           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
469791bc56edSDimitry Andric 
469891bc56edSDimitry Andric         ResultIndex = V;
469991bc56edSDimitry Andric       }
470091bc56edSDimitry Andric 
470191bc56edSDimitry Andric       // Add the scale value.
470291bc56edSDimitry Andric       if (AddrMode.Scale) {
470391bc56edSDimitry Andric         Value *V = AddrMode.ScaledReg;
470491bc56edSDimitry Andric         if (V->getType() == IntPtrTy) {
470591bc56edSDimitry Andric           // done.
470691bc56edSDimitry Andric         } else {
4707c4394386SDimitry Andric           assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4708c4394386SDimitry Andric                  cast<IntegerType>(V->getType())->getBitWidth() &&
4709c4394386SDimitry Andric                  "We can't transform if ScaledReg is too narrow");
4710c4394386SDimitry Andric           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
471191bc56edSDimitry Andric         }
471291bc56edSDimitry Andric 
471391bc56edSDimitry Andric         if (AddrMode.Scale != 1)
471491bc56edSDimitry Andric           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
471591bc56edSDimitry Andric                                 "sunkaddr");
471691bc56edSDimitry Andric         if (ResultIndex)
471791bc56edSDimitry Andric           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
471891bc56edSDimitry Andric         else
471991bc56edSDimitry Andric           ResultIndex = V;
472091bc56edSDimitry Andric       }
472191bc56edSDimitry Andric 
472291bc56edSDimitry Andric       // Add in the Base Offset if present.
472391bc56edSDimitry Andric       if (AddrMode.BaseOffs) {
472491bc56edSDimitry Andric         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
472591bc56edSDimitry Andric         if (ResultIndex) {
472691bc56edSDimitry Andric           // We need to add this separately from the scale above to help with
472791bc56edSDimitry Andric           // SDAG consecutive load/store merging.
472891bc56edSDimitry Andric           if (ResultPtr->getType() != I8PtrTy)
47297a7e6055SDimitry Andric             ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4730ff0cc061SDimitry Andric           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
473191bc56edSDimitry Andric         }
473291bc56edSDimitry Andric 
473391bc56edSDimitry Andric         ResultIndex = V;
473491bc56edSDimitry Andric       }
473591bc56edSDimitry Andric 
473691bc56edSDimitry Andric       if (!ResultIndex) {
473791bc56edSDimitry Andric         SunkAddr = ResultPtr;
473891bc56edSDimitry Andric       } else {
473991bc56edSDimitry Andric         if (ResultPtr->getType() != I8PtrTy)
47407a7e6055SDimitry Andric           ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4741ff0cc061SDimitry Andric         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
474291bc56edSDimitry Andric       }
474391bc56edSDimitry Andric 
474491bc56edSDimitry Andric       if (SunkAddr->getType() != Addr->getType())
47457a7e6055SDimitry Andric         SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
474691bc56edSDimitry Andric     }
474791bc56edSDimitry Andric   } else {
4748a580b014SDimitry Andric     // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4749a580b014SDimitry Andric     // non-integral pointers, so in that case bail out now.
4750a580b014SDimitry Andric     Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4751a580b014SDimitry Andric     Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4752a580b014SDimitry Andric     PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4753a580b014SDimitry Andric     PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4754a580b014SDimitry Andric     if (DL->isNonIntegralPointerType(Addr->getType()) ||
4755a580b014SDimitry Andric         (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4756a580b014SDimitry Andric         (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4757a580b014SDimitry Andric         (AddrMode.BaseGV &&
4758a580b014SDimitry Andric          DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4759a580b014SDimitry Andric       return false;
4760a580b014SDimitry Andric 
47614ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
47624ba319b5SDimitry Andric                       << " for " << *MemoryInst << "\n");
4763875ed548SDimitry Andric     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
476491bc56edSDimitry Andric     Value *Result = nullptr;
476591bc56edSDimitry Andric 
476691bc56edSDimitry Andric     // Start with the base register. Do this first so that subsequent address
476791bc56edSDimitry Andric     // matching finds it last, which will prevent it from trying to match it
476891bc56edSDimitry Andric     // as the scaled value in case it happens to be a mul. That would be
476991bc56edSDimitry Andric     // problematic if we've sunk a different mul for the scale, because then
477091bc56edSDimitry Andric     // we'd end up sinking both muls.
477191bc56edSDimitry Andric     if (AddrMode.BaseReg) {
477291bc56edSDimitry Andric       Value *V = AddrMode.BaseReg;
477391bc56edSDimitry Andric       if (V->getType()->isPointerTy())
477491bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
477591bc56edSDimitry Andric       if (V->getType() != IntPtrTy)
477691bc56edSDimitry Andric         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
477791bc56edSDimitry Andric       Result = V;
477891bc56edSDimitry Andric     }
477991bc56edSDimitry Andric 
478091bc56edSDimitry Andric     // Add the scale value.
478191bc56edSDimitry Andric     if (AddrMode.Scale) {
478291bc56edSDimitry Andric       Value *V = AddrMode.ScaledReg;
478391bc56edSDimitry Andric       if (V->getType() == IntPtrTy) {
478491bc56edSDimitry Andric         // done.
478591bc56edSDimitry Andric       } else if (V->getType()->isPointerTy()) {
478691bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
478791bc56edSDimitry Andric       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
478891bc56edSDimitry Andric                  cast<IntegerType>(V->getType())->getBitWidth()) {
478991bc56edSDimitry Andric         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
479091bc56edSDimitry Andric       } else {
479191bc56edSDimitry Andric         // It is only safe to sign extend the BaseReg if we know that the math
479291bc56edSDimitry Andric         // required to create it did not overflow before we extend it. Since
479391bc56edSDimitry Andric         // the original IR value was tossed in favor of a constant back when
479491bc56edSDimitry Andric         // the AddrMode was created we need to bail out gracefully if widths
479591bc56edSDimitry Andric         // do not match instead of extending it.
479691bc56edSDimitry Andric         Instruction *I = dyn_cast_or_null<Instruction>(Result);
479791bc56edSDimitry Andric         if (I && (Result != AddrMode.BaseReg))
479891bc56edSDimitry Andric           I->eraseFromParent();
479991bc56edSDimitry Andric         return false;
480091bc56edSDimitry Andric       }
480191bc56edSDimitry Andric       if (AddrMode.Scale != 1)
480291bc56edSDimitry Andric         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
480391bc56edSDimitry Andric                               "sunkaddr");
480491bc56edSDimitry Andric       if (Result)
480591bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
480691bc56edSDimitry Andric       else
480791bc56edSDimitry Andric         Result = V;
480891bc56edSDimitry Andric     }
480991bc56edSDimitry Andric 
481091bc56edSDimitry Andric     // Add in the BaseGV if present.
481191bc56edSDimitry Andric     if (AddrMode.BaseGV) {
481291bc56edSDimitry Andric       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
481391bc56edSDimitry Andric       if (Result)
481491bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
481591bc56edSDimitry Andric       else
481691bc56edSDimitry Andric         Result = V;
481791bc56edSDimitry Andric     }
481891bc56edSDimitry Andric 
481991bc56edSDimitry Andric     // Add in the Base Offset if present.
482091bc56edSDimitry Andric     if (AddrMode.BaseOffs) {
482191bc56edSDimitry Andric       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
482291bc56edSDimitry Andric       if (Result)
482391bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
482491bc56edSDimitry Andric       else
482591bc56edSDimitry Andric         Result = V;
482691bc56edSDimitry Andric     }
482791bc56edSDimitry Andric 
482891bc56edSDimitry Andric     if (!Result)
482991bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
483091bc56edSDimitry Andric     else
483191bc56edSDimitry Andric       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
483291bc56edSDimitry Andric   }
483391bc56edSDimitry Andric 
483491bc56edSDimitry Andric   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
48352cab237bSDimitry Andric   // Store the newly computed address into the cache. In the case we reused a
48362cab237bSDimitry Andric   // value, this should be idempotent.
48372cab237bSDimitry Andric   SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
483891bc56edSDimitry Andric 
483991bc56edSDimitry Andric   // If we have no uses, recursively delete the value and all dead instructions
484091bc56edSDimitry Andric   // using it.
484191bc56edSDimitry Andric   if (Repl->use_empty()) {
484291bc56edSDimitry Andric     // This can cause recursive deletion, which can invalidate our iterator.
4843f37b6182SDimitry Andric     // Use a WeakTrackingVH to hold onto it in case this happens.
48443ca95b02SDimitry Andric     Value *CurValue = &*CurInstIterator;
4845f37b6182SDimitry Andric     WeakTrackingVH IterHandle(CurValue);
484691bc56edSDimitry Andric     BasicBlock *BB = CurInstIterator->getParent();
484791bc56edSDimitry Andric 
484891bc56edSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
484991bc56edSDimitry Andric 
48503ca95b02SDimitry Andric     if (IterHandle != CurValue) {
485191bc56edSDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
485291bc56edSDimitry Andric       // start of the block.
485391bc56edSDimitry Andric       CurInstIterator = BB->begin();
485491bc56edSDimitry Andric       SunkAddrs.clear();
485591bc56edSDimitry Andric     }
485691bc56edSDimitry Andric   }
485791bc56edSDimitry Andric   ++NumMemoryInsts;
485891bc56edSDimitry Andric   return true;
485991bc56edSDimitry Andric }
486091bc56edSDimitry Andric 
48617d523365SDimitry Andric /// If there are any memory operands, use OptimizeMemoryInst to sink their
48627d523365SDimitry Andric /// address computing into the block when possible / profitable.
optimizeInlineAsmInst(CallInst * CS)48637d523365SDimitry Andric bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
486491bc56edSDimitry Andric   bool MadeChange = false;
486591bc56edSDimitry Andric 
4866ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI =
4867db17bf38SDimitry Andric       TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
4868875ed548SDimitry Andric   TargetLowering::AsmOperandInfoVector TargetConstraints =
4869875ed548SDimitry Andric       TLI->ParseConstraints(*DL, TRI, CS);
487091bc56edSDimitry Andric   unsigned ArgNo = 0;
487191bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
487291bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
487391bc56edSDimitry Andric 
487491bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
487591bc56edSDimitry Andric     TLI->ComputeConstraintToUse(OpInfo, SDValue());
487691bc56edSDimitry Andric 
487791bc56edSDimitry Andric     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
487891bc56edSDimitry Andric         OpInfo.isIndirect) {
487991bc56edSDimitry Andric       Value *OpVal = CS->getArgOperand(ArgNo++);
48807d523365SDimitry Andric       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
488191bc56edSDimitry Andric     } else if (OpInfo.Type == InlineAsm::isInput)
488291bc56edSDimitry Andric       ArgNo++;
488391bc56edSDimitry Andric   }
488491bc56edSDimitry Andric 
488591bc56edSDimitry Andric   return MadeChange;
488691bc56edSDimitry Andric }
488791bc56edSDimitry Andric 
48884ba319b5SDimitry Andric /// Check if all the uses of \p Val are equivalent (or free) zero or
488939d628a0SDimitry Andric /// sign extensions.
hasSameExtUse(Value * Val,const TargetLowering & TLI)48907a7e6055SDimitry Andric static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
48917a7e6055SDimitry Andric   assert(!Val->use_empty() && "Input must have at least one use");
48927a7e6055SDimitry Andric   const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
489339d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(FirstUser);
489439d628a0SDimitry Andric   Type *ExtTy = FirstUser->getType();
48957a7e6055SDimitry Andric   for (const User *U : Val->users()) {
489639d628a0SDimitry Andric     const Instruction *UI = cast<Instruction>(U);
489739d628a0SDimitry Andric     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
489839d628a0SDimitry Andric       return false;
489939d628a0SDimitry Andric     Type *CurTy = UI->getType();
490039d628a0SDimitry Andric     // Same input and output types: Same instruction after CSE.
490139d628a0SDimitry Andric     if (CurTy == ExtTy)
490239d628a0SDimitry Andric       continue;
490339d628a0SDimitry Andric 
490439d628a0SDimitry Andric     // If IsSExt is true, we are in this situation:
49057a7e6055SDimitry Andric     // a = Val
490639d628a0SDimitry Andric     // b = sext ty1 a to ty2
490739d628a0SDimitry Andric     // c = sext ty1 a to ty3
490839d628a0SDimitry Andric     // Assuming ty2 is shorter than ty3, this could be turned into:
49097a7e6055SDimitry Andric     // a = Val
491039d628a0SDimitry Andric     // b = sext ty1 a to ty2
491139d628a0SDimitry Andric     // c = sext ty2 b to ty3
491239d628a0SDimitry Andric     // However, the last sext is not free.
491339d628a0SDimitry Andric     if (IsSExt)
491439d628a0SDimitry Andric       return false;
491539d628a0SDimitry Andric 
491639d628a0SDimitry Andric     // This is a ZExt, maybe this is free to extend from one type to another.
491739d628a0SDimitry Andric     // In that case, we would not account for a different use.
491839d628a0SDimitry Andric     Type *NarrowTy;
491939d628a0SDimitry Andric     Type *LargeTy;
492039d628a0SDimitry Andric     if (ExtTy->getScalarType()->getIntegerBitWidth() >
492139d628a0SDimitry Andric         CurTy->getScalarType()->getIntegerBitWidth()) {
492239d628a0SDimitry Andric       NarrowTy = CurTy;
492339d628a0SDimitry Andric       LargeTy = ExtTy;
492439d628a0SDimitry Andric     } else {
492539d628a0SDimitry Andric       NarrowTy = ExtTy;
492639d628a0SDimitry Andric       LargeTy = CurTy;
492739d628a0SDimitry Andric     }
492839d628a0SDimitry Andric 
492939d628a0SDimitry Andric     if (!TLI.isZExtFree(NarrowTy, LargeTy))
493039d628a0SDimitry Andric       return false;
493139d628a0SDimitry Andric   }
493239d628a0SDimitry Andric   // All uses are the same or can be derived from one another for free.
493339d628a0SDimitry Andric   return true;
493439d628a0SDimitry Andric }
493539d628a0SDimitry Andric 
49364ba319b5SDimitry Andric /// Try to speculatively promote extensions in \p Exts and continue
49377a7e6055SDimitry Andric /// promoting through newly promoted operands recursively as far as doing so is
49387a7e6055SDimitry Andric /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
49397a7e6055SDimitry Andric /// When some promotion happened, \p TPT contains the proper state to revert
49407a7e6055SDimitry Andric /// them.
494139d628a0SDimitry Andric ///
49427a7e6055SDimitry Andric /// \return true if some promotion happened, false otherwise.
tryToPromoteExts(TypePromotionTransaction & TPT,const SmallVectorImpl<Instruction * > & Exts,SmallVectorImpl<Instruction * > & ProfitablyMovedExts,unsigned CreatedInstsCost)49437a7e6055SDimitry Andric bool CodeGenPrepare::tryToPromoteExts(
49447a7e6055SDimitry Andric     TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
49457a7e6055SDimitry Andric     SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
49467a7e6055SDimitry Andric     unsigned CreatedInstsCost) {
49477a7e6055SDimitry Andric   bool Promoted = false;
49487a7e6055SDimitry Andric 
49497a7e6055SDimitry Andric   // Iterate over all the extensions to try to promote them.
495039d628a0SDimitry Andric   for (auto I : Exts) {
49517a7e6055SDimitry Andric     // Early check if we directly have ext(load).
49527a7e6055SDimitry Andric     if (isa<LoadInst>(I->getOperand(0))) {
49537a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
49547a7e6055SDimitry Andric       continue;
495539d628a0SDimitry Andric     }
49567a7e6055SDimitry Andric 
49577a7e6055SDimitry Andric     // Check whether or not we want to do any promotion.  The reason we have
49587a7e6055SDimitry Andric     // this check inside the for loop is to catch the case where an extension
49597a7e6055SDimitry Andric     // is directly fed by a load because in such case the extension can be moved
49607a7e6055SDimitry Andric     // up without any promotion on its operands.
496139d628a0SDimitry Andric     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
49627a7e6055SDimitry Andric       return false;
49637a7e6055SDimitry Andric 
496439d628a0SDimitry Andric     // Get the action to perform the promotion.
49657a7e6055SDimitry Andric     TypePromotionHelper::Action TPH =
49667a7e6055SDimitry Andric         TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
496739d628a0SDimitry Andric     // Check if we can promote.
49687a7e6055SDimitry Andric     if (!TPH) {
49697a7e6055SDimitry Andric       // Save the current extension as we cannot move up through its operand.
49707a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
497139d628a0SDimitry Andric       continue;
49727a7e6055SDimitry Andric     }
49737a7e6055SDimitry Andric 
497439d628a0SDimitry Andric     // Save the current state.
497539d628a0SDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
497639d628a0SDimitry Andric         TPT.getRestorationPoint();
497739d628a0SDimitry Andric     SmallVector<Instruction *, 4> NewExts;
4978ff0cc061SDimitry Andric     unsigned NewCreatedInstsCost = 0;
4979ff0cc061SDimitry Andric     unsigned ExtCost = !TLI->isExtFree(I);
498039d628a0SDimitry Andric     // Promote.
4981ff0cc061SDimitry Andric     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4982ff0cc061SDimitry Andric                              &NewExts, nullptr, *TLI);
498339d628a0SDimitry Andric     assert(PromotedVal &&
498439d628a0SDimitry Andric            "TypePromotionHelper should have filtered out those cases");
498539d628a0SDimitry Andric 
498639d628a0SDimitry Andric     // We would be able to merge only one extension in a load.
498739d628a0SDimitry Andric     // Therefore, if we have more than 1 new extension we heuristically
498839d628a0SDimitry Andric     // cut this search path, because it means we degrade the code quality.
498939d628a0SDimitry Andric     // With exactly 2, the transformation is neutral, because we will merge
499039d628a0SDimitry Andric     // one extension but leave one. However, we optimistically keep going,
499139d628a0SDimitry Andric     // because the new extension may be removed too.
4992ff0cc061SDimitry Andric     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
49937a7e6055SDimitry Andric     // FIXME: It would be possible to propagate a negative value instead of
49947a7e6055SDimitry Andric     // conservatively ceiling it to 0.
49957a7e6055SDimitry Andric     TotalCreatedInstsCost =
49967a7e6055SDimitry Andric         std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
499739d628a0SDimitry Andric     if (!StressExtLdPromotion &&
4998ff0cc061SDimitry Andric         (TotalCreatedInstsCost > 1 ||
4999875ed548SDimitry Andric          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
50007a7e6055SDimitry Andric       // This promotion is not profitable, rollback to the previous state, and
50017a7e6055SDimitry Andric       // save the current extension in ProfitablyMovedExts as the latest
50027a7e6055SDimitry Andric       // speculative promotion turned out to be unprofitable.
500339d628a0SDimitry Andric       TPT.rollback(LastKnownGood);
50047a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
50057a7e6055SDimitry Andric       continue;
50067a7e6055SDimitry Andric     }
50077a7e6055SDimitry Andric     // Continue promoting NewExts as far as doing so is profitable.
50087a7e6055SDimitry Andric     SmallVector<Instruction *, 2> NewlyMovedExts;
50097a7e6055SDimitry Andric     (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
50107a7e6055SDimitry Andric     bool NewPromoted = false;
50117a7e6055SDimitry Andric     for (auto ExtInst : NewlyMovedExts) {
50127a7e6055SDimitry Andric       Instruction *MovedExt = cast<Instruction>(ExtInst);
50137a7e6055SDimitry Andric       Value *ExtOperand = MovedExt->getOperand(0);
50147a7e6055SDimitry Andric       // If we have reached to a load, we need this extra profitability check
50157a7e6055SDimitry Andric       // as it could potentially be merged into an ext(load).
50167a7e6055SDimitry Andric       if (isa<LoadInst>(ExtOperand) &&
50177a7e6055SDimitry Andric           !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
50187a7e6055SDimitry Andric             (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
50197a7e6055SDimitry Andric         continue;
50207a7e6055SDimitry Andric 
50217a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(MovedExt);
50227a7e6055SDimitry Andric       NewPromoted = true;
50237a7e6055SDimitry Andric     }
50247a7e6055SDimitry Andric 
50257a7e6055SDimitry Andric     // If none of speculative promotions for NewExts is profitable, rollback
50267a7e6055SDimitry Andric     // and save the current extension (I) as the last profitable extension.
50277a7e6055SDimitry Andric     if (!NewPromoted) {
50287a7e6055SDimitry Andric       TPT.rollback(LastKnownGood);
50297a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
503039d628a0SDimitry Andric       continue;
503139d628a0SDimitry Andric     }
503239d628a0SDimitry Andric     // The promotion is profitable.
50337a7e6055SDimitry Andric     Promoted = true;
503439d628a0SDimitry Andric   }
50357a7e6055SDimitry Andric   return Promoted;
50367a7e6055SDimitry Andric }
50377a7e6055SDimitry Andric 
50387a7e6055SDimitry Andric /// Merging redundant sexts when one is dominating the other.
mergeSExts(Function & F)50397a7e6055SDimitry Andric bool CodeGenPrepare::mergeSExts(Function &F) {
50407a7e6055SDimitry Andric   DominatorTree DT(F);
50417a7e6055SDimitry Andric   bool Changed = false;
50427a7e6055SDimitry Andric   for (auto &Entry : ValToSExtendedUses) {
50437a7e6055SDimitry Andric     SExts &Insts = Entry.second;
50447a7e6055SDimitry Andric     SExts CurPts;
50457a7e6055SDimitry Andric     for (Instruction *Inst : Insts) {
50467a7e6055SDimitry Andric       if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
50477a7e6055SDimitry Andric           Inst->getOperand(0) != Entry.first)
50487a7e6055SDimitry Andric         continue;
50497a7e6055SDimitry Andric       bool inserted = false;
50507a7e6055SDimitry Andric       for (auto &Pt : CurPts) {
50517a7e6055SDimitry Andric         if (DT.dominates(Inst, Pt)) {
50527a7e6055SDimitry Andric           Pt->replaceAllUsesWith(Inst);
50537a7e6055SDimitry Andric           RemovedInsts.insert(Pt);
50547a7e6055SDimitry Andric           Pt->removeFromParent();
50557a7e6055SDimitry Andric           Pt = Inst;
50567a7e6055SDimitry Andric           inserted = true;
50577a7e6055SDimitry Andric           Changed = true;
50587a7e6055SDimitry Andric           break;
50597a7e6055SDimitry Andric         }
50607a7e6055SDimitry Andric         if (!DT.dominates(Pt, Inst))
50617a7e6055SDimitry Andric           // Give up if we need to merge in a common dominator as the
50624ba319b5SDimitry Andric           // experiments show it is not profitable.
50637a7e6055SDimitry Andric           continue;
50647a7e6055SDimitry Andric         Inst->replaceAllUsesWith(Pt);
50657a7e6055SDimitry Andric         RemovedInsts.insert(Inst);
50667a7e6055SDimitry Andric         Inst->removeFromParent();
50677a7e6055SDimitry Andric         inserted = true;
50687a7e6055SDimitry Andric         Changed = true;
50697a7e6055SDimitry Andric         break;
50707a7e6055SDimitry Andric       }
50717a7e6055SDimitry Andric       if (!inserted)
50727a7e6055SDimitry Andric         CurPts.push_back(Inst);
50737a7e6055SDimitry Andric     }
50747a7e6055SDimitry Andric   }
50757a7e6055SDimitry Andric   return Changed;
50767a7e6055SDimitry Andric }
50777a7e6055SDimitry Andric 
50784ba319b5SDimitry Andric // Spliting large data structures so that the GEPs accessing them can have
50794ba319b5SDimitry Andric // smaller offsets so that they can be sunk to the same blocks as their users.
50804ba319b5SDimitry Andric // For example, a large struct starting from %base is splitted into two parts
50814ba319b5SDimitry Andric // where the second part starts from %new_base.
50824ba319b5SDimitry Andric //
50834ba319b5SDimitry Andric // Before:
50844ba319b5SDimitry Andric // BB0:
50854ba319b5SDimitry Andric //   %base     =
50864ba319b5SDimitry Andric //
50874ba319b5SDimitry Andric // BB1:
50884ba319b5SDimitry Andric //   %gep0     = gep %base, off0
50894ba319b5SDimitry Andric //   %gep1     = gep %base, off1
50904ba319b5SDimitry Andric //   %gep2     = gep %base, off2
50914ba319b5SDimitry Andric //
50924ba319b5SDimitry Andric // BB2:
50934ba319b5SDimitry Andric //   %load1    = load %gep0
50944ba319b5SDimitry Andric //   %load2    = load %gep1
50954ba319b5SDimitry Andric //   %load3    = load %gep2
50964ba319b5SDimitry Andric //
50974ba319b5SDimitry Andric // After:
50984ba319b5SDimitry Andric // BB0:
50994ba319b5SDimitry Andric //   %base     =
51004ba319b5SDimitry Andric //   %new_base = gep %base, off0
51014ba319b5SDimitry Andric //
51024ba319b5SDimitry Andric // BB1:
51034ba319b5SDimitry Andric //   %new_gep0 = %new_base
51044ba319b5SDimitry Andric //   %new_gep1 = gep %new_base, off1 - off0
51054ba319b5SDimitry Andric //   %new_gep2 = gep %new_base, off2 - off0
51064ba319b5SDimitry Andric //
51074ba319b5SDimitry Andric // BB2:
51084ba319b5SDimitry Andric //   %load1    = load i32, i32* %new_gep0
51094ba319b5SDimitry Andric //   %load2    = load i32, i32* %new_gep1
51104ba319b5SDimitry Andric //   %load3    = load i32, i32* %new_gep2
51114ba319b5SDimitry Andric //
51124ba319b5SDimitry Andric // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
51134ba319b5SDimitry Andric // their offsets are smaller enough to fit into the addressing mode.
splitLargeGEPOffsets()51144ba319b5SDimitry Andric bool CodeGenPrepare::splitLargeGEPOffsets() {
51154ba319b5SDimitry Andric   bool Changed = false;
51164ba319b5SDimitry Andric   for (auto &Entry : LargeOffsetGEPMap) {
51174ba319b5SDimitry Andric     Value *OldBase = Entry.first;
51184ba319b5SDimitry Andric     SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
51194ba319b5SDimitry Andric         &LargeOffsetGEPs = Entry.second;
51204ba319b5SDimitry Andric     auto compareGEPOffset =
51214ba319b5SDimitry Andric         [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
51224ba319b5SDimitry Andric             const std::pair<GetElementPtrInst *, int64_t> &RHS) {
51234ba319b5SDimitry Andric           if (LHS.first == RHS.first)
51244ba319b5SDimitry Andric             return false;
51254ba319b5SDimitry Andric           if (LHS.second != RHS.second)
51264ba319b5SDimitry Andric             return LHS.second < RHS.second;
51274ba319b5SDimitry Andric           return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
51284ba319b5SDimitry Andric         };
51294ba319b5SDimitry Andric     // Sorting all the GEPs of the same data structures based on the offsets.
5130*b5893f02SDimitry Andric     llvm::sort(LargeOffsetGEPs, compareGEPOffset);
51314ba319b5SDimitry Andric     LargeOffsetGEPs.erase(
51324ba319b5SDimitry Andric         std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
51334ba319b5SDimitry Andric         LargeOffsetGEPs.end());
51344ba319b5SDimitry Andric     // Skip if all the GEPs have the same offsets.
51354ba319b5SDimitry Andric     if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
51364ba319b5SDimitry Andric       continue;
51374ba319b5SDimitry Andric     GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
51384ba319b5SDimitry Andric     int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
51394ba319b5SDimitry Andric     Value *NewBaseGEP = nullptr;
51404ba319b5SDimitry Andric 
51414ba319b5SDimitry Andric     auto LargeOffsetGEP = LargeOffsetGEPs.begin();
51424ba319b5SDimitry Andric     while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
51434ba319b5SDimitry Andric       GetElementPtrInst *GEP = LargeOffsetGEP->first;
51444ba319b5SDimitry Andric       int64_t Offset = LargeOffsetGEP->second;
51454ba319b5SDimitry Andric       if (Offset != BaseOffset) {
51464ba319b5SDimitry Andric         TargetLowering::AddrMode AddrMode;
51474ba319b5SDimitry Andric         AddrMode.BaseOffs = Offset - BaseOffset;
51484ba319b5SDimitry Andric         // The result type of the GEP might not be the type of the memory
51494ba319b5SDimitry Andric         // access.
51504ba319b5SDimitry Andric         if (!TLI->isLegalAddressingMode(*DL, AddrMode,
51514ba319b5SDimitry Andric                                         GEP->getResultElementType(),
51524ba319b5SDimitry Andric                                         GEP->getAddressSpace())) {
51534ba319b5SDimitry Andric           // We need to create a new base if the offset to the current base is
51544ba319b5SDimitry Andric           // too large to fit into the addressing mode. So, a very large struct
51554ba319b5SDimitry Andric           // may be splitted into several parts.
51564ba319b5SDimitry Andric           BaseGEP = GEP;
51574ba319b5SDimitry Andric           BaseOffset = Offset;
51584ba319b5SDimitry Andric           NewBaseGEP = nullptr;
51594ba319b5SDimitry Andric         }
51604ba319b5SDimitry Andric       }
51614ba319b5SDimitry Andric 
51624ba319b5SDimitry Andric       // Generate a new GEP to replace the current one.
5163*b5893f02SDimitry Andric       LLVMContext &Ctx = GEP->getContext();
51644ba319b5SDimitry Andric       Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
51654ba319b5SDimitry Andric       Type *I8PtrTy =
5166*b5893f02SDimitry Andric           Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
5167*b5893f02SDimitry Andric       Type *I8Ty = Type::getInt8Ty(Ctx);
51684ba319b5SDimitry Andric 
51694ba319b5SDimitry Andric       if (!NewBaseGEP) {
51704ba319b5SDimitry Andric         // Create a new base if we don't have one yet.  Find the insertion
51714ba319b5SDimitry Andric         // pointer for the new base first.
51724ba319b5SDimitry Andric         BasicBlock::iterator NewBaseInsertPt;
51734ba319b5SDimitry Andric         BasicBlock *NewBaseInsertBB;
51744ba319b5SDimitry Andric         if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
51754ba319b5SDimitry Andric           // If the base of the struct is an instruction, the new base will be
51764ba319b5SDimitry Andric           // inserted close to it.
51774ba319b5SDimitry Andric           NewBaseInsertBB = BaseI->getParent();
51784ba319b5SDimitry Andric           if (isa<PHINode>(BaseI))
51794ba319b5SDimitry Andric             NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
51804ba319b5SDimitry Andric           else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
51814ba319b5SDimitry Andric             NewBaseInsertBB =
51824ba319b5SDimitry Andric                 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
51834ba319b5SDimitry Andric             NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
51844ba319b5SDimitry Andric           } else
51854ba319b5SDimitry Andric             NewBaseInsertPt = std::next(BaseI->getIterator());
51864ba319b5SDimitry Andric         } else {
51874ba319b5SDimitry Andric           // If the current base is an argument or global value, the new base
51884ba319b5SDimitry Andric           // will be inserted to the entry block.
51894ba319b5SDimitry Andric           NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
51904ba319b5SDimitry Andric           NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
51914ba319b5SDimitry Andric         }
51924ba319b5SDimitry Andric         IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
51934ba319b5SDimitry Andric         // Create a new base.
51944ba319b5SDimitry Andric         Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
51954ba319b5SDimitry Andric         NewBaseGEP = OldBase;
51964ba319b5SDimitry Andric         if (NewBaseGEP->getType() != I8PtrTy)
51974ba319b5SDimitry Andric           NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
51984ba319b5SDimitry Andric         NewBaseGEP =
51994ba319b5SDimitry Andric             NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
52004ba319b5SDimitry Andric         NewGEPBases.insert(NewBaseGEP);
52014ba319b5SDimitry Andric       }
52024ba319b5SDimitry Andric 
5203*b5893f02SDimitry Andric       IRBuilder<> Builder(GEP);
52044ba319b5SDimitry Andric       Value *NewGEP = NewBaseGEP;
52054ba319b5SDimitry Andric       if (Offset == BaseOffset) {
52064ba319b5SDimitry Andric         if (GEP->getType() != I8PtrTy)
52074ba319b5SDimitry Andric           NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
52084ba319b5SDimitry Andric       } else {
52094ba319b5SDimitry Andric         // Calculate the new offset for the new GEP.
52104ba319b5SDimitry Andric         Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
52114ba319b5SDimitry Andric         NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
52124ba319b5SDimitry Andric 
52134ba319b5SDimitry Andric         if (GEP->getType() != I8PtrTy)
52144ba319b5SDimitry Andric           NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
52154ba319b5SDimitry Andric       }
52164ba319b5SDimitry Andric       GEP->replaceAllUsesWith(NewGEP);
52174ba319b5SDimitry Andric       LargeOffsetGEPID.erase(GEP);
52184ba319b5SDimitry Andric       LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
52194ba319b5SDimitry Andric       GEP->eraseFromParent();
52204ba319b5SDimitry Andric       Changed = true;
52214ba319b5SDimitry Andric     }
52224ba319b5SDimitry Andric   }
52234ba319b5SDimitry Andric   return Changed;
52244ba319b5SDimitry Andric }
52254ba319b5SDimitry Andric 
52267a7e6055SDimitry Andric /// Return true, if an ext(load) can be formed from an extension in
52277a7e6055SDimitry Andric /// \p MovedExts.
canFormExtLd(const SmallVectorImpl<Instruction * > & MovedExts,LoadInst * & LI,Instruction * & Inst,bool HasPromoted)52287a7e6055SDimitry Andric bool CodeGenPrepare::canFormExtLd(
52297a7e6055SDimitry Andric     const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
52307a7e6055SDimitry Andric     Instruction *&Inst, bool HasPromoted) {
52317a7e6055SDimitry Andric   for (auto *MovedExtInst : MovedExts) {
52327a7e6055SDimitry Andric     if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
52337a7e6055SDimitry Andric       LI = cast<LoadInst>(MovedExtInst->getOperand(0));
52347a7e6055SDimitry Andric       Inst = MovedExtInst;
52357a7e6055SDimitry Andric       break;
52367a7e6055SDimitry Andric     }
52377a7e6055SDimitry Andric   }
52387a7e6055SDimitry Andric   if (!LI)
523939d628a0SDimitry Andric     return false;
52407a7e6055SDimitry Andric 
52417a7e6055SDimitry Andric   // If they're already in the same block, there's nothing to do.
52427a7e6055SDimitry Andric   // Make the cheap checks first if we did not promote.
52437a7e6055SDimitry Andric   // If we promoted, we need to check if it is indeed profitable.
52447a7e6055SDimitry Andric   if (!HasPromoted && LI->getParent() == Inst->getParent())
52457a7e6055SDimitry Andric     return false;
52467a7e6055SDimitry Andric 
5247b40b48b8SDimitry Andric   return TLI->isExtLoad(LI, Inst, *DL);
524839d628a0SDimitry Andric }
524939d628a0SDimitry Andric 
52507d523365SDimitry Andric /// Move a zext or sext fed by a load into the same basic block as the load,
52517d523365SDimitry Andric /// unless conditions are unfavorable. This allows SelectionDAG to fold the
52527d523365SDimitry Andric /// extend into the load.
525391bc56edSDimitry Andric ///
52547a7e6055SDimitry Andric /// E.g.,
52557a7e6055SDimitry Andric /// \code
52567a7e6055SDimitry Andric /// %ld = load i32* %addr
52577a7e6055SDimitry Andric /// %add = add nuw i32 %ld, 4
52587a7e6055SDimitry Andric /// %zext = zext i32 %add to i64
52597a7e6055SDimitry Andric // \endcode
52607a7e6055SDimitry Andric /// =>
52617a7e6055SDimitry Andric /// \code
52627a7e6055SDimitry Andric /// %ld = load i32* %addr
52637a7e6055SDimitry Andric /// %zext = zext i32 %ld to i64
52647a7e6055SDimitry Andric /// %add = add nuw i64 %zext, 4
52657a7e6055SDimitry Andric /// \encode
52667a7e6055SDimitry Andric /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
52677a7e6055SDimitry Andric /// allow us to match zext(load i32*) to i64.
52687a7e6055SDimitry Andric ///
52697a7e6055SDimitry Andric /// Also, try to promote the computations used to obtain a sign extended
52707a7e6055SDimitry Andric /// value used into memory accesses.
52717a7e6055SDimitry Andric /// E.g.,
52727a7e6055SDimitry Andric /// \code
52737a7e6055SDimitry Andric /// a = add nsw i32 b, 3
52747a7e6055SDimitry Andric /// d = sext i32 a to i64
52757a7e6055SDimitry Andric /// e = getelementptr ..., i64 d
52767a7e6055SDimitry Andric /// \endcode
52777a7e6055SDimitry Andric /// =>
52787a7e6055SDimitry Andric /// \code
52797a7e6055SDimitry Andric /// f = sext i32 b to i64
52807a7e6055SDimitry Andric /// a = add nsw i64 f, 3
52817a7e6055SDimitry Andric /// e = getelementptr ..., i64 a
52827a7e6055SDimitry Andric /// \endcode
52837a7e6055SDimitry Andric ///
52847a7e6055SDimitry Andric /// \p Inst[in/out] the extension may be modified during the process if some
52857a7e6055SDimitry Andric /// promotions apply.
optimizeExt(Instruction * & Inst)52867a7e6055SDimitry Andric bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
52877a7e6055SDimitry Andric   // ExtLoad formation and address type promotion infrastructure requires TLI to
52887a7e6055SDimitry Andric   // be effective.
5289d88c1a5aSDimitry Andric   if (!TLI)
5290d88c1a5aSDimitry Andric     return false;
5291d88c1a5aSDimitry Andric 
52927a7e6055SDimitry Andric   bool AllowPromotionWithoutCommonHeader = false;
52937a7e6055SDimitry Andric   /// See if it is an interesting sext operations for the address type
52947a7e6055SDimitry Andric   /// promotion before trying to promote it, e.g., the ones with the right
52957a7e6055SDimitry Andric   /// type and used in memory accesses.
52967a7e6055SDimitry Andric   bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
52977a7e6055SDimitry Andric       *Inst, AllowPromotionWithoutCommonHeader);
52987a7e6055SDimitry Andric   TypePromotionTransaction TPT(RemovedInsts);
529939d628a0SDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
530039d628a0SDimitry Andric       TPT.getRestorationPoint();
530139d628a0SDimitry Andric   SmallVector<Instruction *, 1> Exts;
53027a7e6055SDimitry Andric   SmallVector<Instruction *, 2> SpeculativelyMovedExts;
53037a7e6055SDimitry Andric   Exts.push_back(Inst);
53047a7e6055SDimitry Andric 
53057a7e6055SDimitry Andric   bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
53067a7e6055SDimitry Andric 
530791bc56edSDimitry Andric   // Look for a load being extended.
530839d628a0SDimitry Andric   LoadInst *LI = nullptr;
53097a7e6055SDimitry Andric   Instruction *ExtFedByLoad;
531091bc56edSDimitry Andric 
53117a7e6055SDimitry Andric   // Try to promote a chain of computation if it allows to form an extended
53127a7e6055SDimitry Andric   // load.
53137a7e6055SDimitry Andric   if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
53147a7e6055SDimitry Andric     assert(LI && ExtFedByLoad && "Expect a valid load and extension");
531539d628a0SDimitry Andric     TPT.commit();
53167a7e6055SDimitry Andric     // Move the extend into the same block as the load
53172cab237bSDimitry Andric     ExtFedByLoad->moveAfter(LI);
5318d88c1a5aSDimitry Andric     // CGP does not check if the zext would be speculatively executed when moved
53197a7e6055SDimitry Andric     // to the same basic block as the load. Preserving its original location
53207a7e6055SDimitry Andric     // would pessimize the debugging experience, as well as negatively impact
53217a7e6055SDimitry Andric     // the quality of sample pgo. We don't want to use "line 0" as that has a
5322d88c1a5aSDimitry Andric     // size cost in the line-table section and logically the zext can be seen as
53237a7e6055SDimitry Andric     // part of the load. Therefore we conservatively reuse the same debug
53247a7e6055SDimitry Andric     // location for the load and the zext.
53257a7e6055SDimitry Andric     ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
532691bc56edSDimitry Andric     ++NumExtsMoved;
53277a7e6055SDimitry Andric     Inst = ExtFedByLoad;
532891bc56edSDimitry Andric     return true;
532991bc56edSDimitry Andric   }
533091bc56edSDimitry Andric 
53317a7e6055SDimitry Andric   // Continue promoting SExts if known as considerable depending on targets.
53327a7e6055SDimitry Andric   if (ATPConsiderable &&
53337a7e6055SDimitry Andric       performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
53347a7e6055SDimitry Andric                                   HasPromoted, TPT, SpeculativelyMovedExts))
53357a7e6055SDimitry Andric     return true;
53367a7e6055SDimitry Andric 
53377a7e6055SDimitry Andric   TPT.rollback(LastKnownGood);
53387a7e6055SDimitry Andric   return false;
53397a7e6055SDimitry Andric }
53407a7e6055SDimitry Andric 
53417a7e6055SDimitry Andric // Perform address type promotion if doing so is profitable.
53427a7e6055SDimitry Andric // If AllowPromotionWithoutCommonHeader == false, we should find other sext
53437a7e6055SDimitry Andric // instructions that sign extended the same initial value. However, if
53447a7e6055SDimitry Andric // AllowPromotionWithoutCommonHeader == true, we expect promoting the
53457a7e6055SDimitry Andric // extension is just profitable.
performAddressTypePromotion(Instruction * & Inst,bool AllowPromotionWithoutCommonHeader,bool HasPromoted,TypePromotionTransaction & TPT,SmallVectorImpl<Instruction * > & SpeculativelyMovedExts)53467a7e6055SDimitry Andric bool CodeGenPrepare::performAddressTypePromotion(
53477a7e6055SDimitry Andric     Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
53487a7e6055SDimitry Andric     bool HasPromoted, TypePromotionTransaction &TPT,
53497a7e6055SDimitry Andric     SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
53507a7e6055SDimitry Andric   bool Promoted = false;
53517a7e6055SDimitry Andric   SmallPtrSet<Instruction *, 1> UnhandledExts;
53527a7e6055SDimitry Andric   bool AllSeenFirst = true;
53537a7e6055SDimitry Andric   for (auto I : SpeculativelyMovedExts) {
53547a7e6055SDimitry Andric     Value *HeadOfChain = I->getOperand(0);
53557a7e6055SDimitry Andric     DenseMap<Value *, Instruction *>::iterator AlreadySeen =
53567a7e6055SDimitry Andric         SeenChainsForSExt.find(HeadOfChain);
53577a7e6055SDimitry Andric     // If there is an unhandled SExt which has the same header, try to promote
53587a7e6055SDimitry Andric     // it as well.
53597a7e6055SDimitry Andric     if (AlreadySeen != SeenChainsForSExt.end()) {
53607a7e6055SDimitry Andric       if (AlreadySeen->second != nullptr)
53617a7e6055SDimitry Andric         UnhandledExts.insert(AlreadySeen->second);
53627a7e6055SDimitry Andric       AllSeenFirst = false;
53637a7e6055SDimitry Andric     }
53647a7e6055SDimitry Andric   }
53657a7e6055SDimitry Andric 
53667a7e6055SDimitry Andric   if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
53677a7e6055SDimitry Andric                         SpeculativelyMovedExts.size() == 1)) {
53687a7e6055SDimitry Andric     TPT.commit();
53697a7e6055SDimitry Andric     if (HasPromoted)
53707a7e6055SDimitry Andric       Promoted = true;
53717a7e6055SDimitry Andric     for (auto I : SpeculativelyMovedExts) {
53727a7e6055SDimitry Andric       Value *HeadOfChain = I->getOperand(0);
53737a7e6055SDimitry Andric       SeenChainsForSExt[HeadOfChain] = nullptr;
53747a7e6055SDimitry Andric       ValToSExtendedUses[HeadOfChain].push_back(I);
53757a7e6055SDimitry Andric     }
53767a7e6055SDimitry Andric     // Update Inst as promotion happen.
53777a7e6055SDimitry Andric     Inst = SpeculativelyMovedExts.pop_back_val();
53787a7e6055SDimitry Andric   } else {
53797a7e6055SDimitry Andric     // This is the first chain visited from the header, keep the current chain
53807a7e6055SDimitry Andric     // as unhandled. Defer to promote this until we encounter another SExt
53817a7e6055SDimitry Andric     // chain derived from the same header.
53827a7e6055SDimitry Andric     for (auto I : SpeculativelyMovedExts) {
53837a7e6055SDimitry Andric       Value *HeadOfChain = I->getOperand(0);
53847a7e6055SDimitry Andric       SeenChainsForSExt[HeadOfChain] = Inst;
53857a7e6055SDimitry Andric     }
53867a7e6055SDimitry Andric     return false;
53877a7e6055SDimitry Andric   }
53887a7e6055SDimitry Andric 
53897a7e6055SDimitry Andric   if (!AllSeenFirst && !UnhandledExts.empty())
53907a7e6055SDimitry Andric     for (auto VisitedSExt : UnhandledExts) {
53917a7e6055SDimitry Andric       if (RemovedInsts.count(VisitedSExt))
53927a7e6055SDimitry Andric         continue;
53937a7e6055SDimitry Andric       TypePromotionTransaction TPT(RemovedInsts);
53947a7e6055SDimitry Andric       SmallVector<Instruction *, 1> Exts;
53957a7e6055SDimitry Andric       SmallVector<Instruction *, 2> Chains;
53967a7e6055SDimitry Andric       Exts.push_back(VisitedSExt);
53977a7e6055SDimitry Andric       bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
53987a7e6055SDimitry Andric       TPT.commit();
53997a7e6055SDimitry Andric       if (HasPromoted)
54007a7e6055SDimitry Andric         Promoted = true;
54017a7e6055SDimitry Andric       for (auto I : Chains) {
54027a7e6055SDimitry Andric         Value *HeadOfChain = I->getOperand(0);
54037a7e6055SDimitry Andric         // Mark this as handled.
54047a7e6055SDimitry Andric         SeenChainsForSExt[HeadOfChain] = nullptr;
54057a7e6055SDimitry Andric         ValToSExtendedUses[HeadOfChain].push_back(I);
54067a7e6055SDimitry Andric       }
54077a7e6055SDimitry Andric     }
54087a7e6055SDimitry Andric   return Promoted;
54097a7e6055SDimitry Andric }
54107a7e6055SDimitry Andric 
optimizeExtUses(Instruction * I)54117d523365SDimitry Andric bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
541291bc56edSDimitry Andric   BasicBlock *DefBB = I->getParent();
541391bc56edSDimitry Andric 
541491bc56edSDimitry Andric   // If the result of a {s|z}ext and its source are both live out, rewrite all
541591bc56edSDimitry Andric   // other uses of the source with result of extension.
541691bc56edSDimitry Andric   Value *Src = I->getOperand(0);
541791bc56edSDimitry Andric   if (Src->hasOneUse())
541891bc56edSDimitry Andric     return false;
541991bc56edSDimitry Andric 
542091bc56edSDimitry Andric   // Only do this xform if truncating is free.
542191bc56edSDimitry Andric   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
542291bc56edSDimitry Andric     return false;
542391bc56edSDimitry Andric 
542491bc56edSDimitry Andric   // Only safe to perform the optimization if the source is also defined in
542591bc56edSDimitry Andric   // this block.
542691bc56edSDimitry Andric   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
542791bc56edSDimitry Andric     return false;
542891bc56edSDimitry Andric 
542991bc56edSDimitry Andric   bool DefIsLiveOut = false;
543091bc56edSDimitry Andric   for (User *U : I->users()) {
543191bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
543291bc56edSDimitry Andric 
543391bc56edSDimitry Andric     // Figure out which BB this ext is used in.
543491bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
543591bc56edSDimitry Andric     if (UserBB == DefBB) continue;
543691bc56edSDimitry Andric     DefIsLiveOut = true;
543791bc56edSDimitry Andric     break;
543891bc56edSDimitry Andric   }
543991bc56edSDimitry Andric   if (!DefIsLiveOut)
544091bc56edSDimitry Andric     return false;
544191bc56edSDimitry Andric 
544291bc56edSDimitry Andric   // Make sure none of the uses are PHI nodes.
544391bc56edSDimitry Andric   for (User *U : Src->users()) {
544491bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
544591bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
544691bc56edSDimitry Andric     if (UserBB == DefBB) continue;
544791bc56edSDimitry Andric     // Be conservative. We don't want this xform to end up introducing
544891bc56edSDimitry Andric     // reloads just before load / store instructions.
544991bc56edSDimitry Andric     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
545091bc56edSDimitry Andric       return false;
545191bc56edSDimitry Andric   }
545291bc56edSDimitry Andric 
545391bc56edSDimitry Andric   // InsertedTruncs - Only insert one trunc in each block once.
545491bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
545591bc56edSDimitry Andric 
545691bc56edSDimitry Andric   bool MadeChange = false;
545791bc56edSDimitry Andric   for (Use &U : Src->uses()) {
545891bc56edSDimitry Andric     Instruction *User = cast<Instruction>(U.getUser());
545991bc56edSDimitry Andric 
546091bc56edSDimitry Andric     // Figure out which BB this ext is used in.
546191bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
546291bc56edSDimitry Andric     if (UserBB == DefBB) continue;
546391bc56edSDimitry Andric 
546491bc56edSDimitry Andric     // Both src and def are live in this block. Rewrite the use.
546591bc56edSDimitry Andric     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
546691bc56edSDimitry Andric 
546791bc56edSDimitry Andric     if (!InsertedTrunc) {
546891bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
54697d523365SDimitry Andric       assert(InsertPt != UserBB->end());
54707d523365SDimitry Andric       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
54718f0fd8f6SDimitry Andric       InsertedInsts.insert(InsertedTrunc);
547291bc56edSDimitry Andric     }
547391bc56edSDimitry Andric 
547491bc56edSDimitry Andric     // Replace a use of the {s|z}ext source with a use of the result.
547591bc56edSDimitry Andric     U = InsertedTrunc;
547691bc56edSDimitry Andric     ++NumExtUses;
547791bc56edSDimitry Andric     MadeChange = true;
547891bc56edSDimitry Andric   }
547991bc56edSDimitry Andric 
548091bc56edSDimitry Andric   return MadeChange;
548191bc56edSDimitry Andric }
548291bc56edSDimitry Andric 
54837d523365SDimitry Andric // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
54847d523365SDimitry Andric // just after the load if the target can fold this into one extload instruction,
54857d523365SDimitry Andric // with the hope of eliminating some of the other later "and" instructions using
54867d523365SDimitry Andric // the loaded value.  "and"s that are made trivially redundant by the insertion
54877d523365SDimitry Andric // of the new "and" are removed by this function, while others (e.g. those whose
54887d523365SDimitry Andric // path from the load goes through a phi) are left for isel to potentially
54897d523365SDimitry Andric // remove.
54907d523365SDimitry Andric //
54917d523365SDimitry Andric // For example:
54927d523365SDimitry Andric //
54937d523365SDimitry Andric // b0:
54947d523365SDimitry Andric //   x = load i32
54957d523365SDimitry Andric //   ...
54967d523365SDimitry Andric // b1:
54977d523365SDimitry Andric //   y = and x, 0xff
54987d523365SDimitry Andric //   z = use y
54997d523365SDimitry Andric //
55007d523365SDimitry Andric // becomes:
55017d523365SDimitry Andric //
55027d523365SDimitry Andric // b0:
55037d523365SDimitry Andric //   x = load i32
55047d523365SDimitry Andric //   x' = and x, 0xff
55057d523365SDimitry Andric //   ...
55067d523365SDimitry Andric // b1:
55077d523365SDimitry Andric //   z = use x'
55087d523365SDimitry Andric //
55097d523365SDimitry Andric // whereas:
55107d523365SDimitry Andric //
55117d523365SDimitry Andric // b0:
55127d523365SDimitry Andric //   x1 = load i32
55137d523365SDimitry Andric //   ...
55147d523365SDimitry Andric // b1:
55157d523365SDimitry Andric //   x2 = load i32
55167d523365SDimitry Andric //   ...
55177d523365SDimitry Andric // b2:
55187d523365SDimitry Andric //   x = phi x1, x2
55197d523365SDimitry Andric //   y = and x, 0xff
55207d523365SDimitry Andric //
55217d523365SDimitry Andric // becomes (after a call to optimizeLoadExt for each load):
55227d523365SDimitry Andric //
55237d523365SDimitry Andric // b0:
55247d523365SDimitry Andric //   x1 = load i32
55257d523365SDimitry Andric //   x1' = and x1, 0xff
55267d523365SDimitry Andric //   ...
55277d523365SDimitry Andric // b1:
55287d523365SDimitry Andric //   x2 = load i32
55297d523365SDimitry Andric //   x2' = and x2, 0xff
55307d523365SDimitry Andric //   ...
55317d523365SDimitry Andric // b2:
55327d523365SDimitry Andric //   x = phi x1', x2'
55337d523365SDimitry Andric //   y = and x, 0xff
optimizeLoadExt(LoadInst * Load)55347d523365SDimitry Andric bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
55354ba319b5SDimitry Andric   if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
55367d523365SDimitry Andric     return false;
55377d523365SDimitry Andric 
55387a7e6055SDimitry Andric   // Skip loads we've already transformed.
55397a7e6055SDimitry Andric   if (Load->hasOneUse() &&
55407a7e6055SDimitry Andric       InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
55417d523365SDimitry Andric     return false;
55427d523365SDimitry Andric 
55437d523365SDimitry Andric   // Look at all uses of Load, looking through phis, to determine how many bits
55447d523365SDimitry Andric   // of the loaded value are needed.
55457d523365SDimitry Andric   SmallVector<Instruction *, 8> WorkList;
55467d523365SDimitry Andric   SmallPtrSet<Instruction *, 16> Visited;
55477d523365SDimitry Andric   SmallVector<Instruction *, 8> AndsToMaybeRemove;
55487d523365SDimitry Andric   for (auto *U : Load->users())
55497d523365SDimitry Andric     WorkList.push_back(cast<Instruction>(U));
55507d523365SDimitry Andric 
55517d523365SDimitry Andric   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
55527d523365SDimitry Andric   unsigned BitWidth = LoadResultVT.getSizeInBits();
55537d523365SDimitry Andric   APInt DemandBits(BitWidth, 0);
55547d523365SDimitry Andric   APInt WidestAndBits(BitWidth, 0);
55557d523365SDimitry Andric 
55567d523365SDimitry Andric   while (!WorkList.empty()) {
55577d523365SDimitry Andric     Instruction *I = WorkList.back();
55587d523365SDimitry Andric     WorkList.pop_back();
55597d523365SDimitry Andric 
55607d523365SDimitry Andric     // Break use-def graph loops.
55617d523365SDimitry Andric     if (!Visited.insert(I).second)
55627d523365SDimitry Andric       continue;
55637d523365SDimitry Andric 
55647d523365SDimitry Andric     // For a PHI node, push all of its users.
55657d523365SDimitry Andric     if (auto *Phi = dyn_cast<PHINode>(I)) {
55667d523365SDimitry Andric       for (auto *U : Phi->users())
55677d523365SDimitry Andric         WorkList.push_back(cast<Instruction>(U));
55687d523365SDimitry Andric       continue;
55697d523365SDimitry Andric     }
55707d523365SDimitry Andric 
55717d523365SDimitry Andric     switch (I->getOpcode()) {
55722cab237bSDimitry Andric     case Instruction::And: {
55737d523365SDimitry Andric       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
55747d523365SDimitry Andric       if (!AndC)
55757d523365SDimitry Andric         return false;
55767d523365SDimitry Andric       APInt AndBits = AndC->getValue();
55777d523365SDimitry Andric       DemandBits |= AndBits;
55787d523365SDimitry Andric       // Keep track of the widest and mask we see.
55797d523365SDimitry Andric       if (AndBits.ugt(WidestAndBits))
55807d523365SDimitry Andric         WidestAndBits = AndBits;
55817d523365SDimitry Andric       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
55827d523365SDimitry Andric         AndsToMaybeRemove.push_back(I);
55837d523365SDimitry Andric       break;
55847d523365SDimitry Andric     }
55857d523365SDimitry Andric 
55862cab237bSDimitry Andric     case Instruction::Shl: {
55877d523365SDimitry Andric       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
55887d523365SDimitry Andric       if (!ShlC)
55897d523365SDimitry Andric         return false;
55907d523365SDimitry Andric       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
55916bc11b14SDimitry Andric       DemandBits.setLowBits(BitWidth - ShiftAmt);
55927d523365SDimitry Andric       break;
55937d523365SDimitry Andric     }
55947d523365SDimitry Andric 
55952cab237bSDimitry Andric     case Instruction::Trunc: {
55967d523365SDimitry Andric       EVT TruncVT = TLI->getValueType(*DL, I->getType());
55977d523365SDimitry Andric       unsigned TruncBitWidth = TruncVT.getSizeInBits();
55986bc11b14SDimitry Andric       DemandBits.setLowBits(TruncBitWidth);
55997d523365SDimitry Andric       break;
56007d523365SDimitry Andric     }
56017d523365SDimitry Andric 
56027d523365SDimitry Andric     default:
56037d523365SDimitry Andric       return false;
56047d523365SDimitry Andric     }
56057d523365SDimitry Andric   }
56067d523365SDimitry Andric 
56077d523365SDimitry Andric   uint32_t ActiveBits = DemandBits.getActiveBits();
56087d523365SDimitry Andric   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
56097d523365SDimitry Andric   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
56107d523365SDimitry Andric   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
56117d523365SDimitry Andric   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
56127d523365SDimitry Andric   // followed by an AND.
56137d523365SDimitry Andric   // TODO: Look into removing this restriction by fixing backends to either
56147d523365SDimitry Andric   // return false for isLoadExtLegal for i1 or have them select this pattern to
56157d523365SDimitry Andric   // a single instruction.
56167d523365SDimitry Andric   //
56177d523365SDimitry Andric   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
56187d523365SDimitry Andric   // mask, since these are the only ands that will be removed by isel.
56197a7e6055SDimitry Andric   if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
56207d523365SDimitry Andric       WidestAndBits != DemandBits)
56217d523365SDimitry Andric     return false;
56227d523365SDimitry Andric 
56237d523365SDimitry Andric   LLVMContext &Ctx = Load->getType()->getContext();
56247d523365SDimitry Andric   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
56257d523365SDimitry Andric   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
56267d523365SDimitry Andric 
56277d523365SDimitry Andric   // Reject cases that won't be matched as extloads.
56287d523365SDimitry Andric   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
56297d523365SDimitry Andric       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
56307d523365SDimitry Andric     return false;
56317d523365SDimitry Andric 
56327d523365SDimitry Andric   IRBuilder<> Builder(Load->getNextNode());
56337d523365SDimitry Andric   auto *NewAnd = dyn_cast<Instruction>(
56347d523365SDimitry Andric       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
56357a7e6055SDimitry Andric   // Mark this instruction as "inserted by CGP", so that other
56367a7e6055SDimitry Andric   // optimizations don't touch it.
56377a7e6055SDimitry Andric   InsertedInsts.insert(NewAnd);
56387d523365SDimitry Andric 
56397d523365SDimitry Andric   // Replace all uses of load with new and (except for the use of load in the
56407d523365SDimitry Andric   // new and itself).
56417d523365SDimitry Andric   Load->replaceAllUsesWith(NewAnd);
56427d523365SDimitry Andric   NewAnd->setOperand(0, Load);
56437d523365SDimitry Andric 
56447d523365SDimitry Andric   // Remove any and instructions that are now redundant.
56457d523365SDimitry Andric   for (auto *And : AndsToMaybeRemove)
56467d523365SDimitry Andric     // Check that the and mask is the same as the one we decided to put on the
56477d523365SDimitry Andric     // new and.
56487d523365SDimitry Andric     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
56497d523365SDimitry Andric       And->replaceAllUsesWith(NewAnd);
56507d523365SDimitry Andric       if (&*CurInstIterator == And)
56517d523365SDimitry Andric         CurInstIterator = std::next(And->getIterator());
56527d523365SDimitry Andric       And->eraseFromParent();
56537d523365SDimitry Andric       ++NumAndUses;
56547d523365SDimitry Andric     }
56557d523365SDimitry Andric 
56567d523365SDimitry Andric   ++NumAndsAdded;
56577d523365SDimitry Andric   return true;
56587d523365SDimitry Andric }
56597d523365SDimitry Andric 
56607d523365SDimitry Andric /// Check if V (an operand of a select instruction) is an expensive instruction
56617d523365SDimitry Andric /// that is only used once.
sinkSelectOperand(const TargetTransformInfo * TTI,Value * V)56627d523365SDimitry Andric static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
56637d523365SDimitry Andric   auto *I = dyn_cast<Instruction>(V);
56647d523365SDimitry Andric   // If it's safe to speculatively execute, then it should not have side
56657d523365SDimitry Andric   // effects; therefore, it's safe to sink and possibly *not* execute.
56667d523365SDimitry Andric   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
56677d523365SDimitry Andric          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
56687d523365SDimitry Andric }
56697d523365SDimitry Andric 
56707d523365SDimitry Andric /// Returns true if a SelectInst should be turned into an explicit branch.
isFormingBranchFromSelectProfitable(const TargetTransformInfo * TTI,const TargetLowering * TLI,SelectInst * SI)56717d523365SDimitry Andric static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
56723ca95b02SDimitry Andric                                                 const TargetLowering *TLI,
56737d523365SDimitry Andric                                                 SelectInst *SI) {
56743ca95b02SDimitry Andric   // If even a predictable select is cheap, then a branch can't be cheaper.
56753ca95b02SDimitry Andric   if (!TLI->isPredictableSelectExpensive())
56763ca95b02SDimitry Andric     return false;
56773ca95b02SDimitry Andric 
567891bc56edSDimitry Andric   // FIXME: This should use the same heuristics as IfConversion to determine
56793ca95b02SDimitry Andric   // whether a select is better represented as a branch.
56803ca95b02SDimitry Andric 
56813ca95b02SDimitry Andric   // If metadata tells us that the select condition is obviously predictable,
56823ca95b02SDimitry Andric   // then we want to replace the select with a branch.
56833ca95b02SDimitry Andric   uint64_t TrueWeight, FalseWeight;
56843ca95b02SDimitry Andric   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
56853ca95b02SDimitry Andric     uint64_t Max = std::max(TrueWeight, FalseWeight);
56863ca95b02SDimitry Andric     uint64_t Sum = TrueWeight + FalseWeight;
56873ca95b02SDimitry Andric     if (Sum != 0) {
56883ca95b02SDimitry Andric       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
56893ca95b02SDimitry Andric       if (Probability > TLI->getPredictableBranchThreshold())
56903ca95b02SDimitry Andric         return true;
56913ca95b02SDimitry Andric     }
56923ca95b02SDimitry Andric   }
569391bc56edSDimitry Andric 
569491bc56edSDimitry Andric   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
569591bc56edSDimitry Andric 
56967d523365SDimitry Andric   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
56977d523365SDimitry Andric   // comparison condition. If the compare has more than one use, there's
56987d523365SDimitry Andric   // probably another cmov or setcc around, so it's not worth emitting a branch.
56997d523365SDimitry Andric   if (!Cmp || !Cmp->hasOneUse())
570091bc56edSDimitry Andric     return false;
570191bc56edSDimitry Andric 
57027d523365SDimitry Andric   // If either operand of the select is expensive and only needed on one side
57037d523365SDimitry Andric   // of the select, we should form a branch.
57047d523365SDimitry Andric   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
57057d523365SDimitry Andric       sinkSelectOperand(TTI, SI->getFalseValue()))
57067d523365SDimitry Andric     return true;
57077d523365SDimitry Andric 
57087d523365SDimitry Andric   return false;
570991bc56edSDimitry Andric }
571091bc56edSDimitry Andric 
5711d88c1a5aSDimitry Andric /// If \p isTrue is true, return the true value of \p SI, otherwise return
5712d88c1a5aSDimitry Andric /// false value of \p SI. If the true/false value of \p SI is defined by any
5713d88c1a5aSDimitry Andric /// select instructions in \p Selects, look through the defining select
5714d88c1a5aSDimitry Andric /// instruction until the true/false value is not defined in \p Selects.
getTrueOrFalseValue(SelectInst * SI,bool isTrue,const SmallPtrSet<const Instruction *,2> & Selects)5715d88c1a5aSDimitry Andric static Value *getTrueOrFalseValue(
5716d88c1a5aSDimitry Andric     SelectInst *SI, bool isTrue,
5717d88c1a5aSDimitry Andric     const SmallPtrSet<const Instruction *, 2> &Selects) {
5718d88c1a5aSDimitry Andric   Value *V;
5719d88c1a5aSDimitry Andric 
5720d88c1a5aSDimitry Andric   for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5721d88c1a5aSDimitry Andric        DefSI = dyn_cast<SelectInst>(V)) {
5722d88c1a5aSDimitry Andric     assert(DefSI->getCondition() == SI->getCondition() &&
5723d88c1a5aSDimitry Andric            "The condition of DefSI does not match with SI");
5724d88c1a5aSDimitry Andric     V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5725d88c1a5aSDimitry Andric   }
5726d88c1a5aSDimitry Andric   return V;
5727d88c1a5aSDimitry Andric }
572891bc56edSDimitry Andric 
572991bc56edSDimitry Andric /// If we have a SelectInst that will likely profit from branch prediction,
573091bc56edSDimitry Andric /// turn it into a branch.
optimizeSelectInst(SelectInst * SI)57317d523365SDimitry Andric bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5732*b5893f02SDimitry Andric   // If branch conversion isn't desirable, exit early.
5733*b5893f02SDimitry Andric   if (DisableSelectToBranch || OptSize || !TLI)
5734*b5893f02SDimitry Andric     return false;
5735*b5893f02SDimitry Andric 
5736d88c1a5aSDimitry Andric   // Find all consecutive select instructions that share the same condition.
5737d88c1a5aSDimitry Andric   SmallVector<SelectInst *, 2> ASI;
5738d88c1a5aSDimitry Andric   ASI.push_back(SI);
5739d88c1a5aSDimitry Andric   for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5740d88c1a5aSDimitry Andric        It != SI->getParent()->end(); ++It) {
5741d88c1a5aSDimitry Andric     SelectInst *I = dyn_cast<SelectInst>(&*It);
5742d88c1a5aSDimitry Andric     if (I && SI->getCondition() == I->getCondition()) {
5743d88c1a5aSDimitry Andric       ASI.push_back(I);
5744d88c1a5aSDimitry Andric     } else {
5745d88c1a5aSDimitry Andric       break;
5746d88c1a5aSDimitry Andric     }
5747d88c1a5aSDimitry Andric   }
5748d88c1a5aSDimitry Andric 
5749d88c1a5aSDimitry Andric   SelectInst *LastSI = ASI.back();
5750d88c1a5aSDimitry Andric   // Increment the current iterator to skip all the rest of select instructions
5751d88c1a5aSDimitry Andric   // because they will be either "not lowered" or "all lowered" to branch.
5752d88c1a5aSDimitry Andric   CurInstIterator = std::next(LastSI->getIterator());
5753d88c1a5aSDimitry Andric 
575491bc56edSDimitry Andric   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
575591bc56edSDimitry Andric 
575691bc56edSDimitry Andric   // Can we convert the 'select' to CF ?
5757*b5893f02SDimitry Andric   if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
575891bc56edSDimitry Andric     return false;
575991bc56edSDimitry Andric 
576091bc56edSDimitry Andric   TargetLowering::SelectSupportKind SelectKind;
576191bc56edSDimitry Andric   if (VectorCond)
576291bc56edSDimitry Andric     SelectKind = TargetLowering::VectorMaskSelect;
576391bc56edSDimitry Andric   else if (SI->getType()->isVectorTy())
576491bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarCondVectorVal;
576591bc56edSDimitry Andric   else
576691bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarValSelect;
576791bc56edSDimitry Andric 
57683ca95b02SDimitry Andric   if (TLI->isSelectSupported(SelectKind) &&
57693ca95b02SDimitry Andric       !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
577091bc56edSDimitry Andric     return false;
577191bc56edSDimitry Andric 
577291bc56edSDimitry Andric   ModifiedDT = true;
577391bc56edSDimitry Andric 
57747d523365SDimitry Andric   // Transform a sequence like this:
57757d523365SDimitry Andric   //    start:
57767d523365SDimitry Andric   //       %cmp = cmp uge i32 %a, %b
57777d523365SDimitry Andric   //       %sel = select i1 %cmp, i32 %c, i32 %d
57787d523365SDimitry Andric   //
57797d523365SDimitry Andric   // Into:
57807d523365SDimitry Andric   //    start:
57817d523365SDimitry Andric   //       %cmp = cmp uge i32 %a, %b
57827d523365SDimitry Andric   //       br i1 %cmp, label %select.true, label %select.false
57837d523365SDimitry Andric   //    select.true:
57847d523365SDimitry Andric   //       br label %select.end
57857d523365SDimitry Andric   //    select.false:
57867d523365SDimitry Andric   //       br label %select.end
57877d523365SDimitry Andric   //    select.end:
57887d523365SDimitry Andric   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
57897d523365SDimitry Andric   //
57907d523365SDimitry Andric   // In addition, we may sink instructions that produce %c or %d from
57917d523365SDimitry Andric   // the entry block into the destination(s) of the new branch.
57927d523365SDimitry Andric   // If the true or false blocks do not contain a sunken instruction, that
57937d523365SDimitry Andric   // block and its branch may be optimized away. In that case, one side of the
57947d523365SDimitry Andric   // first branch will point directly to select.end, and the corresponding PHI
57957d523365SDimitry Andric   // predecessor block will be the start block.
57967d523365SDimitry Andric 
579791bc56edSDimitry Andric   // First, we split the block containing the select into 2 blocks.
579891bc56edSDimitry Andric   BasicBlock *StartBlock = SI->getParent();
5799d88c1a5aSDimitry Andric   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
58007d523365SDimitry Andric   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
580191bc56edSDimitry Andric 
58027d523365SDimitry Andric   // Delete the unconditional branch that was just created by the split.
580391bc56edSDimitry Andric   StartBlock->getTerminator()->eraseFromParent();
58047d523365SDimitry Andric 
58057d523365SDimitry Andric   // These are the new basic blocks for the conditional branch.
58067d523365SDimitry Andric   // At least one will become an actual new basic block.
58077d523365SDimitry Andric   BasicBlock *TrueBlock = nullptr;
58087d523365SDimitry Andric   BasicBlock *FalseBlock = nullptr;
5809d88c1a5aSDimitry Andric   BranchInst *TrueBranch = nullptr;
5810d88c1a5aSDimitry Andric   BranchInst *FalseBranch = nullptr;
58117d523365SDimitry Andric 
58127d523365SDimitry Andric   // Sink expensive instructions into the conditional blocks to avoid executing
58137d523365SDimitry Andric   // them speculatively.
5814d88c1a5aSDimitry Andric   for (SelectInst *SI : ASI) {
58157d523365SDimitry Andric     if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5816d88c1a5aSDimitry Andric       if (TrueBlock == nullptr) {
58177d523365SDimitry Andric         TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
58187d523365SDimitry Andric                                        EndBlock->getParent(), EndBlock);
5819d88c1a5aSDimitry Andric         TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5820*b5893f02SDimitry Andric         TrueBranch->setDebugLoc(SI->getDebugLoc());
5821d88c1a5aSDimitry Andric       }
58227d523365SDimitry Andric       auto *TrueInst = cast<Instruction>(SI->getTrueValue());
58237d523365SDimitry Andric       TrueInst->moveBefore(TrueBranch);
58247d523365SDimitry Andric     }
58257d523365SDimitry Andric     if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5826d88c1a5aSDimitry Andric       if (FalseBlock == nullptr) {
58277d523365SDimitry Andric         FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
58287d523365SDimitry Andric                                         EndBlock->getParent(), EndBlock);
5829d88c1a5aSDimitry Andric         FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5830*b5893f02SDimitry Andric         FalseBranch->setDebugLoc(SI->getDebugLoc());
5831d88c1a5aSDimitry Andric       }
58327d523365SDimitry Andric       auto *FalseInst = cast<Instruction>(SI->getFalseValue());
58337d523365SDimitry Andric       FalseInst->moveBefore(FalseBranch);
58347d523365SDimitry Andric     }
5835d88c1a5aSDimitry Andric   }
58367d523365SDimitry Andric 
58377d523365SDimitry Andric   // If there was nothing to sink, then arbitrarily choose the 'false' side
58387d523365SDimitry Andric   // for a new input value to the PHI.
58397d523365SDimitry Andric   if (TrueBlock == FalseBlock) {
58407d523365SDimitry Andric     assert(TrueBlock == nullptr &&
58417d523365SDimitry Andric            "Unexpected basic block transform while optimizing select");
58427d523365SDimitry Andric 
58437d523365SDimitry Andric     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
58447d523365SDimitry Andric                                     EndBlock->getParent(), EndBlock);
5845*b5893f02SDimitry Andric     auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5846*b5893f02SDimitry Andric     FalseBranch->setDebugLoc(SI->getDebugLoc());
58477d523365SDimitry Andric   }
584891bc56edSDimitry Andric 
584991bc56edSDimitry Andric   // Insert the real conditional branch based on the original condition.
58507d523365SDimitry Andric   // If we did not create a new block for one of the 'true' or 'false' paths
58517d523365SDimitry Andric   // of the condition, it means that side of the branch goes to the end block
58527d523365SDimitry Andric   // directly and the path originates from the start block from the point of
58537d523365SDimitry Andric   // view of the new PHI.
5854d88c1a5aSDimitry Andric   BasicBlock *TT, *FT;
58557d523365SDimitry Andric   if (TrueBlock == nullptr) {
5856d88c1a5aSDimitry Andric     TT = EndBlock;
5857d88c1a5aSDimitry Andric     FT = FalseBlock;
58587d523365SDimitry Andric     TrueBlock = StartBlock;
58597d523365SDimitry Andric   } else if (FalseBlock == nullptr) {
5860d88c1a5aSDimitry Andric     TT = TrueBlock;
5861d88c1a5aSDimitry Andric     FT = EndBlock;
58627d523365SDimitry Andric     FalseBlock = StartBlock;
58637d523365SDimitry Andric   } else {
5864d88c1a5aSDimitry Andric     TT = TrueBlock;
5865d88c1a5aSDimitry Andric     FT = FalseBlock;
58667d523365SDimitry Andric   }
5867d88c1a5aSDimitry Andric   IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
586891bc56edSDimitry Andric 
5869d88c1a5aSDimitry Andric   SmallPtrSet<const Instruction *, 2> INS;
5870d88c1a5aSDimitry Andric   INS.insert(ASI.begin(), ASI.end());
5871d88c1a5aSDimitry Andric   // Use reverse iterator because later select may use the value of the
5872d88c1a5aSDimitry Andric   // earlier select, and we need to propagate value through earlier select
5873d88c1a5aSDimitry Andric   // to get the PHI operand.
5874d88c1a5aSDimitry Andric   for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5875d88c1a5aSDimitry Andric     SelectInst *SI = *It;
587691bc56edSDimitry Andric     // The select itself is replaced with a PHI Node.
58777d523365SDimitry Andric     PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
587891bc56edSDimitry Andric     PN->takeName(SI);
5879d88c1a5aSDimitry Andric     PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5880d88c1a5aSDimitry Andric     PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
5881*b5893f02SDimitry Andric     PN->setDebugLoc(SI->getDebugLoc());
58827d523365SDimitry Andric 
588391bc56edSDimitry Andric     SI->replaceAllUsesWith(PN);
588491bc56edSDimitry Andric     SI->eraseFromParent();
5885d88c1a5aSDimitry Andric     INS.erase(SI);
5886d88c1a5aSDimitry Andric     ++NumSelectsExpanded;
5887d88c1a5aSDimitry Andric   }
588891bc56edSDimitry Andric 
588991bc56edSDimitry Andric   // Instruct OptimizeBlock to skip to the next block.
589091bc56edSDimitry Andric   CurInstIterator = StartBlock->end();
589191bc56edSDimitry Andric   return true;
589291bc56edSDimitry Andric }
589391bc56edSDimitry Andric 
isBroadcastShuffle(ShuffleVectorInst * SVI)589491bc56edSDimitry Andric static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
589591bc56edSDimitry Andric   SmallVector<int, 16> Mask(SVI->getShuffleMask());
589691bc56edSDimitry Andric   int SplatElem = -1;
589791bc56edSDimitry Andric   for (unsigned i = 0; i < Mask.size(); ++i) {
589891bc56edSDimitry Andric     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
589991bc56edSDimitry Andric       return false;
590091bc56edSDimitry Andric     SplatElem = Mask[i];
590191bc56edSDimitry Andric   }
590291bc56edSDimitry Andric 
590391bc56edSDimitry Andric   return true;
590491bc56edSDimitry Andric }
590591bc56edSDimitry Andric 
590691bc56edSDimitry Andric /// Some targets have expensive vector shifts if the lanes aren't all the same
590791bc56edSDimitry Andric /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
590891bc56edSDimitry Andric /// it's often worth sinking a shufflevector splat down to its use so that
590991bc56edSDimitry Andric /// codegen can spot all lanes are identical.
optimizeShuffleVectorInst(ShuffleVectorInst * SVI)59107d523365SDimitry Andric bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
591191bc56edSDimitry Andric   BasicBlock *DefBB = SVI->getParent();
591291bc56edSDimitry Andric 
591391bc56edSDimitry Andric   // Only do this xform if variable vector shifts are particularly expensive.
591491bc56edSDimitry Andric   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
591591bc56edSDimitry Andric     return false;
591691bc56edSDimitry Andric 
591791bc56edSDimitry Andric   // We only expect better codegen by sinking a shuffle if we can recognise a
591891bc56edSDimitry Andric   // constant splat.
591991bc56edSDimitry Andric   if (!isBroadcastShuffle(SVI))
592091bc56edSDimitry Andric     return false;
592191bc56edSDimitry Andric 
592291bc56edSDimitry Andric   // InsertedShuffles - Only insert a shuffle in each block once.
592391bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
592491bc56edSDimitry Andric 
592591bc56edSDimitry Andric   bool MadeChange = false;
592691bc56edSDimitry Andric   for (User *U : SVI->users()) {
592791bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
592891bc56edSDimitry Andric 
592991bc56edSDimitry Andric     // Figure out which BB this ext is used in.
593091bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
593191bc56edSDimitry Andric     if (UserBB == DefBB) continue;
593291bc56edSDimitry Andric 
593391bc56edSDimitry Andric     // For now only apply this when the splat is used by a shift instruction.
593491bc56edSDimitry Andric     if (!UI->isShift()) continue;
593591bc56edSDimitry Andric 
593691bc56edSDimitry Andric     // Everything checks out, sink the shuffle if the user's block doesn't
593791bc56edSDimitry Andric     // already have a copy.
593891bc56edSDimitry Andric     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
593991bc56edSDimitry Andric 
594091bc56edSDimitry Andric     if (!InsertedShuffle) {
594191bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
59427d523365SDimitry Andric       assert(InsertPt != UserBB->end());
59437d523365SDimitry Andric       InsertedShuffle =
59447d523365SDimitry Andric           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
59457d523365SDimitry Andric                                 SVI->getOperand(2), "", &*InsertPt);
594691bc56edSDimitry Andric     }
594791bc56edSDimitry Andric 
594891bc56edSDimitry Andric     UI->replaceUsesOfWith(SVI, InsertedShuffle);
594991bc56edSDimitry Andric     MadeChange = true;
595091bc56edSDimitry Andric   }
595191bc56edSDimitry Andric 
595291bc56edSDimitry Andric   // If we removed all uses, nuke the shuffle.
595391bc56edSDimitry Andric   if (SVI->use_empty()) {
595491bc56edSDimitry Andric     SVI->eraseFromParent();
595591bc56edSDimitry Andric     MadeChange = true;
595691bc56edSDimitry Andric   }
595791bc56edSDimitry Andric 
595891bc56edSDimitry Andric   return MadeChange;
595991bc56edSDimitry Andric }
596091bc56edSDimitry Andric 
optimizeSwitchInst(SwitchInst * SI)59617d523365SDimitry Andric bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
59627d523365SDimitry Andric   if (!TLI || !DL)
59637d523365SDimitry Andric     return false;
59647d523365SDimitry Andric 
59657d523365SDimitry Andric   Value *Cond = SI->getCondition();
59667d523365SDimitry Andric   Type *OldType = Cond->getType();
59677d523365SDimitry Andric   LLVMContext &Context = Cond->getContext();
59687d523365SDimitry Andric   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
59697d523365SDimitry Andric   unsigned RegWidth = RegType.getSizeInBits();
59707d523365SDimitry Andric 
59717d523365SDimitry Andric   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
59727d523365SDimitry Andric     return false;
59737d523365SDimitry Andric 
59747d523365SDimitry Andric   // If the register width is greater than the type width, expand the condition
59757d523365SDimitry Andric   // of the switch instruction and each case constant to the width of the
59767d523365SDimitry Andric   // register. By widening the type of the switch condition, subsequent
59777d523365SDimitry Andric   // comparisons (for case comparisons) will not need to be extended to the
59787d523365SDimitry Andric   // preferred register width, so we will potentially eliminate N-1 extends,
59797d523365SDimitry Andric   // where N is the number of cases in the switch.
59807d523365SDimitry Andric   auto *NewType = Type::getIntNTy(Context, RegWidth);
59817d523365SDimitry Andric 
59827d523365SDimitry Andric   // Zero-extend the switch condition and case constants unless the switch
59837d523365SDimitry Andric   // condition is a function argument that is already being sign-extended.
59847d523365SDimitry Andric   // In that case, we can avoid an unnecessary mask/extension by sign-extending
59857d523365SDimitry Andric   // everything instead.
59867d523365SDimitry Andric   Instruction::CastOps ExtType = Instruction::ZExt;
59877d523365SDimitry Andric   if (auto *Arg = dyn_cast<Argument>(Cond))
59887d523365SDimitry Andric     if (Arg->hasSExtAttr())
59897d523365SDimitry Andric       ExtType = Instruction::SExt;
59907d523365SDimitry Andric 
59917d523365SDimitry Andric   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
59927d523365SDimitry Andric   ExtInst->insertBefore(SI);
5993*b5893f02SDimitry Andric   ExtInst->setDebugLoc(SI->getDebugLoc());
59947d523365SDimitry Andric   SI->setCondition(ExtInst);
59957a7e6055SDimitry Andric   for (auto Case : SI->cases()) {
59967d523365SDimitry Andric     APInt NarrowConst = Case.getCaseValue()->getValue();
59977d523365SDimitry Andric     APInt WideConst = (ExtType == Instruction::ZExt) ?
59987d523365SDimitry Andric                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
59997d523365SDimitry Andric     Case.setValue(ConstantInt::get(Context, WideConst));
60007d523365SDimitry Andric   }
60017d523365SDimitry Andric 
60027d523365SDimitry Andric   return true;
60037d523365SDimitry Andric }
60047d523365SDimitry Andric 
6005f9448bf3SDimitry Andric 
600639d628a0SDimitry Andric namespace {
60072cab237bSDimitry Andric 
60084ba319b5SDimitry Andric /// Helper class to promote a scalar operation to a vector one.
600939d628a0SDimitry Andric /// This class is used to move downward extractelement transition.
601039d628a0SDimitry Andric /// E.g.,
601139d628a0SDimitry Andric /// a = vector_op <2 x i32>
601239d628a0SDimitry Andric /// b = extractelement <2 x i32> a, i32 0
601339d628a0SDimitry Andric /// c = scalar_op b
601439d628a0SDimitry Andric /// store c
601539d628a0SDimitry Andric ///
601639d628a0SDimitry Andric /// =>
601739d628a0SDimitry Andric /// a = vector_op <2 x i32>
601839d628a0SDimitry Andric /// c = vector_op a (equivalent to scalar_op on the related lane)
601939d628a0SDimitry Andric /// * d = extractelement <2 x i32> c, i32 0
602039d628a0SDimitry Andric /// * store d
602139d628a0SDimitry Andric /// Assuming both extractelement and store can be combine, we get rid of the
602239d628a0SDimitry Andric /// transition.
602339d628a0SDimitry Andric class VectorPromoteHelper {
6024875ed548SDimitry Andric   /// DataLayout associated with the current module.
6025875ed548SDimitry Andric   const DataLayout &DL;
6026875ed548SDimitry Andric 
602739d628a0SDimitry Andric   /// Used to perform some checks on the legality of vector operations.
602839d628a0SDimitry Andric   const TargetLowering &TLI;
602939d628a0SDimitry Andric 
603039d628a0SDimitry Andric   /// Used to estimated the cost of the promoted chain.
603139d628a0SDimitry Andric   const TargetTransformInfo &TTI;
603239d628a0SDimitry Andric 
603339d628a0SDimitry Andric   /// The transition being moved downwards.
603439d628a0SDimitry Andric   Instruction *Transition;
60352cab237bSDimitry Andric 
603639d628a0SDimitry Andric   /// The sequence of instructions to be promoted.
603739d628a0SDimitry Andric   SmallVector<Instruction *, 4> InstsToBePromoted;
60382cab237bSDimitry Andric 
603939d628a0SDimitry Andric   /// Cost of combining a store and an extract.
604039d628a0SDimitry Andric   unsigned StoreExtractCombineCost;
60412cab237bSDimitry Andric 
604239d628a0SDimitry Andric   /// Instruction that will be combined with the transition.
60432cab237bSDimitry Andric   Instruction *CombineInst = nullptr;
604439d628a0SDimitry Andric 
60454ba319b5SDimitry Andric   /// The instruction that represents the current end of the transition.
604639d628a0SDimitry Andric   /// Since we are faking the promotion until we reach the end of the chain
604739d628a0SDimitry Andric   /// of computation, we need a way to get the current end of the transition.
getEndOfTransition() const604839d628a0SDimitry Andric   Instruction *getEndOfTransition() const {
604939d628a0SDimitry Andric     if (InstsToBePromoted.empty())
605039d628a0SDimitry Andric       return Transition;
605139d628a0SDimitry Andric     return InstsToBePromoted.back();
605239d628a0SDimitry Andric   }
605339d628a0SDimitry Andric 
60544ba319b5SDimitry Andric   /// Return the index of the original value in the transition.
605539d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
605639d628a0SDimitry Andric   /// c, is at index 0.
getTransitionOriginalValueIdx() const605739d628a0SDimitry Andric   unsigned getTransitionOriginalValueIdx() const {
605839d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
605939d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
606039d628a0SDimitry Andric     return 0;
606139d628a0SDimitry Andric   }
606239d628a0SDimitry Andric 
60634ba319b5SDimitry Andric   /// Return the index of the index in the transition.
606439d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
606539d628a0SDimitry Andric   /// is at index 1.
getTransitionIdx() const606639d628a0SDimitry Andric   unsigned getTransitionIdx() const {
606739d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
606839d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
606939d628a0SDimitry Andric     return 1;
607039d628a0SDimitry Andric   }
607139d628a0SDimitry Andric 
60724ba319b5SDimitry Andric   /// Get the type of the transition.
607339d628a0SDimitry Andric   /// This is the type of the original value.
607439d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
607539d628a0SDimitry Andric   /// transition is <2 x i32>.
getTransitionType() const607639d628a0SDimitry Andric   Type *getTransitionType() const {
607739d628a0SDimitry Andric     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
607839d628a0SDimitry Andric   }
607939d628a0SDimitry Andric 
60804ba319b5SDimitry Andric   /// Promote \p ToBePromoted by moving \p Def downward through.
608139d628a0SDimitry Andric   /// I.e., we have the following sequence:
608239d628a0SDimitry Andric   /// Def = Transition <ty1> a to <ty2>
608339d628a0SDimitry Andric   /// b = ToBePromoted <ty2> Def, ...
608439d628a0SDimitry Andric   /// =>
608539d628a0SDimitry Andric   /// b = ToBePromoted <ty1> a, ...
608639d628a0SDimitry Andric   /// Def = Transition <ty1> ToBePromoted to <ty2>
608739d628a0SDimitry Andric   void promoteImpl(Instruction *ToBePromoted);
608839d628a0SDimitry Andric 
60894ba319b5SDimitry Andric   /// Check whether or not it is profitable to promote all the
609039d628a0SDimitry Andric   /// instructions enqueued to be promoted.
isProfitableToPromote()609139d628a0SDimitry Andric   bool isProfitableToPromote() {
609239d628a0SDimitry Andric     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
609339d628a0SDimitry Andric     unsigned Index = isa<ConstantInt>(ValIdx)
609439d628a0SDimitry Andric                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
609539d628a0SDimitry Andric                          : -1;
609639d628a0SDimitry Andric     Type *PromotedType = getTransitionType();
609739d628a0SDimitry Andric 
609839d628a0SDimitry Andric     StoreInst *ST = cast<StoreInst>(CombineInst);
609939d628a0SDimitry Andric     unsigned AS = ST->getPointerAddressSpace();
610039d628a0SDimitry Andric     unsigned Align = ST->getAlignment();
610139d628a0SDimitry Andric     // Check if this store is supported.
610239d628a0SDimitry Andric     if (!TLI.allowsMisalignedMemoryAccesses(
6103875ed548SDimitry Andric             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6104875ed548SDimitry Andric             Align)) {
610539d628a0SDimitry Andric       // If this is not supported, there is no way we can combine
610639d628a0SDimitry Andric       // the extract with the store.
610739d628a0SDimitry Andric       return false;
610839d628a0SDimitry Andric     }
610939d628a0SDimitry Andric 
611039d628a0SDimitry Andric     // The scalar chain of computation has to pay for the transition
611139d628a0SDimitry Andric     // scalar to vector.
611239d628a0SDimitry Andric     // The vector chain has to account for the combining cost.
611339d628a0SDimitry Andric     uint64_t ScalarCost =
611439d628a0SDimitry Andric         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
611539d628a0SDimitry Andric     uint64_t VectorCost = StoreExtractCombineCost;
611639d628a0SDimitry Andric     for (const auto &Inst : InstsToBePromoted) {
611739d628a0SDimitry Andric       // Compute the cost.
611839d628a0SDimitry Andric       // By construction, all instructions being promoted are arithmetic ones.
611939d628a0SDimitry Andric       // Moreover, one argument is a constant that can be viewed as a splat
612039d628a0SDimitry Andric       // constant.
612139d628a0SDimitry Andric       Value *Arg0 = Inst->getOperand(0);
612239d628a0SDimitry Andric       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
612339d628a0SDimitry Andric                             isa<ConstantFP>(Arg0);
612439d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg0OVK =
612539d628a0SDimitry Andric           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
612639d628a0SDimitry Andric                          : TargetTransformInfo::OK_AnyValue;
612739d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg1OVK =
612839d628a0SDimitry Andric           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
612939d628a0SDimitry Andric                           : TargetTransformInfo::OK_AnyValue;
613039d628a0SDimitry Andric       ScalarCost += TTI.getArithmeticInstrCost(
613139d628a0SDimitry Andric           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
613239d628a0SDimitry Andric       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
613339d628a0SDimitry Andric                                                Arg0OVK, Arg1OVK);
613439d628a0SDimitry Andric     }
61354ba319b5SDimitry Andric     LLVM_DEBUG(
61364ba319b5SDimitry Andric         dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
613739d628a0SDimitry Andric                << ScalarCost << "\nVector: " << VectorCost << '\n');
613839d628a0SDimitry Andric     return ScalarCost > VectorCost;
613939d628a0SDimitry Andric   }
614039d628a0SDimitry Andric 
61414ba319b5SDimitry Andric   /// Generate a constant vector with \p Val with the same
614239d628a0SDimitry Andric   /// number of elements as the transition.
614339d628a0SDimitry Andric   /// \p UseSplat defines whether or not \p Val should be replicated
61447d523365SDimitry Andric   /// across the whole vector.
614539d628a0SDimitry Andric   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
614639d628a0SDimitry Andric   /// otherwise we generate a vector with as many undef as possible:
614739d628a0SDimitry Andric   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
614839d628a0SDimitry Andric   /// used at the index of the extract.
getConstantVector(Constant * Val,bool UseSplat) const614939d628a0SDimitry Andric   Value *getConstantVector(Constant *Val, bool UseSplat) const {
61502cab237bSDimitry Andric     unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
615139d628a0SDimitry Andric     if (!UseSplat) {
615239d628a0SDimitry Andric       // If we cannot determine where the constant must be, we have to
615339d628a0SDimitry Andric       // use a splat constant.
615439d628a0SDimitry Andric       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
615539d628a0SDimitry Andric       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
615639d628a0SDimitry Andric         ExtractIdx = CstVal->getSExtValue();
615739d628a0SDimitry Andric       else
615839d628a0SDimitry Andric         UseSplat = true;
615939d628a0SDimitry Andric     }
616039d628a0SDimitry Andric 
616139d628a0SDimitry Andric     unsigned End = getTransitionType()->getVectorNumElements();
616239d628a0SDimitry Andric     if (UseSplat)
616339d628a0SDimitry Andric       return ConstantVector::getSplat(End, Val);
616439d628a0SDimitry Andric 
616539d628a0SDimitry Andric     SmallVector<Constant *, 4> ConstVec;
616639d628a0SDimitry Andric     UndefValue *UndefVal = UndefValue::get(Val->getType());
616739d628a0SDimitry Andric     for (unsigned Idx = 0; Idx != End; ++Idx) {
616839d628a0SDimitry Andric       if (Idx == ExtractIdx)
616939d628a0SDimitry Andric         ConstVec.push_back(Val);
617039d628a0SDimitry Andric       else
617139d628a0SDimitry Andric         ConstVec.push_back(UndefVal);
617239d628a0SDimitry Andric     }
617339d628a0SDimitry Andric     return ConstantVector::get(ConstVec);
617439d628a0SDimitry Andric   }
617539d628a0SDimitry Andric 
61764ba319b5SDimitry Andric   /// Check if promoting to a vector type an operand at \p OperandIdx
617739d628a0SDimitry Andric   /// in \p Use can trigger undefined behavior.
canCauseUndefinedBehavior(const Instruction * Use,unsigned OperandIdx)617839d628a0SDimitry Andric   static bool canCauseUndefinedBehavior(const Instruction *Use,
617939d628a0SDimitry Andric                                         unsigned OperandIdx) {
618039d628a0SDimitry Andric     // This is not safe to introduce undef when the operand is on
618139d628a0SDimitry Andric     // the right hand side of a division-like instruction.
618239d628a0SDimitry Andric     if (OperandIdx != 1)
618339d628a0SDimitry Andric       return false;
618439d628a0SDimitry Andric     switch (Use->getOpcode()) {
618539d628a0SDimitry Andric     default:
618639d628a0SDimitry Andric       return false;
618739d628a0SDimitry Andric     case Instruction::SDiv:
618839d628a0SDimitry Andric     case Instruction::UDiv:
618939d628a0SDimitry Andric     case Instruction::SRem:
619039d628a0SDimitry Andric     case Instruction::URem:
619139d628a0SDimitry Andric       return true;
619239d628a0SDimitry Andric     case Instruction::FDiv:
619339d628a0SDimitry Andric     case Instruction::FRem:
619439d628a0SDimitry Andric       return !Use->hasNoNaNs();
619539d628a0SDimitry Andric     }
619639d628a0SDimitry Andric     llvm_unreachable(nullptr);
619739d628a0SDimitry Andric   }
619839d628a0SDimitry Andric 
619939d628a0SDimitry Andric public:
VectorPromoteHelper(const DataLayout & DL,const TargetLowering & TLI,const TargetTransformInfo & TTI,Instruction * Transition,unsigned CombineCost)6200875ed548SDimitry Andric   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6201875ed548SDimitry Andric                       const TargetTransformInfo &TTI, Instruction *Transition,
6202875ed548SDimitry Andric                       unsigned CombineCost)
6203875ed548SDimitry Andric       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
62042cab237bSDimitry Andric         StoreExtractCombineCost(CombineCost) {
620539d628a0SDimitry Andric     assert(Transition && "Do not know how to promote null");
620639d628a0SDimitry Andric   }
620739d628a0SDimitry Andric 
62084ba319b5SDimitry Andric   /// Check if we can promote \p ToBePromoted to \p Type.
canPromote(const Instruction * ToBePromoted) const620939d628a0SDimitry Andric   bool canPromote(const Instruction *ToBePromoted) const {
621039d628a0SDimitry Andric     // We could support CastInst too.
621139d628a0SDimitry Andric     return isa<BinaryOperator>(ToBePromoted);
621239d628a0SDimitry Andric   }
621339d628a0SDimitry Andric 
62144ba319b5SDimitry Andric   /// Check if it is profitable to promote \p ToBePromoted
621539d628a0SDimitry Andric   /// by moving downward the transition through.
shouldPromote(const Instruction * ToBePromoted) const621639d628a0SDimitry Andric   bool shouldPromote(const Instruction *ToBePromoted) const {
621739d628a0SDimitry Andric     // Promote only if all the operands can be statically expanded.
621839d628a0SDimitry Andric     // Indeed, we do not want to introduce any new kind of transitions.
621939d628a0SDimitry Andric     for (const Use &U : ToBePromoted->operands()) {
622039d628a0SDimitry Andric       const Value *Val = U.get();
622139d628a0SDimitry Andric       if (Val == getEndOfTransition()) {
622239d628a0SDimitry Andric         // If the use is a division and the transition is on the rhs,
622339d628a0SDimitry Andric         // we cannot promote the operation, otherwise we may create a
622439d628a0SDimitry Andric         // division by zero.
622539d628a0SDimitry Andric         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
622639d628a0SDimitry Andric           return false;
622739d628a0SDimitry Andric         continue;
622839d628a0SDimitry Andric       }
622939d628a0SDimitry Andric       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
623039d628a0SDimitry Andric           !isa<ConstantFP>(Val))
623139d628a0SDimitry Andric         return false;
623239d628a0SDimitry Andric     }
623339d628a0SDimitry Andric     // Check that the resulting operation is legal.
623439d628a0SDimitry Andric     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
623539d628a0SDimitry Andric     if (!ISDOpcode)
623639d628a0SDimitry Andric       return false;
623739d628a0SDimitry Andric     return StressStoreExtract ||
623839d628a0SDimitry Andric            TLI.isOperationLegalOrCustom(
6239875ed548SDimitry Andric                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
624039d628a0SDimitry Andric   }
624139d628a0SDimitry Andric 
62424ba319b5SDimitry Andric   /// Check whether or not \p Use can be combined
624339d628a0SDimitry Andric   /// with the transition.
624439d628a0SDimitry Andric   /// I.e., is it possible to do Use(Transition) => AnotherUse?
canCombine(const Instruction * Use)624539d628a0SDimitry Andric   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
624639d628a0SDimitry Andric 
62474ba319b5SDimitry Andric   /// Record \p ToBePromoted as part of the chain to be promoted.
enqueueForPromotion(Instruction * ToBePromoted)624839d628a0SDimitry Andric   void enqueueForPromotion(Instruction *ToBePromoted) {
624939d628a0SDimitry Andric     InstsToBePromoted.push_back(ToBePromoted);
625039d628a0SDimitry Andric   }
625139d628a0SDimitry Andric 
62524ba319b5SDimitry Andric   /// Set the instruction that will be combined with the transition.
recordCombineInstruction(Instruction * ToBeCombined)625339d628a0SDimitry Andric   void recordCombineInstruction(Instruction *ToBeCombined) {
625439d628a0SDimitry Andric     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
625539d628a0SDimitry Andric     CombineInst = ToBeCombined;
625639d628a0SDimitry Andric   }
625739d628a0SDimitry Andric 
62584ba319b5SDimitry Andric   /// Promote all the instructions enqueued for promotion if it is
625939d628a0SDimitry Andric   /// is profitable.
626039d628a0SDimitry Andric   /// \return True if the promotion happened, false otherwise.
promote()626139d628a0SDimitry Andric   bool promote() {
626239d628a0SDimitry Andric     // Check if there is something to promote.
626339d628a0SDimitry Andric     // Right now, if we do not have anything to combine with,
626439d628a0SDimitry Andric     // we assume the promotion is not profitable.
626539d628a0SDimitry Andric     if (InstsToBePromoted.empty() || !CombineInst)
626639d628a0SDimitry Andric       return false;
626739d628a0SDimitry Andric 
626839d628a0SDimitry Andric     // Check cost.
626939d628a0SDimitry Andric     if (!StressStoreExtract && !isProfitableToPromote())
627039d628a0SDimitry Andric       return false;
627139d628a0SDimitry Andric 
627239d628a0SDimitry Andric     // Promote.
627339d628a0SDimitry Andric     for (auto &ToBePromoted : InstsToBePromoted)
627439d628a0SDimitry Andric       promoteImpl(ToBePromoted);
627539d628a0SDimitry Andric     InstsToBePromoted.clear();
627639d628a0SDimitry Andric     return true;
627739d628a0SDimitry Andric   }
627839d628a0SDimitry Andric };
62792cab237bSDimitry Andric 
62802cab237bSDimitry Andric } // end anonymous namespace
628139d628a0SDimitry Andric 
promoteImpl(Instruction * ToBePromoted)628239d628a0SDimitry Andric void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
628339d628a0SDimitry Andric   // At this point, we know that all the operands of ToBePromoted but Def
628439d628a0SDimitry Andric   // can be statically promoted.
628539d628a0SDimitry Andric   // For Def, we need to use its parameter in ToBePromoted:
628639d628a0SDimitry Andric   // b = ToBePromoted ty1 a
628739d628a0SDimitry Andric   // Def = Transition ty1 b to ty2
628839d628a0SDimitry Andric   // Move the transition down.
628939d628a0SDimitry Andric   // 1. Replace all uses of the promoted operation by the transition.
629039d628a0SDimitry Andric   // = ... b => = ... Def.
629139d628a0SDimitry Andric   assert(ToBePromoted->getType() == Transition->getType() &&
629239d628a0SDimitry Andric          "The type of the result of the transition does not match "
629339d628a0SDimitry Andric          "the final type");
629439d628a0SDimitry Andric   ToBePromoted->replaceAllUsesWith(Transition);
629539d628a0SDimitry Andric   // 2. Update the type of the uses.
629639d628a0SDimitry Andric   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
629739d628a0SDimitry Andric   Type *TransitionTy = getTransitionType();
629839d628a0SDimitry Andric   ToBePromoted->mutateType(TransitionTy);
629939d628a0SDimitry Andric   // 3. Update all the operands of the promoted operation with promoted
630039d628a0SDimitry Andric   // operands.
630139d628a0SDimitry Andric   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
630239d628a0SDimitry Andric   for (Use &U : ToBePromoted->operands()) {
630339d628a0SDimitry Andric     Value *Val = U.get();
630439d628a0SDimitry Andric     Value *NewVal = nullptr;
630539d628a0SDimitry Andric     if (Val == Transition)
630639d628a0SDimitry Andric       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
630739d628a0SDimitry Andric     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
630839d628a0SDimitry Andric              isa<ConstantFP>(Val)) {
630939d628a0SDimitry Andric       // Use a splat constant if it is not safe to use undef.
631039d628a0SDimitry Andric       NewVal = getConstantVector(
631139d628a0SDimitry Andric           cast<Constant>(Val),
631239d628a0SDimitry Andric           isa<UndefValue>(Val) ||
631339d628a0SDimitry Andric               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
631439d628a0SDimitry Andric     } else
631539d628a0SDimitry Andric       llvm_unreachable("Did you modified shouldPromote and forgot to update "
631639d628a0SDimitry Andric                        "this?");
631739d628a0SDimitry Andric     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
631839d628a0SDimitry Andric   }
63192cab237bSDimitry Andric   Transition->moveAfter(ToBePromoted);
632039d628a0SDimitry Andric   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
632139d628a0SDimitry Andric }
632239d628a0SDimitry Andric 
632339d628a0SDimitry Andric /// Some targets can do store(extractelement) with one instruction.
632439d628a0SDimitry Andric /// Try to push the extractelement towards the stores when the target
632539d628a0SDimitry Andric /// has this feature and this is profitable.
optimizeExtractElementInst(Instruction * Inst)63267d523365SDimitry Andric bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
63272cab237bSDimitry Andric   unsigned CombineCost = std::numeric_limits<unsigned>::max();
632839d628a0SDimitry Andric   if (DisableStoreExtract || !TLI ||
632939d628a0SDimitry Andric       (!StressStoreExtract &&
633039d628a0SDimitry Andric        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
633139d628a0SDimitry Andric                                        Inst->getOperand(1), CombineCost)))
633239d628a0SDimitry Andric     return false;
633339d628a0SDimitry Andric 
633439d628a0SDimitry Andric   // At this point we know that Inst is a vector to scalar transition.
633539d628a0SDimitry Andric   // Try to move it down the def-use chain, until:
633639d628a0SDimitry Andric   // - We can combine the transition with its single use
633739d628a0SDimitry Andric   //   => we got rid of the transition.
633839d628a0SDimitry Andric   // - We escape the current basic block
633939d628a0SDimitry Andric   //   => we would need to check that we are moving it at a cheaper place and
634039d628a0SDimitry Andric   //      we do not do that for now.
634139d628a0SDimitry Andric   BasicBlock *Parent = Inst->getParent();
63424ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
6343875ed548SDimitry Andric   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
634439d628a0SDimitry Andric   // If the transition has more than one use, assume this is not going to be
634539d628a0SDimitry Andric   // beneficial.
634639d628a0SDimitry Andric   while (Inst->hasOneUse()) {
634739d628a0SDimitry Andric     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
63484ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
634939d628a0SDimitry Andric 
635039d628a0SDimitry Andric     if (ToBePromoted->getParent() != Parent) {
63514ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
635239d628a0SDimitry Andric                         << ToBePromoted->getParent()->getName()
63534ba319b5SDimitry Andric                         << ") than the transition (" << Parent->getName()
63544ba319b5SDimitry Andric                         << ").\n");
635539d628a0SDimitry Andric       return false;
635639d628a0SDimitry Andric     }
635739d628a0SDimitry Andric 
635839d628a0SDimitry Andric     if (VPH.canCombine(ToBePromoted)) {
63594ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
636039d628a0SDimitry Andric                         << "will be combined with: " << *ToBePromoted << '\n');
636139d628a0SDimitry Andric       VPH.recordCombineInstruction(ToBePromoted);
636239d628a0SDimitry Andric       bool Changed = VPH.promote();
636339d628a0SDimitry Andric       NumStoreExtractExposed += Changed;
636439d628a0SDimitry Andric       return Changed;
636539d628a0SDimitry Andric     }
636639d628a0SDimitry Andric 
63674ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Try promoting.\n");
636839d628a0SDimitry Andric     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
636939d628a0SDimitry Andric       return false;
637039d628a0SDimitry Andric 
63714ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
637239d628a0SDimitry Andric 
637339d628a0SDimitry Andric     VPH.enqueueForPromotion(ToBePromoted);
637439d628a0SDimitry Andric     Inst = ToBePromoted;
637539d628a0SDimitry Andric   }
637639d628a0SDimitry Andric   return false;
637739d628a0SDimitry Andric }
637839d628a0SDimitry Andric 
6379d88c1a5aSDimitry Andric /// For the instruction sequence of store below, F and I values
6380d88c1a5aSDimitry Andric /// are bundled together as an i64 value before being stored into memory.
63814ba319b5SDimitry Andric /// Sometimes it is more efficient to generate separate stores for F and I,
6382d88c1a5aSDimitry Andric /// which can remove the bitwise instructions or sink them to colder places.
6383d88c1a5aSDimitry Andric ///
6384d88c1a5aSDimitry Andric ///   (store (or (zext (bitcast F to i32) to i64),
6385d88c1a5aSDimitry Andric ///              (shl (zext I to i64), 32)), addr)  -->
6386d88c1a5aSDimitry Andric ///   (store F, addr) and (store I, addr+4)
6387d88c1a5aSDimitry Andric ///
6388d88c1a5aSDimitry Andric /// Similarly, splitting for other merged store can also be beneficial, like:
6389d88c1a5aSDimitry Andric /// For pair of {i32, i32}, i64 store --> two i32 stores.
6390d88c1a5aSDimitry Andric /// For pair of {i32, i16}, i64 store --> two i32 stores.
6391d88c1a5aSDimitry Andric /// For pair of {i16, i16}, i32 store --> two i16 stores.
6392d88c1a5aSDimitry Andric /// For pair of {i16, i8},  i32 store --> two i16 stores.
6393d88c1a5aSDimitry Andric /// For pair of {i8, i8},   i16 store --> two i8 stores.
6394d88c1a5aSDimitry Andric ///
6395d88c1a5aSDimitry Andric /// We allow each target to determine specifically which kind of splitting is
6396d88c1a5aSDimitry Andric /// supported.
6397d88c1a5aSDimitry Andric ///
6398d88c1a5aSDimitry Andric /// The store patterns are commonly seen from the simple code snippet below
6399d88c1a5aSDimitry Andric /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6400d88c1a5aSDimitry Andric ///   void goo(const std::pair<int, float> &);
6401d88c1a5aSDimitry Andric ///   hoo() {
6402d88c1a5aSDimitry Andric ///     ...
6403d88c1a5aSDimitry Andric ///     goo(std::make_pair(tmp, ftmp));
6404d88c1a5aSDimitry Andric ///     ...
6405d88c1a5aSDimitry Andric ///   }
6406d88c1a5aSDimitry Andric ///
6407d88c1a5aSDimitry Andric /// Although we already have similar splitting in DAG Combine, we duplicate
6408d88c1a5aSDimitry Andric /// it in CodeGenPrepare to catch the case in which pattern is across
6409d88c1a5aSDimitry Andric /// multiple BBs. The logic in DAG Combine is kept to catch case generated
6410d88c1a5aSDimitry Andric /// during code expansion.
splitMergedValStore(StoreInst & SI,const DataLayout & DL,const TargetLowering & TLI)6411d88c1a5aSDimitry Andric static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6412d88c1a5aSDimitry Andric                                 const TargetLowering &TLI) {
6413d88c1a5aSDimitry Andric   // Handle simple but common cases only.
6414d88c1a5aSDimitry Andric   Type *StoreType = SI.getValueOperand()->getType();
6415d88c1a5aSDimitry Andric   if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6416d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(StoreType) == 0)
6417d88c1a5aSDimitry Andric     return false;
6418d88c1a5aSDimitry Andric 
6419d88c1a5aSDimitry Andric   unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6420d88c1a5aSDimitry Andric   Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6421d88c1a5aSDimitry Andric   if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6422d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(SplitStoreType))
6423d88c1a5aSDimitry Andric     return false;
6424d88c1a5aSDimitry Andric 
6425d88c1a5aSDimitry Andric   // Match the following patterns:
6426d88c1a5aSDimitry Andric   // (store (or (zext LValue to i64),
6427d88c1a5aSDimitry Andric   //            (shl (zext HValue to i64), 32)), HalfValBitSize)
6428d88c1a5aSDimitry Andric   //  or
6429d88c1a5aSDimitry Andric   // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6430d88c1a5aSDimitry Andric   //            (zext LValue to i64),
6431d88c1a5aSDimitry Andric   // Expect both operands of OR and the first operand of SHL have only
6432d88c1a5aSDimitry Andric   // one use.
6433d88c1a5aSDimitry Andric   Value *LValue, *HValue;
6434d88c1a5aSDimitry Andric   if (!match(SI.getValueOperand(),
6435d88c1a5aSDimitry Andric              m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6436d88c1a5aSDimitry Andric                     m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6437d88c1a5aSDimitry Andric                                    m_SpecificInt(HalfValBitSize))))))
6438d88c1a5aSDimitry Andric     return false;
6439d88c1a5aSDimitry Andric 
6440d88c1a5aSDimitry Andric   // Check LValue and HValue are int with size less or equal than 32.
6441d88c1a5aSDimitry Andric   if (!LValue->getType()->isIntegerTy() ||
6442d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6443d88c1a5aSDimitry Andric       !HValue->getType()->isIntegerTy() ||
6444d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6445d88c1a5aSDimitry Andric     return false;
6446d88c1a5aSDimitry Andric 
6447d88c1a5aSDimitry Andric   // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6448d88c1a5aSDimitry Andric   // as the input of target query.
6449d88c1a5aSDimitry Andric   auto *LBC = dyn_cast<BitCastInst>(LValue);
6450d88c1a5aSDimitry Andric   auto *HBC = dyn_cast<BitCastInst>(HValue);
6451d88c1a5aSDimitry Andric   EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6452d88c1a5aSDimitry Andric                   : EVT::getEVT(LValue->getType());
6453d88c1a5aSDimitry Andric   EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6454d88c1a5aSDimitry Andric                    : EVT::getEVT(HValue->getType());
6455d88c1a5aSDimitry Andric   if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6456d88c1a5aSDimitry Andric     return false;
6457d88c1a5aSDimitry Andric 
6458d88c1a5aSDimitry Andric   // Start to split store.
6459d88c1a5aSDimitry Andric   IRBuilder<> Builder(SI.getContext());
6460d88c1a5aSDimitry Andric   Builder.SetInsertPoint(&SI);
6461d88c1a5aSDimitry Andric 
6462d88c1a5aSDimitry Andric   // If LValue/HValue is a bitcast in another BB, create a new one in current
6463d88c1a5aSDimitry Andric   // BB so it may be merged with the splitted stores by dag combiner.
6464d88c1a5aSDimitry Andric   if (LBC && LBC->getParent() != SI.getParent())
6465d88c1a5aSDimitry Andric     LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6466d88c1a5aSDimitry Andric   if (HBC && HBC->getParent() != SI.getParent())
6467d88c1a5aSDimitry Andric     HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6468d88c1a5aSDimitry Andric 
64694ba319b5SDimitry Andric   bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
6470d88c1a5aSDimitry Andric   auto CreateSplitStore = [&](Value *V, bool Upper) {
6471d88c1a5aSDimitry Andric     V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6472d88c1a5aSDimitry Andric     Value *Addr = Builder.CreateBitCast(
6473d88c1a5aSDimitry Andric         SI.getOperand(1),
6474d88c1a5aSDimitry Andric         SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
64754ba319b5SDimitry Andric     if ((IsLE && Upper) || (!IsLE && !Upper))
6476d88c1a5aSDimitry Andric       Addr = Builder.CreateGEP(
6477d88c1a5aSDimitry Andric           SplitStoreType, Addr,
6478d88c1a5aSDimitry Andric           ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6479d88c1a5aSDimitry Andric     Builder.CreateAlignedStore(
6480d88c1a5aSDimitry Andric         V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6481d88c1a5aSDimitry Andric   };
6482d88c1a5aSDimitry Andric 
6483d88c1a5aSDimitry Andric   CreateSplitStore(LValue, false);
6484d88c1a5aSDimitry Andric   CreateSplitStore(HValue, true);
6485d88c1a5aSDimitry Andric 
6486d88c1a5aSDimitry Andric   // Delete the old store.
6487d88c1a5aSDimitry Andric   SI.eraseFromParent();
6488d88c1a5aSDimitry Andric   return true;
6489d88c1a5aSDimitry Andric }
6490d88c1a5aSDimitry Andric 
64912cab237bSDimitry Andric // Return true if the GEP has two operands, the first operand is of a sequential
64922cab237bSDimitry Andric // type, and the second operand is a constant.
GEPSequentialConstIndexed(GetElementPtrInst * GEP)64932cab237bSDimitry Andric static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
64942cab237bSDimitry Andric   gep_type_iterator I = gep_type_begin(*GEP);
64952cab237bSDimitry Andric   return GEP->getNumOperands() == 2 &&
64962cab237bSDimitry Andric       I.isSequential() &&
64972cab237bSDimitry Andric       isa<ConstantInt>(GEP->getOperand(1));
64982cab237bSDimitry Andric }
64992cab237bSDimitry Andric 
65002cab237bSDimitry Andric // Try unmerging GEPs to reduce liveness interference (register pressure) across
65012cab237bSDimitry Andric // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
65022cab237bSDimitry Andric // reducing liveness interference across those edges benefits global register
65032cab237bSDimitry Andric // allocation. Currently handles only certain cases.
65042cab237bSDimitry Andric //
65052cab237bSDimitry Andric // For example, unmerge %GEPI and %UGEPI as below.
65062cab237bSDimitry Andric //
65072cab237bSDimitry Andric // ---------- BEFORE ----------
65082cab237bSDimitry Andric // SrcBlock:
65092cab237bSDimitry Andric //   ...
65102cab237bSDimitry Andric //   %GEPIOp = ...
65112cab237bSDimitry Andric //   ...
65122cab237bSDimitry Andric //   %GEPI = gep %GEPIOp, Idx
65132cab237bSDimitry Andric //   ...
65142cab237bSDimitry Andric //   indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
65152cab237bSDimitry Andric //   (* %GEPI is alive on the indirectbr edges due to other uses ahead)
65162cab237bSDimitry Andric //   (* %GEPIOp is alive on the indirectbr edges only because of it's used by
65172cab237bSDimitry Andric //   %UGEPI)
65182cab237bSDimitry Andric //
65192cab237bSDimitry Andric // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
65202cab237bSDimitry Andric // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
65212cab237bSDimitry Andric // ...
65222cab237bSDimitry Andric //
65232cab237bSDimitry Andric // DstBi:
65242cab237bSDimitry Andric //   ...
65252cab237bSDimitry Andric //   %UGEPI = gep %GEPIOp, UIdx
65262cab237bSDimitry Andric // ...
65272cab237bSDimitry Andric // ---------------------------
65282cab237bSDimitry Andric //
65292cab237bSDimitry Andric // ---------- AFTER ----------
65302cab237bSDimitry Andric // SrcBlock:
65312cab237bSDimitry Andric //   ... (same as above)
65322cab237bSDimitry Andric //    (* %GEPI is still alive on the indirectbr edges)
65332cab237bSDimitry Andric //    (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
65342cab237bSDimitry Andric //    unmerging)
65352cab237bSDimitry Andric // ...
65362cab237bSDimitry Andric //
65372cab237bSDimitry Andric // DstBi:
65382cab237bSDimitry Andric //   ...
65392cab237bSDimitry Andric //   %UGEPI = gep %GEPI, (UIdx-Idx)
65402cab237bSDimitry Andric //   ...
65412cab237bSDimitry Andric // ---------------------------
65422cab237bSDimitry Andric //
65432cab237bSDimitry Andric // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
65442cab237bSDimitry Andric // no longer alive on them.
65452cab237bSDimitry Andric //
65462cab237bSDimitry Andric // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
65472cab237bSDimitry Andric // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
65482cab237bSDimitry Andric // not to disable further simplications and optimizations as a result of GEP
65492cab237bSDimitry Andric // merging.
65502cab237bSDimitry Andric //
65512cab237bSDimitry Andric // Note this unmerging may increase the length of the data flow critical path
65522cab237bSDimitry Andric // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
65532cab237bSDimitry Andric // between the register pressure and the length of data-flow critical
65542cab237bSDimitry Andric // path. Restricting this to the uncommon IndirectBr case would minimize the
65552cab237bSDimitry Andric // impact of potentially longer critical path, if any, and the impact on compile
65562cab237bSDimitry Andric // time.
tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst * GEPI,const TargetTransformInfo * TTI)65572cab237bSDimitry Andric static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
65582cab237bSDimitry Andric                                              const TargetTransformInfo *TTI) {
65592cab237bSDimitry Andric   BasicBlock *SrcBlock = GEPI->getParent();
65602cab237bSDimitry Andric   // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
65612cab237bSDimitry Andric   // (non-IndirectBr) cases exit early here.
65622cab237bSDimitry Andric   if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
65632cab237bSDimitry Andric     return false;
65642cab237bSDimitry Andric   // Check that GEPI is a simple gep with a single constant index.
65652cab237bSDimitry Andric   if (!GEPSequentialConstIndexed(GEPI))
65662cab237bSDimitry Andric     return false;
65672cab237bSDimitry Andric   ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
65682cab237bSDimitry Andric   // Check that GEPI is a cheap one.
65692cab237bSDimitry Andric   if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
65702cab237bSDimitry Andric       > TargetTransformInfo::TCC_Basic)
65712cab237bSDimitry Andric     return false;
65722cab237bSDimitry Andric   Value *GEPIOp = GEPI->getOperand(0);
65732cab237bSDimitry Andric   // Check that GEPIOp is an instruction that's also defined in SrcBlock.
65742cab237bSDimitry Andric   if (!isa<Instruction>(GEPIOp))
65752cab237bSDimitry Andric     return false;
65762cab237bSDimitry Andric   auto *GEPIOpI = cast<Instruction>(GEPIOp);
65772cab237bSDimitry Andric   if (GEPIOpI->getParent() != SrcBlock)
65782cab237bSDimitry Andric     return false;
65792cab237bSDimitry Andric   // Check that GEP is used outside the block, meaning it's alive on the
65802cab237bSDimitry Andric   // IndirectBr edge(s).
65812cab237bSDimitry Andric   if (find_if(GEPI->users(), [&](User *Usr) {
65822cab237bSDimitry Andric         if (auto *I = dyn_cast<Instruction>(Usr)) {
65832cab237bSDimitry Andric           if (I->getParent() != SrcBlock) {
65842cab237bSDimitry Andric             return true;
65852cab237bSDimitry Andric           }
65862cab237bSDimitry Andric         }
65872cab237bSDimitry Andric         return false;
65882cab237bSDimitry Andric       }) == GEPI->users().end())
65892cab237bSDimitry Andric     return false;
65902cab237bSDimitry Andric   // The second elements of the GEP chains to be unmerged.
65912cab237bSDimitry Andric   std::vector<GetElementPtrInst *> UGEPIs;
65922cab237bSDimitry Andric   // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
65932cab237bSDimitry Andric   // on IndirectBr edges.
65942cab237bSDimitry Andric   for (User *Usr : GEPIOp->users()) {
65952cab237bSDimitry Andric     if (Usr == GEPI) continue;
65962cab237bSDimitry Andric     // Check if Usr is an Instruction. If not, give up.
65972cab237bSDimitry Andric     if (!isa<Instruction>(Usr))
65982cab237bSDimitry Andric       return false;
65992cab237bSDimitry Andric     auto *UI = cast<Instruction>(Usr);
66002cab237bSDimitry Andric     // Check if Usr in the same block as GEPIOp, which is fine, skip.
66012cab237bSDimitry Andric     if (UI->getParent() == SrcBlock)
66022cab237bSDimitry Andric       continue;
66032cab237bSDimitry Andric     // Check if Usr is a GEP. If not, give up.
66042cab237bSDimitry Andric     if (!isa<GetElementPtrInst>(Usr))
66052cab237bSDimitry Andric       return false;
66062cab237bSDimitry Andric     auto *UGEPI = cast<GetElementPtrInst>(Usr);
66072cab237bSDimitry Andric     // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
66082cab237bSDimitry Andric     // the pointer operand to it. If so, record it in the vector. If not, give
66092cab237bSDimitry Andric     // up.
66102cab237bSDimitry Andric     if (!GEPSequentialConstIndexed(UGEPI))
66112cab237bSDimitry Andric       return false;
66122cab237bSDimitry Andric     if (UGEPI->getOperand(0) != GEPIOp)
66132cab237bSDimitry Andric       return false;
66142cab237bSDimitry Andric     if (GEPIIdx->getType() !=
66152cab237bSDimitry Andric         cast<ConstantInt>(UGEPI->getOperand(1))->getType())
66162cab237bSDimitry Andric       return false;
66172cab237bSDimitry Andric     ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
66182cab237bSDimitry Andric     if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
66192cab237bSDimitry Andric         > TargetTransformInfo::TCC_Basic)
66202cab237bSDimitry Andric       return false;
66212cab237bSDimitry Andric     UGEPIs.push_back(UGEPI);
66222cab237bSDimitry Andric   }
66232cab237bSDimitry Andric   if (UGEPIs.size() == 0)
66242cab237bSDimitry Andric     return false;
66252cab237bSDimitry Andric   // Check the materializing cost of (Uidx-Idx).
66262cab237bSDimitry Andric   for (GetElementPtrInst *UGEPI : UGEPIs) {
66272cab237bSDimitry Andric     ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
66282cab237bSDimitry Andric     APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
66292cab237bSDimitry Andric     unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
66302cab237bSDimitry Andric     if (ImmCost > TargetTransformInfo::TCC_Basic)
66312cab237bSDimitry Andric       return false;
66322cab237bSDimitry Andric   }
66332cab237bSDimitry Andric   // Now unmerge between GEPI and UGEPIs.
66342cab237bSDimitry Andric   for (GetElementPtrInst *UGEPI : UGEPIs) {
66352cab237bSDimitry Andric     UGEPI->setOperand(0, GEPI);
66362cab237bSDimitry Andric     ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
66372cab237bSDimitry Andric     Constant *NewUGEPIIdx =
66382cab237bSDimitry Andric         ConstantInt::get(GEPIIdx->getType(),
66392cab237bSDimitry Andric                          UGEPIIdx->getValue() - GEPIIdx->getValue());
66402cab237bSDimitry Andric     UGEPI->setOperand(1, NewUGEPIIdx);
66412cab237bSDimitry Andric     // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
66422cab237bSDimitry Andric     // inbounds to avoid UB.
66432cab237bSDimitry Andric     if (!GEPI->isInBounds()) {
66442cab237bSDimitry Andric       UGEPI->setIsInBounds(false);
66452cab237bSDimitry Andric     }
66462cab237bSDimitry Andric   }
66472cab237bSDimitry Andric   // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
66482cab237bSDimitry Andric   // alive on IndirectBr edges).
66492cab237bSDimitry Andric   assert(find_if(GEPIOp->users(), [&](User *Usr) {
66502cab237bSDimitry Andric         return cast<Instruction>(Usr)->getParent() != SrcBlock;
66512cab237bSDimitry Andric       }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
66522cab237bSDimitry Andric   return true;
66532cab237bSDimitry Andric }
66542cab237bSDimitry Andric 
optimizeInst(Instruction * I,bool & ModifiedDT)66557d523365SDimitry Andric bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
66568f0fd8f6SDimitry Andric   // Bail out if we inserted the instruction to prevent optimizations from
66578f0fd8f6SDimitry Andric   // stepping on each other's toes.
66588f0fd8f6SDimitry Andric   if (InsertedInsts.count(I))
66598f0fd8f6SDimitry Andric     return false;
66608f0fd8f6SDimitry Andric 
666191bc56edSDimitry Andric   if (PHINode *P = dyn_cast<PHINode>(I)) {
666291bc56edSDimitry Andric     // It is possible for very late stage optimizations (such as SimplifyCFG)
666391bc56edSDimitry Andric     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
666491bc56edSDimitry Andric     // trivial PHI, go ahead and zap it here.
6665f37b6182SDimitry Andric     if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
666691bc56edSDimitry Andric       P->replaceAllUsesWith(V);
666791bc56edSDimitry Andric       P->eraseFromParent();
666891bc56edSDimitry Andric       ++NumPHIsElim;
666991bc56edSDimitry Andric       return true;
667091bc56edSDimitry Andric     }
667191bc56edSDimitry Andric     return false;
667291bc56edSDimitry Andric   }
667391bc56edSDimitry Andric 
667491bc56edSDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
667591bc56edSDimitry Andric     // If the source of the cast is a constant, then this should have
667691bc56edSDimitry Andric     // already been constant folded.  The only reason NOT to constant fold
667791bc56edSDimitry Andric     // it is if something (e.g. LSR) was careful to place the constant
667891bc56edSDimitry Andric     // evaluation in a block other than then one that uses it (e.g. to hoist
667991bc56edSDimitry Andric     // the address of globals out of a loop).  If this is the case, we don't
668091bc56edSDimitry Andric     // want to forward-subst the cast.
668191bc56edSDimitry Andric     if (isa<Constant>(CI->getOperand(0)))
668291bc56edSDimitry Andric       return false;
668391bc56edSDimitry Andric 
6684875ed548SDimitry Andric     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
668591bc56edSDimitry Andric       return true;
668691bc56edSDimitry Andric 
668791bc56edSDimitry Andric     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
668891bc56edSDimitry Andric       /// Sink a zext or sext into its user blocks if the target type doesn't
668991bc56edSDimitry Andric       /// fit in one register
6690875ed548SDimitry Andric       if (TLI &&
6691875ed548SDimitry Andric           TLI->getTypeAction(CI->getContext(),
6692875ed548SDimitry Andric                              TLI->getValueType(*DL, CI->getType())) ==
669391bc56edSDimitry Andric               TargetLowering::TypeExpandInteger) {
669491bc56edSDimitry Andric         return SinkCast(CI);
669591bc56edSDimitry Andric       } else {
66967a7e6055SDimitry Andric         bool MadeChange = optimizeExt(I);
66977d523365SDimitry Andric         return MadeChange | optimizeExtUses(I);
669891bc56edSDimitry Andric       }
669991bc56edSDimitry Andric     }
670091bc56edSDimitry Andric     return false;
670191bc56edSDimitry Andric   }
670291bc56edSDimitry Andric 
670391bc56edSDimitry Andric   if (CmpInst *CI = dyn_cast<CmpInst>(I))
670491bc56edSDimitry Andric     if (!TLI || !TLI->hasMultipleConditionRegisters())
67053ca95b02SDimitry Andric       return OptimizeCmpExpression(CI, TLI);
670691bc56edSDimitry Andric 
670791bc56edSDimitry Andric   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6708d88c1a5aSDimitry Andric     LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
670997bc6c73SDimitry Andric     if (TLI) {
67107d523365SDimitry Andric       bool Modified = optimizeLoadExt(LI);
671197bc6c73SDimitry Andric       unsigned AS = LI->getPointerAddressSpace();
67127d523365SDimitry Andric       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
67137d523365SDimitry Andric       return Modified;
671497bc6c73SDimitry Andric     }
671591bc56edSDimitry Andric     return false;
671691bc56edSDimitry Andric   }
671791bc56edSDimitry Andric 
671891bc56edSDimitry Andric   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6719d88c1a5aSDimitry Andric     if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6720d88c1a5aSDimitry Andric       return true;
6721d88c1a5aSDimitry Andric     SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
672297bc6c73SDimitry Andric     if (TLI) {
672397bc6c73SDimitry Andric       unsigned AS = SI->getPointerAddressSpace();
67247d523365SDimitry Andric       return optimizeMemoryInst(I, SI->getOperand(1),
672597bc6c73SDimitry Andric                                 SI->getOperand(0)->getType(), AS);
672697bc6c73SDimitry Andric     }
672791bc56edSDimitry Andric     return false;
672891bc56edSDimitry Andric   }
672991bc56edSDimitry Andric 
67307a7e6055SDimitry Andric   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
67317a7e6055SDimitry Andric       unsigned AS = RMW->getPointerAddressSpace();
67327a7e6055SDimitry Andric       return optimizeMemoryInst(I, RMW->getPointerOperand(),
67337a7e6055SDimitry Andric                                 RMW->getType(), AS);
67347a7e6055SDimitry Andric   }
67357a7e6055SDimitry Andric 
67367a7e6055SDimitry Andric   if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
67377a7e6055SDimitry Andric       unsigned AS = CmpX->getPointerAddressSpace();
67387a7e6055SDimitry Andric       return optimizeMemoryInst(I, CmpX->getPointerOperand(),
67397a7e6055SDimitry Andric                                 CmpX->getCompareOperand()->getType(), AS);
67407a7e6055SDimitry Andric   }
67417a7e6055SDimitry Andric 
674291bc56edSDimitry Andric   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
674391bc56edSDimitry Andric 
67447a7e6055SDimitry Andric   if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
67457a7e6055SDimitry Andric       EnableAndCmpSinking && TLI)
67467a7e6055SDimitry Andric     return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
67477a7e6055SDimitry Andric 
674891bc56edSDimitry Andric   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
674991bc56edSDimitry Andric                 BinOp->getOpcode() == Instruction::LShr)) {
675091bc56edSDimitry Andric     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
675191bc56edSDimitry Andric     if (TLI && CI && TLI->hasExtractBitsInsn())
6752875ed548SDimitry Andric       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
675391bc56edSDimitry Andric 
675491bc56edSDimitry Andric     return false;
675591bc56edSDimitry Andric   }
675691bc56edSDimitry Andric 
675791bc56edSDimitry Andric   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
675891bc56edSDimitry Andric     if (GEPI->hasAllZeroIndices()) {
675991bc56edSDimitry Andric       /// The GEP operand must be a pointer, so must its result -> BitCast
676091bc56edSDimitry Andric       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
676191bc56edSDimitry Andric                                         GEPI->getName(), GEPI);
67624ba319b5SDimitry Andric       NC->setDebugLoc(GEPI->getDebugLoc());
676391bc56edSDimitry Andric       GEPI->replaceAllUsesWith(NC);
676491bc56edSDimitry Andric       GEPI->eraseFromParent();
676591bc56edSDimitry Andric       ++NumGEPsElim;
67667d523365SDimitry Andric       optimizeInst(NC, ModifiedDT);
676791bc56edSDimitry Andric       return true;
676891bc56edSDimitry Andric     }
67692cab237bSDimitry Andric     if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
67702cab237bSDimitry Andric       return true;
67712cab237bSDimitry Andric     }
677291bc56edSDimitry Andric     return false;
677391bc56edSDimitry Andric   }
677491bc56edSDimitry Andric 
677591bc56edSDimitry Andric   if (CallInst *CI = dyn_cast<CallInst>(I))
67767d523365SDimitry Andric     return optimizeCallInst(CI, ModifiedDT);
677791bc56edSDimitry Andric 
677891bc56edSDimitry Andric   if (SelectInst *SI = dyn_cast<SelectInst>(I))
67797d523365SDimitry Andric     return optimizeSelectInst(SI);
678091bc56edSDimitry Andric 
678191bc56edSDimitry Andric   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
67827d523365SDimitry Andric     return optimizeShuffleVectorInst(SVI);
67837d523365SDimitry Andric 
67847d523365SDimitry Andric   if (auto *Switch = dyn_cast<SwitchInst>(I))
67857d523365SDimitry Andric     return optimizeSwitchInst(Switch);
678691bc56edSDimitry Andric 
678739d628a0SDimitry Andric   if (isa<ExtractElementInst>(I))
67887d523365SDimitry Andric     return optimizeExtractElementInst(I);
678939d628a0SDimitry Andric 
679091bc56edSDimitry Andric   return false;
679191bc56edSDimitry Andric }
679291bc56edSDimitry Andric 
67938c24ff90SDimitry Andric /// Given an OR instruction, check to see if this is a bitreverse
67948c24ff90SDimitry Andric /// idiom. If so, insert the new intrinsic and return true.
makeBitReverse(Instruction & I,const DataLayout & DL,const TargetLowering & TLI)67958c24ff90SDimitry Andric static bool makeBitReverse(Instruction &I, const DataLayout &DL,
67968c24ff90SDimitry Andric                            const TargetLowering &TLI) {
67978c24ff90SDimitry Andric   if (!I.getType()->isIntegerTy() ||
67988c24ff90SDimitry Andric       !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
67998c24ff90SDimitry Andric                                     TLI.getValueType(DL, I.getType(), true)))
68008c24ff90SDimitry Andric     return false;
68018c24ff90SDimitry Andric 
68028c24ff90SDimitry Andric   SmallVector<Instruction*, 4> Insts;
68033ca95b02SDimitry Andric   if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
68048c24ff90SDimitry Andric     return false;
68058c24ff90SDimitry Andric   Instruction *LastInst = Insts.back();
68068c24ff90SDimitry Andric   I.replaceAllUsesWith(LastInst);
68078c24ff90SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(&I);
68088c24ff90SDimitry Andric   return true;
68098c24ff90SDimitry Andric }
68108c24ff90SDimitry Andric 
681191bc56edSDimitry Andric // In this pass we look for GEP and cast instructions that are used
681291bc56edSDimitry Andric // across basic blocks and rewrite them to improve basic-block-at-a-time
681391bc56edSDimitry Andric // selection.
optimizeBlock(BasicBlock & BB,bool & ModifiedDT)68147d523365SDimitry Andric bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
681591bc56edSDimitry Andric   SunkAddrs.clear();
681691bc56edSDimitry Andric   bool MadeChange = false;
681791bc56edSDimitry Andric 
681891bc56edSDimitry Andric   CurInstIterator = BB.begin();
681939d628a0SDimitry Andric   while (CurInstIterator != BB.end()) {
68207d523365SDimitry Andric     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
682139d628a0SDimitry Andric     if (ModifiedDT)
682239d628a0SDimitry Andric       return true;
682339d628a0SDimitry Andric   }
68248c24ff90SDimitry Andric 
68258c24ff90SDimitry Andric   bool MadeBitReverse = true;
68268c24ff90SDimitry Andric   while (TLI && MadeBitReverse) {
68278c24ff90SDimitry Andric     MadeBitReverse = false;
68288c24ff90SDimitry Andric     for (auto &I : reverse(BB)) {
68298c24ff90SDimitry Andric       if (makeBitReverse(I, *DL, *TLI)) {
68308c24ff90SDimitry Andric         MadeBitReverse = MadeChange = true;
68313ca95b02SDimitry Andric         ModifiedDT = true;
68328c24ff90SDimitry Andric         break;
68338c24ff90SDimitry Andric       }
68348c24ff90SDimitry Andric     }
68358c24ff90SDimitry Andric   }
68367d523365SDimitry Andric   MadeChange |= dupRetToEnableTailCallOpts(&BB);
683791bc56edSDimitry Andric 
683891bc56edSDimitry Andric   return MadeChange;
683991bc56edSDimitry Andric }
684091bc56edSDimitry Andric 
684191bc56edSDimitry Andric // llvm.dbg.value is far away from the value then iSel may not be able
684291bc56edSDimitry Andric // handle it properly. iSel will drop llvm.dbg.value if it can not
684391bc56edSDimitry Andric // find a node corresponding to the value.
placeDbgValues(Function & F)68447d523365SDimitry Andric bool CodeGenPrepare::placeDbgValues(Function &F) {
684591bc56edSDimitry Andric   bool MadeChange = false;
684639d628a0SDimitry Andric   for (BasicBlock &BB : F) {
684791bc56edSDimitry Andric     Instruction *PrevNonDbgInst = nullptr;
684839d628a0SDimitry Andric     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
68497d523365SDimitry Andric       Instruction *Insn = &*BI++;
685091bc56edSDimitry Andric       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
685191bc56edSDimitry Andric       // Leave dbg.values that refer to an alloca alone. These
68522cab237bSDimitry Andric       // intrinsics describe the address of a variable (= the alloca)
685391bc56edSDimitry Andric       // being taken.  They should not be moved next to the alloca
685491bc56edSDimitry Andric       // (and to the beginning of the scope), but rather stay close to
685591bc56edSDimitry Andric       // where said address is used.
685691bc56edSDimitry Andric       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
685791bc56edSDimitry Andric         PrevNonDbgInst = Insn;
685891bc56edSDimitry Andric         continue;
685991bc56edSDimitry Andric       }
686091bc56edSDimitry Andric 
686191bc56edSDimitry Andric       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
686291bc56edSDimitry Andric       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
68637d523365SDimitry Andric         // If VI is a phi in a block with an EHPad terminator, we can't insert
68647d523365SDimitry Andric         // after it.
68657d523365SDimitry Andric         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
68667d523365SDimitry Andric           continue;
68674ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
68684ba319b5SDimitry Andric                           << *DVI << ' ' << *VI);
686991bc56edSDimitry Andric         DVI->removeFromParent();
687091bc56edSDimitry Andric         if (isa<PHINode>(VI))
68717d523365SDimitry Andric           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
687291bc56edSDimitry Andric         else
687391bc56edSDimitry Andric           DVI->insertAfter(VI);
687491bc56edSDimitry Andric         MadeChange = true;
687591bc56edSDimitry Andric         ++NumDbgValueMoved;
687691bc56edSDimitry Andric       }
687791bc56edSDimitry Andric     }
687891bc56edSDimitry Andric   }
687991bc56edSDimitry Andric   return MadeChange;
688091bc56edSDimitry Andric }
688191bc56edSDimitry Andric 
68824ba319b5SDimitry Andric /// Scale down both weights to fit into uint32_t.
scaleWeights(uint64_t & NewTrue,uint64_t & NewFalse)688339d628a0SDimitry Andric static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
688439d628a0SDimitry Andric   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
68852cab237bSDimitry Andric   uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
688639d628a0SDimitry Andric   NewTrue = NewTrue / Scale;
688739d628a0SDimitry Andric   NewFalse = NewFalse / Scale;
688839d628a0SDimitry Andric }
688939d628a0SDimitry Andric 
68904ba319b5SDimitry Andric /// Some targets prefer to split a conditional branch like:
689139d628a0SDimitry Andric /// \code
689239d628a0SDimitry Andric ///   %0 = icmp ne i32 %a, 0
689339d628a0SDimitry Andric ///   %1 = icmp ne i32 %b, 0
689439d628a0SDimitry Andric ///   %or.cond = or i1 %0, %1
689539d628a0SDimitry Andric ///   br i1 %or.cond, label %TrueBB, label %FalseBB
689639d628a0SDimitry Andric /// \endcode
689739d628a0SDimitry Andric /// into multiple branch instructions like:
689839d628a0SDimitry Andric /// \code
689939d628a0SDimitry Andric ///   bb1:
690039d628a0SDimitry Andric ///     %0 = icmp ne i32 %a, 0
690139d628a0SDimitry Andric ///     br i1 %0, label %TrueBB, label %bb2
690239d628a0SDimitry Andric ///   bb2:
690339d628a0SDimitry Andric ///     %1 = icmp ne i32 %b, 0
690439d628a0SDimitry Andric ///     br i1 %1, label %TrueBB, label %FalseBB
690539d628a0SDimitry Andric /// \endcode
690639d628a0SDimitry Andric /// This usually allows instruction selection to do even further optimizations
690739d628a0SDimitry Andric /// and combine the compare with the branch instruction. Currently this is
690839d628a0SDimitry Andric /// applied for targets which have "cheap" jump instructions.
690939d628a0SDimitry Andric ///
691039d628a0SDimitry Andric /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
691139d628a0SDimitry Andric ///
splitBranchCondition(Function & F)691239d628a0SDimitry Andric bool CodeGenPrepare::splitBranchCondition(Function &F) {
6913ff0cc061SDimitry Andric   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
691439d628a0SDimitry Andric     return false;
691539d628a0SDimitry Andric 
691639d628a0SDimitry Andric   bool MadeChange = false;
691739d628a0SDimitry Andric   for (auto &BB : F) {
691839d628a0SDimitry Andric     // Does this BB end with the following?
691939d628a0SDimitry Andric     //   %cond1 = icmp|fcmp|binary instruction ...
692039d628a0SDimitry Andric     //   %cond2 = icmp|fcmp|binary instruction ...
692139d628a0SDimitry Andric     //   %cond.or = or|and i1 %cond1, cond2
692239d628a0SDimitry Andric     //   br i1 %cond.or label %dest1, label %dest2"
692339d628a0SDimitry Andric     BinaryOperator *LogicOp;
692439d628a0SDimitry Andric     BasicBlock *TBB, *FBB;
692539d628a0SDimitry Andric     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
692639d628a0SDimitry Andric       continue;
692739d628a0SDimitry Andric 
69287d523365SDimitry Andric     auto *Br1 = cast<BranchInst>(BB.getTerminator());
69297d523365SDimitry Andric     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
69307d523365SDimitry Andric       continue;
69317d523365SDimitry Andric 
693239d628a0SDimitry Andric     unsigned Opc;
693339d628a0SDimitry Andric     Value *Cond1, *Cond2;
693439d628a0SDimitry Andric     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
693539d628a0SDimitry Andric                              m_OneUse(m_Value(Cond2)))))
693639d628a0SDimitry Andric       Opc = Instruction::And;
693739d628a0SDimitry Andric     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
693839d628a0SDimitry Andric                                  m_OneUse(m_Value(Cond2)))))
693939d628a0SDimitry Andric       Opc = Instruction::Or;
694039d628a0SDimitry Andric     else
694139d628a0SDimitry Andric       continue;
694239d628a0SDimitry Andric 
694339d628a0SDimitry Andric     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
694439d628a0SDimitry Andric         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
694539d628a0SDimitry Andric       continue;
694639d628a0SDimitry Andric 
69474ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
694839d628a0SDimitry Andric 
694939d628a0SDimitry Andric     // Create a new BB.
69503ca95b02SDimitry Andric     auto TmpBB =
69513ca95b02SDimitry Andric         BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
69523ca95b02SDimitry Andric                            BB.getParent(), BB.getNextNode());
695339d628a0SDimitry Andric 
695439d628a0SDimitry Andric     // Update original basic block by using the first condition directly by the
695539d628a0SDimitry Andric     // branch instruction and removing the no longer needed and/or instruction.
695639d628a0SDimitry Andric     Br1->setCondition(Cond1);
695739d628a0SDimitry Andric     LogicOp->eraseFromParent();
695839d628a0SDimitry Andric 
69594ba319b5SDimitry Andric     // Depending on the condition we have to either replace the true or the
69604ba319b5SDimitry Andric     // false successor of the original branch instruction.
696139d628a0SDimitry Andric     if (Opc == Instruction::And)
696239d628a0SDimitry Andric       Br1->setSuccessor(0, TmpBB);
696339d628a0SDimitry Andric     else
696439d628a0SDimitry Andric       Br1->setSuccessor(1, TmpBB);
696539d628a0SDimitry Andric 
696639d628a0SDimitry Andric     // Fill in the new basic block.
696739d628a0SDimitry Andric     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
696839d628a0SDimitry Andric     if (auto *I = dyn_cast<Instruction>(Cond2)) {
696939d628a0SDimitry Andric       I->removeFromParent();
697039d628a0SDimitry Andric       I->insertBefore(Br2);
697139d628a0SDimitry Andric     }
697239d628a0SDimitry Andric 
697339d628a0SDimitry Andric     // Update PHI nodes in both successors. The original BB needs to be
6974a580b014SDimitry Andric     // replaced in one successor's PHI nodes, because the branch comes now from
697539d628a0SDimitry Andric     // the newly generated BB (NewBB). In the other successor we need to add one
697639d628a0SDimitry Andric     // incoming edge to the PHI nodes, because both branch instructions target
697739d628a0SDimitry Andric     // now the same successor. Depending on the original branch condition
697839d628a0SDimitry Andric     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6979d88c1a5aSDimitry Andric     // we perform the correct update for the PHI nodes.
698039d628a0SDimitry Andric     // This doesn't change the successor order of the just created branch
698139d628a0SDimitry Andric     // instruction (or any other instruction).
698239d628a0SDimitry Andric     if (Opc == Instruction::Or)
698339d628a0SDimitry Andric       std::swap(TBB, FBB);
698439d628a0SDimitry Andric 
698539d628a0SDimitry Andric     // Replace the old BB with the new BB.
698630785c0eSDimitry Andric     for (PHINode &PN : TBB->phis()) {
698739d628a0SDimitry Andric       int i;
698830785c0eSDimitry Andric       while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
698930785c0eSDimitry Andric         PN.setIncomingBlock(i, TmpBB);
699039d628a0SDimitry Andric     }
699139d628a0SDimitry Andric 
699239d628a0SDimitry Andric     // Add another incoming edge form the new BB.
699330785c0eSDimitry Andric     for (PHINode &PN : FBB->phis()) {
699430785c0eSDimitry Andric       auto *Val = PN.getIncomingValueForBlock(&BB);
699530785c0eSDimitry Andric       PN.addIncoming(Val, TmpBB);
699639d628a0SDimitry Andric     }
699739d628a0SDimitry Andric 
699839d628a0SDimitry Andric     // Update the branch weights (from SelectionDAGBuilder::
699939d628a0SDimitry Andric     // FindMergedConditions).
700039d628a0SDimitry Andric     if (Opc == Instruction::Or) {
700139d628a0SDimitry Andric       // Codegen X | Y as:
700239d628a0SDimitry Andric       // BB1:
700339d628a0SDimitry Andric       //   jmp_if_X TBB
700439d628a0SDimitry Andric       //   jmp TmpBB
700539d628a0SDimitry Andric       // TmpBB:
700639d628a0SDimitry Andric       //   jmp_if_Y TBB
700739d628a0SDimitry Andric       //   jmp FBB
700839d628a0SDimitry Andric       //
700939d628a0SDimitry Andric 
701039d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
701139d628a0SDimitry Andric       // The requirement is that
701239d628a0SDimitry Andric       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
70134ba319b5SDimitry Andric       //     = TrueProb for original BB.
70144ba319b5SDimitry Andric       // Assuming the original weights are A and B, one choice is to set BB1's
701539d628a0SDimitry Andric       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
701639d628a0SDimitry Andric       // assumes that
701739d628a0SDimitry Andric       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
701839d628a0SDimitry Andric       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
701939d628a0SDimitry Andric       // TmpBB, but the math is more complicated.
702039d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
70213ca95b02SDimitry Andric       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
702239d628a0SDimitry Andric         uint64_t NewTrueWeight = TrueWeight;
702339d628a0SDimitry Andric         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
702439d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
702539d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
702639d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
702739d628a0SDimitry Andric 
702839d628a0SDimitry Andric         NewTrueWeight = TrueWeight;
702939d628a0SDimitry Andric         NewFalseWeight = 2 * FalseWeight;
703039d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
703139d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
703239d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
703339d628a0SDimitry Andric       }
703439d628a0SDimitry Andric     } else {
703539d628a0SDimitry Andric       // Codegen X & Y as:
703639d628a0SDimitry Andric       // BB1:
703739d628a0SDimitry Andric       //   jmp_if_X TmpBB
703839d628a0SDimitry Andric       //   jmp FBB
703939d628a0SDimitry Andric       // TmpBB:
704039d628a0SDimitry Andric       //   jmp_if_Y TBB
704139d628a0SDimitry Andric       //   jmp FBB
704239d628a0SDimitry Andric       //
704339d628a0SDimitry Andric       //  This requires creation of TmpBB after CurBB.
704439d628a0SDimitry Andric 
704539d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
704639d628a0SDimitry Andric       // The requirement is that
704739d628a0SDimitry Andric       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
70484ba319b5SDimitry Andric       //     = FalseProb for original BB.
70494ba319b5SDimitry Andric       // Assuming the original weights are A and B, one choice is to set BB1's
705039d628a0SDimitry Andric       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
705139d628a0SDimitry Andric       // assumes that
705239d628a0SDimitry Andric       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
705339d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
70543ca95b02SDimitry Andric       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
705539d628a0SDimitry Andric         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
705639d628a0SDimitry Andric         uint64_t NewFalseWeight = FalseWeight;
705739d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
705839d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
705939d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
706039d628a0SDimitry Andric 
706139d628a0SDimitry Andric         NewTrueWeight = 2 * TrueWeight;
706239d628a0SDimitry Andric         NewFalseWeight = FalseWeight;
706339d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
706439d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
706539d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
706639d628a0SDimitry Andric       }
706739d628a0SDimitry Andric     }
706839d628a0SDimitry Andric 
706939d628a0SDimitry Andric     // Note: No point in getting fancy here, since the DT info is never
7070ff0cc061SDimitry Andric     // available to CodeGenPrepare.
707139d628a0SDimitry Andric     ModifiedDT = true;
707239d628a0SDimitry Andric 
707339d628a0SDimitry Andric     MadeChange = true;
707439d628a0SDimitry Andric 
70754ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
707639d628a0SDimitry Andric                TmpBB->dump());
707739d628a0SDimitry Andric   }
707839d628a0SDimitry Andric   return MadeChange;
707939d628a0SDimitry Andric }
7080