blob: 61c071f5bd38d1f7935f3534f00b43187a3c849d [file] [log] [blame]
Andrew Lenharthcf996d42008-09-03 21:00:28 +00001//===-- PartialSpecialization.cpp - Specialize for common constants--------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass finds function arguments that are often a common constant and
11// specializes a version of the called function for that constant.
12//
Andrew Lenharthef780322008-09-04 14:34:22 +000013// This pass simply does the cloning for functions it specializes. It depends
14// on IPSCCP and DAE to clean up the results.
15//
16// The initial heuristic favors constant arguments that are used in control
17// flow.
Andrew Lenharthcf996d42008-09-03 21:00:28 +000018//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "partialspecialization"
22#include "llvm/Transforms/IPO.h"
23#include "llvm/Constant.h"
24#include "llvm/Instructions.h"
25#include "llvm/Module.h"
26#include "llvm/Pass.h"
27#include "llvm/ADT/Statistic.h"
Kenneth Uildriks74fa7322010-10-09 22:06:36 +000028#include "llvm/Analysis/InlineCost.h"
Andrew Lenharthcf996d42008-09-03 21:00:28 +000029#include "llvm/Transforms/Utils/Cloning.h"
Andrew Lenhartheb504792008-09-04 18:51:26 +000030#include "llvm/Support/CallSite.h"
Andrew Lenhartheb504792008-09-04 18:51:26 +000031#include "llvm/ADT/DenseSet.h"
Andrew Lenharthcf996d42008-09-03 21:00:28 +000032#include <map>
Andrew Lenharthcf996d42008-09-03 21:00:28 +000033using namespace llvm;
34
35STATISTIC(numSpecialized, "Number of specialized functions created");
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +000036STATISTIC(numReplaced, "Number of callers replaced by specialization");
37
38// Maximum number of arguments markable interested
39static const int MaxInterests = 6;
Andrew Lenharthcf996d42008-09-03 21:00:28 +000040
Andrew Lenharthcf996d42008-09-03 21:00:28 +000041namespace {
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +000042 typedef SmallVector<int, MaxInterests> InterestingArgVector;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000043 class PartSpec : public ModulePass {
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +000044 void scanForInterest(Function&, InterestingArgVector&);
Andrew Lenharthcf996d42008-09-03 21:00:28 +000045 int scanDistribution(Function&, int, std::map<Constant*, int>&);
Kenneth Uildriks74fa7322010-10-09 22:06:36 +000046 InlineCostAnalyzer CA;
Andrew Lenharthcf996d42008-09-03 21:00:28 +000047 public :
48 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000049 PartSpec() : ModulePass(ID) {
50 initializePartSpecPass(*PassRegistry::getPassRegistry());
51 }
Andrew Lenharthcf996d42008-09-03 21:00:28 +000052 bool runOnModule(Module &M);
53 };
54}
55
56char PartSpec::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000057INITIALIZE_PASS(PartSpec, "partialspecialization",
Owen Andersonce665bd2010-10-07 22:25:06 +000058 "Partial Specialization", false, false)
Andrew Lenharthcf996d42008-09-03 21:00:28 +000059
Andrew Lenhartheb504792008-09-04 18:51:26 +000060// Specialize F by replacing the arguments (keys) in replacements with the
61// constants (values). Replace all calls to F with those constants with
62// a call to the specialized function. Returns the specialized function
63static Function*
64SpecializeFunction(Function* F,
Rafael Espindola1ed219a2010-10-13 01:36:30 +000065 ValueToValueMapTy& replacements) {
Andrew Lenhartheb504792008-09-04 18:51:26 +000066 // arg numbers of deleted arguments
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +000067 DenseMap<unsigned, const Argument*> deleted;
Rafael Espindola1ed219a2010-10-13 01:36:30 +000068 for (ValueToValueMapTy::iterator
Andrew Lenhartheb504792008-09-04 18:51:26 +000069 repb = replacements.begin(), repe = replacements.end();
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +000070 repb != repe; ++repb) {
71 Argument const *arg = cast<const Argument>(repb->first);
72 deleted[arg->getArgNo()] = arg;
73 }
Andrew Lenhartheb504792008-09-04 18:51:26 +000074
Dan Gohman6cb8c232010-08-26 15:41:53 +000075 Function* NF = CloneFunction(F, replacements,
76 /*ModuleLevelChanges=*/false);
Andrew Lenhartheb504792008-09-04 18:51:26 +000077 NF->setLinkage(GlobalValue::InternalLinkage);
78 F->getParent()->getFunctionList().push_back(NF);
79
Kenneth Uildriks74fa7322010-10-09 22:06:36 +000080 // FIXME: Specialized versions getting the same constants should also get
81 // the same name. That way, specializations for public functions can be
82 // marked linkonce_odr and reused across modules.
83
Andrew Lenhartheb504792008-09-04 18:51:26 +000084 for (Value::use_iterator ii = F->use_begin(), ee = F->use_end();
85 ii != ee; ) {
Nick Lewyckyd694a782009-03-08 19:02:17 +000086 Value::use_iterator i = ii;
Andrew Lenhartheb504792008-09-04 18:51:26 +000087 ++ii;
Gabor Greifefdf0392010-07-22 13:04:32 +000088 User *U = *i;
Gabor Greif945f1ab2010-07-22 13:07:39 +000089 CallSite CS(U);
90 if (CS) {
Andrew Lenhartheb504792008-09-04 18:51:26 +000091 if (CS.getCalledFunction() == F) {
Andrew Lenhartheb504792008-09-04 18:51:26 +000092 SmallVector<Value*, 6> args;
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +000093 // Assemble the non-specialized arguments for the updated callsite.
94 // In the process, make sure that the specialized arguments are
95 // constant and match the specialization. If that's not the case,
96 // this callsite needs to call the original or some other
97 // specialization; don't change it here.
98 CallSite::arg_iterator as = CS.arg_begin(), ae = CS.arg_end();
99 for (CallSite::arg_iterator ai = as; ai != ae; ++ai) {
100 DenseMap<unsigned, const Argument*>::iterator delit = deleted.find(
101 std::distance(as, ai));
102 if (delit == deleted.end())
103 args.push_back(cast<Value>(ai));
104 else {
105 Constant *ci = dyn_cast<Constant>(ai);
106 if (!(ci && ci == replacements[delit->second]))
107 goto next_use;
108 }
109 }
Andrew Lenhartheb504792008-09-04 18:51:26 +0000110 Value* NCall;
Gabor Greifefdf0392010-07-22 13:04:32 +0000111 if (CallInst *CI = dyn_cast<CallInst>(U)) {
Andrew Lenhartheb504792008-09-04 18:51:26 +0000112 NCall = CallInst::Create(NF, args.begin(), args.end(),
Nick Lewyckyd694a782009-03-08 19:02:17 +0000113 CI->getName(), CI);
114 cast<CallInst>(NCall)->setTailCall(CI->isTailCall());
115 cast<CallInst>(NCall)->setCallingConv(CI->getCallingConv());
116 } else {
Gabor Greifefdf0392010-07-22 13:04:32 +0000117 InvokeInst *II = cast<InvokeInst>(U);
Nick Lewyckyd694a782009-03-08 19:02:17 +0000118 NCall = InvokeInst::Create(NF, II->getNormalDest(),
119 II->getUnwindDest(),
Andrew Lenhartheb504792008-09-04 18:51:26 +0000120 args.begin(), args.end(),
Nick Lewyckyd694a782009-03-08 19:02:17 +0000121 II->getName(), II);
122 cast<InvokeInst>(NCall)->setCallingConv(II->getCallingConv());
123 }
Andrew Lenhartheb504792008-09-04 18:51:26 +0000124 CS.getInstruction()->replaceAllUsesWith(NCall);
125 CS.getInstruction()->eraseFromParent();
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +0000126 ++numReplaced;
Andrew Lenhartheb504792008-09-04 18:51:26 +0000127 }
128 }
Gabor Greifefdf0392010-07-22 13:04:32 +0000129 next_use:;
Andrew Lenhartheb504792008-09-04 18:51:26 +0000130 }
131 return NF;
132}
133
134
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000135bool PartSpec::runOnModule(Module &M) {
136 bool Changed = false;
137 for (Module::iterator I = M.begin(); I != M.end(); ++I) {
138 Function &F = *I;
Nuno Lopes7a85a622008-10-08 18:45:59 +0000139 if (F.isDeclaration() || F.mayBeOverridden()) continue;
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +0000140 InterestingArgVector interestingArgs;
Andrew Lenharthef780322008-09-04 14:34:22 +0000141 scanForInterest(F, interestingArgs);
142
143 // Find the first interesting Argument that we can specialize on
144 // If there are multiple interesting Arguments, then those will be found
145 // when processing the cloned function.
146 bool breakOuter = false;
147 for (unsigned int x = 0; !breakOuter && x < interestingArgs.size(); ++x) {
148 std::map<Constant*, int> distribution;
Kenneth Uildriks74fa7322010-10-09 22:06:36 +0000149 scanDistribution(F, interestingArgs[x], distribution);
150 for (std::map<Constant*, int>::iterator ii = distribution.begin(),
151 ee = distribution.end(); ii != ee; ++ii) {
152 // The distribution map might have an entry for NULL (i.e., one or more
153 // callsites were passing a non-constant there). We allow that to
154 // happen so that we can see whether any callsites pass a non-constant;
155 // if none do and the function is internal, we might have an opportunity
156 // to kill the original function.
157 if (!ii->first) continue;
158 int bonus = ii->second;
159 SmallVector<unsigned, 1> argnos;
160 argnos.push_back(interestingArgs[x]);
161 InlineCost cost = CA.getSpecializationCost(&F, argnos);
162 // FIXME: If this is the last constant entry, and no non-constant
163 // entries exist, and the target function is internal, the cost should
164 // be reduced by the original size of the target function, almost
165 // certainly making it negative and causing a specialization that will
166 // leave the original function dead and removable.
167 if (cost.isAlways() ||
168 (cost.isVariable() && cost.getValue() < bonus)) {
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000169 ValueToValueMapTy m;
Kenneth Uildriks74fa7322010-10-09 22:06:36 +0000170 Function::arg_iterator arg = F.arg_begin();
171 for (int y = 0; y < interestingArgs[x]; ++y)
172 ++arg;
173 m[&*arg] = ii->first;
174 SpecializeFunction(&F, m);
175 ++numSpecialized;
176 breakOuter = true;
177 Changed = true;
178 }
179 }
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000180 }
181 }
182 return Changed;
183}
184
185/// scanForInterest - This function decides which arguments would be worth
Andrew Lenharthef780322008-09-04 14:34:22 +0000186/// specializing on.
Kenneth Uildriks3a4340d2010-06-05 14:50:21 +0000187void PartSpec::scanForInterest(Function& F, InterestingArgVector& args) {
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000188 for(Function::arg_iterator ii = F.arg_begin(), ee = F.arg_end();
189 ii != ee; ++ii) {
Kenneth Uildriks74fa7322010-10-09 22:06:36 +0000190 int argno = std::distance(F.arg_begin(), ii);
191 SmallVector<unsigned, 1> argnos;
192 argnos.push_back(argno);
193 int bonus = CA.getSpecializationBonus(&F, argnos);
194 if (bonus > 0) {
195 args.push_back(argno);
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000196 }
197 }
198}
199
Andrew Lenharth06a12422008-11-03 19:29:29 +0000200/// scanDistribution - Construct a histogram of constants for arg of F at arg.
Kenneth Uildriks74fa7322010-10-09 22:06:36 +0000201/// For each distinct constant, we'll compute the total of the specialization
202/// bonus across all callsites passing that constant; if that total exceeds
203/// the specialization cost, we will create the specialization.
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000204int PartSpec::scanDistribution(Function& F, int arg,
205 std::map<Constant*, int>& dist) {
Andrew Lenharthef780322008-09-04 14:34:22 +0000206 bool hasIndirect = false;
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000207 int total = 0;
Gabor Greifefdf0392010-07-22 13:04:32 +0000208 for (Value::use_iterator ii = F.use_begin(), ee = F.use_end();
209 ii != ee; ++ii) {
210 User *U = *ii;
211 CallSite CS(U);
212 if (CS && CS.getCalledFunction() == &F) {
Kenneth Uildriks74fa7322010-10-09 22:06:36 +0000213 SmallVector<unsigned, 1> argnos;
214 argnos.push_back(arg);
215 dist[dyn_cast<Constant>(CS.getArgument(arg))] +=
216 CA.getSpecializationBonus(&F, argnos);
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000217 ++total;
218 } else
Andrew Lenharthef780322008-09-04 14:34:22 +0000219 hasIndirect = true;
Gabor Greifefdf0392010-07-22 13:04:32 +0000220 }
Andrew Lenharthef780322008-09-04 14:34:22 +0000221
222 // Preserve the original address taken function even if all other uses
223 // will be specialized.
224 if (hasIndirect) ++total;
Andrew Lenharthcf996d42008-09-03 21:00:28 +0000225 return total;
226}
227
228ModulePass* llvm::createPartialSpecializationPass() { return new PartSpec(); }