blob: 377fa153a25498f1e6a0cfd92cb9c2082f580f15 [file] [log] [blame]
Chris Lattner9e7cc2f2004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattnered570a72004-03-07 21:29:54 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattnered570a72004-03-07 21:29:54 +00008//===----------------------------------------------------------------------===//
9//
10// This pass promotes "by reference" arguments to be "by value" arguments. In
11// practice, this means looking for internal functions that have pointer
Gordon Henriksen55cbec32007-10-26 03:03:51 +000012// arguments. If it can prove, through the use of alias analysis, that an
13// argument is *only* loaded, then it can pass the value into the function
Chris Lattnered570a72004-03-07 21:29:54 +000014// instead of the address of the value. This can cause recursive simplification
Chris Lattner9e7cc2f2004-05-23 21:21:17 +000015// of code and lead to the elimination of allocas (especially in C++ template
16// code like the STL).
Chris Lattnered570a72004-03-07 21:29:54 +000017//
Chris Lattner9440db82004-03-08 01:04:36 +000018// This pass also handles aggregate arguments that are passed into a function,
19// scalarizing them if the elements of the aggregate are only loaded. Note that
Matthijs Kooijman477f5a22008-07-29 10:00:13 +000020// by default it refuses to scalarize aggregates which would require passing in
21// more than three operands to the function, because passing thousands of
Duncan Sands4cddaf72008-09-07 09:54:09 +000022// operands for a large array or structure is unprofitable! This limit can be
Matthijs Kooijman477f5a22008-07-29 10:00:13 +000023// configured or disabled, however.
Chris Lattner9440db82004-03-08 01:04:36 +000024//
Chris Lattnered570a72004-03-07 21:29:54 +000025// Note that this transformation could also be done for arguments that are only
Gordon Henriksen55cbec32007-10-26 03:03:51 +000026// stored to (returning the value instead), but does not currently. This case
27// would be best handled when and if LLVM begins supporting multiple return
28// values from functions.
Chris Lattnered570a72004-03-07 21:29:54 +000029//
30//===----------------------------------------------------------------------===//
31
32#include "llvm/Transforms/IPO.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/DepthFirstIterator.h"
34#include "llvm/ADT/Statistic.h"
Chris Lattner23132b12009-08-24 03:52:50 +000035#include "llvm/ADT/StringExtras.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/Analysis/CallGraph.h"
Chandler Carruth3251e812013-01-07 15:26:48 +000038#include "llvm/Analysis/CallGraphSCCPass.h"
Stephen Hines36b56882014-04-23 16:57:46 -070039#include "llvm/IR/CFG.h"
40#include "llvm/IR/CallSite.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000041#include "llvm/IR/Constants.h"
42#include "llvm/IR/DerivedTypes.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/LLVMContext.h"
45#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000046#include "llvm/Support/Debug.h"
47#include "llvm/Support/raw_ostream.h"
Chris Lattnered570a72004-03-07 21:29:54 +000048#include <set>
49using namespace llvm;
50
Stephen Hinesdce4a402014-05-29 02:49:00 -070051#define DEBUG_TYPE "argpromotion"
52
Chris Lattner86453c52006-12-19 22:09:18 +000053STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
54STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
Chris Lattner10603e02008-01-11 22:31:41 +000055STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
Chris Lattner86453c52006-12-19 22:09:18 +000056STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
Chris Lattnered570a72004-03-07 21:29:54 +000057
Chris Lattner86453c52006-12-19 22:09:18 +000058namespace {
Chris Lattnered570a72004-03-07 21:29:54 +000059 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
60 ///
Nick Lewycky6726b6d2009-10-25 06:33:48 +000061 struct ArgPromotion : public CallGraphSCCPass {
Stephen Hines36b56882014-04-23 16:57:46 -070062 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattnered570a72004-03-07 21:29:54 +000063 AU.addRequired<AliasAnalysis>();
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000064 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnered570a72004-03-07 21:29:54 +000065 }
66
Stephen Hines36b56882014-04-23 16:57:46 -070067 bool runOnSCC(CallGraphSCC &SCC) override;
Nick Lewyckyecd94c82007-05-06 13:37:16 +000068 static char ID; // Pass identification, replacement for typeid
Dan Gohman38deef92009-02-18 16:37:45 +000069 explicit ArgPromotion(unsigned maxElements = 3)
Owen Anderson081c34b2010-10-19 17:21:58 +000070 : CallGraphSCCPass(ID), maxElements(maxElements) {
71 initializeArgPromotionPass(*PassRegistry::getPassRegistry());
72 }
Duncan Sands4cddaf72008-09-07 09:54:09 +000073
Matthijs Kooijman477f5a22008-07-29 10:00:13 +000074 /// A vector used to hold the indices of a single GEP instruction
75 typedef std::vector<uint64_t> IndicesVector;
Devang Patel794fd752007-05-01 21:15:47 +000076
Chris Lattnered570a72004-03-07 21:29:54 +000077 private:
Chris Lattner5095e3d2009-08-31 00:19:58 +000078 CallGraphNode *PromoteArguments(CallGraphNode *CGN);
Chris Lattner40c14be2008-01-11 19:20:39 +000079 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
Chris Lattner5095e3d2009-08-31 00:19:58 +000080 CallGraphNode *DoPromotion(Function *F,
81 SmallPtrSet<Argument*, 8> &ArgsToPromote,
82 SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
Matthijs Kooijman992e97e2008-05-23 07:57:02 +000083 /// The maximum number of elements to expand, or 0 for unlimited.
84 unsigned maxElements;
Chris Lattnered570a72004-03-07 21:29:54 +000085 };
Chris Lattnered570a72004-03-07 21:29:54 +000086}
87
Dan Gohman844731a2008-05-13 00:00:25 +000088char ArgPromotion::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000089INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
90 "Promote 'by reference' arguments to scalars", false, false)
91INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Stephen Hines36b56882014-04-23 16:57:46 -070092INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Owen Anderson2ab36d32010-10-12 19:48:12 +000093INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
Owen Andersonce665bd2010-10-07 22:25:06 +000094 "Promote 'by reference' arguments to scalars", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000095
Chris Lattnerbcd203c2008-04-19 19:50:01 +000096Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
97 return new ArgPromotion(maxElements);
Chris Lattnered570a72004-03-07 21:29:54 +000098}
99
Chris Lattner2decb222010-04-16 22:42:17 +0000100bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000101 bool Changed = false, LocalChange;
Chris Lattnered570a72004-03-07 21:29:54 +0000102
Chris Lattnerf5afcab2004-09-19 01:05:16 +0000103 do { // Iterate until we stop promoting from this SCC.
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000104 LocalChange = false;
105 // Attempt to promote arguments from all functions in this SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000106 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
107 if (CallGraphNode *CGN = PromoteArguments(*I)) {
Chris Lattner5095e3d2009-08-31 00:19:58 +0000108 LocalChange = true;
Chris Lattner2decb222010-04-16 22:42:17 +0000109 SCC.ReplaceNode(*I, CGN);
Chris Lattner5095e3d2009-08-31 00:19:58 +0000110 }
Chris Lattner2decb222010-04-16 22:42:17 +0000111 }
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000112 Changed |= LocalChange; // Remember that we changed something.
113 } while (LocalChange);
Chris Lattnereae22022010-04-20 00:46:50 +0000114
Chris Lattnered570a72004-03-07 21:29:54 +0000115 return Changed;
116}
117
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000118/// PromoteArguments - This method checks the specified function to see if there
119/// are any promotable arguments and if it is safe to promote the function (for
120/// example, all callers are direct). If safe to promote some arguments, it
121/// calls the DoPromotion method.
122///
Chris Lattner5095e3d2009-08-31 00:19:58 +0000123CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000124 Function *F = CGN->getFunction();
125
126 // Make sure that it is local to this module.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700127 if (!F || !F->hasLocalLinkage()) return nullptr;
Chris Lattnered570a72004-03-07 21:29:54 +0000128
129 // First check: see if there are any pointer arguments! If not, quick exit.
Nick Lewyckyb05ad792013-07-18 22:32:32 +0000130 SmallVector<Argument*, 16> PointerArgs;
131 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000132 if (I->getType()->isPointerTy())
Nick Lewyckyb05ad792013-07-18 22:32:32 +0000133 PointerArgs.push_back(I);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700134 if (PointerArgs.empty()) return nullptr;
Chris Lattnered570a72004-03-07 21:29:54 +0000135
136 // Second check: make sure that all callers are direct callers. We can't
Chris Lattner28252b62011-01-16 08:09:24 +0000137 // transform functions that have indirect callers. Also see if the function
138 // is self-recursive.
139 bool isSelfRecursive = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700140 for (Use &U : F->uses()) {
141 CallSite CS(U.getUser());
Chris Lattner28252b62011-01-16 08:09:24 +0000142 // Must be a direct call.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700143 if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr;
Chris Lattner28252b62011-01-16 08:09:24 +0000144
145 if (CS.getInstruction()->getParent()->getParent() == F)
146 isSelfRecursive = true;
147 }
148
Chris Lattner40c14be2008-01-11 19:20:39 +0000149 // Check to see which arguments are promotable. If an argument is promotable,
150 // add it to ArgsToPromote.
151 SmallPtrSet<Argument*, 8> ArgsToPromote;
Chris Lattner10603e02008-01-11 22:31:41 +0000152 SmallPtrSet<Argument*, 8> ByValArgsToTransform;
Nick Lewyckyb05ad792013-07-18 22:32:32 +0000153 for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) {
154 Argument *PtrArg = PointerArgs[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000155 Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
Duncan Sands4cddaf72008-09-07 09:54:09 +0000156
Chris Lattner10603e02008-01-11 22:31:41 +0000157 // If this is a byval argument, and if the aggregate type is small, just
Stephen Hines36b56882014-04-23 16:57:46 -0700158 // pass the elements, which is always safe. This does not apply to
159 // inalloca.
Nick Lewyckyb05ad792013-07-18 22:32:32 +0000160 if (PtrArg->hasByValAttr()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000161 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
Chris Lattnerbcd203c2008-04-19 19:50:01 +0000162 if (maxElements > 0 && STy->getNumElements() > maxElements) {
David Greene5ededf72010-01-05 01:28:37 +0000163 DEBUG(dbgs() << "argpromotion disable promoting argument '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000164 << PtrArg->getName() << "' because it would require adding more"
165 << " than " << maxElements << " arguments to the function.\n");
Chris Lattner28252b62011-01-16 08:09:24 +0000166 continue;
167 }
168
169 // If all the elements are single-value types, we can promote it.
170 bool AllSimple = true;
171 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
172 if (!STy->getElementType(i)->isSingleValueType()) {
173 AllSimple = false;
174 break;
Chris Lattner10603e02008-01-11 22:31:41 +0000175 }
176 }
Chris Lattner28252b62011-01-16 08:09:24 +0000177
178 // Safe to transform, don't even bother trying to "promote" it.
179 // Passing the elements as a scalar will allow scalarrepl to hack on
180 // the new alloca we introduce.
181 if (AllSimple) {
182 ByValArgsToTransform.insert(PtrArg);
183 continue;
184 }
Duncan Sands43e2a032008-05-27 11:50:51 +0000185 }
Chris Lattner10603e02008-01-11 22:31:41 +0000186 }
Duncan Sands4cddaf72008-09-07 09:54:09 +0000187
Chris Lattner28252b62011-01-16 08:09:24 +0000188 // If the argument is a recursive type and we're in a recursive
189 // function, we could end up infinitely peeling the function argument.
190 if (isSelfRecursive) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000191 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
Chris Lattner28252b62011-01-16 08:09:24 +0000192 bool RecursiveType = false;
193 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
194 if (STy->getElementType(i) == PtrArg->getType()) {
195 RecursiveType = true;
196 break;
197 }
198 }
199 if (RecursiveType)
200 continue;
201 }
202 }
203
Chris Lattner10603e02008-01-11 22:31:41 +0000204 // Otherwise, see if we can promote the pointer to its value.
Stephen Hines36b56882014-04-23 16:57:46 -0700205 if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr()))
Chris Lattner10603e02008-01-11 22:31:41 +0000206 ArgsToPromote.insert(PtrArg);
Chris Lattner40c14be2008-01-11 19:20:39 +0000207 }
Duncan Sands4cddaf72008-09-07 09:54:09 +0000208
Chris Lattnered570a72004-03-07 21:29:54 +0000209 // No promotable pointer arguments.
Chris Lattner5095e3d2009-08-31 00:19:58 +0000210 if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700211 return nullptr;
Chris Lattnered570a72004-03-07 21:29:54 +0000212
Chris Lattner5095e3d2009-08-31 00:19:58 +0000213 return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
Chris Lattnered570a72004-03-07 21:29:54 +0000214}
215
Chris Lattner28252b62011-01-16 08:09:24 +0000216/// AllCallersPassInValidPointerForArgument - Return true if we can prove that
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000217/// all callees pass in a valid pointer for the specified function argument.
Chris Lattner28252b62011-01-16 08:09:24 +0000218static bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000219 Function *Callee = Arg->getParent();
220
Nick Lewyckyb05ad792013-07-18 22:32:32 +0000221 unsigned ArgNo = Arg->getArgNo();
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000222
223 // Look at all call sites of the function. At this pointer we know we only
224 // have direct callees.
Stephen Hines36b56882014-04-23 16:57:46 -0700225 for (User *U : Callee->users()) {
226 CallSite CS(U);
Gabor Greif7d3056b2010-07-28 22:50:26 +0000227 assert(CS && "Should only have direct calls!");
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000228
Dan Gohman4d70a292010-11-11 21:23:25 +0000229 if (!CS.getArgument(ArgNo)->isDereferenceablePointer())
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000230 return false;
231 }
232 return true;
233}
234
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000235/// Returns true if Prefix is a prefix of longer. That means, Longer has a size
236/// that is greater than or equal to the size of prefix, and each of the
237/// elements in Prefix is the same as the corresponding elements in Longer.
238///
239/// This means it also returns true when Prefix and Longer are equal!
240static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
241 const ArgPromotion::IndicesVector &Longer) {
242 if (Prefix.size() > Longer.size())
243 return false;
Benjamin Kramerb26e2912012-07-19 10:46:05 +0000244 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000245}
246
247
248/// Checks if Indices, or a prefix of Indices, is in Set.
249static bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
250 std::set<ArgPromotion::IndicesVector> &Set) {
251 std::set<ArgPromotion::IndicesVector>::iterator Low;
252 Low = Set.upper_bound(Indices);
253 if (Low != Set.begin())
254 Low--;
255 // Low is now the last element smaller than or equal to Indices. This means
256 // it points to a prefix of Indices (possibly Indices itself), if such
257 // prefix exists.
258 //
259 // This load is safe if any prefix of its operands is safe to load.
260 return Low != Set.end() && IsPrefix(*Low, Indices);
261}
262
Dan Gohmanf451cb82010-02-10 16:03:48 +0000263/// Mark the given indices (ToMark) as safe in the given set of indices
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000264/// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
265/// is already a prefix of Indices in Safe, Indices are implicitely marked safe
266/// already. Furthermore, any indices that Indices is itself a prefix of, are
267/// removed from Safe (since they are implicitely safe because of Indices now).
268static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
269 std::set<ArgPromotion::IndicesVector> &Safe) {
270 std::set<ArgPromotion::IndicesVector>::iterator Low;
271 Low = Safe.upper_bound(ToMark);
272 // Guard against the case where Safe is empty
273 if (Low != Safe.begin())
274 Low--;
275 // Low is now the last element smaller than or equal to Indices. This
276 // means it points to a prefix of Indices (possibly Indices itself), if
277 // such prefix exists.
278 if (Low != Safe.end()) {
279 if (IsPrefix(*Low, ToMark))
280 // If there is already a prefix of these indices (or exactly these
281 // indices) marked a safe, don't bother adding these indices
282 return;
283
284 // Increment Low, so we can use it as a "insert before" hint
Duncan Sands4cddaf72008-09-07 09:54:09 +0000285 ++Low;
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000286 }
Duncan Sands4cddaf72008-09-07 09:54:09 +0000287 // Insert
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000288 Low = Safe.insert(Low, ToMark);
289 ++Low;
290 // If there we're a prefix of longer index list(s), remove those
291 std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
292 while (Low != End && IsPrefix(ToMark, *Low)) {
293 std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
294 ++Low;
295 Safe.erase(Remove);
296 }
297}
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000298
299/// isSafeToPromoteArgument - As you might guess from the name of this method,
300/// it checks to see if it is both safe and useful to promote the argument.
301/// This method limits promotion of aggregates to only promote up to three
302/// elements of the aggregate in order to avoid exploding the number of
303/// arguments passed in.
Stephen Hines36b56882014-04-23 16:57:46 -0700304bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg,
305 bool isByValOrInAlloca) const {
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000306 typedef std::set<IndicesVector> GEPIndicesSet;
307
308 // Quick exit for unused arguments
309 if (Arg->use_empty())
310 return true;
311
Chris Lattner9440db82004-03-08 01:04:36 +0000312 // We can only promote this argument if all of the uses are loads, or are GEP
313 // instructions (with constant indices) that are subsequently loaded.
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000314 //
315 // Promoting the argument causes it to be loaded in the caller
316 // unconditionally. This is only safe if we can prove that either the load
317 // would have happened in the callee anyway (ie, there is a load in the entry
318 // block) or the pointer passed in at every call site is guaranteed to be
319 // valid.
320 // In the former case, invalid loads can happen, but would have happened
321 // anyway, in the latter case, invalid loads won't happen. This prevents us
322 // from introducing an invalid load that wouldn't have happened in the
323 // original code.
324 //
325 // This set will contain all sets of indices that are loaded in the entry
326 // block, and thus are safe to unconditionally load in the caller.
Stephen Hines36b56882014-04-23 16:57:46 -0700327 //
328 // This optimization is also safe for InAlloca parameters, because it verifies
329 // that the address isn't captured.
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000330 GEPIndicesSet SafeToUnconditionallyLoad;
Chris Lattner170b1812008-01-11 19:34:32 +0000331
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000332 // This set contains all the sets of indices that we are planning to promote.
333 // This makes it possible to limit the number of arguments added.
334 GEPIndicesSet ToPromote;
Duncan Sands4cddaf72008-09-07 09:54:09 +0000335
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000336 // If the pointer is always valid, any load with first index 0 is valid.
Stephen Hines36b56882014-04-23 16:57:46 -0700337 if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg))
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000338 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
339
340 // First, iterate the entry block and mark loads of (geps of) arguments as
341 // safe.
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000342 BasicBlock *EntryBlock = Arg->getParent()->begin();
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000343 // Declare this here so we can reuse it
344 IndicesVector Indices;
345 for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
346 I != E; ++I)
347 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
348 Value *V = LI->getPointerOperand();
349 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
350 V = GEP->getPointerOperand();
351 if (V == Arg) {
352 // This load actually loads (part of) Arg? Check the indices then.
353 Indices.reserve(GEP->getNumIndices());
354 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
355 II != IE; ++II)
356 if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
357 Indices.push_back(CI->getSExtValue());
358 else
359 // We found a non-constant GEP index for this argument? Bail out
360 // right away, can't promote this argument at all.
361 return false;
362
363 // Indices checked out, mark them as safe
364 MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
365 Indices.clear();
366 }
367 } else if (V == Arg) {
368 // Direct loads are equivalent to a GEP with a single 0 index.
369 MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
370 }
371 }
372
373 // Now, iterate all uses of the argument to see if there are any uses that are
374 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
Chris Lattnera10145f2008-01-11 18:43:58 +0000375 SmallVector<LoadInst*, 16> Loads;
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000376 IndicesVector Operands;
Stephen Hines36b56882014-04-23 16:57:46 -0700377 for (Use &U : Arg->uses()) {
378 User *UR = U.getUser();
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000379 Operands.clear();
Stephen Hines36b56882014-04-23 16:57:46 -0700380 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
Eli Friedman3d30b432011-08-15 22:16:46 +0000381 // Don't hack volatile/atomic loads
382 if (!LI->isSimple()) return false;
Chris Lattnered570a72004-03-07 21:29:54 +0000383 Loads.push_back(LI);
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000384 // Direct loads are equivalent to a GEP with a zero index and then a load.
385 Operands.push_back(0);
Stephen Hines36b56882014-04-23 16:57:46 -0700386 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
Chris Lattner9440db82004-03-08 01:04:36 +0000387 if (GEP->use_empty()) {
388 // Dead GEP's cause trouble later. Just remove them if we run into
389 // them.
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000390 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattner40c14be2008-01-11 19:20:39 +0000391 GEP->eraseFromParent();
Gabor Greifa53029b2010-07-12 14:15:10 +0000392 // TODO: This runs the above loop over and over again for dead GEPs
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000393 // Couldn't we just do increment the UI iterator earlier and erase the
394 // use?
Stephen Hines36b56882014-04-23 16:57:46 -0700395 return isSafeToPromoteArgument(Arg, isByValOrInAlloca);
Chris Lattner9440db82004-03-08 01:04:36 +0000396 }
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000397
Chris Lattner9440db82004-03-08 01:04:36 +0000398 // Ensure that all of the indices are constants.
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000399 for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
400 i != e; ++i)
Gabor Greif5e463212008-05-29 01:59:18 +0000401 if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000402 Operands.push_back(C->getSExtValue());
Chris Lattner9440db82004-03-08 01:04:36 +0000403 else
404 return false; // Not a constant operand GEP!
405
406 // Ensure that the only users of the GEP are load instructions.
Stephen Hines36b56882014-04-23 16:57:46 -0700407 for (User *GEPU : GEP->users())
408 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
Eli Friedman3d30b432011-08-15 22:16:46 +0000409 // Don't hack volatile/atomic loads
410 if (!LI->isSimple()) return false;
Chris Lattner9440db82004-03-08 01:04:36 +0000411 Loads.push_back(LI);
412 } else {
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000413 // Other uses than load?
Chris Lattner9440db82004-03-08 01:04:36 +0000414 return false;
415 }
Chris Lattner9440db82004-03-08 01:04:36 +0000416 } else {
417 return false; // Not a load or a GEP.
418 }
Duncan Sands4cddaf72008-09-07 09:54:09 +0000419
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000420 // Now, see if it is safe to promote this load / loads of this GEP. Loading
421 // is safe if Operands, or a prefix of Operands, is marked as safe.
422 if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
423 return false;
424
425 // See if we are already promoting a load with these indices. If not, check
426 // to make sure that we aren't promoting too many elements. If so, nothing
427 // to do.
428 if (ToPromote.find(Operands) == ToPromote.end()) {
429 if (maxElements > 0 && ToPromote.size() == maxElements) {
David Greene5ededf72010-01-05 01:28:37 +0000430 DEBUG(dbgs() << "argpromotion not promoting argument '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000431 << Arg->getName() << "' because it would require adding more "
432 << "than " << maxElements << " arguments to the function.\n");
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000433 // We limit aggregate promotion to only promoting up to a fixed number
434 // of elements of the aggregate.
435 return false;
436 }
437 ToPromote.insert(Operands);
438 }
439 }
Chris Lattnered570a72004-03-07 21:29:54 +0000440
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000441 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattnered570a72004-03-07 21:29:54 +0000442
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000443 // Okay, now we know that the argument is only used by load instructions and
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000444 // it is safe to unconditionally perform all of them. Use alias analysis to
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000445 // check to see if the pointer is guaranteed to not be modified from entry of
446 // the function to each of the load instructions.
Chris Lattnered570a72004-03-07 21:29:54 +0000447
448 // Because there could be several/many load instructions, remember which
449 // blocks we know to be transparent to the load.
Chris Lattnere027efa2008-01-11 19:36:30 +0000450 SmallPtrSet<BasicBlock*, 16> TranspBlocks;
Owen Anderson46f022a2006-09-15 05:22:51 +0000451
452 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnered570a72004-03-07 21:29:54 +0000453
454 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
455 // Check to see if the load is invalidated from the start of the block to
456 // the load itself.
457 LoadInst *Load = Loads[i];
458 BasicBlock *BB = Load->getParent();
Chris Lattner9440db82004-03-08 01:04:36 +0000459
Dan Gohman6d8eb152010-11-11 21:50:19 +0000460 AliasAnalysis::Location Loc = AA.getLocation(Load);
Dan Gohman56653f02010-11-11 18:09:32 +0000461 if (AA.canInstructionRangeModify(BB->front(), *Load, Loc))
Chris Lattnered570a72004-03-07 21:29:54 +0000462 return false; // Pointer is invalidated!
463
464 // Now check every path from the entry block to the load for transparency.
465 // To do this, we perform a depth first search on the inverse CFG from the
466 // loading block.
Gabor Greifa53029b2010-07-12 14:15:10 +0000467 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
468 BasicBlock *P = *PI;
Chris Lattnere027efa2008-01-11 19:36:30 +0000469 for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
Gabor Greifa53029b2010-07-12 14:15:10 +0000470 I = idf_ext_begin(P, TranspBlocks),
471 E = idf_ext_end(P, TranspBlocks); I != E; ++I)
Dan Gohman56653f02010-11-11 18:09:32 +0000472 if (AA.canBasicBlockModify(**I, Loc))
Chris Lattnered570a72004-03-07 21:29:54 +0000473 return false;
Gabor Greifa53029b2010-07-12 14:15:10 +0000474 }
Chris Lattnered570a72004-03-07 21:29:54 +0000475 }
476
477 // If the path from the entry of the function to each load is free of
478 // instructions that potentially invalidate the load, we can make the
479 // transformation!
480 return true;
481}
482
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000483/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000484/// arguments, and returns the new function. At this point, we know that it's
485/// safe to do so.
Chris Lattner5095e3d2009-08-31 00:19:58 +0000486CallGraphNode *ArgPromotion::DoPromotion(Function *F,
487 SmallPtrSet<Argument*, 8> &ArgsToPromote,
Chris Lattner10603e02008-01-11 22:31:41 +0000488 SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000489
Chris Lattnered570a72004-03-07 21:29:54 +0000490 // Start by computing a new prototype for the function, which is the same as
491 // the old function, but has modified arguments.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000492 FunctionType *FTy = F->getFunctionType();
Jay Foad5fdd6c82011-07-12 14:06:48 +0000493 std::vector<Type*> Params;
Chris Lattnered570a72004-03-07 21:29:54 +0000494
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000495 typedef std::set<IndicesVector> ScalarizeTable;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000496
Chris Lattner9440db82004-03-08 01:04:36 +0000497 // ScalarizedElements - If we are promoting a pointer that has elements
498 // accessed out of it, keep track of which elements are accessed so that we
499 // can add one argument for each.
500 //
501 // Arguments that are directly loaded will have a zero element value here, to
502 // handle cases where there are both a direct load and GEP accesses.
503 //
Chris Lattnerbeabf452004-06-21 00:07:58 +0000504 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattner9440db82004-03-08 01:04:36 +0000505
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000506 // OriginalLoads - Keep track of a representative load instruction from the
507 // original function so that we can tell the alias analysis implementation
508 // what the new GEP/Load instructions we are inserting look like.
Manman Renc160efc2013-11-15 20:41:15 +0000509 // We need to keep the original loads for each argument and the elements
510 // of the argument that are accessed.
511 std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000512
Bill Wendling034b94b2012-12-19 07:18:57 +0000513 // Attribute - Keep track of the parameter attributes for the arguments
Duncan Sandsdc024672007-11-27 13:23:08 +0000514 // that we are *not* promoting. For the ones that we do promote, the parameter
515 // attributes are lost
Bill Wendlingb2484b42013-01-27 01:57:28 +0000516 SmallVector<AttributeSet, 8> AttributesVec;
Bill Wendling99faa3b2012-12-07 23:16:57 +0000517 const AttributeSet &PAL = F->getAttributes();
Duncan Sandsdc024672007-11-27 13:23:08 +0000518
Duncan Sands532d0222008-02-01 20:37:16 +0000519 // Add any return attributes.
Bill Wendling1b0c54f2013-01-18 21:53:16 +0000520 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendlingb2484b42013-01-27 01:57:28 +0000521 AttributesVec.push_back(AttributeSet::get(F->getContext(),
522 PAL.getRetAttributes()));
Duncan Sands4cddaf72008-09-07 09:54:09 +0000523
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000524 // First, determine the new argument list
Chris Lattnerab04e132008-01-17 01:17:03 +0000525 unsigned ArgIndex = 1;
Duncan Sandsdc024672007-11-27 13:23:08 +0000526 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
Chris Lattnerab04e132008-01-17 01:17:03 +0000527 ++I, ++ArgIndex) {
Chris Lattner10603e02008-01-11 22:31:41 +0000528 if (ByValArgsToTransform.count(I)) {
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000529 // Simple byval argument? Just add all the struct element types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000530 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
531 StructType *STy = cast<StructType>(AgTy);
Chris Lattner10603e02008-01-11 22:31:41 +0000532 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
533 Params.push_back(STy->getElementType(i));
534 ++NumByValArgsPromoted;
535 } else if (!ArgsToPromote.count(I)) {
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000536 // Unchanged argument
Chris Lattnered570a72004-03-07 21:29:54 +0000537 Params.push_back(I->getType());
Bill Wendling28d65722013-01-23 06:14:59 +0000538 AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
539 if (attrs.hasAttributes(ArgIndex)) {
Bill Wendlingb2484b42013-01-27 01:57:28 +0000540 AttrBuilder B(attrs, ArgIndex);
Bill Wendling28d65722013-01-23 06:14:59 +0000541 AttributesVec.
Bill Wendlingb2484b42013-01-27 01:57:28 +0000542 push_back(AttributeSet::get(F->getContext(), Params.size(), B));
Bill Wendling28d65722013-01-23 06:14:59 +0000543 }
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000544 } else if (I->use_empty()) {
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000545 // Dead argument (which are always marked as promotable)
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000546 ++NumArgumentsDead;
547 } else {
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000548 // Okay, this is being promoted. This means that the only uses are loads
549 // or GEPs which are only used by loads
550
551 // In this table, we will track which indices are loaded from the argument
552 // (where direct loads are tracked as no indices).
Chris Lattnerbeabf452004-06-21 00:07:58 +0000553 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Stephen Hines36b56882014-04-23 16:57:46 -0700554 for (User *U : I->users()) {
555 Instruction *UI = cast<Instruction>(U);
556 assert(isa<LoadInst>(UI) || isa<GetElementPtrInst>(UI));
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000557 IndicesVector Indices;
Stephen Hines36b56882014-04-23 16:57:46 -0700558 Indices.reserve(UI->getNumOperands() - 1);
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000559 // Since loads will only have a single operand, and GEPs only a single
560 // non-index operand, this will record direct loads without any indices,
561 // and gep+loads with the GEP indices.
Stephen Hines36b56882014-04-23 16:57:46 -0700562 for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000563 II != IE; ++II)
564 Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
565 // GEPs with a single 0 index can be merged with direct loads
566 if (Indices.size() == 1 && Indices.front() == 0)
567 Indices.clear();
Owen Anderson46f022a2006-09-15 05:22:51 +0000568 ArgIndices.insert(Indices);
569 LoadInst *OrigLoad;
Stephen Hines36b56882014-04-23 16:57:46 -0700570 if (LoadInst *L = dyn_cast<LoadInst>(UI))
Owen Anderson46f022a2006-09-15 05:22:51 +0000571 OrigLoad = L;
572 else
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000573 // Take any load, we will use it only to update Alias Analysis
Stephen Hines36b56882014-04-23 16:57:46 -0700574 OrigLoad = cast<LoadInst>(UI->user_back());
Manman Renc160efc2013-11-15 20:41:15 +0000575 OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
Chris Lattner9440db82004-03-08 01:04:36 +0000576 }
577
578 // Add a parameter to the function for each element passed in.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000579 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000580 E = ArgIndices.end(); SI != E; ++SI) {
Torok Edwinb079a392008-11-16 17:21:25 +0000581 // not allowed to dereference ->begin() if size() is 0
Jay Foada9203102011-07-25 09:48:08 +0000582 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000583 assert(Params.back());
584 }
Chris Lattner9440db82004-03-08 01:04:36 +0000585
586 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
587 ++NumArgumentsPromoted;
588 else
589 ++NumAggregatesPromoted;
Chris Lattnered570a72004-03-07 21:29:54 +0000590 }
Chris Lattner10603e02008-01-11 22:31:41 +0000591 }
Chris Lattnered570a72004-03-07 21:29:54 +0000592
Devang Patel19c87462008-09-26 22:53:05 +0000593 // Add any function attributes.
Bill Wendling956f1342013-01-18 21:11:39 +0000594 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendlingb2484b42013-01-27 01:57:28 +0000595 AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
596 PAL.getFnAttributes()));
Devang Patel19c87462008-09-26 22:53:05 +0000597
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000598 Type *RetTy = FTy->getReturnType();
Chris Lattnered570a72004-03-07 21:29:54 +0000599
Duncan Sandsdc024672007-11-27 13:23:08 +0000600 // Construct the new function type using the new arguments.
Owen Andersondebcb012009-07-29 22:17:13 +0000601 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanfd939082005-04-21 23:48:37 +0000602
Chris Lattnera51c39c2009-09-15 05:40:35 +0000603 // Create the new function body and insert it into the module.
Gabor Greif051a9502008-04-06 20:25:17 +0000604 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000605 NF->copyAttributesFrom(F);
Chris Lattnerab04e132008-01-17 01:17:03 +0000606
Chris Lattnera3512bd2009-08-31 05:22:48 +0000607
David Greene5ededf72010-01-05 01:28:37 +0000608 DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n"
Chris Lattnera3512bd2009-08-31 05:22:48 +0000609 << "From: " << *F);
610
Chris Lattnerab04e132008-01-17 01:17:03 +0000611 // Recompute the parameter attributes list based on the new arguments for
612 // the function.
Bill Wendling99faa3b2012-12-07 23:16:57 +0000613 NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
Devang Patel05988662008-09-25 21:00:45 +0000614 AttributesVec.clear();
Duncan Sands28c3cff2008-05-26 19:58:59 +0000615
Chris Lattnered570a72004-03-07 21:29:54 +0000616 F->getParent()->getFunctionList().insert(F, NF);
Zhou Sheng2b3407f2008-03-20 08:05:05 +0000617 NF->takeName(F);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000618
619 // Get the alias analysis information that we need to update to reflect our
620 // changes.
621 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
622
Duncan Sands34c88472008-09-08 11:07:35 +0000623 // Get the callgraph information that we need to update to reflect our
624 // changes.
Stephen Hines36b56882014-04-23 16:57:46 -0700625 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
626
Chris Lattner5095e3d2009-08-31 00:19:58 +0000627 // Get a new callgraph node for NF.
628 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
Duncan Sands34c88472008-09-08 11:07:35 +0000629
Chris Lattnered570a72004-03-07 21:29:54 +0000630 // Loop over all of the callers of the function, transforming the call sites
631 // to pass in the loaded pointers.
632 //
Chris Lattnerab04e132008-01-17 01:17:03 +0000633 SmallVector<Value*, 16> Args;
Chris Lattnered570a72004-03-07 21:29:54 +0000634 while (!F->use_empty()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700635 CallSite CS(F->user_back());
Gabor Greif0054c7a2010-03-23 14:40:20 +0000636 assert(CS.getCalledFunction() == F);
Chris Lattnered570a72004-03-07 21:29:54 +0000637 Instruction *Call = CS.getInstruction();
Bill Wendling99faa3b2012-12-07 23:16:57 +0000638 const AttributeSet &CallPAL = CS.getAttributes();
Duncan Sands4cddaf72008-09-07 09:54:09 +0000639
Duncan Sands532d0222008-02-01 20:37:16 +0000640 // Add any return attributes.
Bill Wendling1b0c54f2013-01-18 21:53:16 +0000641 if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendlingb2484b42013-01-27 01:57:28 +0000642 AttributesVec.push_back(AttributeSet::get(F->getContext(),
643 CallPAL.getRetAttributes()));
Duncan Sands532d0222008-02-01 20:37:16 +0000644
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000645 // Loop over the operands, inserting GEP and loads in the caller as
646 // appropriate.
Chris Lattnered570a72004-03-07 21:29:54 +0000647 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerab04e132008-01-17 01:17:03 +0000648 ArgIndex = 1;
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000649 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
Chris Lattnerab04e132008-01-17 01:17:03 +0000650 I != E; ++I, ++AI, ++ArgIndex)
Chris Lattner10603e02008-01-11 22:31:41 +0000651 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
Chris Lattnered570a72004-03-07 21:29:54 +0000652 Args.push_back(*AI); // Unmodified argument
Duncan Sands4cddaf72008-09-07 09:54:09 +0000653
Bill Wendling28d65722013-01-23 06:14:59 +0000654 if (CallPAL.hasAttributes(ArgIndex)) {
Bill Wendlingb2484b42013-01-27 01:57:28 +0000655 AttrBuilder B(CallPAL, ArgIndex);
Bill Wendling28d65722013-01-23 06:14:59 +0000656 AttributesVec.
Bill Wendlingb2484b42013-01-27 01:57:28 +0000657 push_back(AttributeSet::get(F->getContext(), Args.size(), B));
Bill Wendling28d65722013-01-23 06:14:59 +0000658 }
Chris Lattner10603e02008-01-11 22:31:41 +0000659 } else if (ByValArgsToTransform.count(I)) {
660 // Emit a GEP and load for each element of the struct.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000661 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
662 StructType *STy = cast<StructType>(AgTy);
Owen Anderson1d0be152009-08-13 21:58:54 +0000663 Value *Idxs[2] = {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700664 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
Chris Lattner10603e02008-01-11 22:31:41 +0000665 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000666 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
Jay Foada9203102011-07-25 09:48:08 +0000667 Value *Idx = GetElementPtrInst::Create(*AI, Idxs,
Gabor Greif051a9502008-04-06 20:25:17 +0000668 (*AI)->getName()+"."+utostr(i),
669 Call);
Chris Lattner10603e02008-01-11 22:31:41 +0000670 // TODO: Tell AA about the new values?
671 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
Duncan Sands4cddaf72008-09-07 09:54:09 +0000672 }
Chris Lattner10603e02008-01-11 22:31:41 +0000673 } else if (!I->use_empty()) {
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000674 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000675 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000676 // Store the Value* version of the indices in here, but declare it now
Gabor Greif0054c7a2010-03-23 14:40:20 +0000677 // for reuse.
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000678 std::vector<Value*> Ops;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000679 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000680 E = ArgIndices.end(); SI != E; ++SI) {
681 Value *V = *AI;
Manman Renc160efc2013-11-15 20:41:15 +0000682 LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000683 if (!SI->empty()) {
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000684 Ops.reserve(SI->size());
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000685 Type *ElTy = V->getType();
Duncan Sands4cddaf72008-09-07 09:54:09 +0000686 for (IndicesVector::const_iterator II = SI->begin(),
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000687 IE = SI->end(); II != IE; ++II) {
688 // Use i32 to index structs, and i64 for others (pointers/arrays).
689 // This satisfies GEP constraints.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000690 Type *IdxTy = (ElTy->isStructTy() ?
Owen Anderson1d0be152009-08-13 21:58:54 +0000691 Type::getInt32Ty(F->getContext()) :
692 Type::getInt64Ty(F->getContext()));
Owen Andersoneed707b2009-07-24 23:12:02 +0000693 Ops.push_back(ConstantInt::get(IdxTy, *II));
Gabor Greif0054c7a2010-03-23 14:40:20 +0000694 // Keep track of the type we're currently indexing.
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000695 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
696 }
Gabor Greif0054c7a2010-03-23 14:40:20 +0000697 // And create a GEP to extract those indices.
Jay Foada9203102011-07-25 09:48:08 +0000698 V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000699 Ops.clear();
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000700 AA.copyValue(OrigLoad->getOperand(0), V);
701 }
Eric Christopher6fde0bd2010-03-27 01:54:00 +0000702 // Since we're replacing a load make sure we take the alignment
703 // of the previous load.
704 LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
705 newLoad->setAlignment(OrigLoad->getAlignment());
Dan Gohman56653f02010-11-11 18:09:32 +0000706 // Transfer the TBAA info too.
707 newLoad->setMetadata(LLVMContext::MD_tbaa,
708 OrigLoad->getMetadata(LLVMContext::MD_tbaa));
Eric Christopher6fde0bd2010-03-27 01:54:00 +0000709 Args.push_back(newLoad);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000710 AA.copyValue(OrigLoad, Args.back());
Chris Lattner9440db82004-03-08 01:04:36 +0000711 }
Chris Lattnered570a72004-03-07 21:29:54 +0000712 }
713
Gabor Greif0054c7a2010-03-23 14:40:20 +0000714 // Push any varargs arguments on the list.
Chris Lattnerab04e132008-01-17 01:17:03 +0000715 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
Chris Lattnered570a72004-03-07 21:29:54 +0000716 Args.push_back(*AI);
Bill Wendling28d65722013-01-23 06:14:59 +0000717 if (CallPAL.hasAttributes(ArgIndex)) {
Bill Wendlingb2484b42013-01-27 01:57:28 +0000718 AttrBuilder B(CallPAL, ArgIndex);
Bill Wendling28d65722013-01-23 06:14:59 +0000719 AttributesVec.
Bill Wendlingb2484b42013-01-27 01:57:28 +0000720 push_back(AttributeSet::get(F->getContext(), Args.size(), B));
Bill Wendling28d65722013-01-23 06:14:59 +0000721 }
Chris Lattnerab04e132008-01-17 01:17:03 +0000722 }
Chris Lattnered570a72004-03-07 21:29:54 +0000723
Devang Patel19c87462008-09-26 22:53:05 +0000724 // Add any function attributes.
Bill Wendling956f1342013-01-18 21:11:39 +0000725 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendlingb2484b42013-01-27 01:57:28 +0000726 AttributesVec.push_back(AttributeSet::get(Call->getContext(),
727 CallPAL.getFnAttributes()));
Devang Patel19c87462008-09-26 22:53:05 +0000728
Chris Lattnered570a72004-03-07 21:29:54 +0000729 Instruction *New;
730 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000731 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
Jay Foada3efbb12011-07-15 08:37:34 +0000732 Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000733 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Bill Wendling99faa3b2012-12-07 23:16:57 +0000734 cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
Bill Wendling0976e002012-11-20 05:09:20 +0000735 AttributesVec));
Chris Lattnered570a72004-03-07 21:29:54 +0000736 } else {
Jay Foada3efbb12011-07-15 08:37:34 +0000737 New = CallInst::Create(NF, Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000738 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Bill Wendling99faa3b2012-12-07 23:16:57 +0000739 cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
Bill Wendling0976e002012-11-20 05:09:20 +0000740 AttributesVec));
Chris Lattner1430ef12005-05-06 06:46:58 +0000741 if (cast<CallInst>(Call)->isTailCall())
742 cast<CallInst>(New)->setTailCall();
Chris Lattnered570a72004-03-07 21:29:54 +0000743 }
744 Args.clear();
Devang Patel05988662008-09-25 21:00:45 +0000745 AttributesVec.clear();
Chris Lattnered570a72004-03-07 21:29:54 +0000746
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000747 // Update the alias analysis implementation to know that we are replacing
748 // the old call with a new one.
749 AA.replaceWithNewValue(Call, New);
750
Duncan Sands34c88472008-09-08 11:07:35 +0000751 // Update the callgraph to know that the callsite has been transformed.
Chris Lattnerda230cb2009-09-01 18:52:39 +0000752 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
Chris Lattnera51c39c2009-09-15 05:40:35 +0000753 CalleeNode->replaceCallEdge(Call, New, NF_CGN);
Duncan Sands34c88472008-09-08 11:07:35 +0000754
Chris Lattnered570a72004-03-07 21:29:54 +0000755 if (!Call->use_empty()) {
756 Call->replaceAllUsesWith(New);
Chris Lattner046800a2007-02-11 01:08:35 +0000757 New->takeName(Call);
Chris Lattnered570a72004-03-07 21:29:54 +0000758 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000759
Chris Lattnered570a72004-03-07 21:29:54 +0000760 // Finally, remove the old call from the program, reducing the use-count of
761 // F.
Chris Lattner40c14be2008-01-11 19:20:39 +0000762 Call->eraseFromParent();
Chris Lattnered570a72004-03-07 21:29:54 +0000763 }
764
765 // Since we have now created the new function, splice the body of the old
766 // function right into the new function, leaving the old rotting hulk of the
767 // function empty.
768 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
769
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000770 // Loop over the argument list, transferring uses of the old arguments over to
771 // the new arguments, also transferring over the names as well.
Chris Lattnered570a72004-03-07 21:29:54 +0000772 //
Chris Lattner93e985f2007-02-13 02:10:56 +0000773 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Chris Lattner10603e02008-01-11 22:31:41 +0000774 I2 = NF->arg_begin(); I != E; ++I) {
775 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
Chris Lattnered570a72004-03-07 21:29:54 +0000776 // If this is an unmodified argument, move the name and users over to the
777 // new version.
778 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000779 I2->takeName(I);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000780 AA.replaceWithNewValue(I, I2);
Chris Lattnered570a72004-03-07 21:29:54 +0000781 ++I2;
Chris Lattner10603e02008-01-11 22:31:41 +0000782 continue;
Chris Lattnered570a72004-03-07 21:29:54 +0000783 }
Duncan Sands4cddaf72008-09-07 09:54:09 +0000784
Chris Lattner10603e02008-01-11 22:31:41 +0000785 if (ByValArgsToTransform.count(I)) {
786 // In the callee, we create an alloca, and store each of the new incoming
787 // arguments into the alloca.
788 Instruction *InsertPt = NF->begin()->begin();
Duncan Sands4cddaf72008-09-07 09:54:09 +0000789
Chris Lattner10603e02008-01-11 22:31:41 +0000790 // Just add all the struct element types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000791 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700792 Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000793 StructType *STy = cast<StructType>(AgTy);
Owen Anderson1d0be152009-08-13 21:58:54 +0000794 Value *Idxs[2] = {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700795 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
Duncan Sands4cddaf72008-09-07 09:54:09 +0000796
Chris Lattner10603e02008-01-11 22:31:41 +0000797 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000798 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
Daniel Dunbardfd3b642009-07-22 20:46:46 +0000799 Value *Idx =
Jay Foada9203102011-07-25 09:48:08 +0000800 GetElementPtrInst::Create(TheAlloca, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000801 TheAlloca->getName()+"."+Twine(i),
Daniel Dunbardfd3b642009-07-22 20:46:46 +0000802 InsertPt);
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000803 I2->setName(I->getName()+"."+Twine(i));
Chris Lattner10603e02008-01-11 22:31:41 +0000804 new StoreInst(I2++, Idx, InsertPt);
805 }
Duncan Sands4cddaf72008-09-07 09:54:09 +0000806
Chris Lattner10603e02008-01-11 22:31:41 +0000807 // Anything that used the arg should now use the alloca.
808 I->replaceAllUsesWith(TheAlloca);
809 TheAlloca->takeName(I);
810 AA.replaceWithNewValue(I, TheAlloca);
Stephen Hines36b56882014-04-23 16:57:46 -0700811
812 // If the alloca is used in a call, we must clear the tail flag since
813 // the callee now uses an alloca from the caller.
814 for (User *U : TheAlloca->users()) {
815 CallInst *Call = dyn_cast<CallInst>(U);
816 if (!Call)
817 continue;
818 Call->setTailCall(false);
819 }
Chris Lattner10603e02008-01-11 22:31:41 +0000820 continue;
Duncan Sands4cddaf72008-09-07 09:54:09 +0000821 }
822
Chris Lattner10603e02008-01-11 22:31:41 +0000823 if (I->use_empty()) {
824 AA.deleteValue(I);
825 continue;
826 }
Duncan Sands4cddaf72008-09-07 09:54:09 +0000827
Chris Lattner10603e02008-01-11 22:31:41 +0000828 // Otherwise, if we promoted this argument, then all users are load
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000829 // instructions (or GEPs with only load users), and all loads should be
830 // using the new argument that we added.
Chris Lattner10603e02008-01-11 22:31:41 +0000831 ScalarizeTable &ArgIndices = ScalarizedElements[I];
832
833 while (!I->use_empty()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700834 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
Chris Lattner10603e02008-01-11 22:31:41 +0000835 assert(ArgIndices.begin()->empty() &&
836 "Load element should sort to front!");
837 I2->setName(I->getName()+".val");
838 LI->replaceAllUsesWith(I2);
839 AA.replaceWithNewValue(LI, I2);
840 LI->eraseFromParent();
David Greene5ededf72010-01-05 01:28:37 +0000841 DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000842 << "' in function '" << F->getName() << "'\n");
Chris Lattner10603e02008-01-11 22:31:41 +0000843 } else {
Stephen Hines36b56882014-04-23 16:57:46 -0700844 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000845 IndicesVector Operands;
846 Operands.reserve(GEP->getNumIndices());
847 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
848 II != IE; ++II)
849 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
850
851 // GEPs with a single 0 index can be merged with direct loads
852 if (Operands.size() == 1 && Operands.front() == 0)
853 Operands.clear();
Chris Lattner10603e02008-01-11 22:31:41 +0000854
855 Function::arg_iterator TheArg = I2;
856 for (ScalarizeTable::iterator It = ArgIndices.begin();
857 *It != Operands; ++It, ++TheArg) {
858 assert(It != ArgIndices.end() && "GEP not handled??");
859 }
860
861 std::string NewName = I->getName();
Matthijs Kooijman477f5a22008-07-29 10:00:13 +0000862 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
863 NewName += "." + utostr(Operands[i]);
864 }
865 NewName += ".val";
866 TheArg->setName(NewName);
Chris Lattner10603e02008-01-11 22:31:41 +0000867
David Greene5ededf72010-01-05 01:28:37 +0000868 DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000869 << "' of function '" << NF->getName() << "'\n");
Chris Lattner10603e02008-01-11 22:31:41 +0000870
871 // All of the uses must be load instructions. Replace them all with
872 // the argument specified by ArgNo.
873 while (!GEP->use_empty()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700874 LoadInst *L = cast<LoadInst>(GEP->user_back());
Chris Lattner10603e02008-01-11 22:31:41 +0000875 L->replaceAllUsesWith(TheArg);
876 AA.replaceWithNewValue(L, TheArg);
877 L->eraseFromParent();
878 }
879 AA.deleteValue(GEP);
880 GEP->eraseFromParent();
881 }
882 }
883
884 // Increment I2 past all of the arguments added for this promoted pointer.
Benjamin Kramer72f09762012-09-30 17:31:56 +0000885 std::advance(I2, ArgIndices.size());
Chris Lattner10603e02008-01-11 22:31:41 +0000886 }
Chris Lattnered570a72004-03-07 21:29:54 +0000887
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000888 // Tell the alias analysis that the old function is about to disappear.
889 AA.replaceWithNewValue(F, NF);
890
Chris Lattner5095e3d2009-08-31 00:19:58 +0000891
892 NF_CGN->stealCalledFunctionsFrom(CG[F]);
893
Chris Lattnereae22022010-04-20 00:46:50 +0000894 // Now that the old function is dead, delete it. If there is a dangling
895 // reference to the CallgraphNode, just leave the dead function around for
896 // someone else to nuke.
897 CallGraphNode *CGN = CG[F];
898 if (CGN->getNumReferences() == 0)
899 delete CG.removeFunctionFromModule(CGN);
900 else
901 F->setLinkage(Function::ExternalLinkage);
Chris Lattner5095e3d2009-08-31 00:19:58 +0000902
903 return NF_CGN;
Chris Lattnered570a72004-03-07 21:29:54 +0000904}