blob: 985d885694569d8f58423aa2c868addf55527801 [file] [log] [blame]
Reid Spencer9bbaa2a2005-04-25 03:59:26 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
Reid Spencer39a762d2005-04-25 02:53:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer9bbaa2a2005-04-25 03:59:26 +00005// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencer39a762d2005-04-25 02:53:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a variety of small optimizations for calls to specific
11// well-known (e.g. runtime library) function calls. For example, a call to the
12// function "exit(3)" that occurs within the main() function can be transformed
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000013// into a simple "return 3" instruction. Any optimization that takes this form
14// (replace call to library function with simpler code that provides same
15// result) belongs in this file.
Reid Spencer39a762d2005-04-25 02:53:12 +000016//
17//===----------------------------------------------------------------------===//
18
Reid Spencer18b99812005-04-26 23:05:17 +000019#define DEBUG_TYPE "simplify-libcalls"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Instructions.h"
Reid Spencer39a762d2005-04-25 02:53:12 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000025#include "llvm/ADT/hash_map"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000026#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Debug.h"
Reid Spencerbb92b4f2005-04-26 19:13:17 +000028#include "llvm/Target/TargetData.h"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000029#include "llvm/Transforms/IPO.h"
Reid Spencerf2534c72005-04-25 21:11:48 +000030#include <iostream>
Reid Spencer39a762d2005-04-25 02:53:12 +000031using namespace llvm;
32
33namespace {
Reid Spencer39a762d2005-04-25 02:53:12 +000034
Reid Spencere249a822005-04-27 07:54:40 +000035/// This statistic keeps track of the total number of library calls that have
36/// been simplified regardless of which call it is.
37Statistic<> SimplifiedLibCalls("simplify-libcalls",
38 "Number of well-known library calls simplified");
Reid Spencer39a762d2005-04-25 02:53:12 +000039
Reid Spencer7ddcfb32005-04-27 21:29:20 +000040// Forward declarations
Reid Spencere249a822005-04-27 07:54:40 +000041class LibCallOptimization;
42class SimplifyLibCalls;
Reid Spencer7ddcfb32005-04-27 21:29:20 +000043
44/// @brief The list of optimizations deriving from LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +000045hash_map<std::string,LibCallOptimization*> optlist;
Reid Spencer39a762d2005-04-25 02:53:12 +000046
Reid Spencere249a822005-04-27 07:54:40 +000047/// This class is the abstract base class for the set of optimizations that
Reid Spencer7ddcfb32005-04-27 21:29:20 +000048/// corresponds to one library call. The SimplifyLibCalls pass will call the
Reid Spencere249a822005-04-27 07:54:40 +000049/// ValidateCalledFunction method to ask the optimization if a given Function
Reid Spencer7ddcfb32005-04-27 21:29:20 +000050/// is the kind that the optimization can handle. If the subclass returns true,
51/// then SImplifyLibCalls will also call the OptimizeCall method to perform,
52/// or attempt to perform, the optimization(s) for the library call. Otherwise,
53/// OptimizeCall won't be called. Subclasses are responsible for providing the
54/// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
55/// constructor. This is used to efficiently select which call instructions to
56/// optimize. The criteria for a "lib call" is "anything with well known
57/// semantics", typically a library function that is defined by an international
58/// standard. Because the semantics are well known, the optimizations can
59/// generally short-circuit actually calling the function if there's a simpler
60/// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
Reid Spencere249a822005-04-27 07:54:40 +000061/// @brief Base class for library call optimizations
Jeff Cohen4bc952f2005-04-29 03:05:44 +000062class LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +000063{
Jeff Cohen4bc952f2005-04-29 03:05:44 +000064public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +000065 /// The \p fname argument must be the name of the library function being
66 /// optimized by the subclass.
67 /// @brief Constructor that registers the optimization.
Reid Spencere249a822005-04-27 07:54:40 +000068 LibCallOptimization(const char * fname )
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000069 : func_name(fname)
Reid Spencere95a6472005-04-27 00:05:45 +000070#ifndef NDEBUG
Reid Spencerdc11db62005-04-27 00:20:23 +000071 , stat_name(std::string("simplify-libcalls:")+fname)
Reid Spencer93616972005-04-29 09:39:47 +000072 , stat_desc(std::string("Number of ")+fname+"(...) calls simplified")
73 , occurrences(stat_name.c_str(),stat_desc.c_str())
Reid Spencere95a6472005-04-27 00:05:45 +000074#endif
Reid Spencer39a762d2005-04-25 02:53:12 +000075 {
Reid Spencer7ddcfb32005-04-27 21:29:20 +000076 // Register this call optimizer in the optlist (a hash_map)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000077 optlist[func_name] = this;
Reid Spencer39a762d2005-04-25 02:53:12 +000078 }
79
Reid Spencer7ddcfb32005-04-27 21:29:20 +000080 /// @brief Deregister from the optlist
81 virtual ~LibCallOptimization() { optlist.erase(func_name); }
Reid Spencer8ee5aac2005-04-26 03:26:15 +000082
Reid Spencere249a822005-04-27 07:54:40 +000083 /// The implementation of this function in subclasses should determine if
84 /// \p F is suitable for the optimization. This method is called by
Reid Spencer7ddcfb32005-04-27 21:29:20 +000085 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
86 /// sites of such a function if that function is not suitable in the first
87 /// place. If the called function is suitabe, this method should return true;
Reid Spencere249a822005-04-27 07:54:40 +000088 /// false, otherwise. This function should also perform any lazy
89 /// initialization that the LibCallOptimization needs to do, if its to return
90 /// true. This avoids doing initialization until the optimizer is actually
91 /// going to be called upon to do some optimization.
Reid Spencer7ddcfb32005-04-27 21:29:20 +000092 /// @brief Determine if the function is suitable for optimization
Reid Spencere249a822005-04-27 07:54:40 +000093 virtual bool ValidateCalledFunction(
94 const Function* F, ///< The function that is the target of call sites
95 SimplifyLibCalls& SLC ///< The pass object invoking us
96 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +000097
Reid Spencere249a822005-04-27 07:54:40 +000098 /// The implementations of this function in subclasses is the heart of the
99 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
100 /// OptimizeCall to determine if (a) the conditions are right for optimizing
101 /// the call and (b) to perform the optimization. If an action is taken
102 /// against ci, the subclass is responsible for returning true and ensuring
103 /// that ci is erased from its parent.
Reid Spencere249a822005-04-27 07:54:40 +0000104 /// @brief Optimize a call, if possible.
105 virtual bool OptimizeCall(
106 CallInst* ci, ///< The call instruction that should be optimized.
107 SimplifyLibCalls& SLC ///< The pass object invoking us
108 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000109
Reid Spencere249a822005-04-27 07:54:40 +0000110 /// @brief Get the name of the library call being optimized
111 const char * getFunctionName() const { return func_name; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000112
Reid Spencere95a6472005-04-27 00:05:45 +0000113#ifndef NDEBUG
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000114 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
115 void succeeded() { ++occurrences; }
Reid Spencere95a6472005-04-27 00:05:45 +0000116#endif
Reid Spencere249a822005-04-27 07:54:40 +0000117
118private:
119 const char* func_name; ///< Name of the library call we optimize
120#ifndef NDEBUG
121 std::string stat_name; ///< Holder for debug statistic name
Reid Spencer93616972005-04-29 09:39:47 +0000122 std::string stat_desc; ///< Holder for debug statistic description
Reid Spencere249a822005-04-27 07:54:40 +0000123 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
124#endif
125};
126
Reid Spencere249a822005-04-27 07:54:40 +0000127/// This class is an LLVM Pass that applies each of the LibCallOptimization
128/// instances to all the call sites in a module, relatively efficiently. The
129/// purpose of this pass is to provide optimizations for calls to well-known
130/// functions with well-known semantics, such as those in the c library. The
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000131/// class provides the basic infrastructure for handling runOnModule. Whenever /// this pass finds a function call, it asks the appropriate optimizer to
132/// validate the call (ValidateLibraryCall). If it is validated, then
133/// the OptimizeCall method is also called.
Reid Spencere249a822005-04-27 07:54:40 +0000134/// @brief A ModulePass for optimizing well-known function calls.
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000135class SimplifyLibCalls : public ModulePass
Reid Spencere249a822005-04-27 07:54:40 +0000136{
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000137public:
Reid Spencere249a822005-04-27 07:54:40 +0000138 /// We need some target data for accurate signature details that are
139 /// target dependent. So we require target data in our AnalysisUsage.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000140 /// @brief Require TargetData from AnalysisUsage.
Reid Spencere249a822005-04-27 07:54:40 +0000141 virtual void getAnalysisUsage(AnalysisUsage& Info) const
142 {
143 // Ask that the TargetData analysis be performed before us so we can use
144 // the target data.
145 Info.addRequired<TargetData>();
146 }
147
148 /// For this pass, process all of the function calls in the module, calling
149 /// ValidateLibraryCall and OptimizeCall as appropriate.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000150 /// @brief Run all the lib call optimizations on a Module.
Reid Spencere249a822005-04-27 07:54:40 +0000151 virtual bool runOnModule(Module &M)
152 {
153 reset(M);
154
155 bool result = false;
156
157 // The call optimizations can be recursive. That is, the optimization might
158 // generate a call to another function which can also be optimized. This way
159 // we make the LibCallOptimization instances very specific to the case they
160 // handle. It also means we need to keep running over the function calls in
161 // the module until we don't get any more optimizations possible.
162 bool found_optimization = false;
163 do
164 {
165 found_optimization = false;
166 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
167 {
168 // All the "well-known" functions are external and have external linkage
169 // because they live in a runtime library somewhere and were (probably)
170 // not compiled by LLVM. So, we only act on external functions that have
171 // external linkage and non-empty uses.
172 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
173 continue;
174
175 // Get the optimization class that pertains to this function
176 LibCallOptimization* CO = optlist[FI->getName().c_str()];
177 if (!CO)
178 continue;
179
180 // Make sure the called function is suitable for the optimization
181 if (!CO->ValidateCalledFunction(FI,*this))
182 continue;
183
184 // Loop over each of the uses of the function
185 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
186 UI != UE ; )
187 {
188 // If the use of the function is a call instruction
189 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
190 {
191 // Do the optimization on the LibCallOptimization.
192 if (CO->OptimizeCall(CI,*this))
193 {
194 ++SimplifiedLibCalls;
195 found_optimization = result = true;
196#ifndef NDEBUG
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000197 CO->succeeded();
Reid Spencere249a822005-04-27 07:54:40 +0000198#endif
199 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000200 }
201 }
202 }
Reid Spencere249a822005-04-27 07:54:40 +0000203 } while (found_optimization);
204 return result;
205 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000206
Reid Spencere249a822005-04-27 07:54:40 +0000207 /// @brief Return the *current* module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000208 Module* getModule() const { return M; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000209
Reid Spencere249a822005-04-27 07:54:40 +0000210 /// @brief Return the *current* target data for the module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000211 TargetData* getTargetData() const { return TD; }
212
213 /// @brief Return the size_t type -- syntactic shortcut
214 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
215
216 /// @brief Return a Function* for the fputc libcall
217 Function* get_fputc()
218 {
219 if (!fputc_func)
220 {
221 std::vector<const Type*> args;
222 args.push_back(Type::IntTy);
223 const Type* FILE_type = M->getTypeByName("struct._IO_FILE");
224 if (!FILE_type)
225 FILE_type = M->getTypeByName("struct._FILE");
226 if (!FILE_type)
227 return 0;
228 args.push_back(PointerType::get(FILE_type));
229 FunctionType* fputc_type =
230 FunctionType::get(Type::IntTy, args, false);
231 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
232 }
233 return fputc_func;
234 }
235
236 /// @brief Return a Function* for the fwrite libcall
237 Function* get_fwrite()
238 {
239 if (!fwrite_func)
240 {
241 std::vector<const Type*> args;
242 args.push_back(PointerType::get(Type::SByteTy));
243 args.push_back(TD->getIntPtrType());
244 args.push_back(TD->getIntPtrType());
245 const Type* FILE_type = M->getTypeByName("struct._IO_FILE");
246 if (!FILE_type)
247 FILE_type = M->getTypeByName("struct._FILE");
248 if (!FILE_type)
249 return 0;
250 args.push_back(PointerType::get(FILE_type));
251 FunctionType* fwrite_type =
252 FunctionType::get(TD->getIntPtrType(), args, false);
253 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
254 }
255 return fwrite_func;
256 }
257
258 /// @brief Return a Function* for the sqrt libcall
259 Function* get_sqrt()
260 {
261 if (!sqrt_func)
262 {
263 std::vector<const Type*> args;
264 args.push_back(Type::DoubleTy);
265 FunctionType* sqrt_type =
266 FunctionType::get(Type::DoubleTy, args, false);
267 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
268 }
269 return sqrt_func;
270 }
Reid Spencere249a822005-04-27 07:54:40 +0000271
272 /// @brief Return a Function* for the strlen libcall
273 Function* get_strlen()
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000274 {
Reid Spencere249a822005-04-27 07:54:40 +0000275 if (!strlen_func)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000276 {
277 std::vector<const Type*> args;
278 args.push_back(PointerType::get(Type::SByteTy));
Reid Spencere249a822005-04-27 07:54:40 +0000279 FunctionType* strlen_type =
280 FunctionType::get(TD->getIntPtrType(), args, false);
281 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000282 }
Reid Spencere249a822005-04-27 07:54:40 +0000283 return strlen_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000284 }
285
Reid Spencere249a822005-04-27 07:54:40 +0000286 /// @brief Return a Function* for the memcpy libcall
287 Function* get_memcpy()
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000288 {
Reid Spencere249a822005-04-27 07:54:40 +0000289 if (!memcpy_func)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000290 {
291 // Note: this is for llvm.memcpy intrinsic
292 std::vector<const Type*> args;
293 args.push_back(PointerType::get(Type::SByteTy));
294 args.push_back(PointerType::get(Type::SByteTy));
295 args.push_back(Type::IntTy);
296 args.push_back(Type::IntTy);
Reid Spencere249a822005-04-27 07:54:40 +0000297 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
298 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000299 }
Reid Spencere249a822005-04-27 07:54:40 +0000300 return memcpy_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000301 }
Reid Spencer76dab9a2005-04-26 05:24:00 +0000302
Reid Spencere249a822005-04-27 07:54:40 +0000303private:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000304 /// @brief Reset our cached data for a new Module
Reid Spencere249a822005-04-27 07:54:40 +0000305 void reset(Module& mod)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000306 {
Reid Spencere249a822005-04-27 07:54:40 +0000307 M = &mod;
308 TD = &getAnalysis<TargetData>();
Reid Spencer93616972005-04-29 09:39:47 +0000309 fputc_func = 0;
310 fwrite_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000311 memcpy_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000312 sqrt_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000313 strlen_func = 0;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000314 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000315
Reid Spencere249a822005-04-27 07:54:40 +0000316private:
Reid Spencer93616972005-04-29 09:39:47 +0000317 Function* fputc_func; ///< Cached fputc function
318 Function* fwrite_func; ///< Cached fwrite function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000319 Function* memcpy_func; ///< Cached llvm.memcpy function
Reid Spencer93616972005-04-29 09:39:47 +0000320 Function* sqrt_func; ///< Cached sqrt function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000321 Function* strlen_func; ///< Cached strlen function
322 Module* M; ///< Cached Module
323 TargetData* TD; ///< Cached TargetData
Reid Spencere249a822005-04-27 07:54:40 +0000324};
325
326// Register the pass
327RegisterOpt<SimplifyLibCalls>
328X("simplify-libcalls","Simplify well-known library calls");
329
330} // anonymous namespace
331
332// The only public symbol in this file which just instantiates the pass object
333ModulePass *llvm::createSimplifyLibCallsPass()
334{
335 return new SimplifyLibCalls();
336}
337
338// Classes below here, in the anonymous namespace, are all subclasses of the
339// LibCallOptimization class, each implementing all optimizations possible for a
340// single well-known library call. Each has a static singleton instance that
341// auto registers it into the "optlist" global above.
342namespace {
343
Reid Spencer08b49402005-04-27 17:46:54 +0000344// Forward declare a utility function.
Reid Spencere249a822005-04-27 07:54:40 +0000345bool getConstantStringLength(Value* V, uint64_t& len );
346
347/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000348/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000349/// the same value passed to the exit function. When this is done, it splits the
350/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000351/// @brief Replace calls to exit in main with a simple return
Reid Spencere249a822005-04-27 07:54:40 +0000352struct ExitInMainOptimization : public LibCallOptimization
Reid Spencer39a762d2005-04-25 02:53:12 +0000353{
Reid Spencere249a822005-04-27 07:54:40 +0000354 ExitInMainOptimization() : LibCallOptimization("exit") {}
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000355 virtual ~ExitInMainOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000356
357 // Make sure the called function looks like exit (int argument, int return
358 // type, external linkage, not varargs).
Reid Spencere249a822005-04-27 07:54:40 +0000359 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000360 {
Reid Spencerb4f7b832005-04-26 07:45:18 +0000361 if (f->arg_size() >= 1)
362 if (f->arg_begin()->getType()->isInteger())
363 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +0000364 return false;
365 }
366
Reid Spencere249a822005-04-27 07:54:40 +0000367 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000368 {
Reid Spencerf2534c72005-04-25 21:11:48 +0000369 // To be careful, we check that the call to exit is coming from "main", that
370 // main has external linkage, and the return type of main and the argument
371 // to exit have the same type.
372 Function *from = ci->getParent()->getParent();
373 if (from->hasExternalLinkage())
374 if (from->getReturnType() == ci->getOperand(1)->getType())
375 if (from->getName() == "main")
376 {
377 // Okay, time to actually do the optimization. First, get the basic
378 // block of the call instruction
379 BasicBlock* bb = ci->getParent();
Reid Spencer39a762d2005-04-25 02:53:12 +0000380
Reid Spencerf2534c72005-04-25 21:11:48 +0000381 // Create a return instruction that we'll replace the call with.
382 // Note that the argument of the return is the argument of the call
383 // instruction.
384 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000385
Reid Spencerf2534c72005-04-25 21:11:48 +0000386 // Split the block at the call instruction which places it in a new
387 // basic block.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000388 bb->splitBasicBlock(ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000389
Reid Spencerf2534c72005-04-25 21:11:48 +0000390 // The block split caused a branch instruction to be inserted into
391 // the end of the original block, right after the return instruction
392 // that we put there. That's not a valid block, so delete the branch
393 // instruction.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000394 bb->getInstList().pop_back();
Reid Spencer39a762d2005-04-25 02:53:12 +0000395
Reid Spencerf2534c72005-04-25 21:11:48 +0000396 // Now we can finally get rid of the call instruction which now lives
397 // in the new basic block.
398 ci->eraseFromParent();
399
400 // Optimization succeeded, return true.
401 return true;
402 }
403 // We didn't pass the criteria for this optimization so return false
404 return false;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000405 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000406} ExitInMainOptimizer;
407
Reid Spencere249a822005-04-27 07:54:40 +0000408/// This LibCallOptimization will simplify a call to the strcat library
409/// function. The simplification is possible only if the string being
410/// concatenated is a constant array or a constant expression that results in
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000411/// a constant string. In this case we can replace it with strlen + llvm.memcpy
412/// of the constant string. Both of these calls are further reduced, if possible
413/// on subsequent passes.
Reid Spencerf2534c72005-04-25 21:11:48 +0000414/// @brief Simplify the strcat library function.
Reid Spencere249a822005-04-27 07:54:40 +0000415struct StrCatOptimization : public LibCallOptimization
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000416{
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000417public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000418 /// @brief Default constructor
Reid Spencere249a822005-04-27 07:54:40 +0000419 StrCatOptimization() : LibCallOptimization("strcat") {}
420
421public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000422 /// @breif Destructor
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000423 virtual ~StrCatOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000424
425 /// @brief Make sure that the "strcat" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000426 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000427 {
428 if (f->getReturnType() == PointerType::get(Type::SByteTy))
429 if (f->arg_size() == 2)
430 {
431 Function::const_arg_iterator AI = f->arg_begin();
432 if (AI++->getType() == PointerType::get(Type::SByteTy))
433 if (AI->getType() == PointerType::get(Type::SByteTy))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000434 {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000435 // Indicate this is a suitable call type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000436 return true;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000437 }
Reid Spencerf2534c72005-04-25 21:11:48 +0000438 }
439 return false;
440 }
441
Reid Spencere249a822005-04-27 07:54:40 +0000442 /// @brief Optimize the strcat library function
443 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000444 {
Reid Spencer08b49402005-04-27 17:46:54 +0000445 // Extract some information from the instruction
446 Module* M = ci->getParent()->getParent()->getParent();
447 Value* dest = ci->getOperand(1);
448 Value* src = ci->getOperand(2);
449
Reid Spencer76dab9a2005-04-26 05:24:00 +0000450 // Extract the initializer (while making numerous checks) from the
451 // source operand of the call to strcat. If we get null back, one of
452 // a variety of checks in get_GVInitializer failed
Reid Spencerb4f7b832005-04-26 07:45:18 +0000453 uint64_t len = 0;
Reid Spencer08b49402005-04-27 17:46:54 +0000454 if (!getConstantStringLength(src,len))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000455 return false;
456
Reid Spencerb4f7b832005-04-26 07:45:18 +0000457 // Handle the simple, do-nothing case
458 if (len == 0)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000459 {
Reid Spencer08b49402005-04-27 17:46:54 +0000460 ci->replaceAllUsesWith(dest);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000461 ci->eraseFromParent();
462 return true;
463 }
464
Reid Spencerb4f7b832005-04-26 07:45:18 +0000465 // Increment the length because we actually want to memcpy the null
466 // terminator as well.
467 len++;
Reid Spencerf2534c72005-04-25 21:11:48 +0000468
Reid Spencerb4f7b832005-04-26 07:45:18 +0000469 // We need to find the end of the destination string. That's where the
470 // memory is to be moved to. We just generate a call to strlen (further
Reid Spencere249a822005-04-27 07:54:40 +0000471 // optimized in another pass). Note that the SLC.get_strlen() call
Reid Spencerb4f7b832005-04-26 07:45:18 +0000472 // caches the Function* for us.
473 CallInst* strlen_inst =
Reid Spencer08b49402005-04-27 17:46:54 +0000474 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000475
476 // Now that we have the destination's length, we must index into the
477 // destination's pointer to get the actual memcpy destination (end of
478 // the string .. we're concatenating).
479 std::vector<Value*> idx;
480 idx.push_back(strlen_inst);
481 GetElementPtrInst* gep =
Reid Spencer08b49402005-04-27 17:46:54 +0000482 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000483
484 // We have enough information to now generate the memcpy call to
485 // do the concatenation for us.
486 std::vector<Value*> vals;
487 vals.push_back(gep); // destination
488 vals.push_back(ci->getOperand(2)); // source
489 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
490 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000491 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000492
493 // Finally, substitute the first operand of the strcat call for the
494 // strcat call itself since strcat returns its first operand; and,
495 // kill the strcat CallInst.
Reid Spencer08b49402005-04-27 17:46:54 +0000496 ci->replaceAllUsesWith(dest);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000497 ci->eraseFromParent();
498 return true;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000499 }
500} StrCatOptimizer;
501
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000502/// This LibCallOptimization will simplify a call to the strcpy library
503/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000504/// (1) If src and dest are the same and not volatile, just return dest
505/// (2) If the src is a constant then we can convert to llvm.memmove
506/// @brief Simplify the strcpy library function.
507struct StrCpyOptimization : public LibCallOptimization
508{
509public:
510 StrCpyOptimization() : LibCallOptimization("strcpy") {}
511 virtual ~StrCpyOptimization() {}
512
513 /// @brief Make sure that the "strcpy" function has the right prototype
514 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
515 {
516 if (f->getReturnType() == PointerType::get(Type::SByteTy))
517 if (f->arg_size() == 2)
518 {
519 Function::const_arg_iterator AI = f->arg_begin();
520 if (AI++->getType() == PointerType::get(Type::SByteTy))
521 if (AI->getType() == PointerType::get(Type::SByteTy))
522 {
523 // Indicate this is a suitable call type.
524 return true;
525 }
526 }
527 return false;
528 }
529
530 /// @brief Perform the strcpy optimization
531 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
532 {
533 // First, check to see if src and destination are the same. If they are,
534 // then the optimization is to replace the CallInst with the destination
535 // because the call is a no-op. Note that this corresponds to the
536 // degenerate strcpy(X,X) case which should have "undefined" results
537 // according to the C specification. However, it occurs sometimes and
538 // we optimize it as a no-op.
539 Value* dest = ci->getOperand(1);
540 Value* src = ci->getOperand(2);
541 if (dest == src)
542 {
543 ci->replaceAllUsesWith(dest);
544 ci->eraseFromParent();
545 return true;
546 }
547
548 // Get the length of the constant string referenced by the second operand,
549 // the "src" parameter. Fail the optimization if we can't get the length
550 // (note that getConstantStringLength does lots of checks to make sure this
551 // is valid).
552 uint64_t len = 0;
553 if (!getConstantStringLength(ci->getOperand(2),len))
554 return false;
555
556 // If the constant string's length is zero we can optimize this by just
557 // doing a store of 0 at the first byte of the destination
558 if (len == 0)
559 {
560 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
561 ci->replaceAllUsesWith(dest);
562 ci->eraseFromParent();
563 return true;
564 }
565
566 // Increment the length because we actually want to memcpy the null
567 // terminator as well.
568 len++;
569
570 // Extract some information from the instruction
571 Module* M = ci->getParent()->getParent()->getParent();
572
573 // We have enough information to now generate the memcpy call to
574 // do the concatenation for us.
575 std::vector<Value*> vals;
576 vals.push_back(dest); // destination
577 vals.push_back(src); // source
578 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
579 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000580 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencere249a822005-04-27 07:54:40 +0000581
582 // Finally, substitute the first operand of the strcat call for the
583 // strcat call itself since strcat returns its first operand; and,
584 // kill the strcat CallInst.
585 ci->replaceAllUsesWith(dest);
586 ci->eraseFromParent();
587 return true;
588 }
589} StrCpyOptimizer;
590
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000591/// This LibCallOptimization will simplify a call to the strlen library
592/// function by replacing it with a constant value if the string provided to
593/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000594/// @brief Simplify the strlen library function.
Reid Spencere249a822005-04-27 07:54:40 +0000595struct StrLenOptimization : public LibCallOptimization
Reid Spencer76dab9a2005-04-26 05:24:00 +0000596{
Reid Spencere249a822005-04-27 07:54:40 +0000597 StrLenOptimization() : LibCallOptimization("strlen") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000598 virtual ~StrLenOptimization() {}
599
600 /// @brief Make sure that the "strlen" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000601 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000602 {
Reid Spencere249a822005-04-27 07:54:40 +0000603 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
Reid Spencer76dab9a2005-04-26 05:24:00 +0000604 if (f->arg_size() == 1)
605 if (Function::const_arg_iterator AI = f->arg_begin())
606 if (AI->getType() == PointerType::get(Type::SByteTy))
607 return true;
608 return false;
609 }
610
611 /// @brief Perform the strlen optimization
Reid Spencere249a822005-04-27 07:54:40 +0000612 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000613 {
Reid Spencerb4f7b832005-04-26 07:45:18 +0000614 // Get the length of the string
615 uint64_t len = 0;
616 if (!getConstantStringLength(ci->getOperand(1),len))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000617 return false;
618
Reid Spencere249a822005-04-27 07:54:40 +0000619 ci->replaceAllUsesWith(
620 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
Reid Spencerb4f7b832005-04-26 07:45:18 +0000621 ci->eraseFromParent();
622 return true;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000623 }
624} StrLenOptimizer;
625
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000626/// This LibCallOptimization will simplify a call to the memcpy library
627/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
628/// bytes depending on the length of the string and the alignment. Additional
629/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +0000630/// @brief Simplify the memcpy library function.
Reid Spencere249a822005-04-27 07:54:40 +0000631struct MemCpyOptimization : public LibCallOptimization
Reid Spencerf2534c72005-04-25 21:11:48 +0000632{
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000633 /// @brief Default Constructor
Reid Spencere249a822005-04-27 07:54:40 +0000634 MemCpyOptimization() : LibCallOptimization("llvm.memcpy") {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000635protected:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000636 /// @brief Subclass Constructor
Reid Spencere249a822005-04-27 07:54:40 +0000637 MemCpyOptimization(const char* fname) : LibCallOptimization(fname) {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000638public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000639 /// @brief Destructor
Reid Spencerf2534c72005-04-25 21:11:48 +0000640 virtual ~MemCpyOptimization() {}
641
642 /// @brief Make sure that the "memcpy" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000643 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +0000644 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000645 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +0000646 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +0000647 }
648
Reid Spencerb4f7b832005-04-26 07:45:18 +0000649 /// Because of alignment and instruction information that we don't have, we
650 /// leave the bulk of this to the code generators. The optimization here just
651 /// deals with a few degenerate cases where the length of the string and the
652 /// alignment match the sizes of our intrinsic types so we can do a load and
653 /// store instead of the memcpy call.
654 /// @brief Perform the memcpy optimization.
Reid Spencere249a822005-04-27 07:54:40 +0000655 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +0000656 {
Reid Spencer4855ebf2005-04-26 19:55:57 +0000657 // Make sure we have constant int values to work with
658 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
659 if (!LEN)
660 return false;
661 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
662 if (!ALIGN)
663 return false;
664
665 // If the length is larger than the alignment, we can't optimize
666 uint64_t len = LEN->getRawValue();
667 uint64_t alignment = ALIGN->getRawValue();
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000668 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +0000669 return false;
670
Reid Spencer08b49402005-04-27 17:46:54 +0000671 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +0000672 Value* dest = ci->getOperand(1);
673 Value* src = ci->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +0000674 Type* castType = 0;
Reid Spencerb4f7b832005-04-26 07:45:18 +0000675 switch (len)
676 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000677 case 0:
Reid Spencer93616972005-04-29 09:39:47 +0000678 // memcpy(d,s,0,a) -> noop
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000679 ci->eraseFromParent();
680 return true;
Reid Spencer08b49402005-04-27 17:46:54 +0000681 case 1: castType = Type::SByteTy; break;
682 case 2: castType = Type::ShortTy; break;
683 case 4: castType = Type::IntTy; break;
684 case 8: castType = Type::LongTy; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +0000685 default:
686 return false;
687 }
Reid Spencer08b49402005-04-27 17:46:54 +0000688
689 // Cast source and dest to the right sized primitive and then load/store
690 CastInst* SrcCast =
691 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
692 CastInst* DestCast =
693 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
694 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000695 StoreInst* SI = new StoreInst(LI, DestCast, ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000696 ci->eraseFromParent();
697 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +0000698 }
699} MemCpyOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000700
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000701/// This LibCallOptimization will simplify a call to the memmove library
702/// function. It is identical to MemCopyOptimization except for the name of
703/// the intrinsic.
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000704/// @brief Simplify the memmove library function.
705struct MemMoveOptimization : public MemCpyOptimization
706{
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000707 /// @brief Default Constructor
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000708 MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
709
710} MemMoveOptimizer;
711
Reid Spencer93616972005-04-29 09:39:47 +0000712/// This LibCallOptimization will simplify calls to the "pow" library
713/// function. It looks for cases where the result of pow is well known and
714/// substitutes the appropriate value.
715/// @brief Simplify the pow library function.
716struct PowOptimization : public LibCallOptimization
717{
718public:
719 /// @brief Default Constructor
720 PowOptimization() : LibCallOptimization("pow") {}
721 /// @brief Destructor
722 virtual ~PowOptimization() {}
723
724 /// @brief Make sure that the "pow" function has the right prototype
725 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
726 {
727 // Just make sure this has 2 arguments
728 return (f->arg_size() == 2);
729 }
730
731 /// @brief Perform the pow optimization.
732 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
733 {
734 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
735 Value* base = ci->getOperand(1);
736 Value* expn = ci->getOperand(2);
737 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
738 double Op1V = Op1->getValue();
739 if (Op1V == 1.0)
740 {
741 // pow(1.0,x) -> 1.0
742 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
743 ci->eraseFromParent();
744 return true;
745 }
746 }
747 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
748 {
749 double Op2V = Op2->getValue();
750 if (Op2V == 0.0)
751 {
752 // pow(x,0.0) -> 1.0
753 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
754 ci->eraseFromParent();
755 return true;
756 }
757 else if (Op2V == 0.5)
758 {
759 // pow(x,0.5) -> sqrt(x)
760 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
761 ci->getName()+".pow",ci);
762 ci->replaceAllUsesWith(sqrt_inst);
763 ci->eraseFromParent();
764 return true;
765 }
766 else if (Op2V == 1.0)
767 {
768 // pow(x,1.0) -> x
769 ci->replaceAllUsesWith(base);
770 ci->eraseFromParent();
771 return true;
772 }
773 else if (Op2V == -1.0)
774 {
775 // pow(x,-1.0) -> 1.0/x
776 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
777 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
778 ci->replaceAllUsesWith(div_inst);
779 ci->eraseFromParent();
780 return true;
781 }
782 }
783 return false; // opt failed
784 }
785} PowOptimizer;
786
787/// This LibCallOptimization will simplify calls to the "fputs" library
788/// function. It looks for cases where the result of fputs is not used and the
789/// operation can be reduced to something simpler.
790/// @brief Simplify the pow library function.
791struct PutsOptimization : public LibCallOptimization
792{
793public:
794 /// @brief Default Constructor
795 PutsOptimization() : LibCallOptimization("fputs") {}
796
797 /// @brief Destructor
798 virtual ~PutsOptimization() {}
799
800 /// @brief Make sure that the "fputs" function has the right prototype
801 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
802 {
803 // Just make sure this has 2 arguments
804 return (f->arg_size() == 2);
805 }
806
807 /// @brief Perform the fputs optimization.
808 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
809 {
810 // If the result is used, none of these optimizations work
811 if (!ci->hasNUses(0))
812 return false;
813
814 // All the optimizations depend on the length of the first argument and the
815 // fact that it is a constant string array. Check that now
816 uint64_t len = 0;
817 if (!getConstantStringLength(ci->getOperand(1), len))
818 return false;
819
820 switch (len)
821 {
822 case 0:
823 // fputs("",F) -> noop
824 break;
825 case 1:
826 {
827 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
828 Function* fputc_func = SLC.get_fputc();
829 if (!fputc_func)
830 return false;
831 LoadInst* loadi = new LoadInst(ci->getOperand(1),
832 ci->getOperand(1)->getName()+".byte",ci);
833 CastInst* casti = new CastInst(loadi,Type::IntTy,
834 loadi->getName()+".int",ci);
835 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
836 break;
837 }
838 default:
839 {
840 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
841 Function* fwrite_func = SLC.get_fwrite();
842 if (!fwrite_func)
843 return false;
844 std::vector<Value*> parms;
845 parms.push_back(ci->getOperand(1));
846 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
847 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
848 parms.push_back(ci->getOperand(2));
849 new CallInst(fwrite_func,parms,"",ci);
850 break;
851 }
852 }
853 ci->eraseFromParent();
854 return true; // success
855 }
856} PutsOptimizer;
857
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000858/// A function to compute the length of a null-terminated constant array of
859/// integers. This function can't rely on the size of the constant array
860/// because there could be a null terminator in the middle of the array.
861/// We also have to bail out if we find a non-integer constant initializer
862/// of one of the elements or if there is no null-terminator. The logic
863/// below checks each of these conditions and will return true only if all
864/// conditions are met. In that case, the \p len parameter is set to the length
865/// of the null-terminated string. If false is returned, the conditions were
866/// not met and len is set to 0.
867/// @brief Get the length of a constant string (null-terminated array).
Reid Spencere249a822005-04-27 07:54:40 +0000868bool getConstantStringLength(Value* V, uint64_t& len )
869{
870 assert(V != 0 && "Invalid args to getConstantStringLength");
871 len = 0; // make sure we initialize this
872 User* GEP = 0;
873 // If the value is not a GEP instruction nor a constant expression with a
874 // GEP instruction, then return false because ConstantArray can't occur
875 // any other way
876 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
877 GEP = GEPI;
878 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
879 if (CE->getOpcode() == Instruction::GetElementPtr)
880 GEP = CE;
881 else
882 return false;
883 else
884 return false;
885
886 // Make sure the GEP has exactly three arguments.
887 if (GEP->getNumOperands() != 3)
888 return false;
889
890 // Check to make sure that the first operand of the GEP is an integer and
891 // has value 0 so that we are sure we're indexing into the initializer.
892 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
893 {
894 if (!op1->isNullValue())
895 return false;
896 }
897 else
898 return false;
899
900 // Ensure that the second operand is a ConstantInt. If it isn't then this
901 // GEP is wonky and we're not really sure what were referencing into and
902 // better of not optimizing it. While we're at it, get the second index
903 // value. We'll need this later for indexing the ConstantArray.
904 uint64_t start_idx = 0;
905 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
906 start_idx = CI->getRawValue();
907 else
908 return false;
909
910 // The GEP instruction, constant or instruction, must reference a global
911 // variable that is a constant and is initialized. The referenced constant
912 // initializer is the array that we'll use for optimization.
913 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
914 if (!GV || !GV->isConstant() || !GV->hasInitializer())
915 return false;
916
917 // Get the initializer.
918 Constant* INTLZR = GV->getInitializer();
919
920 // Handle the ConstantAggregateZero case
921 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
922 {
923 // This is a degenerate case. The initializer is constant zero so the
924 // length of the string must be zero.
925 len = 0;
926 return true;
927 }
928
929 // Must be a Constant Array
930 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
931 if (!A)
932 return false;
933
934 // Get the number of elements in the array
935 uint64_t max_elems = A->getType()->getNumElements();
936
937 // Traverse the constant array from start_idx (derived above) which is
938 // the place the GEP refers to in the array.
939 for ( len = start_idx; len < max_elems; len++)
940 {
941 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
942 {
943 // Check for the null terminator
944 if (CI->isNullValue())
945 break; // we found end of string
946 }
947 else
948 return false; // This array isn't suitable, non-int initializer
949 }
950 if (len >= max_elems)
951 return false; // This array isn't null terminated
952
953 // Subtract out the initial value from the length
954 len -= start_idx;
955 return true; // success!
956}
957
Reid Spencer649ac282005-04-28 04:40:06 +0000958// TODO:
959// Additional cases that we need to add to this file:
960//
Reid Spencer649ac282005-04-28 04:40:06 +0000961// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +0000962// * cbrt(expN(X)) -> expN(x/3)
963// * cbrt(sqrt(x)) -> pow(x,1/6)
964// * cbrt(sqrt(x)) -> pow(x,1/9)
965//
Reid Spencer649ac282005-04-28 04:40:06 +0000966// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +0000967// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +0000968//
969// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +0000970// * exp(log(x)) -> x
971//
Reid Spencer649ac282005-04-28 04:40:06 +0000972// ffs, ffsl, ffsll:
973// * ffs(cnst) -> cnst'
974//
Reid Spencer649ac282005-04-28 04:40:06 +0000975// fprintf:
976// * fprintf(file,fmt) -> fputs(fmt,file)
977// (if fmt is constant and constains no % characters)
978// * fprintf(file,"%s",str) -> fputs(orig,str)
979// (only if the fprintf result is not used)
980// * fprintf(file,"%c",chr) -> fputc(chr,file)
981//
Reid Spencer649ac282005-04-28 04:40:06 +0000982// isascii:
983// * isascii(c) -> ((c & ~0x7f) == 0)
984//
985// isdigit:
986// * isdigit(c) -> (unsigned)(c) - '0' <= 9
987//
988// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +0000989// * log(exp(x)) -> x
990// * log(x**y) -> y*log(x)
991// * log(exp(y)) -> y*log(e)
992// * log(exp2(y)) -> y*log(2)
993// * log(exp10(y)) -> y*log(10)
994// * log(sqrt(x)) -> 0.5*log(x)
995// * log(pow(x,y)) -> y*log(x)
996//
997// lround, lroundf, lroundl:
998// * lround(cnst) -> cnst'
999//
1000// memcmp:
1001// * memcmp(s1,s2,0) -> 0
1002// * memcmp(x,x,l) -> 0
1003// * memcmp(x,y,l) -> cnst
1004// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1005// * memcpy(x,y,1) -> *x - *y
1006//
Reid Spencer649ac282005-04-28 04:40:06 +00001007// memmove:
1008// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1009// (if s is a global constant array)
1010//
1011// memset:
1012// * memset(s,c,0) -> noop
1013// * memset(s,c,n) -> store s, c
1014// (for n=1,2,4,8)
1015//
1016// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00001017// * pow(exp(x),y) -> exp(x*y)
1018// * pow(sqrt(x),y) -> pow(x,y*0.5)
1019// * pow(pow(x,y),z)-> pow(x,y*z)
1020//
1021// puts:
1022// * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1023//
1024// round, roundf, roundl:
1025// * round(cnst) -> cnst'
1026//
1027// signbit:
1028// * signbit(cnst) -> cnst'
1029// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1030//
Reid Spencer649ac282005-04-28 04:40:06 +00001031// sprintf:
1032// * sprintf(dest,fmt) -> strcpy(dest,fmt)
1033// (if fmt is constant and constains no % characters)
1034// * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1035// (only if the sprintf result is not used)
1036//
1037// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00001038// * sqrt(expN(x)) -> expN(x*0.5)
1039// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1040// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1041//
1042// strchr, strrchr:
1043// * strchr(s,c) -> offset_of_in(c,s)
1044// (if c is a constant integer and s is a constant string)
1045// * strrchr(s,c) -> reverse_offset_of_in(c,s)
1046// (if c is a constant integer and s is a constant string)
1047// * strrchr(s1,0) -> strchr(s1,0)
1048//
1049// strcmp:
1050// * strcmp(x,x) -> 0
1051// * strcmp(x,"") -> *x
1052// * strcmp("",x) -> *x
1053// * strcmp(x,y) -> cnst (if both x and y are constant strings)
1054//
1055// strncat:
1056// * strncat(x,y,0) -> x
1057// * strncat(x,y,0) -> x (if strlen(y) = 0)
1058// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1059//
1060// strncmp:
1061// * strncmp(x,y,0) -> 0
1062// * strncmp(x,x,l) -> 0
1063// * strncmp(x,"",l) -> *x
1064// * strncmp("",x,l) -> *x
1065// * strncmp(x,y,1) -> *x - *y
1066//
1067// strncpy:
1068// * strncpy(d,s,0) -> d
1069// * strncpy(d,s,l) -> memcpy(d,s,l,1)
1070// (if s and l are constants)
1071//
1072// strpbrk:
1073// * strpbrk(s,a) -> offset_in_for(s,a)
1074// (if s and a are both constant strings)
1075// * strpbrk(s,"") -> 0
1076// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1077//
1078// strspn, strcspn:
1079// * strspn(s,a) -> const_int (if both args are constant)
1080// * strspn("",a) -> 0
1081// * strspn(s,"") -> 0
1082// * strcspn(s,a) -> const_int (if both args are constant)
1083// * strcspn("",a) -> 0
1084// * strcspn(s,"") -> strlen(a)
1085//
1086// strstr:
1087// * strstr(x,x) -> x
1088// * strstr(s1,s2) -> offset_of_s2_in(s1)
1089// (if s1 and s2 are constant strings)
1090//
1091// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00001092// * tan(atan(x)) -> x
1093//
1094// toascii:
1095// * toascii(c) -> (c & 0x7f)
1096//
1097// trunc, truncf, truncl:
1098// * trunc(cnst) -> cnst'
1099//
1100//
Reid Spencer39a762d2005-04-25 02:53:12 +00001101}