1*9880d681SAndroid Build Coastguard Worker //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass promotes "by reference" arguments to be "by value" arguments. In
11*9880d681SAndroid Build Coastguard Worker // practice, this means looking for internal functions that have pointer
12*9880d681SAndroid Build Coastguard Worker // arguments. If it can prove, through the use of alias analysis, that an
13*9880d681SAndroid Build Coastguard Worker // argument is *only* loaded, then it can pass the value into the function
14*9880d681SAndroid Build Coastguard Worker // instead of the address of the value. This can cause recursive simplification
15*9880d681SAndroid Build Coastguard Worker // of code and lead to the elimination of allocas (especially in C++ template
16*9880d681SAndroid Build Coastguard Worker // code like the STL).
17*9880d681SAndroid Build Coastguard Worker //
18*9880d681SAndroid Build Coastguard Worker // This pass also handles aggregate arguments that are passed into a function,
19*9880d681SAndroid Build Coastguard Worker // scalarizing them if the elements of the aggregate are only loaded. Note that
20*9880d681SAndroid Build Coastguard Worker // by default it refuses to scalarize aggregates which would require passing in
21*9880d681SAndroid Build Coastguard Worker // more than three operands to the function, because passing thousands of
22*9880d681SAndroid Build Coastguard Worker // operands for a large array or structure is unprofitable! This limit can be
23*9880d681SAndroid Build Coastguard Worker // configured or disabled, however.
24*9880d681SAndroid Build Coastguard Worker //
25*9880d681SAndroid Build Coastguard Worker // Note that this transformation could also be done for arguments that are only
26*9880d681SAndroid Build Coastguard Worker // stored to (returning the value instead), but does not currently. This case
27*9880d681SAndroid Build Coastguard Worker // would be best handled when and if LLVM begins supporting multiple return
28*9880d681SAndroid Build Coastguard Worker // values from functions.
29*9880d681SAndroid Build Coastguard Worker //
30*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
31*9880d681SAndroid Build Coastguard Worker
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/IPO.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DepthFirstIterator.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringExtras.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BasicAliasAnalysis.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CallGraph.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CallGraphSCCPass.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/Loads.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallSite.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DebugInfo.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
55*9880d681SAndroid Build Coastguard Worker #include <set>
56*9880d681SAndroid Build Coastguard Worker using namespace llvm;
57*9880d681SAndroid Build Coastguard Worker
58*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "argpromotion"
59*9880d681SAndroid Build Coastguard Worker
60*9880d681SAndroid Build Coastguard Worker STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
61*9880d681SAndroid Build Coastguard Worker STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
62*9880d681SAndroid Build Coastguard Worker STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
63*9880d681SAndroid Build Coastguard Worker STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
64*9880d681SAndroid Build Coastguard Worker
65*9880d681SAndroid Build Coastguard Worker namespace {
66*9880d681SAndroid Build Coastguard Worker /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
67*9880d681SAndroid Build Coastguard Worker ///
68*9880d681SAndroid Build Coastguard Worker struct ArgPromotion : public CallGraphSCCPass {
getAnalysisUsage__anon7d1c76870111::ArgPromotion69*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
70*9880d681SAndroid Build Coastguard Worker AU.addRequired<AssumptionCacheTracker>();
71*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetLibraryInfoWrapperPass>();
72*9880d681SAndroid Build Coastguard Worker getAAResultsAnalysisUsage(AU);
73*9880d681SAndroid Build Coastguard Worker CallGraphSCCPass::getAnalysisUsage(AU);
74*9880d681SAndroid Build Coastguard Worker }
75*9880d681SAndroid Build Coastguard Worker
76*9880d681SAndroid Build Coastguard Worker bool runOnSCC(CallGraphSCC &SCC) override;
77*9880d681SAndroid Build Coastguard Worker static char ID; // Pass identification, replacement for typeid
ArgPromotion__anon7d1c76870111::ArgPromotion78*9880d681SAndroid Build Coastguard Worker explicit ArgPromotion(unsigned maxElements = 3)
79*9880d681SAndroid Build Coastguard Worker : CallGraphSCCPass(ID), maxElements(maxElements) {
80*9880d681SAndroid Build Coastguard Worker initializeArgPromotionPass(*PassRegistry::getPassRegistry());
81*9880d681SAndroid Build Coastguard Worker }
82*9880d681SAndroid Build Coastguard Worker
83*9880d681SAndroid Build Coastguard Worker private:
84*9880d681SAndroid Build Coastguard Worker
85*9880d681SAndroid Build Coastguard Worker using llvm::Pass::doInitialization;
86*9880d681SAndroid Build Coastguard Worker bool doInitialization(CallGraph &CG) override;
87*9880d681SAndroid Build Coastguard Worker /// The maximum number of elements to expand, or 0 for unlimited.
88*9880d681SAndroid Build Coastguard Worker unsigned maxElements;
89*9880d681SAndroid Build Coastguard Worker };
90*9880d681SAndroid Build Coastguard Worker }
91*9880d681SAndroid Build Coastguard Worker
92*9880d681SAndroid Build Coastguard Worker /// A vector used to hold the indices of a single GEP instruction
93*9880d681SAndroid Build Coastguard Worker typedef std::vector<uint64_t> IndicesVector;
94*9880d681SAndroid Build Coastguard Worker
95*9880d681SAndroid Build Coastguard Worker static CallGraphNode *
96*9880d681SAndroid Build Coastguard Worker PromoteArguments(CallGraphNode *CGN, CallGraph &CG,
97*9880d681SAndroid Build Coastguard Worker function_ref<AAResults &(Function &F)> AARGetter,
98*9880d681SAndroid Build Coastguard Worker unsigned MaxElements);
99*9880d681SAndroid Build Coastguard Worker static bool isDenselyPacked(Type *type, const DataLayout &DL);
100*9880d681SAndroid Build Coastguard Worker static bool canPaddingBeAccessed(Argument *Arg);
101*9880d681SAndroid Build Coastguard Worker static bool isSafeToPromoteArgument(Argument *Arg, bool isByVal, AAResults &AAR,
102*9880d681SAndroid Build Coastguard Worker unsigned MaxElements);
103*9880d681SAndroid Build Coastguard Worker static CallGraphNode *
104*9880d681SAndroid Build Coastguard Worker DoPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote,
105*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<Argument *> &ByValArgsToTransform, CallGraph &CG);
106*9880d681SAndroid Build Coastguard Worker
107*9880d681SAndroid Build Coastguard Worker char ArgPromotion::ID = 0;
108*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
109*9880d681SAndroid Build Coastguard Worker "Promote 'by reference' arguments to scalars", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)110*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
111*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
112*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
113*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
114*9880d681SAndroid Build Coastguard Worker "Promote 'by reference' arguments to scalars", false, false)
115*9880d681SAndroid Build Coastguard Worker
116*9880d681SAndroid Build Coastguard Worker Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
117*9880d681SAndroid Build Coastguard Worker return new ArgPromotion(maxElements);
118*9880d681SAndroid Build Coastguard Worker }
119*9880d681SAndroid Build Coastguard Worker
runImpl(CallGraphSCC & SCC,CallGraph & CG,function_ref<AAResults & (Function & F)> AARGetter,unsigned MaxElements)120*9880d681SAndroid Build Coastguard Worker static bool runImpl(CallGraphSCC &SCC, CallGraph &CG,
121*9880d681SAndroid Build Coastguard Worker function_ref<AAResults &(Function &F)> AARGetter,
122*9880d681SAndroid Build Coastguard Worker unsigned MaxElements) {
123*9880d681SAndroid Build Coastguard Worker bool Changed = false, LocalChange;
124*9880d681SAndroid Build Coastguard Worker
125*9880d681SAndroid Build Coastguard Worker do { // Iterate until we stop promoting from this SCC.
126*9880d681SAndroid Build Coastguard Worker LocalChange = false;
127*9880d681SAndroid Build Coastguard Worker // Attempt to promote arguments from all functions in this SCC.
128*9880d681SAndroid Build Coastguard Worker for (CallGraphNode *OldNode : SCC) {
129*9880d681SAndroid Build Coastguard Worker if (CallGraphNode *NewNode =
130*9880d681SAndroid Build Coastguard Worker PromoteArguments(OldNode, CG, AARGetter, MaxElements)) {
131*9880d681SAndroid Build Coastguard Worker LocalChange = true;
132*9880d681SAndroid Build Coastguard Worker SCC.ReplaceNode(OldNode, NewNode);
133*9880d681SAndroid Build Coastguard Worker }
134*9880d681SAndroid Build Coastguard Worker }
135*9880d681SAndroid Build Coastguard Worker Changed |= LocalChange; // Remember that we changed something.
136*9880d681SAndroid Build Coastguard Worker } while (LocalChange);
137*9880d681SAndroid Build Coastguard Worker
138*9880d681SAndroid Build Coastguard Worker return Changed;
139*9880d681SAndroid Build Coastguard Worker }
140*9880d681SAndroid Build Coastguard Worker
runOnSCC(CallGraphSCC & SCC)141*9880d681SAndroid Build Coastguard Worker bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
142*9880d681SAndroid Build Coastguard Worker if (skipSCC(SCC))
143*9880d681SAndroid Build Coastguard Worker return false;
144*9880d681SAndroid Build Coastguard Worker
145*9880d681SAndroid Build Coastguard Worker // Get the callgraph information that we need to update to reflect our
146*9880d681SAndroid Build Coastguard Worker // changes.
147*9880d681SAndroid Build Coastguard Worker CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
148*9880d681SAndroid Build Coastguard Worker
149*9880d681SAndroid Build Coastguard Worker // We compute dedicated AA results for each function in the SCC as needed. We
150*9880d681SAndroid Build Coastguard Worker // use a lambda referencing external objects so that they live long enough to
151*9880d681SAndroid Build Coastguard Worker // be queried, but we re-use them each time.
152*9880d681SAndroid Build Coastguard Worker Optional<BasicAAResult> BAR;
153*9880d681SAndroid Build Coastguard Worker Optional<AAResults> AAR;
154*9880d681SAndroid Build Coastguard Worker auto AARGetter = [&](Function &F) -> AAResults & {
155*9880d681SAndroid Build Coastguard Worker BAR.emplace(createLegacyPMBasicAAResult(*this, F));
156*9880d681SAndroid Build Coastguard Worker AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
157*9880d681SAndroid Build Coastguard Worker return *AAR;
158*9880d681SAndroid Build Coastguard Worker };
159*9880d681SAndroid Build Coastguard Worker
160*9880d681SAndroid Build Coastguard Worker return runImpl(SCC, CG, AARGetter, maxElements);
161*9880d681SAndroid Build Coastguard Worker }
162*9880d681SAndroid Build Coastguard Worker
163*9880d681SAndroid Build Coastguard Worker /// \brief Checks if a type could have padding bytes.
isDenselyPacked(Type * type,const DataLayout & DL)164*9880d681SAndroid Build Coastguard Worker static bool isDenselyPacked(Type *type, const DataLayout &DL) {
165*9880d681SAndroid Build Coastguard Worker
166*9880d681SAndroid Build Coastguard Worker // There is no size information, so be conservative.
167*9880d681SAndroid Build Coastguard Worker if (!type->isSized())
168*9880d681SAndroid Build Coastguard Worker return false;
169*9880d681SAndroid Build Coastguard Worker
170*9880d681SAndroid Build Coastguard Worker // If the alloc size is not equal to the storage size, then there are padding
171*9880d681SAndroid Build Coastguard Worker // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
172*9880d681SAndroid Build Coastguard Worker if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
173*9880d681SAndroid Build Coastguard Worker return false;
174*9880d681SAndroid Build Coastguard Worker
175*9880d681SAndroid Build Coastguard Worker if (!isa<CompositeType>(type))
176*9880d681SAndroid Build Coastguard Worker return true;
177*9880d681SAndroid Build Coastguard Worker
178*9880d681SAndroid Build Coastguard Worker // For homogenous sequential types, check for padding within members.
179*9880d681SAndroid Build Coastguard Worker if (SequentialType *seqTy = dyn_cast<SequentialType>(type))
180*9880d681SAndroid Build Coastguard Worker return isa<PointerType>(seqTy) ||
181*9880d681SAndroid Build Coastguard Worker isDenselyPacked(seqTy->getElementType(), DL);
182*9880d681SAndroid Build Coastguard Worker
183*9880d681SAndroid Build Coastguard Worker // Check for padding within and between elements of a struct.
184*9880d681SAndroid Build Coastguard Worker StructType *StructTy = cast<StructType>(type);
185*9880d681SAndroid Build Coastguard Worker const StructLayout *Layout = DL.getStructLayout(StructTy);
186*9880d681SAndroid Build Coastguard Worker uint64_t StartPos = 0;
187*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
188*9880d681SAndroid Build Coastguard Worker Type *ElTy = StructTy->getElementType(i);
189*9880d681SAndroid Build Coastguard Worker if (!isDenselyPacked(ElTy, DL))
190*9880d681SAndroid Build Coastguard Worker return false;
191*9880d681SAndroid Build Coastguard Worker if (StartPos != Layout->getElementOffsetInBits(i))
192*9880d681SAndroid Build Coastguard Worker return false;
193*9880d681SAndroid Build Coastguard Worker StartPos += DL.getTypeAllocSizeInBits(ElTy);
194*9880d681SAndroid Build Coastguard Worker }
195*9880d681SAndroid Build Coastguard Worker
196*9880d681SAndroid Build Coastguard Worker return true;
197*9880d681SAndroid Build Coastguard Worker }
198*9880d681SAndroid Build Coastguard Worker
199*9880d681SAndroid Build Coastguard Worker /// \brief Checks if the padding bytes of an argument could be accessed.
canPaddingBeAccessed(Argument * arg)200*9880d681SAndroid Build Coastguard Worker static bool canPaddingBeAccessed(Argument *arg) {
201*9880d681SAndroid Build Coastguard Worker
202*9880d681SAndroid Build Coastguard Worker assert(arg->hasByValAttr());
203*9880d681SAndroid Build Coastguard Worker
204*9880d681SAndroid Build Coastguard Worker // Track all the pointers to the argument to make sure they are not captured.
205*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Value *, 16> PtrValues;
206*9880d681SAndroid Build Coastguard Worker PtrValues.insert(arg);
207*9880d681SAndroid Build Coastguard Worker
208*9880d681SAndroid Build Coastguard Worker // Track all of the stores.
209*9880d681SAndroid Build Coastguard Worker SmallVector<StoreInst *, 16> Stores;
210*9880d681SAndroid Build Coastguard Worker
211*9880d681SAndroid Build Coastguard Worker // Scan through the uses recursively to make sure the pointer is always used
212*9880d681SAndroid Build Coastguard Worker // sanely.
213*9880d681SAndroid Build Coastguard Worker SmallVector<Value *, 16> WorkList;
214*9880d681SAndroid Build Coastguard Worker WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end());
215*9880d681SAndroid Build Coastguard Worker while (!WorkList.empty()) {
216*9880d681SAndroid Build Coastguard Worker Value *V = WorkList.back();
217*9880d681SAndroid Build Coastguard Worker WorkList.pop_back();
218*9880d681SAndroid Build Coastguard Worker if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
219*9880d681SAndroid Build Coastguard Worker if (PtrValues.insert(V).second)
220*9880d681SAndroid Build Coastguard Worker WorkList.insert(WorkList.end(), V->user_begin(), V->user_end());
221*9880d681SAndroid Build Coastguard Worker } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
222*9880d681SAndroid Build Coastguard Worker Stores.push_back(Store);
223*9880d681SAndroid Build Coastguard Worker } else if (!isa<LoadInst>(V)) {
224*9880d681SAndroid Build Coastguard Worker return true;
225*9880d681SAndroid Build Coastguard Worker }
226*9880d681SAndroid Build Coastguard Worker }
227*9880d681SAndroid Build Coastguard Worker
228*9880d681SAndroid Build Coastguard Worker // Check to make sure the pointers aren't captured
229*9880d681SAndroid Build Coastguard Worker for (StoreInst *Store : Stores)
230*9880d681SAndroid Build Coastguard Worker if (PtrValues.count(Store->getValueOperand()))
231*9880d681SAndroid Build Coastguard Worker return true;
232*9880d681SAndroid Build Coastguard Worker
233*9880d681SAndroid Build Coastguard Worker return false;
234*9880d681SAndroid Build Coastguard Worker }
235*9880d681SAndroid Build Coastguard Worker
236*9880d681SAndroid Build Coastguard Worker /// PromoteArguments - This method checks the specified function to see if there
237*9880d681SAndroid Build Coastguard Worker /// are any promotable arguments and if it is safe to promote the function (for
238*9880d681SAndroid Build Coastguard Worker /// example, all callers are direct). If safe to promote some arguments, it
239*9880d681SAndroid Build Coastguard Worker /// calls the DoPromotion method.
240*9880d681SAndroid Build Coastguard Worker ///
241*9880d681SAndroid Build Coastguard Worker static CallGraphNode *
PromoteArguments(CallGraphNode * CGN,CallGraph & CG,function_ref<AAResults & (Function & F)> AARGetter,unsigned MaxElements)242*9880d681SAndroid Build Coastguard Worker PromoteArguments(CallGraphNode *CGN, CallGraph &CG,
243*9880d681SAndroid Build Coastguard Worker function_ref<AAResults &(Function &F)> AARGetter,
244*9880d681SAndroid Build Coastguard Worker unsigned MaxElements) {
245*9880d681SAndroid Build Coastguard Worker Function *F = CGN->getFunction();
246*9880d681SAndroid Build Coastguard Worker
247*9880d681SAndroid Build Coastguard Worker // Make sure that it is local to this module.
248*9880d681SAndroid Build Coastguard Worker if (!F || !F->hasLocalLinkage()) return nullptr;
249*9880d681SAndroid Build Coastguard Worker
250*9880d681SAndroid Build Coastguard Worker // Don't promote arguments for variadic functions. Adding, removing, or
251*9880d681SAndroid Build Coastguard Worker // changing non-pack parameters can change the classification of pack
252*9880d681SAndroid Build Coastguard Worker // parameters. Frontends encode that classification at the call site in the
253*9880d681SAndroid Build Coastguard Worker // IR, while in the callee the classification is determined dynamically based
254*9880d681SAndroid Build Coastguard Worker // on the number of registers consumed so far.
255*9880d681SAndroid Build Coastguard Worker if (F->isVarArg()) return nullptr;
256*9880d681SAndroid Build Coastguard Worker
257*9880d681SAndroid Build Coastguard Worker // First check: see if there are any pointer arguments! If not, quick exit.
258*9880d681SAndroid Build Coastguard Worker SmallVector<Argument*, 16> PointerArgs;
259*9880d681SAndroid Build Coastguard Worker for (Argument &I : F->args())
260*9880d681SAndroid Build Coastguard Worker if (I.getType()->isPointerTy())
261*9880d681SAndroid Build Coastguard Worker PointerArgs.push_back(&I);
262*9880d681SAndroid Build Coastguard Worker if (PointerArgs.empty()) return nullptr;
263*9880d681SAndroid Build Coastguard Worker
264*9880d681SAndroid Build Coastguard Worker // Second check: make sure that all callers are direct callers. We can't
265*9880d681SAndroid Build Coastguard Worker // transform functions that have indirect callers. Also see if the function
266*9880d681SAndroid Build Coastguard Worker // is self-recursive.
267*9880d681SAndroid Build Coastguard Worker bool isSelfRecursive = false;
268*9880d681SAndroid Build Coastguard Worker for (Use &U : F->uses()) {
269*9880d681SAndroid Build Coastguard Worker CallSite CS(U.getUser());
270*9880d681SAndroid Build Coastguard Worker // Must be a direct call.
271*9880d681SAndroid Build Coastguard Worker if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr;
272*9880d681SAndroid Build Coastguard Worker
273*9880d681SAndroid Build Coastguard Worker if (CS.getInstruction()->getParent()->getParent() == F)
274*9880d681SAndroid Build Coastguard Worker isSelfRecursive = true;
275*9880d681SAndroid Build Coastguard Worker }
276*9880d681SAndroid Build Coastguard Worker
277*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = F->getParent()->getDataLayout();
278*9880d681SAndroid Build Coastguard Worker
279*9880d681SAndroid Build Coastguard Worker AAResults &AAR = AARGetter(*F);
280*9880d681SAndroid Build Coastguard Worker
281*9880d681SAndroid Build Coastguard Worker // Check to see which arguments are promotable. If an argument is promotable,
282*9880d681SAndroid Build Coastguard Worker // add it to ArgsToPromote.
283*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Argument*, 8> ArgsToPromote;
284*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Argument*, 8> ByValArgsToTransform;
285*9880d681SAndroid Build Coastguard Worker for (Argument *PtrArg : PointerArgs) {
286*9880d681SAndroid Build Coastguard Worker Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
287*9880d681SAndroid Build Coastguard Worker
288*9880d681SAndroid Build Coastguard Worker // Replace sret attribute with noalias. This reduces register pressure by
289*9880d681SAndroid Build Coastguard Worker // avoiding a register copy.
290*9880d681SAndroid Build Coastguard Worker if (PtrArg->hasStructRetAttr()) {
291*9880d681SAndroid Build Coastguard Worker unsigned ArgNo = PtrArg->getArgNo();
292*9880d681SAndroid Build Coastguard Worker F->setAttributes(
293*9880d681SAndroid Build Coastguard Worker F->getAttributes()
294*9880d681SAndroid Build Coastguard Worker .removeAttribute(F->getContext(), ArgNo + 1, Attribute::StructRet)
295*9880d681SAndroid Build Coastguard Worker .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
296*9880d681SAndroid Build Coastguard Worker for (Use &U : F->uses()) {
297*9880d681SAndroid Build Coastguard Worker CallSite CS(U.getUser());
298*9880d681SAndroid Build Coastguard Worker CS.setAttributes(
299*9880d681SAndroid Build Coastguard Worker CS.getAttributes()
300*9880d681SAndroid Build Coastguard Worker .removeAttribute(F->getContext(), ArgNo + 1,
301*9880d681SAndroid Build Coastguard Worker Attribute::StructRet)
302*9880d681SAndroid Build Coastguard Worker .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
303*9880d681SAndroid Build Coastguard Worker }
304*9880d681SAndroid Build Coastguard Worker }
305*9880d681SAndroid Build Coastguard Worker
306*9880d681SAndroid Build Coastguard Worker // If this is a byval argument, and if the aggregate type is small, just
307*9880d681SAndroid Build Coastguard Worker // pass the elements, which is always safe, if the passed value is densely
308*9880d681SAndroid Build Coastguard Worker // packed or if we can prove the padding bytes are never accessed. This does
309*9880d681SAndroid Build Coastguard Worker // not apply to inalloca.
310*9880d681SAndroid Build Coastguard Worker bool isSafeToPromote =
311*9880d681SAndroid Build Coastguard Worker PtrArg->hasByValAttr() &&
312*9880d681SAndroid Build Coastguard Worker (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg));
313*9880d681SAndroid Build Coastguard Worker if (isSafeToPromote) {
314*9880d681SAndroid Build Coastguard Worker if (StructType *STy = dyn_cast<StructType>(AgTy)) {
315*9880d681SAndroid Build Coastguard Worker if (MaxElements > 0 && STy->getNumElements() > MaxElements) {
316*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "argpromotion disable promoting argument '"
317*9880d681SAndroid Build Coastguard Worker << PtrArg->getName() << "' because it would require adding more"
318*9880d681SAndroid Build Coastguard Worker << " than " << MaxElements << " arguments to the function.\n");
319*9880d681SAndroid Build Coastguard Worker continue;
320*9880d681SAndroid Build Coastguard Worker }
321*9880d681SAndroid Build Coastguard Worker
322*9880d681SAndroid Build Coastguard Worker // If all the elements are single-value types, we can promote it.
323*9880d681SAndroid Build Coastguard Worker bool AllSimple = true;
324*9880d681SAndroid Build Coastguard Worker for (const auto *EltTy : STy->elements()) {
325*9880d681SAndroid Build Coastguard Worker if (!EltTy->isSingleValueType()) {
326*9880d681SAndroid Build Coastguard Worker AllSimple = false;
327*9880d681SAndroid Build Coastguard Worker break;
328*9880d681SAndroid Build Coastguard Worker }
329*9880d681SAndroid Build Coastguard Worker }
330*9880d681SAndroid Build Coastguard Worker
331*9880d681SAndroid Build Coastguard Worker // Safe to transform, don't even bother trying to "promote" it.
332*9880d681SAndroid Build Coastguard Worker // Passing the elements as a scalar will allow sroa to hack on
333*9880d681SAndroid Build Coastguard Worker // the new alloca we introduce.
334*9880d681SAndroid Build Coastguard Worker if (AllSimple) {
335*9880d681SAndroid Build Coastguard Worker ByValArgsToTransform.insert(PtrArg);
336*9880d681SAndroid Build Coastguard Worker continue;
337*9880d681SAndroid Build Coastguard Worker }
338*9880d681SAndroid Build Coastguard Worker }
339*9880d681SAndroid Build Coastguard Worker }
340*9880d681SAndroid Build Coastguard Worker
341*9880d681SAndroid Build Coastguard Worker // If the argument is a recursive type and we're in a recursive
342*9880d681SAndroid Build Coastguard Worker // function, we could end up infinitely peeling the function argument.
343*9880d681SAndroid Build Coastguard Worker if (isSelfRecursive) {
344*9880d681SAndroid Build Coastguard Worker if (StructType *STy = dyn_cast<StructType>(AgTy)) {
345*9880d681SAndroid Build Coastguard Worker bool RecursiveType = false;
346*9880d681SAndroid Build Coastguard Worker for (const auto *EltTy : STy->elements()) {
347*9880d681SAndroid Build Coastguard Worker if (EltTy == PtrArg->getType()) {
348*9880d681SAndroid Build Coastguard Worker RecursiveType = true;
349*9880d681SAndroid Build Coastguard Worker break;
350*9880d681SAndroid Build Coastguard Worker }
351*9880d681SAndroid Build Coastguard Worker }
352*9880d681SAndroid Build Coastguard Worker if (RecursiveType)
353*9880d681SAndroid Build Coastguard Worker continue;
354*9880d681SAndroid Build Coastguard Worker }
355*9880d681SAndroid Build Coastguard Worker }
356*9880d681SAndroid Build Coastguard Worker
357*9880d681SAndroid Build Coastguard Worker // Otherwise, see if we can promote the pointer to its value.
358*9880d681SAndroid Build Coastguard Worker if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr(), AAR,
359*9880d681SAndroid Build Coastguard Worker MaxElements))
360*9880d681SAndroid Build Coastguard Worker ArgsToPromote.insert(PtrArg);
361*9880d681SAndroid Build Coastguard Worker }
362*9880d681SAndroid Build Coastguard Worker
363*9880d681SAndroid Build Coastguard Worker // No promotable pointer arguments.
364*9880d681SAndroid Build Coastguard Worker if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
365*9880d681SAndroid Build Coastguard Worker return nullptr;
366*9880d681SAndroid Build Coastguard Worker
367*9880d681SAndroid Build Coastguard Worker return DoPromotion(F, ArgsToPromote, ByValArgsToTransform, CG);
368*9880d681SAndroid Build Coastguard Worker }
369*9880d681SAndroid Build Coastguard Worker
370*9880d681SAndroid Build Coastguard Worker /// AllCallersPassInValidPointerForArgument - Return true if we can prove that
371*9880d681SAndroid Build Coastguard Worker /// all callees pass in a valid pointer for the specified function argument.
AllCallersPassInValidPointerForArgument(Argument * Arg)372*9880d681SAndroid Build Coastguard Worker static bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
373*9880d681SAndroid Build Coastguard Worker Function *Callee = Arg->getParent();
374*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = Callee->getParent()->getDataLayout();
375*9880d681SAndroid Build Coastguard Worker
376*9880d681SAndroid Build Coastguard Worker unsigned ArgNo = Arg->getArgNo();
377*9880d681SAndroid Build Coastguard Worker
378*9880d681SAndroid Build Coastguard Worker // Look at all call sites of the function. At this pointer we know we only
379*9880d681SAndroid Build Coastguard Worker // have direct callees.
380*9880d681SAndroid Build Coastguard Worker for (User *U : Callee->users()) {
381*9880d681SAndroid Build Coastguard Worker CallSite CS(U);
382*9880d681SAndroid Build Coastguard Worker assert(CS && "Should only have direct calls!");
383*9880d681SAndroid Build Coastguard Worker
384*9880d681SAndroid Build Coastguard Worker if (!isDereferenceablePointer(CS.getArgument(ArgNo), DL))
385*9880d681SAndroid Build Coastguard Worker return false;
386*9880d681SAndroid Build Coastguard Worker }
387*9880d681SAndroid Build Coastguard Worker return true;
388*9880d681SAndroid Build Coastguard Worker }
389*9880d681SAndroid Build Coastguard Worker
390*9880d681SAndroid Build Coastguard Worker /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
391*9880d681SAndroid Build Coastguard Worker /// that is greater than or equal to the size of prefix, and each of the
392*9880d681SAndroid Build Coastguard Worker /// elements in Prefix is the same as the corresponding elements in Longer.
393*9880d681SAndroid Build Coastguard Worker ///
394*9880d681SAndroid Build Coastguard Worker /// This means it also returns true when Prefix and Longer are equal!
IsPrefix(const IndicesVector & Prefix,const IndicesVector & Longer)395*9880d681SAndroid Build Coastguard Worker static bool IsPrefix(const IndicesVector &Prefix, const IndicesVector &Longer) {
396*9880d681SAndroid Build Coastguard Worker if (Prefix.size() > Longer.size())
397*9880d681SAndroid Build Coastguard Worker return false;
398*9880d681SAndroid Build Coastguard Worker return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
399*9880d681SAndroid Build Coastguard Worker }
400*9880d681SAndroid Build Coastguard Worker
401*9880d681SAndroid Build Coastguard Worker
402*9880d681SAndroid Build Coastguard Worker /// Checks if Indices, or a prefix of Indices, is in Set.
PrefixIn(const IndicesVector & Indices,std::set<IndicesVector> & Set)403*9880d681SAndroid Build Coastguard Worker static bool PrefixIn(const IndicesVector &Indices,
404*9880d681SAndroid Build Coastguard Worker std::set<IndicesVector> &Set) {
405*9880d681SAndroid Build Coastguard Worker std::set<IndicesVector>::iterator Low;
406*9880d681SAndroid Build Coastguard Worker Low = Set.upper_bound(Indices);
407*9880d681SAndroid Build Coastguard Worker if (Low != Set.begin())
408*9880d681SAndroid Build Coastguard Worker Low--;
409*9880d681SAndroid Build Coastguard Worker // Low is now the last element smaller than or equal to Indices. This means
410*9880d681SAndroid Build Coastguard Worker // it points to a prefix of Indices (possibly Indices itself), if such
411*9880d681SAndroid Build Coastguard Worker // prefix exists.
412*9880d681SAndroid Build Coastguard Worker //
413*9880d681SAndroid Build Coastguard Worker // This load is safe if any prefix of its operands is safe to load.
414*9880d681SAndroid Build Coastguard Worker return Low != Set.end() && IsPrefix(*Low, Indices);
415*9880d681SAndroid Build Coastguard Worker }
416*9880d681SAndroid Build Coastguard Worker
417*9880d681SAndroid Build Coastguard Worker /// Mark the given indices (ToMark) as safe in the given set of indices
418*9880d681SAndroid Build Coastguard Worker /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
419*9880d681SAndroid Build Coastguard Worker /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
420*9880d681SAndroid Build Coastguard Worker /// already. Furthermore, any indices that Indices is itself a prefix of, are
421*9880d681SAndroid Build Coastguard Worker /// removed from Safe (since they are implicitely safe because of Indices now).
MarkIndicesSafe(const IndicesVector & ToMark,std::set<IndicesVector> & Safe)422*9880d681SAndroid Build Coastguard Worker static void MarkIndicesSafe(const IndicesVector &ToMark,
423*9880d681SAndroid Build Coastguard Worker std::set<IndicesVector> &Safe) {
424*9880d681SAndroid Build Coastguard Worker std::set<IndicesVector>::iterator Low;
425*9880d681SAndroid Build Coastguard Worker Low = Safe.upper_bound(ToMark);
426*9880d681SAndroid Build Coastguard Worker // Guard against the case where Safe is empty
427*9880d681SAndroid Build Coastguard Worker if (Low != Safe.begin())
428*9880d681SAndroid Build Coastguard Worker Low--;
429*9880d681SAndroid Build Coastguard Worker // Low is now the last element smaller than or equal to Indices. This
430*9880d681SAndroid Build Coastguard Worker // means it points to a prefix of Indices (possibly Indices itself), if
431*9880d681SAndroid Build Coastguard Worker // such prefix exists.
432*9880d681SAndroid Build Coastguard Worker if (Low != Safe.end()) {
433*9880d681SAndroid Build Coastguard Worker if (IsPrefix(*Low, ToMark))
434*9880d681SAndroid Build Coastguard Worker // If there is already a prefix of these indices (or exactly these
435*9880d681SAndroid Build Coastguard Worker // indices) marked a safe, don't bother adding these indices
436*9880d681SAndroid Build Coastguard Worker return;
437*9880d681SAndroid Build Coastguard Worker
438*9880d681SAndroid Build Coastguard Worker // Increment Low, so we can use it as a "insert before" hint
439*9880d681SAndroid Build Coastguard Worker ++Low;
440*9880d681SAndroid Build Coastguard Worker }
441*9880d681SAndroid Build Coastguard Worker // Insert
442*9880d681SAndroid Build Coastguard Worker Low = Safe.insert(Low, ToMark);
443*9880d681SAndroid Build Coastguard Worker ++Low;
444*9880d681SAndroid Build Coastguard Worker // If there we're a prefix of longer index list(s), remove those
445*9880d681SAndroid Build Coastguard Worker std::set<IndicesVector>::iterator End = Safe.end();
446*9880d681SAndroid Build Coastguard Worker while (Low != End && IsPrefix(ToMark, *Low)) {
447*9880d681SAndroid Build Coastguard Worker std::set<IndicesVector>::iterator Remove = Low;
448*9880d681SAndroid Build Coastguard Worker ++Low;
449*9880d681SAndroid Build Coastguard Worker Safe.erase(Remove);
450*9880d681SAndroid Build Coastguard Worker }
451*9880d681SAndroid Build Coastguard Worker }
452*9880d681SAndroid Build Coastguard Worker
453*9880d681SAndroid Build Coastguard Worker /// isSafeToPromoteArgument - As you might guess from the name of this method,
454*9880d681SAndroid Build Coastguard Worker /// it checks to see if it is both safe and useful to promote the argument.
455*9880d681SAndroid Build Coastguard Worker /// This method limits promotion of aggregates to only promote up to three
456*9880d681SAndroid Build Coastguard Worker /// elements of the aggregate in order to avoid exploding the number of
457*9880d681SAndroid Build Coastguard Worker /// arguments passed in.
isSafeToPromoteArgument(Argument * Arg,bool isByValOrInAlloca,AAResults & AAR,unsigned MaxElements)458*9880d681SAndroid Build Coastguard Worker static bool isSafeToPromoteArgument(Argument *Arg, bool isByValOrInAlloca,
459*9880d681SAndroid Build Coastguard Worker AAResults &AAR, unsigned MaxElements) {
460*9880d681SAndroid Build Coastguard Worker typedef std::set<IndicesVector> GEPIndicesSet;
461*9880d681SAndroid Build Coastguard Worker
462*9880d681SAndroid Build Coastguard Worker // Quick exit for unused arguments
463*9880d681SAndroid Build Coastguard Worker if (Arg->use_empty())
464*9880d681SAndroid Build Coastguard Worker return true;
465*9880d681SAndroid Build Coastguard Worker
466*9880d681SAndroid Build Coastguard Worker // We can only promote this argument if all of the uses are loads, or are GEP
467*9880d681SAndroid Build Coastguard Worker // instructions (with constant indices) that are subsequently loaded.
468*9880d681SAndroid Build Coastguard Worker //
469*9880d681SAndroid Build Coastguard Worker // Promoting the argument causes it to be loaded in the caller
470*9880d681SAndroid Build Coastguard Worker // unconditionally. This is only safe if we can prove that either the load
471*9880d681SAndroid Build Coastguard Worker // would have happened in the callee anyway (ie, there is a load in the entry
472*9880d681SAndroid Build Coastguard Worker // block) or the pointer passed in at every call site is guaranteed to be
473*9880d681SAndroid Build Coastguard Worker // valid.
474*9880d681SAndroid Build Coastguard Worker // In the former case, invalid loads can happen, but would have happened
475*9880d681SAndroid Build Coastguard Worker // anyway, in the latter case, invalid loads won't happen. This prevents us
476*9880d681SAndroid Build Coastguard Worker // from introducing an invalid load that wouldn't have happened in the
477*9880d681SAndroid Build Coastguard Worker // original code.
478*9880d681SAndroid Build Coastguard Worker //
479*9880d681SAndroid Build Coastguard Worker // This set will contain all sets of indices that are loaded in the entry
480*9880d681SAndroid Build Coastguard Worker // block, and thus are safe to unconditionally load in the caller.
481*9880d681SAndroid Build Coastguard Worker //
482*9880d681SAndroid Build Coastguard Worker // This optimization is also safe for InAlloca parameters, because it verifies
483*9880d681SAndroid Build Coastguard Worker // that the address isn't captured.
484*9880d681SAndroid Build Coastguard Worker GEPIndicesSet SafeToUnconditionallyLoad;
485*9880d681SAndroid Build Coastguard Worker
486*9880d681SAndroid Build Coastguard Worker // This set contains all the sets of indices that we are planning to promote.
487*9880d681SAndroid Build Coastguard Worker // This makes it possible to limit the number of arguments added.
488*9880d681SAndroid Build Coastguard Worker GEPIndicesSet ToPromote;
489*9880d681SAndroid Build Coastguard Worker
490*9880d681SAndroid Build Coastguard Worker // If the pointer is always valid, any load with first index 0 is valid.
491*9880d681SAndroid Build Coastguard Worker if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg))
492*9880d681SAndroid Build Coastguard Worker SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
493*9880d681SAndroid Build Coastguard Worker
494*9880d681SAndroid Build Coastguard Worker // First, iterate the entry block and mark loads of (geps of) arguments as
495*9880d681SAndroid Build Coastguard Worker // safe.
496*9880d681SAndroid Build Coastguard Worker BasicBlock &EntryBlock = Arg->getParent()->front();
497*9880d681SAndroid Build Coastguard Worker // Declare this here so we can reuse it
498*9880d681SAndroid Build Coastguard Worker IndicesVector Indices;
499*9880d681SAndroid Build Coastguard Worker for (Instruction &I : EntryBlock)
500*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
501*9880d681SAndroid Build Coastguard Worker Value *V = LI->getPointerOperand();
502*9880d681SAndroid Build Coastguard Worker if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
503*9880d681SAndroid Build Coastguard Worker V = GEP->getPointerOperand();
504*9880d681SAndroid Build Coastguard Worker if (V == Arg) {
505*9880d681SAndroid Build Coastguard Worker // This load actually loads (part of) Arg? Check the indices then.
506*9880d681SAndroid Build Coastguard Worker Indices.reserve(GEP->getNumIndices());
507*9880d681SAndroid Build Coastguard Worker for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
508*9880d681SAndroid Build Coastguard Worker II != IE; ++II)
509*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
510*9880d681SAndroid Build Coastguard Worker Indices.push_back(CI->getSExtValue());
511*9880d681SAndroid Build Coastguard Worker else
512*9880d681SAndroid Build Coastguard Worker // We found a non-constant GEP index for this argument? Bail out
513*9880d681SAndroid Build Coastguard Worker // right away, can't promote this argument at all.
514*9880d681SAndroid Build Coastguard Worker return false;
515*9880d681SAndroid Build Coastguard Worker
516*9880d681SAndroid Build Coastguard Worker // Indices checked out, mark them as safe
517*9880d681SAndroid Build Coastguard Worker MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
518*9880d681SAndroid Build Coastguard Worker Indices.clear();
519*9880d681SAndroid Build Coastguard Worker }
520*9880d681SAndroid Build Coastguard Worker } else if (V == Arg) {
521*9880d681SAndroid Build Coastguard Worker // Direct loads are equivalent to a GEP with a single 0 index.
522*9880d681SAndroid Build Coastguard Worker MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
523*9880d681SAndroid Build Coastguard Worker }
524*9880d681SAndroid Build Coastguard Worker }
525*9880d681SAndroid Build Coastguard Worker
526*9880d681SAndroid Build Coastguard Worker // Now, iterate all uses of the argument to see if there are any uses that are
527*9880d681SAndroid Build Coastguard Worker // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
528*9880d681SAndroid Build Coastguard Worker SmallVector<LoadInst*, 16> Loads;
529*9880d681SAndroid Build Coastguard Worker IndicesVector Operands;
530*9880d681SAndroid Build Coastguard Worker for (Use &U : Arg->uses()) {
531*9880d681SAndroid Build Coastguard Worker User *UR = U.getUser();
532*9880d681SAndroid Build Coastguard Worker Operands.clear();
533*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
534*9880d681SAndroid Build Coastguard Worker // Don't hack volatile/atomic loads
535*9880d681SAndroid Build Coastguard Worker if (!LI->isSimple()) return false;
536*9880d681SAndroid Build Coastguard Worker Loads.push_back(LI);
537*9880d681SAndroid Build Coastguard Worker // Direct loads are equivalent to a GEP with a zero index and then a load.
538*9880d681SAndroid Build Coastguard Worker Operands.push_back(0);
539*9880d681SAndroid Build Coastguard Worker } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
540*9880d681SAndroid Build Coastguard Worker if (GEP->use_empty()) {
541*9880d681SAndroid Build Coastguard Worker // Dead GEP's cause trouble later. Just remove them if we run into
542*9880d681SAndroid Build Coastguard Worker // them.
543*9880d681SAndroid Build Coastguard Worker GEP->eraseFromParent();
544*9880d681SAndroid Build Coastguard Worker // TODO: This runs the above loop over and over again for dead GEPs
545*9880d681SAndroid Build Coastguard Worker // Couldn't we just do increment the UI iterator earlier and erase the
546*9880d681SAndroid Build Coastguard Worker // use?
547*9880d681SAndroid Build Coastguard Worker return isSafeToPromoteArgument(Arg, isByValOrInAlloca, AAR,
548*9880d681SAndroid Build Coastguard Worker MaxElements);
549*9880d681SAndroid Build Coastguard Worker }
550*9880d681SAndroid Build Coastguard Worker
551*9880d681SAndroid Build Coastguard Worker // Ensure that all of the indices are constants.
552*9880d681SAndroid Build Coastguard Worker for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
553*9880d681SAndroid Build Coastguard Worker i != e; ++i)
554*9880d681SAndroid Build Coastguard Worker if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
555*9880d681SAndroid Build Coastguard Worker Operands.push_back(C->getSExtValue());
556*9880d681SAndroid Build Coastguard Worker else
557*9880d681SAndroid Build Coastguard Worker return false; // Not a constant operand GEP!
558*9880d681SAndroid Build Coastguard Worker
559*9880d681SAndroid Build Coastguard Worker // Ensure that the only users of the GEP are load instructions.
560*9880d681SAndroid Build Coastguard Worker for (User *GEPU : GEP->users())
561*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
562*9880d681SAndroid Build Coastguard Worker // Don't hack volatile/atomic loads
563*9880d681SAndroid Build Coastguard Worker if (!LI->isSimple()) return false;
564*9880d681SAndroid Build Coastguard Worker Loads.push_back(LI);
565*9880d681SAndroid Build Coastguard Worker } else {
566*9880d681SAndroid Build Coastguard Worker // Other uses than load?
567*9880d681SAndroid Build Coastguard Worker return false;
568*9880d681SAndroid Build Coastguard Worker }
569*9880d681SAndroid Build Coastguard Worker } else {
570*9880d681SAndroid Build Coastguard Worker return false; // Not a load or a GEP.
571*9880d681SAndroid Build Coastguard Worker }
572*9880d681SAndroid Build Coastguard Worker
573*9880d681SAndroid Build Coastguard Worker // Now, see if it is safe to promote this load / loads of this GEP. Loading
574*9880d681SAndroid Build Coastguard Worker // is safe if Operands, or a prefix of Operands, is marked as safe.
575*9880d681SAndroid Build Coastguard Worker if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
576*9880d681SAndroid Build Coastguard Worker return false;
577*9880d681SAndroid Build Coastguard Worker
578*9880d681SAndroid Build Coastguard Worker // See if we are already promoting a load with these indices. If not, check
579*9880d681SAndroid Build Coastguard Worker // to make sure that we aren't promoting too many elements. If so, nothing
580*9880d681SAndroid Build Coastguard Worker // to do.
581*9880d681SAndroid Build Coastguard Worker if (ToPromote.find(Operands) == ToPromote.end()) {
582*9880d681SAndroid Build Coastguard Worker if (MaxElements > 0 && ToPromote.size() == MaxElements) {
583*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "argpromotion not promoting argument '"
584*9880d681SAndroid Build Coastguard Worker << Arg->getName() << "' because it would require adding more "
585*9880d681SAndroid Build Coastguard Worker << "than " << MaxElements << " arguments to the function.\n");
586*9880d681SAndroid Build Coastguard Worker // We limit aggregate promotion to only promoting up to a fixed number
587*9880d681SAndroid Build Coastguard Worker // of elements of the aggregate.
588*9880d681SAndroid Build Coastguard Worker return false;
589*9880d681SAndroid Build Coastguard Worker }
590*9880d681SAndroid Build Coastguard Worker ToPromote.insert(std::move(Operands));
591*9880d681SAndroid Build Coastguard Worker }
592*9880d681SAndroid Build Coastguard Worker }
593*9880d681SAndroid Build Coastguard Worker
594*9880d681SAndroid Build Coastguard Worker if (Loads.empty()) return true; // No users, this is a dead argument.
595*9880d681SAndroid Build Coastguard Worker
596*9880d681SAndroid Build Coastguard Worker // Okay, now we know that the argument is only used by load instructions and
597*9880d681SAndroid Build Coastguard Worker // it is safe to unconditionally perform all of them. Use alias analysis to
598*9880d681SAndroid Build Coastguard Worker // check to see if the pointer is guaranteed to not be modified from entry of
599*9880d681SAndroid Build Coastguard Worker // the function to each of the load instructions.
600*9880d681SAndroid Build Coastguard Worker
601*9880d681SAndroid Build Coastguard Worker // Because there could be several/many load instructions, remember which
602*9880d681SAndroid Build Coastguard Worker // blocks we know to be transparent to the load.
603*9880d681SAndroid Build Coastguard Worker SmallPtrSet<BasicBlock*, 16> TranspBlocks;
604*9880d681SAndroid Build Coastguard Worker
605*9880d681SAndroid Build Coastguard Worker for (LoadInst *Load : Loads) {
606*9880d681SAndroid Build Coastguard Worker // Check to see if the load is invalidated from the start of the block to
607*9880d681SAndroid Build Coastguard Worker // the load itself.
608*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = Load->getParent();
609*9880d681SAndroid Build Coastguard Worker
610*9880d681SAndroid Build Coastguard Worker MemoryLocation Loc = MemoryLocation::get(Load);
611*9880d681SAndroid Build Coastguard Worker if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, MRI_Mod))
612*9880d681SAndroid Build Coastguard Worker return false; // Pointer is invalidated!
613*9880d681SAndroid Build Coastguard Worker
614*9880d681SAndroid Build Coastguard Worker // Now check every path from the entry block to the load for transparency.
615*9880d681SAndroid Build Coastguard Worker // To do this, we perform a depth first search on the inverse CFG from the
616*9880d681SAndroid Build Coastguard Worker // loading block.
617*9880d681SAndroid Build Coastguard Worker for (BasicBlock *P : predecessors(BB)) {
618*9880d681SAndroid Build Coastguard Worker for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
619*9880d681SAndroid Build Coastguard Worker if (AAR.canBasicBlockModify(*TranspBB, Loc))
620*9880d681SAndroid Build Coastguard Worker return false;
621*9880d681SAndroid Build Coastguard Worker }
622*9880d681SAndroid Build Coastguard Worker }
623*9880d681SAndroid Build Coastguard Worker
624*9880d681SAndroid Build Coastguard Worker // If the path from the entry of the function to each load is free of
625*9880d681SAndroid Build Coastguard Worker // instructions that potentially invalidate the load, we can make the
626*9880d681SAndroid Build Coastguard Worker // transformation!
627*9880d681SAndroid Build Coastguard Worker return true;
628*9880d681SAndroid Build Coastguard Worker }
629*9880d681SAndroid Build Coastguard Worker
630*9880d681SAndroid Build Coastguard Worker /// DoPromotion - This method actually performs the promotion of the specified
631*9880d681SAndroid Build Coastguard Worker /// arguments, and returns the new function. At this point, we know that it's
632*9880d681SAndroid Build Coastguard Worker /// safe to do so.
633*9880d681SAndroid Build Coastguard Worker static CallGraphNode *
DoPromotion(Function * F,SmallPtrSetImpl<Argument * > & ArgsToPromote,SmallPtrSetImpl<Argument * > & ByValArgsToTransform,CallGraph & CG)634*9880d681SAndroid Build Coastguard Worker DoPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote,
635*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<Argument *> &ByValArgsToTransform, CallGraph &CG) {
636*9880d681SAndroid Build Coastguard Worker
637*9880d681SAndroid Build Coastguard Worker // Start by computing a new prototype for the function, which is the same as
638*9880d681SAndroid Build Coastguard Worker // the old function, but has modified arguments.
639*9880d681SAndroid Build Coastguard Worker FunctionType *FTy = F->getFunctionType();
640*9880d681SAndroid Build Coastguard Worker std::vector<Type*> Params;
641*9880d681SAndroid Build Coastguard Worker
642*9880d681SAndroid Build Coastguard Worker typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable;
643*9880d681SAndroid Build Coastguard Worker
644*9880d681SAndroid Build Coastguard Worker // ScalarizedElements - If we are promoting a pointer that has elements
645*9880d681SAndroid Build Coastguard Worker // accessed out of it, keep track of which elements are accessed so that we
646*9880d681SAndroid Build Coastguard Worker // can add one argument for each.
647*9880d681SAndroid Build Coastguard Worker //
648*9880d681SAndroid Build Coastguard Worker // Arguments that are directly loaded will have a zero element value here, to
649*9880d681SAndroid Build Coastguard Worker // handle cases where there are both a direct load and GEP accesses.
650*9880d681SAndroid Build Coastguard Worker //
651*9880d681SAndroid Build Coastguard Worker std::map<Argument*, ScalarizeTable> ScalarizedElements;
652*9880d681SAndroid Build Coastguard Worker
653*9880d681SAndroid Build Coastguard Worker // OriginalLoads - Keep track of a representative load instruction from the
654*9880d681SAndroid Build Coastguard Worker // original function so that we can tell the alias analysis implementation
655*9880d681SAndroid Build Coastguard Worker // what the new GEP/Load instructions we are inserting look like.
656*9880d681SAndroid Build Coastguard Worker // We need to keep the original loads for each argument and the elements
657*9880d681SAndroid Build Coastguard Worker // of the argument that are accessed.
658*9880d681SAndroid Build Coastguard Worker std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads;
659*9880d681SAndroid Build Coastguard Worker
660*9880d681SAndroid Build Coastguard Worker // Attribute - Keep track of the parameter attributes for the arguments
661*9880d681SAndroid Build Coastguard Worker // that we are *not* promoting. For the ones that we do promote, the parameter
662*9880d681SAndroid Build Coastguard Worker // attributes are lost
663*9880d681SAndroid Build Coastguard Worker SmallVector<AttributeSet, 8> AttributesVec;
664*9880d681SAndroid Build Coastguard Worker const AttributeSet &PAL = F->getAttributes();
665*9880d681SAndroid Build Coastguard Worker
666*9880d681SAndroid Build Coastguard Worker // Add any return attributes.
667*9880d681SAndroid Build Coastguard Worker if (PAL.hasAttributes(AttributeSet::ReturnIndex))
668*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(F->getContext(),
669*9880d681SAndroid Build Coastguard Worker PAL.getRetAttributes()));
670*9880d681SAndroid Build Coastguard Worker
671*9880d681SAndroid Build Coastguard Worker // First, determine the new argument list
672*9880d681SAndroid Build Coastguard Worker unsigned ArgIndex = 1;
673*9880d681SAndroid Build Coastguard Worker for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
674*9880d681SAndroid Build Coastguard Worker ++I, ++ArgIndex) {
675*9880d681SAndroid Build Coastguard Worker if (ByValArgsToTransform.count(&*I)) {
676*9880d681SAndroid Build Coastguard Worker // Simple byval argument? Just add all the struct element types.
677*9880d681SAndroid Build Coastguard Worker Type *AgTy = cast<PointerType>(I->getType())->getElementType();
678*9880d681SAndroid Build Coastguard Worker StructType *STy = cast<StructType>(AgTy);
679*9880d681SAndroid Build Coastguard Worker Params.insert(Params.end(), STy->element_begin(), STy->element_end());
680*9880d681SAndroid Build Coastguard Worker ++NumByValArgsPromoted;
681*9880d681SAndroid Build Coastguard Worker } else if (!ArgsToPromote.count(&*I)) {
682*9880d681SAndroid Build Coastguard Worker // Unchanged argument
683*9880d681SAndroid Build Coastguard Worker Params.push_back(I->getType());
684*9880d681SAndroid Build Coastguard Worker AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
685*9880d681SAndroid Build Coastguard Worker if (attrs.hasAttributes(ArgIndex)) {
686*9880d681SAndroid Build Coastguard Worker AttrBuilder B(attrs, ArgIndex);
687*9880d681SAndroid Build Coastguard Worker AttributesVec.
688*9880d681SAndroid Build Coastguard Worker push_back(AttributeSet::get(F->getContext(), Params.size(), B));
689*9880d681SAndroid Build Coastguard Worker }
690*9880d681SAndroid Build Coastguard Worker } else if (I->use_empty()) {
691*9880d681SAndroid Build Coastguard Worker // Dead argument (which are always marked as promotable)
692*9880d681SAndroid Build Coastguard Worker ++NumArgumentsDead;
693*9880d681SAndroid Build Coastguard Worker } else {
694*9880d681SAndroid Build Coastguard Worker // Okay, this is being promoted. This means that the only uses are loads
695*9880d681SAndroid Build Coastguard Worker // or GEPs which are only used by loads
696*9880d681SAndroid Build Coastguard Worker
697*9880d681SAndroid Build Coastguard Worker // In this table, we will track which indices are loaded from the argument
698*9880d681SAndroid Build Coastguard Worker // (where direct loads are tracked as no indices).
699*9880d681SAndroid Build Coastguard Worker ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
700*9880d681SAndroid Build Coastguard Worker for (User *U : I->users()) {
701*9880d681SAndroid Build Coastguard Worker Instruction *UI = cast<Instruction>(U);
702*9880d681SAndroid Build Coastguard Worker Type *SrcTy;
703*9880d681SAndroid Build Coastguard Worker if (LoadInst *L = dyn_cast<LoadInst>(UI))
704*9880d681SAndroid Build Coastguard Worker SrcTy = L->getType();
705*9880d681SAndroid Build Coastguard Worker else
706*9880d681SAndroid Build Coastguard Worker SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
707*9880d681SAndroid Build Coastguard Worker IndicesVector Indices;
708*9880d681SAndroid Build Coastguard Worker Indices.reserve(UI->getNumOperands() - 1);
709*9880d681SAndroid Build Coastguard Worker // Since loads will only have a single operand, and GEPs only a single
710*9880d681SAndroid Build Coastguard Worker // non-index operand, this will record direct loads without any indices,
711*9880d681SAndroid Build Coastguard Worker // and gep+loads with the GEP indices.
712*9880d681SAndroid Build Coastguard Worker for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
713*9880d681SAndroid Build Coastguard Worker II != IE; ++II)
714*9880d681SAndroid Build Coastguard Worker Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
715*9880d681SAndroid Build Coastguard Worker // GEPs with a single 0 index can be merged with direct loads
716*9880d681SAndroid Build Coastguard Worker if (Indices.size() == 1 && Indices.front() == 0)
717*9880d681SAndroid Build Coastguard Worker Indices.clear();
718*9880d681SAndroid Build Coastguard Worker ArgIndices.insert(std::make_pair(SrcTy, Indices));
719*9880d681SAndroid Build Coastguard Worker LoadInst *OrigLoad;
720*9880d681SAndroid Build Coastguard Worker if (LoadInst *L = dyn_cast<LoadInst>(UI))
721*9880d681SAndroid Build Coastguard Worker OrigLoad = L;
722*9880d681SAndroid Build Coastguard Worker else
723*9880d681SAndroid Build Coastguard Worker // Take any load, we will use it only to update Alias Analysis
724*9880d681SAndroid Build Coastguard Worker OrigLoad = cast<LoadInst>(UI->user_back());
725*9880d681SAndroid Build Coastguard Worker OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
726*9880d681SAndroid Build Coastguard Worker }
727*9880d681SAndroid Build Coastguard Worker
728*9880d681SAndroid Build Coastguard Worker // Add a parameter to the function for each element passed in.
729*9880d681SAndroid Build Coastguard Worker for (const auto &ArgIndex : ArgIndices) {
730*9880d681SAndroid Build Coastguard Worker // not allowed to dereference ->begin() if size() is 0
731*9880d681SAndroid Build Coastguard Worker Params.push_back(GetElementPtrInst::getIndexedType(
732*9880d681SAndroid Build Coastguard Worker cast<PointerType>(I->getType()->getScalarType())->getElementType(),
733*9880d681SAndroid Build Coastguard Worker ArgIndex.second));
734*9880d681SAndroid Build Coastguard Worker assert(Params.back());
735*9880d681SAndroid Build Coastguard Worker }
736*9880d681SAndroid Build Coastguard Worker
737*9880d681SAndroid Build Coastguard Worker if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
738*9880d681SAndroid Build Coastguard Worker ++NumArgumentsPromoted;
739*9880d681SAndroid Build Coastguard Worker else
740*9880d681SAndroid Build Coastguard Worker ++NumAggregatesPromoted;
741*9880d681SAndroid Build Coastguard Worker }
742*9880d681SAndroid Build Coastguard Worker }
743*9880d681SAndroid Build Coastguard Worker
744*9880d681SAndroid Build Coastguard Worker // Add any function attributes.
745*9880d681SAndroid Build Coastguard Worker if (PAL.hasAttributes(AttributeSet::FunctionIndex))
746*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
747*9880d681SAndroid Build Coastguard Worker PAL.getFnAttributes()));
748*9880d681SAndroid Build Coastguard Worker
749*9880d681SAndroid Build Coastguard Worker Type *RetTy = FTy->getReturnType();
750*9880d681SAndroid Build Coastguard Worker
751*9880d681SAndroid Build Coastguard Worker // Construct the new function type using the new arguments.
752*9880d681SAndroid Build Coastguard Worker FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
753*9880d681SAndroid Build Coastguard Worker
754*9880d681SAndroid Build Coastguard Worker // Create the new function body and insert it into the module.
755*9880d681SAndroid Build Coastguard Worker Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
756*9880d681SAndroid Build Coastguard Worker NF->copyAttributesFrom(F);
757*9880d681SAndroid Build Coastguard Worker
758*9880d681SAndroid Build Coastguard Worker // Patch the pointer to LLVM function in debug info descriptor.
759*9880d681SAndroid Build Coastguard Worker NF->setSubprogram(F->getSubprogram());
760*9880d681SAndroid Build Coastguard Worker F->setSubprogram(nullptr);
761*9880d681SAndroid Build Coastguard Worker
762*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n"
763*9880d681SAndroid Build Coastguard Worker << "From: " << *F);
764*9880d681SAndroid Build Coastguard Worker
765*9880d681SAndroid Build Coastguard Worker // Recompute the parameter attributes list based on the new arguments for
766*9880d681SAndroid Build Coastguard Worker // the function.
767*9880d681SAndroid Build Coastguard Worker NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
768*9880d681SAndroid Build Coastguard Worker AttributesVec.clear();
769*9880d681SAndroid Build Coastguard Worker
770*9880d681SAndroid Build Coastguard Worker F->getParent()->getFunctionList().insert(F->getIterator(), NF);
771*9880d681SAndroid Build Coastguard Worker NF->takeName(F);
772*9880d681SAndroid Build Coastguard Worker
773*9880d681SAndroid Build Coastguard Worker // Get a new callgraph node for NF.
774*9880d681SAndroid Build Coastguard Worker CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
775*9880d681SAndroid Build Coastguard Worker
776*9880d681SAndroid Build Coastguard Worker // Loop over all of the callers of the function, transforming the call sites
777*9880d681SAndroid Build Coastguard Worker // to pass in the loaded pointers.
778*9880d681SAndroid Build Coastguard Worker //
779*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 16> Args;
780*9880d681SAndroid Build Coastguard Worker while (!F->use_empty()) {
781*9880d681SAndroid Build Coastguard Worker CallSite CS(F->user_back());
782*9880d681SAndroid Build Coastguard Worker assert(CS.getCalledFunction() == F);
783*9880d681SAndroid Build Coastguard Worker Instruction *Call = CS.getInstruction();
784*9880d681SAndroid Build Coastguard Worker const AttributeSet &CallPAL = CS.getAttributes();
785*9880d681SAndroid Build Coastguard Worker
786*9880d681SAndroid Build Coastguard Worker // Add any return attributes.
787*9880d681SAndroid Build Coastguard Worker if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
788*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(F->getContext(),
789*9880d681SAndroid Build Coastguard Worker CallPAL.getRetAttributes()));
790*9880d681SAndroid Build Coastguard Worker
791*9880d681SAndroid Build Coastguard Worker // Loop over the operands, inserting GEP and loads in the caller as
792*9880d681SAndroid Build Coastguard Worker // appropriate.
793*9880d681SAndroid Build Coastguard Worker CallSite::arg_iterator AI = CS.arg_begin();
794*9880d681SAndroid Build Coastguard Worker ArgIndex = 1;
795*9880d681SAndroid Build Coastguard Worker for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
796*9880d681SAndroid Build Coastguard Worker I != E; ++I, ++AI, ++ArgIndex)
797*9880d681SAndroid Build Coastguard Worker if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
798*9880d681SAndroid Build Coastguard Worker Args.push_back(*AI); // Unmodified argument
799*9880d681SAndroid Build Coastguard Worker
800*9880d681SAndroid Build Coastguard Worker if (CallPAL.hasAttributes(ArgIndex)) {
801*9880d681SAndroid Build Coastguard Worker AttrBuilder B(CallPAL, ArgIndex);
802*9880d681SAndroid Build Coastguard Worker AttributesVec.
803*9880d681SAndroid Build Coastguard Worker push_back(AttributeSet::get(F->getContext(), Args.size(), B));
804*9880d681SAndroid Build Coastguard Worker }
805*9880d681SAndroid Build Coastguard Worker } else if (ByValArgsToTransform.count(&*I)) {
806*9880d681SAndroid Build Coastguard Worker // Emit a GEP and load for each element of the struct.
807*9880d681SAndroid Build Coastguard Worker Type *AgTy = cast<PointerType>(I->getType())->getElementType();
808*9880d681SAndroid Build Coastguard Worker StructType *STy = cast<StructType>(AgTy);
809*9880d681SAndroid Build Coastguard Worker Value *Idxs[2] = {
810*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
811*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
812*9880d681SAndroid Build Coastguard Worker Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
813*9880d681SAndroid Build Coastguard Worker Value *Idx = GetElementPtrInst::Create(
814*9880d681SAndroid Build Coastguard Worker STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call);
815*9880d681SAndroid Build Coastguard Worker // TODO: Tell AA about the new values?
816*9880d681SAndroid Build Coastguard Worker Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
817*9880d681SAndroid Build Coastguard Worker }
818*9880d681SAndroid Build Coastguard Worker } else if (!I->use_empty()) {
819*9880d681SAndroid Build Coastguard Worker // Non-dead argument: insert GEPs and loads as appropriate.
820*9880d681SAndroid Build Coastguard Worker ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
821*9880d681SAndroid Build Coastguard Worker // Store the Value* version of the indices in here, but declare it now
822*9880d681SAndroid Build Coastguard Worker // for reuse.
823*9880d681SAndroid Build Coastguard Worker std::vector<Value*> Ops;
824*9880d681SAndroid Build Coastguard Worker for (const auto &ArgIndex : ArgIndices) {
825*9880d681SAndroid Build Coastguard Worker Value *V = *AI;
826*9880d681SAndroid Build Coastguard Worker LoadInst *OrigLoad =
827*9880d681SAndroid Build Coastguard Worker OriginalLoads[std::make_pair(&*I, ArgIndex.second)];
828*9880d681SAndroid Build Coastguard Worker if (!ArgIndex.second.empty()) {
829*9880d681SAndroid Build Coastguard Worker Ops.reserve(ArgIndex.second.size());
830*9880d681SAndroid Build Coastguard Worker Type *ElTy = V->getType();
831*9880d681SAndroid Build Coastguard Worker for (unsigned long II : ArgIndex.second) {
832*9880d681SAndroid Build Coastguard Worker // Use i32 to index structs, and i64 for others (pointers/arrays).
833*9880d681SAndroid Build Coastguard Worker // This satisfies GEP constraints.
834*9880d681SAndroid Build Coastguard Worker Type *IdxTy = (ElTy->isStructTy() ?
835*9880d681SAndroid Build Coastguard Worker Type::getInt32Ty(F->getContext()) :
836*9880d681SAndroid Build Coastguard Worker Type::getInt64Ty(F->getContext()));
837*9880d681SAndroid Build Coastguard Worker Ops.push_back(ConstantInt::get(IdxTy, II));
838*9880d681SAndroid Build Coastguard Worker // Keep track of the type we're currently indexing.
839*9880d681SAndroid Build Coastguard Worker ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(II);
840*9880d681SAndroid Build Coastguard Worker }
841*9880d681SAndroid Build Coastguard Worker // And create a GEP to extract those indices.
842*9880d681SAndroid Build Coastguard Worker V = GetElementPtrInst::Create(ArgIndex.first, V, Ops,
843*9880d681SAndroid Build Coastguard Worker V->getName() + ".idx", Call);
844*9880d681SAndroid Build Coastguard Worker Ops.clear();
845*9880d681SAndroid Build Coastguard Worker }
846*9880d681SAndroid Build Coastguard Worker // Since we're replacing a load make sure we take the alignment
847*9880d681SAndroid Build Coastguard Worker // of the previous load.
848*9880d681SAndroid Build Coastguard Worker LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
849*9880d681SAndroid Build Coastguard Worker newLoad->setAlignment(OrigLoad->getAlignment());
850*9880d681SAndroid Build Coastguard Worker // Transfer the AA info too.
851*9880d681SAndroid Build Coastguard Worker AAMDNodes AAInfo;
852*9880d681SAndroid Build Coastguard Worker OrigLoad->getAAMetadata(AAInfo);
853*9880d681SAndroid Build Coastguard Worker newLoad->setAAMetadata(AAInfo);
854*9880d681SAndroid Build Coastguard Worker
855*9880d681SAndroid Build Coastguard Worker Args.push_back(newLoad);
856*9880d681SAndroid Build Coastguard Worker }
857*9880d681SAndroid Build Coastguard Worker }
858*9880d681SAndroid Build Coastguard Worker
859*9880d681SAndroid Build Coastguard Worker // Push any varargs arguments on the list.
860*9880d681SAndroid Build Coastguard Worker for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
861*9880d681SAndroid Build Coastguard Worker Args.push_back(*AI);
862*9880d681SAndroid Build Coastguard Worker if (CallPAL.hasAttributes(ArgIndex)) {
863*9880d681SAndroid Build Coastguard Worker AttrBuilder B(CallPAL, ArgIndex);
864*9880d681SAndroid Build Coastguard Worker AttributesVec.
865*9880d681SAndroid Build Coastguard Worker push_back(AttributeSet::get(F->getContext(), Args.size(), B));
866*9880d681SAndroid Build Coastguard Worker }
867*9880d681SAndroid Build Coastguard Worker }
868*9880d681SAndroid Build Coastguard Worker
869*9880d681SAndroid Build Coastguard Worker // Add any function attributes.
870*9880d681SAndroid Build Coastguard Worker if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
871*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(Call->getContext(),
872*9880d681SAndroid Build Coastguard Worker CallPAL.getFnAttributes()));
873*9880d681SAndroid Build Coastguard Worker
874*9880d681SAndroid Build Coastguard Worker SmallVector<OperandBundleDef, 1> OpBundles;
875*9880d681SAndroid Build Coastguard Worker CS.getOperandBundlesAsDefs(OpBundles);
876*9880d681SAndroid Build Coastguard Worker
877*9880d681SAndroid Build Coastguard Worker Instruction *New;
878*9880d681SAndroid Build Coastguard Worker if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
879*9880d681SAndroid Build Coastguard Worker New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
880*9880d681SAndroid Build Coastguard Worker Args, OpBundles, "", Call);
881*9880d681SAndroid Build Coastguard Worker cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
882*9880d681SAndroid Build Coastguard Worker cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
883*9880d681SAndroid Build Coastguard Worker AttributesVec));
884*9880d681SAndroid Build Coastguard Worker } else {
885*9880d681SAndroid Build Coastguard Worker New = CallInst::Create(NF, Args, OpBundles, "", Call);
886*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
887*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
888*9880d681SAndroid Build Coastguard Worker AttributesVec));
889*9880d681SAndroid Build Coastguard Worker if (cast<CallInst>(Call)->isTailCall())
890*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setTailCall();
891*9880d681SAndroid Build Coastguard Worker }
892*9880d681SAndroid Build Coastguard Worker New->setDebugLoc(Call->getDebugLoc());
893*9880d681SAndroid Build Coastguard Worker Args.clear();
894*9880d681SAndroid Build Coastguard Worker AttributesVec.clear();
895*9880d681SAndroid Build Coastguard Worker
896*9880d681SAndroid Build Coastguard Worker // Update the callgraph to know that the callsite has been transformed.
897*9880d681SAndroid Build Coastguard Worker CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
898*9880d681SAndroid Build Coastguard Worker CalleeNode->replaceCallEdge(CS, CallSite(New), NF_CGN);
899*9880d681SAndroid Build Coastguard Worker
900*9880d681SAndroid Build Coastguard Worker if (!Call->use_empty()) {
901*9880d681SAndroid Build Coastguard Worker Call->replaceAllUsesWith(New);
902*9880d681SAndroid Build Coastguard Worker New->takeName(Call);
903*9880d681SAndroid Build Coastguard Worker }
904*9880d681SAndroid Build Coastguard Worker
905*9880d681SAndroid Build Coastguard Worker // Finally, remove the old call from the program, reducing the use-count of
906*9880d681SAndroid Build Coastguard Worker // F.
907*9880d681SAndroid Build Coastguard Worker Call->eraseFromParent();
908*9880d681SAndroid Build Coastguard Worker }
909*9880d681SAndroid Build Coastguard Worker
910*9880d681SAndroid Build Coastguard Worker // Since we have now created the new function, splice the body of the old
911*9880d681SAndroid Build Coastguard Worker // function right into the new function, leaving the old rotting hulk of the
912*9880d681SAndroid Build Coastguard Worker // function empty.
913*9880d681SAndroid Build Coastguard Worker NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
914*9880d681SAndroid Build Coastguard Worker
915*9880d681SAndroid Build Coastguard Worker // Loop over the argument list, transferring uses of the old arguments over to
916*9880d681SAndroid Build Coastguard Worker // the new arguments, also transferring over the names as well.
917*9880d681SAndroid Build Coastguard Worker //
918*9880d681SAndroid Build Coastguard Worker for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
919*9880d681SAndroid Build Coastguard Worker I2 = NF->arg_begin(); I != E; ++I) {
920*9880d681SAndroid Build Coastguard Worker if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
921*9880d681SAndroid Build Coastguard Worker // If this is an unmodified argument, move the name and users over to the
922*9880d681SAndroid Build Coastguard Worker // new version.
923*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(&*I2);
924*9880d681SAndroid Build Coastguard Worker I2->takeName(&*I);
925*9880d681SAndroid Build Coastguard Worker ++I2;
926*9880d681SAndroid Build Coastguard Worker continue;
927*9880d681SAndroid Build Coastguard Worker }
928*9880d681SAndroid Build Coastguard Worker
929*9880d681SAndroid Build Coastguard Worker if (ByValArgsToTransform.count(&*I)) {
930*9880d681SAndroid Build Coastguard Worker // In the callee, we create an alloca, and store each of the new incoming
931*9880d681SAndroid Build Coastguard Worker // arguments into the alloca.
932*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt = &NF->begin()->front();
933*9880d681SAndroid Build Coastguard Worker
934*9880d681SAndroid Build Coastguard Worker // Just add all the struct element types.
935*9880d681SAndroid Build Coastguard Worker Type *AgTy = cast<PointerType>(I->getType())->getElementType();
936*9880d681SAndroid Build Coastguard Worker Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
937*9880d681SAndroid Build Coastguard Worker StructType *STy = cast<StructType>(AgTy);
938*9880d681SAndroid Build Coastguard Worker Value *Idxs[2] = {
939*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
940*9880d681SAndroid Build Coastguard Worker
941*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
942*9880d681SAndroid Build Coastguard Worker Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
943*9880d681SAndroid Build Coastguard Worker Value *Idx = GetElementPtrInst::Create(
944*9880d681SAndroid Build Coastguard Worker AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
945*9880d681SAndroid Build Coastguard Worker InsertPt);
946*9880d681SAndroid Build Coastguard Worker I2->setName(I->getName()+"."+Twine(i));
947*9880d681SAndroid Build Coastguard Worker new StoreInst(&*I2++, Idx, InsertPt);
948*9880d681SAndroid Build Coastguard Worker }
949*9880d681SAndroid Build Coastguard Worker
950*9880d681SAndroid Build Coastguard Worker // Anything that used the arg should now use the alloca.
951*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(TheAlloca);
952*9880d681SAndroid Build Coastguard Worker TheAlloca->takeName(&*I);
953*9880d681SAndroid Build Coastguard Worker
954*9880d681SAndroid Build Coastguard Worker // If the alloca is used in a call, we must clear the tail flag since
955*9880d681SAndroid Build Coastguard Worker // the callee now uses an alloca from the caller.
956*9880d681SAndroid Build Coastguard Worker for (User *U : TheAlloca->users()) {
957*9880d681SAndroid Build Coastguard Worker CallInst *Call = dyn_cast<CallInst>(U);
958*9880d681SAndroid Build Coastguard Worker if (!Call)
959*9880d681SAndroid Build Coastguard Worker continue;
960*9880d681SAndroid Build Coastguard Worker Call->setTailCall(false);
961*9880d681SAndroid Build Coastguard Worker }
962*9880d681SAndroid Build Coastguard Worker continue;
963*9880d681SAndroid Build Coastguard Worker }
964*9880d681SAndroid Build Coastguard Worker
965*9880d681SAndroid Build Coastguard Worker if (I->use_empty())
966*9880d681SAndroid Build Coastguard Worker continue;
967*9880d681SAndroid Build Coastguard Worker
968*9880d681SAndroid Build Coastguard Worker // Otherwise, if we promoted this argument, then all users are load
969*9880d681SAndroid Build Coastguard Worker // instructions (or GEPs with only load users), and all loads should be
970*9880d681SAndroid Build Coastguard Worker // using the new argument that we added.
971*9880d681SAndroid Build Coastguard Worker ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
972*9880d681SAndroid Build Coastguard Worker
973*9880d681SAndroid Build Coastguard Worker while (!I->use_empty()) {
974*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
975*9880d681SAndroid Build Coastguard Worker assert(ArgIndices.begin()->second.empty() &&
976*9880d681SAndroid Build Coastguard Worker "Load element should sort to front!");
977*9880d681SAndroid Build Coastguard Worker I2->setName(I->getName()+".val");
978*9880d681SAndroid Build Coastguard Worker LI->replaceAllUsesWith(&*I2);
979*9880d681SAndroid Build Coastguard Worker LI->eraseFromParent();
980*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
981*9880d681SAndroid Build Coastguard Worker << "' in function '" << F->getName() << "'\n");
982*9880d681SAndroid Build Coastguard Worker } else {
983*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
984*9880d681SAndroid Build Coastguard Worker IndicesVector Operands;
985*9880d681SAndroid Build Coastguard Worker Operands.reserve(GEP->getNumIndices());
986*9880d681SAndroid Build Coastguard Worker for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
987*9880d681SAndroid Build Coastguard Worker II != IE; ++II)
988*9880d681SAndroid Build Coastguard Worker Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
989*9880d681SAndroid Build Coastguard Worker
990*9880d681SAndroid Build Coastguard Worker // GEPs with a single 0 index can be merged with direct loads
991*9880d681SAndroid Build Coastguard Worker if (Operands.size() == 1 && Operands.front() == 0)
992*9880d681SAndroid Build Coastguard Worker Operands.clear();
993*9880d681SAndroid Build Coastguard Worker
994*9880d681SAndroid Build Coastguard Worker Function::arg_iterator TheArg = I2;
995*9880d681SAndroid Build Coastguard Worker for (ScalarizeTable::iterator It = ArgIndices.begin();
996*9880d681SAndroid Build Coastguard Worker It->second != Operands; ++It, ++TheArg) {
997*9880d681SAndroid Build Coastguard Worker assert(It != ArgIndices.end() && "GEP not handled??");
998*9880d681SAndroid Build Coastguard Worker }
999*9880d681SAndroid Build Coastguard Worker
1000*9880d681SAndroid Build Coastguard Worker std::string NewName = I->getName();
1001*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1002*9880d681SAndroid Build Coastguard Worker NewName += "." + utostr(Operands[i]);
1003*9880d681SAndroid Build Coastguard Worker }
1004*9880d681SAndroid Build Coastguard Worker NewName += ".val";
1005*9880d681SAndroid Build Coastguard Worker TheArg->setName(NewName);
1006*9880d681SAndroid Build Coastguard Worker
1007*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
1008*9880d681SAndroid Build Coastguard Worker << "' of function '" << NF->getName() << "'\n");
1009*9880d681SAndroid Build Coastguard Worker
1010*9880d681SAndroid Build Coastguard Worker // All of the uses must be load instructions. Replace them all with
1011*9880d681SAndroid Build Coastguard Worker // the argument specified by ArgNo.
1012*9880d681SAndroid Build Coastguard Worker while (!GEP->use_empty()) {
1013*9880d681SAndroid Build Coastguard Worker LoadInst *L = cast<LoadInst>(GEP->user_back());
1014*9880d681SAndroid Build Coastguard Worker L->replaceAllUsesWith(&*TheArg);
1015*9880d681SAndroid Build Coastguard Worker L->eraseFromParent();
1016*9880d681SAndroid Build Coastguard Worker }
1017*9880d681SAndroid Build Coastguard Worker GEP->eraseFromParent();
1018*9880d681SAndroid Build Coastguard Worker }
1019*9880d681SAndroid Build Coastguard Worker }
1020*9880d681SAndroid Build Coastguard Worker
1021*9880d681SAndroid Build Coastguard Worker // Increment I2 past all of the arguments added for this promoted pointer.
1022*9880d681SAndroid Build Coastguard Worker std::advance(I2, ArgIndices.size());
1023*9880d681SAndroid Build Coastguard Worker }
1024*9880d681SAndroid Build Coastguard Worker
1025*9880d681SAndroid Build Coastguard Worker NF_CGN->stealCalledFunctionsFrom(CG[F]);
1026*9880d681SAndroid Build Coastguard Worker
1027*9880d681SAndroid Build Coastguard Worker // Now that the old function is dead, delete it. If there is a dangling
1028*9880d681SAndroid Build Coastguard Worker // reference to the CallgraphNode, just leave the dead function around for
1029*9880d681SAndroid Build Coastguard Worker // someone else to nuke.
1030*9880d681SAndroid Build Coastguard Worker CallGraphNode *CGN = CG[F];
1031*9880d681SAndroid Build Coastguard Worker if (CGN->getNumReferences() == 0)
1032*9880d681SAndroid Build Coastguard Worker delete CG.removeFunctionFromModule(CGN);
1033*9880d681SAndroid Build Coastguard Worker else
1034*9880d681SAndroid Build Coastguard Worker F->setLinkage(Function::ExternalLinkage);
1035*9880d681SAndroid Build Coastguard Worker
1036*9880d681SAndroid Build Coastguard Worker return NF_CGN;
1037*9880d681SAndroid Build Coastguard Worker }
1038*9880d681SAndroid Build Coastguard Worker
doInitialization(CallGraph & CG)1039*9880d681SAndroid Build Coastguard Worker bool ArgPromotion::doInitialization(CallGraph &CG) {
1040*9880d681SAndroid Build Coastguard Worker return CallGraphSCCPass::doInitialization(CG);
1041*9880d681SAndroid Build Coastguard Worker }
1042