blob: 916135e33cd50544c6e8c162e100ef2cfde66a14 [file] [log] [blame]
Chris Lattnerf516c692003-10-23 16:52:27 +00001//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf516c692003-10-23 16:52:27 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf516c692003-10-23 16:52:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass implements an _extremely_ simple interprocedural constant
11// propagation pass. It could certainly be improved in many different ways,
12// like using a worklist. This pass makes arguments dead, but does not remove
13// them. The existing dead argument elimination pass should be run after this
14// to clean up the mess.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000022#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Module.h"
Chris Lattnerf516c692003-10-23 16:52:27 +000026#include "llvm/Pass.h"
Chris Lattnerf52e03c2003-11-21 21:54:22 +000027using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000028
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "ipconstprop"
30
Chris Lattner1631bcb2006-12-19 22:09:18 +000031STATISTIC(NumArgumentsProped, "Number of args turned into constants");
32STATISTIC(NumReturnValProped, "Number of return values turned into constants");
Chris Lattnerf516c692003-10-23 16:52:27 +000033
Chris Lattner1631bcb2006-12-19 22:09:18 +000034namespace {
Chris Lattnerf516c692003-10-23 16:52:27 +000035 /// IPCP - The interprocedural constant propagation pass
36 ///
Nick Lewycky02d5f772009-10-25 06:33:48 +000037 struct IPCP : public ModulePass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000038 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000039 IPCP() : ModulePass(ID) {
40 initializeIPCPPass(*PassRegistry::getPassRegistry());
41 }
Devang Patel09f162c2007-05-01 21:15:47 +000042
Craig Topper3e4c6972014-03-05 09:10:37 +000043 bool runOnModule(Module &M) override;
Chris Lattnerf516c692003-10-23 16:52:27 +000044 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000045}
Chris Lattnerf516c692003-10-23 16:52:27 +000046
Chris Lattneraf555ad2004-11-14 06:10:11 +000047/// PropagateConstantsIntoArguments - Look at all uses of the specified
48/// function. If all uses are direct call sites, and all pass a particular
49/// constant in for an argument, propagate that constant in as the argument.
Chris Lattnerf516c692003-10-23 16:52:27 +000050///
Davide Italiano296d12c2016-05-03 20:08:24 +000051static bool PropagateConstantsIntoArguments(Function &F) {
Chris Lattnerc2d3d312006-08-27 22:42:52 +000052 if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
Chris Lattnerf516c692003-10-23 16:52:27 +000053
Chris Lattnera82d6912008-04-23 06:16:27 +000054 // For each argument, keep track of its constant value and whether it is a
55 // constant or not. The bool is driven to true when found to be non-constant.
56 SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
Chris Lattner531f9e92005-03-15 04:54:21 +000057 ArgumentConstants.resize(F.arg_size());
Chris Lattnerf516c692003-10-23 16:52:27 +000058
59 unsigned NumNonconstant = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +000060 for (Use &U : F.uses()) {
61 User *UR = U.getUser();
Chris Lattner1a8b80e2009-11-01 06:11:53 +000062 // Ignore blockaddress uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +000063 if (isa<BlockAddress>(UR)) continue;
Chris Lattner1a8b80e2009-11-01 06:11:53 +000064
Chris Lattnera82d6912008-04-23 06:16:27 +000065 // Used by a non-instruction, or not the callee of a function, do not
66 // transform.
Chandler Carruthcdf47882014-03-09 03:16:01 +000067 if (!isa<CallInst>(UR) && !isa<InvokeInst>(UR))
Chris Lattnera82d6912008-04-23 06:16:27 +000068 return false;
69
Chandler Carruthcdf47882014-03-09 03:16:01 +000070 CallSite CS(cast<Instruction>(UR));
71 if (!CS.isCallee(&U))
Gabor Greiff4013372009-01-22 21:35:57 +000072 return false;
Chris Lattnerf516c692003-10-23 16:52:27 +000073
Chris Lattnera82d6912008-04-23 06:16:27 +000074 // Check out all of the potentially constant arguments. Note that we don't
75 // inspect varargs here.
76 CallSite::arg_iterator AI = CS.arg_begin();
77 Function::arg_iterator Arg = F.arg_begin();
78 for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
79 ++i, ++AI, ++Arg) {
80
81 // If this argument is known non-constant, ignore it.
82 if (ArgumentConstants[i].second)
83 continue;
84
85 Constant *C = dyn_cast<Constant>(*AI);
Craig Topperf40110f2014-04-25 05:29:35 +000086 if (C && ArgumentConstants[i].first == nullptr) {
Chris Lattnera82d6912008-04-23 06:16:27 +000087 ArgumentConstants[i].first = C; // First constant seen.
88 } else if (C && ArgumentConstants[i].first == C) {
89 // Still the constant value we think it is.
90 } else if (*AI == &*Arg) {
91 // Ignore recursive calls passing argument down.
92 } else {
93 // Argument became non-constant. If all arguments are non-constant now,
94 // give up on this function.
95 if (++NumNonconstant == ArgumentConstants.size())
96 return false;
97 ArgumentConstants[i].second = true;
Chris Lattnerf516c692003-10-23 16:52:27 +000098 }
99 }
Chris Lattnera82d6912008-04-23 06:16:27 +0000100 }
Chris Lattnerf516c692003-10-23 16:52:27 +0000101
102 // If we got to this point, there is a constant argument!
103 assert(NumNonconstant != ArgumentConstants.size());
Chris Lattner5e004e82003-10-27 21:09:00 +0000104 bool MadeChange = false;
Chris Lattnera82d6912008-04-23 06:16:27 +0000105 Function::arg_iterator AI = F.arg_begin();
106 for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
107 // Do we have a constant argument?
Torok Edwin21bd8c92009-09-24 18:33:42 +0000108 if (ArgumentConstants[i].second || AI->use_empty() ||
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000109 AI->hasInAllocaAttr() || (AI->hasByValAttr() && !F.onlyReadsMemory()))
Chris Lattnera82d6912008-04-23 06:16:27 +0000110 continue;
111
112 Value *V = ArgumentConstants[i].first;
Craig Topperf40110f2014-04-25 05:29:35 +0000113 if (!V) V = UndefValue::get(AI->getType());
Chris Lattnera82d6912008-04-23 06:16:27 +0000114 AI->replaceAllUsesWith(V);
115 ++NumArgumentsProped;
116 MadeChange = true;
117 }
Chris Lattner5e004e82003-10-27 21:09:00 +0000118 return MadeChange;
Chris Lattnerf516c692003-10-23 16:52:27 +0000119}
Brian Gaeke960707c2003-11-11 22:41:34 +0000120
Chris Lattneraf555ad2004-11-14 06:10:11 +0000121
Matthijs Kooijman97034592008-06-18 08:09:27 +0000122// Check to see if this function returns one or more constants. If so, replace
123// all callers that use those return values with the constant value. This will
124// leave in the actual return values and instructions, but deadargelim will
125// clean that up.
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000126//
127// Additionally if a function always returns one of its arguments directly,
128// callers will be updated to use the value they pass in directly instead of
129// using the return value.
Davide Italiano296d12c2016-05-03 20:08:24 +0000130static bool PropagateConstantReturn(Function &F) {
Nick Lewycky39dbfd32009-11-23 03:29:18 +0000131 if (F.getReturnType()->isVoidTy())
Chris Lattneraf555ad2004-11-14 06:10:11 +0000132 return false; // No return value.
133
Sanjoy Das5ce32722016-04-08 00:48:30 +0000134 // We can infer and propagate the return value only when we know that the
135 // definition we'll get at link time is *exactly* the definition we see now.
136 // For more details, see GlobalValue::mayBeDerefined.
137 if (!F.isDefinitionExact())
Chris Lattnerdbd595f2008-06-09 07:58:07 +0000138 return false;
Owen Anderson47db9412009-07-22 00:24:57 +0000139
Chris Lattneraf555ad2004-11-14 06:10:11 +0000140 // Check to see if this function returns a constant.
Devang Patel73581652008-03-11 22:24:29 +0000141 SmallVector<Value *,4> RetVals;
Chris Lattner229907c2011-07-18 04:54:35 +0000142 StructType *STy = dyn_cast<StructType>(F.getReturnType());
Devang Patel73581652008-03-11 22:24:29 +0000143 if (STy)
Matthijs Kooijman97034592008-06-18 08:09:27 +0000144 for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000145 RetVals.push_back(UndefValue::get(STy->getElementType(i)));
Devang Patel73581652008-03-11 22:24:29 +0000146 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000147 RetVals.push_back(UndefValue::get(F.getReturnType()));
Devang Patel73581652008-03-11 22:24:29 +0000148
Matthijs Kooijman97034592008-06-18 08:09:27 +0000149 unsigned NumNonConstant = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000150 for (BasicBlock &BB : F)
151 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
Chris Lattner5f1802c2008-04-23 05:59:23 +0000152 for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
Matthijs Kooijman97034592008-06-18 08:09:27 +0000153 // Already found conflicting return values?
Chris Lattner5f1802c2008-04-23 05:59:23 +0000154 Value *RV = RetVals[i];
Matthijs Kooijman97034592008-06-18 08:09:27 +0000155 if (!RV)
156 continue;
157
158 // Find the returned value
159 Value *V;
Dan Gohmane2190392008-10-03 22:21:24 +0000160 if (!STy)
Jay Foad11522092011-04-04 07:44:02 +0000161 V = RI->getOperand(0);
Matthijs Kooijman97034592008-06-18 08:09:27 +0000162 else
Nick Lewycky39dbfd32009-11-23 03:29:18 +0000163 V = FindInsertedValue(RI->getOperand(0), i);
Matthijs Kooijman97034592008-06-18 08:09:27 +0000164
165 if (V) {
166 // Ignore undefs, we can change them into anything
167 if (isa<UndefValue>(V))
168 continue;
169
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000170 // Try to see if all the rets return the same constant or argument.
171 if (isa<Constant>(V) || isa<Argument>(V)) {
Matthijs Kooijman97034592008-06-18 08:09:27 +0000172 if (isa<UndefValue>(RV)) {
173 // No value found yet? Try the current one.
174 RetVals[i] = V;
175 continue;
176 }
177 // Returning the same value? Good.
178 if (RV == V)
179 continue;
180 }
181 }
182 // Different or no known return value? Don't propagate this return
183 // value.
Craig Topperf40110f2014-04-25 05:29:35 +0000184 RetVals[i] = nullptr;
Alp Tokerf907b892013-12-05 05:44:44 +0000185 // All values non-constant? Stop looking.
Matthijs Kooijman97034592008-06-18 08:09:27 +0000186 if (++NumNonConstant == RetVals.size())
187 return false;
Chris Lattneraf555ad2004-11-14 06:10:11 +0000188 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000189 }
Chris Lattneraf555ad2004-11-14 06:10:11 +0000190
Matthijs Kooijman97034592008-06-18 08:09:27 +0000191 // If we got here, the function returns at least one constant value. Loop
192 // over all users, replacing any uses of the return value with the returned
193 // constant.
Chris Lattneraf555ad2004-11-14 06:10:11 +0000194 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000195 for (Use &U : F.uses()) {
196 CallSite CS(U.getUser());
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000197 Instruction* Call = CS.getInstruction();
198
199 // Not a call instruction or a call instruction that's not calling F
200 // directly?
Chandler Carruthcdf47882014-03-09 03:16:01 +0000201 if (!Call || !CS.isCallee(&U))
Chris Lattner5f1802c2008-04-23 05:59:23 +0000202 continue;
Chris Lattner5f1802c2008-04-23 05:59:23 +0000203
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000204 // Call result not used?
Chris Lattner5f1802c2008-04-23 05:59:23 +0000205 if (Call->use_empty())
206 continue;
Chris Lattneraf555ad2004-11-14 06:10:11 +0000207
Chris Lattner5f1802c2008-04-23 05:59:23 +0000208 MadeChange = true;
209
Craig Topperf40110f2014-04-25 05:29:35 +0000210 if (!STy) {
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000211 Value* New = RetVals[0];
212 if (Argument *A = dyn_cast<Argument>(New))
213 // Was an argument returned? Then find the corresponding argument in
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000214 // the call instruction and use that.
215 New = CS.getArgument(A->getArgNo());
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000216 Call->replaceAllUsesWith(New);
Chris Lattner5f1802c2008-04-23 05:59:23 +0000217 continue;
218 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000219
220 for (auto I = Call->user_begin(), E = Call->user_end(); I != E;) {
Jay Foade57ba2e2009-06-06 17:49:35 +0000221 Instruction *Ins = cast<Instruction>(*I);
Matthijs Kooijman97034592008-06-18 08:09:27 +0000222
223 // Increment now, so we can remove the use
224 ++I;
225
Matthijs Kooijman97034592008-06-18 08:09:27 +0000226 // Find the index of the retval to replace with
227 int index = -1;
Dan Gohmanfa1211f2008-07-23 00:34:11 +0000228 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
Matthijs Kooijman97034592008-06-18 08:09:27 +0000229 if (EV->hasIndices())
230 index = *EV->idx_begin();
231
232 // If this use uses a specific return value, and we have a replacement,
233 // replace it.
234 if (index != -1) {
235 Value *New = RetVals[index];
236 if (New) {
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000237 if (Argument *A = dyn_cast<Argument>(New))
238 // Was an argument returned? Then find the corresponding argument in
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000239 // the call instruction and use that.
240 New = CS.getArgument(A->getArgNo());
Matthijs Kooijman97034592008-06-18 08:09:27 +0000241 Ins->replaceAllUsesWith(New);
242 Ins->eraseFromParent();
Chris Lattner263b0a12004-12-11 17:00:14 +0000243 }
Devang Patel5ca2ea62008-03-20 18:30:32 +0000244 }
Devang Patel73581652008-03-11 22:24:29 +0000245 }
Chris Lattneraf555ad2004-11-14 06:10:11 +0000246 }
247
248 if (MadeChange) ++NumReturnValProped;
Chris Lattneraf555ad2004-11-14 06:10:11 +0000249 return MadeChange;
250}
Davide Italiano296d12c2016-05-03 20:08:24 +0000251
252char IPCP::ID = 0;
253INITIALIZE_PASS(IPCP, "ipconstprop",
254 "Interprocedural constant propagation", false, false)
255
256ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
257
258bool IPCP::runOnModule(Module &M) {
259 if (skipModule(M))
260 return false;
261
262 bool Changed = false;
263 bool LocalChange = true;
264
265 // FIXME: instead of using smart algorithms, we just iterate until we stop
266 // making changes.
267 while (LocalChange) {
268 LocalChange = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000269 for (Function &F : M)
270 if (!F.isDeclaration()) {
Davide Italiano296d12c2016-05-03 20:08:24 +0000271 // Delete any klingons.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000272 F.removeDeadConstantUsers();
273 if (F.hasLocalLinkage())
274 LocalChange |= PropagateConstantsIntoArguments(F);
275 Changed |= PropagateConstantReturn(F);
Davide Italiano296d12c2016-05-03 20:08:24 +0000276 }
277 Changed |= LocalChange;
278 }
279 return Changed;
280}