blob: 7d65028601c80245fc64858d9c469a4a68893d19 [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//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005// This file was developed by Reid Spencer and is distributed under the
Reid Spencer9bbaa2a2005-04-25 03:59:26 +00006// University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencer39a762d2005-04-25 02:53:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000010// This file implements a module pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
12// library functions). For example, a call to the function "exit(3)" that
Reid Spencer0b13cda2005-05-21 00:57:44 +000013// occurs within the main() function can be transformed into a simple "return 3"
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000014// instruction. Any optimization that takes this form (replace call to library
15// function with simpler code that provides the same result) belongs in this
16// file.
Reid Spencer39a762d2005-04-25 02:53:12 +000017//
18//===----------------------------------------------------------------------===//
19
Reid Spencer18b99812005-04-26 23:05:17 +000020#define DEBUG_TYPE "simplify-libcalls"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000021#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Instructions.h"
Reid Spencer39a762d2005-04-25 02:53:12 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000026#include "llvm/ADT/hash_map"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000027#include "llvm/ADT/Statistic.h"
Reid Spencerade18212006-01-19 08:36:56 +000028#include "llvm/Config/config.h"
Reid Spencer557ab152007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000030#include "llvm/Support/Debug.h"
Reid Spencerbb92b4f2005-04-26 19:13:17 +000031#include "llvm/Target/TargetData.h"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000032#include "llvm/Transforms/IPO.h"
Reid Spencer39a762d2005-04-25 02:53:12 +000033using namespace llvm;
34
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.
Chris Lattner1631bcb2006-12-19 22:09:18 +000037STATISTIC(SimplifiedLibCalls, "Number of library calls simplified");
Reid Spencer39a762d2005-04-25 02:53:12 +000038
Chris Lattner1631bcb2006-12-19 22:09:18 +000039namespace {
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
43
Chris Lattner33081b42006-01-22 23:10:26 +000044/// This list is populated by the constructor for LibCallOptimization class.
Reid Spencer9fbad132005-05-21 01:27:04 +000045/// Therefore all subclasses are registered here at static initialization time
46/// and this list is what the SimplifyLibCalls pass uses to apply the individual
47/// optimizations to the call sites.
Reid Spencer7ddcfb32005-04-27 21:29:20 +000048/// @brief The list of optimizations deriving from LibCallOptimization
Chris Lattner33081b42006-01-22 23:10:26 +000049static LibCallOptimization *OptList = 0;
Reid Spencer39a762d2005-04-25 02:53:12 +000050
Reid Spencere249a822005-04-27 07:54:40 +000051/// This class is the abstract base class for the set of optimizations that
Reid Spencer7ddcfb32005-04-27 21:29:20 +000052/// corresponds to one library call. The SimplifyLibCalls pass will call the
Reid Spencere249a822005-04-27 07:54:40 +000053/// ValidateCalledFunction method to ask the optimization if a given Function
Reid Spencer7ddcfb32005-04-27 21:29:20 +000054/// is the kind that the optimization can handle. If the subclass returns true,
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000055/// then SImplifyLibCalls will also call the OptimizeCall method to perform,
Reid Spencer7ddcfb32005-04-27 21:29:20 +000056/// or attempt to perform, the optimization(s) for the library call. Otherwise,
57/// OptimizeCall won't be called. Subclasses are responsible for providing the
58/// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
59/// constructor. This is used to efficiently select which call instructions to
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000060/// optimize. The criteria for a "lib call" is "anything with well known
Reid Spencer7ddcfb32005-04-27 21:29:20 +000061/// semantics", typically a library function that is defined by an international
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000062/// standard. Because the semantics are well known, the optimizations can
Reid Spencer7ddcfb32005-04-27 21:29:20 +000063/// generally short-circuit actually calling the function if there's a simpler
64/// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
Reid Spencere249a822005-04-27 07:54:40 +000065/// @brief Base class for library call optimizations
Reid Spencer557ab152007-02-05 23:32:05 +000066class VISIBILITY_HIDDEN LibCallOptimization {
Chris Lattner33081b42006-01-22 23:10:26 +000067 LibCallOptimization **Prev, *Next;
68 const char *FunctionName; ///< Name of the library call we optimize
69#ifndef NDEBUG
Chris Lattner700b8732006-12-06 17:46:33 +000070 Statistic occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
Chris Lattner33081b42006-01-22 23:10:26 +000071#endif
Jeff Cohen4bc952f2005-04-29 03:05:44 +000072public:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000073 /// The \p fname argument must be the name of the library function being
Reid Spencer7ddcfb32005-04-27 21:29:20 +000074 /// optimized by the subclass.
75 /// @brief Constructor that registers the optimization.
Chris Lattner33081b42006-01-22 23:10:26 +000076 LibCallOptimization(const char *FName, const char *Description)
Chris Lattner575d3212006-12-19 23:16:47 +000077 : FunctionName(FName) {
78
Reid Spencere95a6472005-04-27 00:05:45 +000079#ifndef NDEBUG
Chris Lattner575d3212006-12-19 23:16:47 +000080 occurrences.construct("simplify-libcalls", Description);
Reid Spencere95a6472005-04-27 00:05:45 +000081#endif
Chris Lattner33081b42006-01-22 23:10:26 +000082 // Register this optimizer in the list of optimizations.
83 Next = OptList;
84 OptList = this;
85 Prev = &OptList;
86 if (Next) Next->Prev = &Next;
Reid Spencer39a762d2005-04-25 02:53:12 +000087 }
Chris Lattner33081b42006-01-22 23:10:26 +000088
89 /// getNext - All libcall optimizations are chained together into a list,
90 /// return the next one in the list.
91 LibCallOptimization *getNext() { return Next; }
Reid Spencer39a762d2005-04-25 02:53:12 +000092
Reid Spencer7ddcfb32005-04-27 21:29:20 +000093 /// @brief Deregister from the optlist
Chris Lattner33081b42006-01-22 23:10:26 +000094 virtual ~LibCallOptimization() {
95 *Prev = Next;
96 if (Next) Next->Prev = Prev;
97 }
Reid Spencer8ee5aac2005-04-26 03:26:15 +000098
Reid Spencere249a822005-04-27 07:54:40 +000099 /// The implementation of this function in subclasses should determine if
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000100 /// \p F is suitable for the optimization. This method is called by
101 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
102 /// sites of such a function if that function is not suitable in the first
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000103 /// place. If the called function is suitabe, this method should return true;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000104 /// false, otherwise. This function should also perform any lazy
105 /// initialization that the LibCallOptimization needs to do, if its to return
Reid Spencere249a822005-04-27 07:54:40 +0000106 /// true. This avoids doing initialization until the optimizer is actually
107 /// going to be called upon to do some optimization.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000108 /// @brief Determine if the function is suitable for optimization
Reid Spencere249a822005-04-27 07:54:40 +0000109 virtual bool ValidateCalledFunction(
110 const Function* F, ///< The function that is the target of call sites
111 SimplifyLibCalls& SLC ///< The pass object invoking us
112 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000113
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000114 /// The implementations of this function in subclasses is the heart of the
115 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
Reid Spencere249a822005-04-27 07:54:40 +0000116 /// OptimizeCall to determine if (a) the conditions are right for optimizing
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000117 /// the call and (b) to perform the optimization. If an action is taken
Reid Spencere249a822005-04-27 07:54:40 +0000118 /// against ci, the subclass is responsible for returning true and ensuring
119 /// that ci is erased from its parent.
Reid Spencere249a822005-04-27 07:54:40 +0000120 /// @brief Optimize a call, if possible.
121 virtual bool OptimizeCall(
122 CallInst* ci, ///< The call instruction that should be optimized.
123 SimplifyLibCalls& SLC ///< The pass object invoking us
124 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000125
Reid Spencere249a822005-04-27 07:54:40 +0000126 /// @brief Get the name of the library call being optimized
Chris Lattner33081b42006-01-22 23:10:26 +0000127 const char *getFunctionName() const { return FunctionName; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000128
Chris Lattner485b6412007-04-07 00:42:32 +0000129 bool ReplaceCallWith(CallInst *CI, Value *V) {
130 if (!CI->use_empty())
131 CI->replaceAllUsesWith(V);
132 CI->eraseFromParent();
133 return true;
134 }
135
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000136 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
Chris Lattner33081b42006-01-22 23:10:26 +0000137 void succeeded() {
Reid Spencere249a822005-04-27 07:54:40 +0000138#ifndef NDEBUG
Chris Lattner33081b42006-01-22 23:10:26 +0000139 DEBUG(++occurrences);
Reid Spencere249a822005-04-27 07:54:40 +0000140#endif
Chris Lattner33081b42006-01-22 23:10:26 +0000141 }
Reid Spencere249a822005-04-27 07:54:40 +0000142};
143
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000144/// This class is an LLVM Pass that applies each of the LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +0000145/// instances to all the call sites in a module, relatively efficiently. The
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000146/// purpose of this pass is to provide optimizations for calls to well-known
Reid Spencere249a822005-04-27 07:54:40 +0000147/// functions with well-known semantics, such as those in the c library. The
Chris Lattner4201cd12005-08-24 17:22:17 +0000148/// class provides the basic infrastructure for handling runOnModule. Whenever
149/// this pass finds a function call, it asks the appropriate optimizer to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000150/// validate the call (ValidateLibraryCall). If it is validated, then
151/// the OptimizeCall method is also called.
Reid Spencere249a822005-04-27 07:54:40 +0000152/// @brief A ModulePass for optimizing well-known function calls.
Reid Spencer557ab152007-02-05 23:32:05 +0000153class VISIBILITY_HIDDEN SimplifyLibCalls : public ModulePass {
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000154public:
Reid Spencere249a822005-04-27 07:54:40 +0000155 /// We need some target data for accurate signature details that are
156 /// target dependent. So we require target data in our AnalysisUsage.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000157 /// @brief Require TargetData from AnalysisUsage.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000158 virtual void getAnalysisUsage(AnalysisUsage& Info) const {
Reid Spencere249a822005-04-27 07:54:40 +0000159 // Ask that the TargetData analysis be performed before us so we can use
160 // the target data.
161 Info.addRequired<TargetData>();
162 }
163
164 /// For this pass, process all of the function calls in the module, calling
165 /// ValidateLibraryCall and OptimizeCall as appropriate.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000166 /// @brief Run all the lib call optimizations on a Module.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000167 virtual bool runOnModule(Module &M) {
Reid Spencere249a822005-04-27 07:54:40 +0000168 reset(M);
169
170 bool result = false;
Chris Lattner33081b42006-01-22 23:10:26 +0000171 hash_map<std::string, LibCallOptimization*> OptznMap;
172 for (LibCallOptimization *Optzn = OptList; Optzn; Optzn = Optzn->getNext())
173 OptznMap[Optzn->getFunctionName()] = Optzn;
Reid Spencere249a822005-04-27 07:54:40 +0000174
175 // The call optimizations can be recursive. That is, the optimization might
176 // generate a call to another function which can also be optimized. This way
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000177 // we make the LibCallOptimization instances very specific to the case they
178 // handle. It also means we need to keep running over the function calls in
Reid Spencere249a822005-04-27 07:54:40 +0000179 // the module until we don't get any more optimizations possible.
180 bool found_optimization = false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000181 do {
Reid Spencere249a822005-04-27 07:54:40 +0000182 found_optimization = false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000183 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Reid Spencere249a822005-04-27 07:54:40 +0000184 // All the "well-known" functions are external and have external linkage
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000185 // because they live in a runtime library somewhere and were (probably)
186 // not compiled by LLVM. So, we only act on external functions that
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000187 // have external or dllimport linkage and non-empty uses.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000188 if (!FI->isDeclaration() ||
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000189 !(FI->hasExternalLinkage() || FI->hasDLLImportLinkage()) ||
190 FI->use_empty())
Reid Spencere249a822005-04-27 07:54:40 +0000191 continue;
192
193 // Get the optimization class that pertains to this function
Chris Lattner33081b42006-01-22 23:10:26 +0000194 hash_map<std::string, LibCallOptimization*>::iterator OMI =
195 OptznMap.find(FI->getName());
196 if (OMI == OptznMap.end()) continue;
197
198 LibCallOptimization *CO = OMI->second;
Reid Spencere249a822005-04-27 07:54:40 +0000199
200 // Make sure the called function is suitable for the optimization
Chris Lattner33081b42006-01-22 23:10:26 +0000201 if (!CO->ValidateCalledFunction(FI, *this))
Reid Spencere249a822005-04-27 07:54:40 +0000202 continue;
203
204 // Loop over each of the uses of the function
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000205 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000206 UI != UE ; ) {
Reid Spencere249a822005-04-27 07:54:40 +0000207 // If the use of the function is a call instruction
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000208 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
Reid Spencere249a822005-04-27 07:54:40 +0000209 // Do the optimization on the LibCallOptimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000210 if (CO->OptimizeCall(CI, *this)) {
Reid Spencere249a822005-04-27 07:54:40 +0000211 ++SimplifiedLibCalls;
212 found_optimization = result = true;
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000213 CO->succeeded();
Reid Spencere249a822005-04-27 07:54:40 +0000214 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000215 }
216 }
217 }
Reid Spencere249a822005-04-27 07:54:40 +0000218 } while (found_optimization);
Chris Lattner33081b42006-01-22 23:10:26 +0000219
Reid Spencere249a822005-04-27 07:54:40 +0000220 return result;
221 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000222
Reid Spencere249a822005-04-27 07:54:40 +0000223 /// @brief Return the *current* module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000224 Module* getModule() const { return M; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000225
Reid Spencere249a822005-04-27 07:54:40 +0000226 /// @brief Return the *current* target data for the module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000227 TargetData* getTargetData() const { return TD; }
228
229 /// @brief Return the size_t type -- syntactic shortcut
230 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
231
Evan Cheng1fc40252006-06-16 08:36:35 +0000232 /// @brief Return a Function* for the putchar libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000233 Constant *get_putchar() {
Evan Cheng1fc40252006-06-16 08:36:35 +0000234 if (!putchar_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000235 putchar_func =
236 M->getOrInsertFunction("putchar", Type::Int32Ty, Type::Int32Ty, NULL);
Evan Cheng1fc40252006-06-16 08:36:35 +0000237 return putchar_func;
238 }
239
240 /// @brief Return a Function* for the puts libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000241 Constant *get_puts() {
Evan Cheng1fc40252006-06-16 08:36:35 +0000242 if (!puts_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000243 puts_func = M->getOrInsertFunction("puts", Type::Int32Ty,
244 PointerType::get(Type::Int8Ty),
Evan Cheng1fc40252006-06-16 08:36:35 +0000245 NULL);
246 return puts_func;
247 }
248
Reid Spencer93616972005-04-29 09:39:47 +0000249 /// @brief Return a Function* for the fputc libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000250 Constant *get_fputc(const Type* FILEptr_type) {
Reid Spencer93616972005-04-29 09:39:47 +0000251 if (!fputc_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000252 fputc_func = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000253 FILEptr_type, NULL);
Reid Spencer93616972005-04-29 09:39:47 +0000254 return fputc_func;
255 }
256
Evan Chengf2ea5872006-06-16 04:52:30 +0000257 /// @brief Return a Function* for the fputs libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000258 Constant *get_fputs(const Type* FILEptr_type) {
Evan Chengf2ea5872006-06-16 04:52:30 +0000259 if (!fputs_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000260 fputs_func = M->getOrInsertFunction("fputs", Type::Int32Ty,
261 PointerType::get(Type::Int8Ty),
Evan Chengf2ea5872006-06-16 04:52:30 +0000262 FILEptr_type, NULL);
263 return fputs_func;
264 }
265
Reid Spencer93616972005-04-29 09:39:47 +0000266 /// @brief Return a Function* for the fwrite libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000267 Constant *get_fwrite(const Type* FILEptr_type) {
Reid Spencer93616972005-04-29 09:39:47 +0000268 if (!fwrite_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000269 fwrite_func = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
Reid Spencerc635f472006-12-31 05:48:39 +0000270 PointerType::get(Type::Int8Ty),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000271 TD->getIntPtrType(),
272 TD->getIntPtrType(),
273 FILEptr_type, NULL);
Reid Spencer93616972005-04-29 09:39:47 +0000274 return fwrite_func;
275 }
276
277 /// @brief Return a Function* for the sqrt libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000278 Constant *get_sqrt() {
Reid Spencer93616972005-04-29 09:39:47 +0000279 if (!sqrt_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000280 sqrt_func = M->getOrInsertFunction("sqrt", Type::DoubleTy,
281 Type::DoubleTy, NULL);
Reid Spencer93616972005-04-29 09:39:47 +0000282 return sqrt_func;
283 }
Reid Spencere249a822005-04-27 07:54:40 +0000284
Owen Andersondfd79ad2007-01-20 10:07:23 +0000285 /// @brief Return a Function* for the strcpy libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000286 Constant *get_strcpy() {
Reid Spencer1e520fd2005-05-04 03:20:21 +0000287 if (!strcpy_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000288 strcpy_func = M->getOrInsertFunction("strcpy",
Reid Spencerc635f472006-12-31 05:48:39 +0000289 PointerType::get(Type::Int8Ty),
290 PointerType::get(Type::Int8Ty),
291 PointerType::get(Type::Int8Ty),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000292 NULL);
Reid Spencer1e520fd2005-05-04 03:20:21 +0000293 return strcpy_func;
294 }
295
296 /// @brief Return a Function* for the strlen libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000297 Constant *get_strlen() {
Reid Spencere249a822005-04-27 07:54:40 +0000298 if (!strlen_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000299 strlen_func = M->getOrInsertFunction("strlen", TD->getIntPtrType(),
Reid Spencerc635f472006-12-31 05:48:39 +0000300 PointerType::get(Type::Int8Ty),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000301 NULL);
Reid Spencere249a822005-04-27 07:54:40 +0000302 return strlen_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000303 }
304
Reid Spencer38cabd72005-05-03 07:23:44 +0000305 /// @brief Return a Function* for the memchr libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000306 Constant *get_memchr() {
Reid Spencer38cabd72005-05-03 07:23:44 +0000307 if (!memchr_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000308 memchr_func = M->getOrInsertFunction("memchr",
Reid Spencerc635f472006-12-31 05:48:39 +0000309 PointerType::get(Type::Int8Ty),
310 PointerType::get(Type::Int8Ty),
311 Type::Int32Ty, TD->getIntPtrType(),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000312 NULL);
Reid Spencer38cabd72005-05-03 07:23:44 +0000313 return memchr_func;
314 }
315
Reid Spencere249a822005-04-27 07:54:40 +0000316 /// @brief Return a Function* for the memcpy libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000317 Constant *get_memcpy() {
Chris Lattner4201cd12005-08-24 17:22:17 +0000318 if (!memcpy_func) {
Reid Spencerc635f472006-12-31 05:48:39 +0000319 const Type *SBP = PointerType::get(Type::Int8Ty);
320 const char *N = TD->getIntPtrType() == Type::Int32Ty ?
Chris Lattnerea7986a2006-03-03 01:30:23 +0000321 "llvm.memcpy.i32" : "llvm.memcpy.i64";
322 memcpy_func = M->getOrInsertFunction(N, Type::VoidTy, SBP, SBP,
Reid Spencerc635f472006-12-31 05:48:39 +0000323 TD->getIntPtrType(), Type::Int32Ty,
Chris Lattnerea7986a2006-03-03 01:30:23 +0000324 NULL);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000325 }
Reid Spencere249a822005-04-27 07:54:40 +0000326 return memcpy_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000327 }
Reid Spencer76dab9a2005-04-26 05:24:00 +0000328
Chris Lattner34acba42007-01-07 08:12:01 +0000329 Constant *getUnaryFloatFunction(const char *Name, Constant *&Cache) {
Chris Lattner57740402006-01-23 06:24:46 +0000330 if (!Cache)
331 Cache = M->getOrInsertFunction(Name, Type::FloatTy, Type::FloatTy, NULL);
332 return Cache;
Chris Lattner4201cd12005-08-24 17:22:17 +0000333 }
334
Chris Lattner34acba42007-01-07 08:12:01 +0000335 Constant *get_floorf() { return getUnaryFloatFunction("floorf", floorf_func);}
336 Constant *get_ceilf() { return getUnaryFloatFunction( "ceilf", ceilf_func);}
337 Constant *get_roundf() { return getUnaryFloatFunction("roundf", roundf_func);}
338 Constant *get_rintf() { return getUnaryFloatFunction( "rintf", rintf_func);}
339 Constant *get_nearbyintf() { return getUnaryFloatFunction("nearbyintf",
Chris Lattner57740402006-01-23 06:24:46 +0000340 nearbyintf_func); }
Reid Spencere249a822005-04-27 07:54:40 +0000341private:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000342 /// @brief Reset our cached data for a new Module
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000343 void reset(Module& mod) {
Reid Spencere249a822005-04-27 07:54:40 +0000344 M = &mod;
345 TD = &getAnalysis<TargetData>();
Evan Cheng1fc40252006-06-16 08:36:35 +0000346 putchar_func = 0;
347 puts_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000348 fputc_func = 0;
Evan Chengf2ea5872006-06-16 04:52:30 +0000349 fputs_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000350 fwrite_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000351 memcpy_func = 0;
Reid Spencer38cabd72005-05-03 07:23:44 +0000352 memchr_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000353 sqrt_func = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +0000354 strcpy_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000355 strlen_func = 0;
Chris Lattner4201cd12005-08-24 17:22:17 +0000356 floorf_func = 0;
Chris Lattner57740402006-01-23 06:24:46 +0000357 ceilf_func = 0;
358 roundf_func = 0;
359 rintf_func = 0;
360 nearbyintf_func = 0;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000361 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000362
Reid Spencere249a822005-04-27 07:54:40 +0000363private:
Chris Lattner57740402006-01-23 06:24:46 +0000364 /// Caches for function pointers.
Chris Lattner34acba42007-01-07 08:12:01 +0000365 Constant *putchar_func, *puts_func;
366 Constant *fputc_func, *fputs_func, *fwrite_func;
367 Constant *memcpy_func, *memchr_func;
368 Constant *sqrt_func;
369 Constant *strcpy_func, *strlen_func;
370 Constant *floorf_func, *ceilf_func, *roundf_func;
371 Constant *rintf_func, *nearbyintf_func;
Chris Lattner57740402006-01-23 06:24:46 +0000372 Module *M; ///< Cached Module
373 TargetData *TD; ///< Cached TargetData
Reid Spencere249a822005-04-27 07:54:40 +0000374};
375
376// Register the pass
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000377RegisterPass<SimplifyLibCalls>
378X("simplify-libcalls", "Simplify well-known library calls");
Reid Spencere249a822005-04-27 07:54:40 +0000379
380} // anonymous namespace
381
382// The only public symbol in this file which just instantiates the pass object
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000383ModulePass *llvm::createSimplifyLibCallsPass() {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000384 return new SimplifyLibCalls();
Reid Spencere249a822005-04-27 07:54:40 +0000385}
386
387// Classes below here, in the anonymous namespace, are all subclasses of the
388// LibCallOptimization class, each implementing all optimizations possible for a
389// single well-known library call. Each has a static singleton instance that
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000390// auto registers it into the "optlist" global above.
Reid Spencere249a822005-04-27 07:54:40 +0000391namespace {
392
Reid Spencera7828ba2005-06-18 17:46:28 +0000393// Forward declare utility functions.
Chris Lattner182a9452007-04-07 21:58:02 +0000394static bool GetConstantStringInfo(Value *V, std::string &Str);
Chris Lattnerbed184c2007-04-07 21:04:50 +0000395static Value *CastToCStr(Value *V, Instruction *IP);
Reid Spencere249a822005-04-27 07:54:40 +0000396
397/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000398/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000399/// the same value passed to the exit function. When this is done, it splits the
400/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000401/// @brief Replace calls to exit in main with a simple return
Reid Spencer557ab152007-02-05 23:32:05 +0000402struct VISIBILITY_HIDDEN ExitInMainOptimization : public LibCallOptimization {
Reid Spencer95d8efd2005-05-03 02:54:54 +0000403 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000404 "Number of 'exit' calls simplified") {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000405
406 // Make sure the called function looks like exit (int argument, int return
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000407 // type, external linkage, not varargs).
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000408 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner03c49532007-01-15 02:27:26 +0000409 return F->arg_size() >= 1 && F->arg_begin()->getType()->isInteger();
Reid Spencerf2534c72005-04-25 21:11:48 +0000410 }
411
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000412 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
Reid Spencerf2534c72005-04-25 21:11:48 +0000413 // To be careful, we check that the call to exit is coming from "main", that
414 // main has external linkage, and the return type of main and the argument
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000415 // to exit have the same type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000416 Function *from = ci->getParent()->getParent();
417 if (from->hasExternalLinkage())
418 if (from->getReturnType() == ci->getOperand(1)->getType())
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000419 if (from->getName() == "main") {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000420 // Okay, time to actually do the optimization. First, get the basic
Reid Spencerf2534c72005-04-25 21:11:48 +0000421 // block of the call instruction
422 BasicBlock* bb = ci->getParent();
Reid Spencer39a762d2005-04-25 02:53:12 +0000423
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000424 // Create a return instruction that we'll replace the call with.
425 // Note that the argument of the return is the argument of the call
Reid Spencerf2534c72005-04-25 21:11:48 +0000426 // instruction.
Chris Lattnercd60d382006-05-12 23:35:26 +0000427 new ReturnInst(ci->getOperand(1), ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000428
Reid Spencerf2534c72005-04-25 21:11:48 +0000429 // Split the block at the call instruction which places it in a new
430 // basic block.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000431 bb->splitBasicBlock(ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000432
Reid Spencerf2534c72005-04-25 21:11:48 +0000433 // The block split caused a branch instruction to be inserted into
434 // the end of the original block, right after the return instruction
435 // that we put there. That's not a valid block, so delete the branch
436 // instruction.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000437 bb->getInstList().pop_back();
Reid Spencer39a762d2005-04-25 02:53:12 +0000438
Reid Spencerf2534c72005-04-25 21:11:48 +0000439 // Now we can finally get rid of the call instruction which now lives
440 // in the new basic block.
441 ci->eraseFromParent();
442
443 // Optimization succeeded, return true.
444 return true;
445 }
446 // We didn't pass the criteria for this optimization so return false
447 return false;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000448 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000449} ExitInMainOptimizer;
450
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000451/// This LibCallOptimization will simplify a call to the strcat library
452/// function. The simplification is possible only if the string being
453/// concatenated is a constant array or a constant expression that results in
454/// a constant string. In this case we can replace it with strlen + llvm.memcpy
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000455/// of the constant string. Both of these calls are further reduced, if possible
456/// on subsequent passes.
Reid Spencerf2534c72005-04-25 21:11:48 +0000457/// @brief Simplify the strcat library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000458struct VISIBILITY_HIDDEN StrCatOptimization : public LibCallOptimization {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000459public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000460 /// @brief Default constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +0000461 StrCatOptimization() : LibCallOptimization("strcat",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000462 "Number of 'strcat' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000463
464public:
Reid Spencerf2534c72005-04-25 21:11:48 +0000465
466 /// @brief Make sure that the "strcat" function has the right prototype
Chris Lattner182a9452007-04-07 21:58:02 +0000467 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
468 const FunctionType *FT = F->getFunctionType();
469 return FT->getNumParams() == 2 &&
470 FT->getReturnType() == PointerType::get(Type::Int8Ty) &&
471 FT->getParamType(0) == FT->getReturnType() &&
472 FT->getParamType(1) == FT->getReturnType();
Reid Spencerf2534c72005-04-25 21:11:48 +0000473 }
474
Reid Spencere249a822005-04-27 07:54:40 +0000475 /// @brief Optimize the strcat library function
Chris Lattner56b7fc72007-04-06 22:59:33 +0000476 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer08b49402005-04-27 17:46:54 +0000477 // Extract some information from the instruction
Chris Lattner56b7fc72007-04-06 22:59:33 +0000478 Value *Dst = CI->getOperand(1);
479 Value *Src = CI->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +0000480
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000481 // Extract the initializer (while making numerous checks) from the
Chris Lattner56b7fc72007-04-06 22:59:33 +0000482 // source operand of the call to strcat.
Chris Lattner182a9452007-04-07 21:58:02 +0000483 std::string SrcStr;
484 if (!GetConstantStringInfo(Src, SrcStr))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000485 return false;
486
Reid Spencerb4f7b832005-04-26 07:45:18 +0000487 // Handle the simple, do-nothing case
Chris Lattner182a9452007-04-07 21:58:02 +0000488 if (SrcStr.empty())
Chris Lattner485b6412007-04-07 00:42:32 +0000489 return ReplaceCallWith(CI, Dst);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000490
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000491 // We need to find the end of the destination string. That's where the
Chris Lattner182a9452007-04-07 21:58:02 +0000492 // memory is to be moved to. We just generate a call to strlen.
Chris Lattner56b7fc72007-04-06 22:59:33 +0000493 CallInst *DstLen = new CallInst(SLC.get_strlen(), Dst,
494 Dst->getName()+".len", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000495
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000496 // Now that we have the destination's length, we must index into the
Reid Spencerb4f7b832005-04-26 07:45:18 +0000497 // destination's pointer to get the actual memcpy destination (end of
498 // the string .. we're concatenating).
Chris Lattner56b7fc72007-04-06 22:59:33 +0000499 Dst = new GetElementPtrInst(Dst, DstLen, Dst->getName()+".indexed", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000500
501 // We have enough information to now generate the memcpy call to
502 // do the concatenation for us.
Chris Lattner56b7fc72007-04-06 22:59:33 +0000503 Value *Vals[] = {
504 Dst, Src,
Chris Lattner182a9452007-04-07 21:58:02 +0000505 ConstantInt::get(SLC.getIntPtrType(), SrcStr.size()+1), // copy nul byte.
Chris Lattner56b7fc72007-04-06 22:59:33 +0000506 ConstantInt::get(Type::Int32Ty, 1) // alignment
507 };
508 new CallInst(SLC.get_memcpy(), Vals, 4, "", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000509
Chris Lattner485b6412007-04-07 00:42:32 +0000510 return ReplaceCallWith(CI, Dst);
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000511 }
512} StrCatOptimizer;
513
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000514/// This LibCallOptimization will simplify a call to the strchr library
Reid Spencer38cabd72005-05-03 07:23:44 +0000515/// function. It optimizes out cases where the arguments are both constant
516/// and the result can be determined statically.
517/// @brief Simplify the strcmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000518struct VISIBILITY_HIDDEN StrChrOptimization : public LibCallOptimization {
Reid Spencer38cabd72005-05-03 07:23:44 +0000519public:
520 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000521 "Number of 'strchr' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +0000522
523 /// @brief Make sure that the "strchr" function has the right prototype
Chris Lattner39f0bb92007-04-06 23:38:55 +0000524 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
525 const FunctionType *FT = F->getFunctionType();
526 return FT->getNumParams() == 2 &&
527 FT->getReturnType() == PointerType::get(Type::Int8Ty) &&
528 FT->getParamType(0) == FT->getReturnType() &&
529 isa<IntegerType>(FT->getParamType(1));
Reid Spencer38cabd72005-05-03 07:23:44 +0000530 }
531
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000532 /// @brief Perform the strchr optimizations
Chris Lattner39f0bb92007-04-06 23:38:55 +0000533 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer38cabd72005-05-03 07:23:44 +0000534 // Check that the first argument to strchr is a constant array of sbyte.
Chris Lattner182a9452007-04-07 21:58:02 +0000535 std::string Str;
536 if (!GetConstantStringInfo(CI->getOperand(1), Str))
Reid Spencer38cabd72005-05-03 07:23:44 +0000537 return false;
538
Chris Lattner39f0bb92007-04-06 23:38:55 +0000539 // If the second operand is not constant, just lower this to memchr since we
540 // know the length of the input string.
541 ConstantInt *CSI = dyn_cast<ConstantInt>(CI->getOperand(2));
Reid Spencerc635f472006-12-31 05:48:39 +0000542 if (!CSI) {
Chris Lattner39f0bb92007-04-06 23:38:55 +0000543 Value *Args[3] = {
544 CI->getOperand(1),
545 CI->getOperand(2),
Chris Lattner182a9452007-04-07 21:58:02 +0000546 ConstantInt::get(SLC.getIntPtrType(), Str.size()+1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +0000547 };
Chris Lattner485b6412007-04-07 00:42:32 +0000548 return ReplaceCallWith(CI, new CallInst(SLC.get_memchr(), Args, 3,
549 CI->getName(), CI));
Reid Spencer38cabd72005-05-03 07:23:44 +0000550 }
551
Chris Lattner182a9452007-04-07 21:58:02 +0000552 // strchr can find the nul character.
553 Str += '\0';
Chris Lattner39f0bb92007-04-06 23:38:55 +0000554
Chris Lattner182a9452007-04-07 21:58:02 +0000555 // Get the character we're looking for
556 char CharValue = CSI->getSExtValue();
557
Reid Spencer38cabd72005-05-03 07:23:44 +0000558 // Compute the offset
Chris Lattner39f0bb92007-04-06 23:38:55 +0000559 uint64_t i = 0;
560 while (1) {
Chris Lattner182a9452007-04-07 21:58:02 +0000561 if (i == Str.size()) // Didn't find the char. strchr returns null.
562 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
563 // Did we find our match?
564 if (Str[i] == CharValue)
565 break;
Chris Lattner39f0bb92007-04-06 23:38:55 +0000566 ++i;
Reid Spencer38cabd72005-05-03 07:23:44 +0000567 }
568
Chris Lattner39f0bb92007-04-06 23:38:55 +0000569 // strchr(s+n,c) -> gep(s+n+i,c)
Reid Spencer38cabd72005-05-03 07:23:44 +0000570 // (if c is a constant integer and s is a constant string)
Chris Lattner39f0bb92007-04-06 23:38:55 +0000571 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
572 Value *GEP = new GetElementPtrInst(CI->getOperand(1), Idx,
573 CI->getOperand(1)->getName() +
574 ".strchr", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000575 return ReplaceCallWith(CI, GEP);
Reid Spencer38cabd72005-05-03 07:23:44 +0000576 }
577} StrChrOptimizer;
578
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000579/// This LibCallOptimization will simplify a call to the strcmp library
Reid Spencer4c444fe2005-04-30 03:17:54 +0000580/// function. It optimizes out cases where one or both arguments are constant
581/// and the result can be determined statically.
582/// @brief Simplify the strcmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000583struct VISIBILITY_HIDDEN StrCmpOptimization : public LibCallOptimization {
Reid Spencer4c444fe2005-04-30 03:17:54 +0000584public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000585 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000586 "Number of 'strcmp' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +0000587
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000588 /// @brief Make sure that the "strcmp" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000589 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000590 const FunctionType *FT = F->getFunctionType();
591 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 2 &&
592 FT->getParamType(0) == FT->getParamType(1) &&
593 FT->getParamType(0) == PointerType::get(Type::Int8Ty);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000594 }
595
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000596 /// @brief Perform the strcmp optimization
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000597 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer4c444fe2005-04-30 03:17:54 +0000598 // First, check to see if src and destination are the same. If they are,
Reid Spencer16449a92005-04-30 06:45:47 +0000599 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000600 // because the call is a no-op.
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000601 Value *Str1P = CI->getOperand(1);
602 Value *Str2P = CI->getOperand(2);
Chris Lattner485b6412007-04-07 00:42:32 +0000603 if (Str1P == Str2P) // strcmp(x,x) -> 0
604 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Reid Spencer4c444fe2005-04-30 03:17:54 +0000605
Chris Lattner182a9452007-04-07 21:58:02 +0000606 std::string Str1;
607 if (!GetConstantStringInfo(Str1P, Str1))
608 return false;
609 if (Str1.empty()) {
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000610 // strcmp("", x) -> *x
611 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
612 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000613 return ReplaceCallWith(CI, V);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000614 }
615
Chris Lattner182a9452007-04-07 21:58:02 +0000616 std::string Str2;
617 if (!GetConstantStringInfo(Str2P, Str2))
618 return false;
619 if (Str2.empty()) {
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000620 // strcmp(x,"") -> *x
621 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
622 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000623 return ReplaceCallWith(CI, V);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000624 }
625
Chris Lattner182a9452007-04-07 21:58:02 +0000626 // strcmp(x, y) -> cnst (if both x and y are constant strings)
627 int R = strcmp(Str1.c_str(), Str2.c_str());
628 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencer4c444fe2005-04-30 03:17:54 +0000629 }
630} StrCmpOptimizer;
631
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000632/// This LibCallOptimization will simplify a call to the strncmp library
Reid Spencer49fa07042005-05-03 01:43:45 +0000633/// function. It optimizes out cases where one or both arguments are constant
634/// and the result can be determined statically.
635/// @brief Simplify the strncmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000636struct VISIBILITY_HIDDEN StrNCmpOptimization : public LibCallOptimization {
Reid Spencer49fa07042005-05-03 01:43:45 +0000637public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000638 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000639 "Number of 'strncmp' calls simplified") {}
Reid Spencer49fa07042005-05-03 01:43:45 +0000640
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000641 /// @brief Make sure that the "strncmp" function has the right prototype
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000642 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
643 const FunctionType *FT = F->getFunctionType();
644 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 3 &&
645 FT->getParamType(0) == FT->getParamType(1) &&
646 FT->getParamType(0) == PointerType::get(Type::Int8Ty) &&
647 isa<IntegerType>(FT->getParamType(2));
Reid Spencer49fa07042005-05-03 01:43:45 +0000648 return false;
649 }
650
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000651 /// @brief Perform the strncmp optimization
652 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer49fa07042005-05-03 01:43:45 +0000653 // First, check to see if src and destination are the same. If they are,
654 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000655 // because the call is a no-op.
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000656 Value *Str1P = CI->getOperand(1);
657 Value *Str2P = CI->getOperand(2);
Chris Lattner182a9452007-04-07 21:58:02 +0000658 if (Str1P == Str2P) // strncmp(x,x, n) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000659 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000660
Reid Spencer49fa07042005-05-03 01:43:45 +0000661 // Check the length argument, if it is Constant zero then the strings are
662 // considered equal.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000663 uint64_t Length;
664 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
665 Length = LengthArg->getZExtValue();
666 else
667 return false;
668
Chris Lattner182a9452007-04-07 21:58:02 +0000669 if (Length == 0) // strncmp(x,y,0) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000670 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000671
Chris Lattner182a9452007-04-07 21:58:02 +0000672 std::string Str1;
673 if (!GetConstantStringInfo(Str1P, Str1))
674 return false;
675 if (Str1.empty()) {
676 // strncmp("", x, n) -> *x
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000677 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
678 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000679 return ReplaceCallWith(CI, V);
Reid Spencer49fa07042005-05-03 01:43:45 +0000680 }
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000681
Chris Lattner182a9452007-04-07 21:58:02 +0000682 std::string Str2;
683 if (!GetConstantStringInfo(Str2P, Str2))
684 return false;
685 if (Str2.empty()) {
686 // strncmp(x, "", n) -> *x
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000687 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
688 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000689 return ReplaceCallWith(CI, V);
Reid Spencer49fa07042005-05-03 01:43:45 +0000690 }
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000691
Chris Lattner182a9452007-04-07 21:58:02 +0000692 // strncmp(x, y, n) -> cnst (if both x and y are constant strings)
693 int R = strncmp(Str1.c_str(), Str2.c_str(), Length);
694 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencer49fa07042005-05-03 01:43:45 +0000695 }
696} StrNCmpOptimizer;
697
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000698/// This LibCallOptimization will simplify a call to the strcpy library
699/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000700/// (1) If src and dest are the same and not volatile, just return dest
701/// (2) If the src is a constant then we can convert to llvm.memmove
702/// @brief Simplify the strcpy library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000703struct VISIBILITY_HIDDEN StrCpyOptimization : public LibCallOptimization {
Reid Spencere249a822005-04-27 07:54:40 +0000704public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000705 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000706 "Number of 'strcpy' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000707
708 /// @brief Make sure that the "strcpy" function has the right prototype
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000709 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
710 const FunctionType *FT = F->getFunctionType();
711 return FT->getNumParams() == 2 &&
712 FT->getParamType(0) == FT->getParamType(1) &&
713 FT->getReturnType() == FT->getParamType(0) &&
714 FT->getParamType(0) == PointerType::get(Type::Int8Ty);
Reid Spencere249a822005-04-27 07:54:40 +0000715 }
716
717 /// @brief Perform the strcpy optimization
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000718 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencere249a822005-04-27 07:54:40 +0000719 // First, check to see if src and destination are the same. If they are,
720 // then the optimization is to replace the CallInst with the destination
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000721 // because the call is a no-op. Note that this corresponds to the
Reid Spencere249a822005-04-27 07:54:40 +0000722 // degenerate strcpy(X,X) case which should have "undefined" results
723 // according to the C specification. However, it occurs sometimes and
724 // we optimize it as a no-op.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000725 Value *Dst = CI->getOperand(1);
726 Value *Src = CI->getOperand(2);
727 if (Dst == Src) {
728 // strcpy(x, x) -> x
Chris Lattner485b6412007-04-07 00:42:32 +0000729 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000730 }
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000731
732 // Get the length of the constant string referenced by the Src operand.
Chris Lattner182a9452007-04-07 21:58:02 +0000733 std::string SrcStr;
734 if (!GetConstantStringInfo(Src, SrcStr))
Reid Spencere249a822005-04-27 07:54:40 +0000735 return false;
Chris Lattner182a9452007-04-07 21:58:02 +0000736
Reid Spencere249a822005-04-27 07:54:40 +0000737 // If the constant string's length is zero we can optimize this by just
738 // doing a store of 0 at the first byte of the destination
Chris Lattner182a9452007-04-07 21:58:02 +0000739 if (SrcStr.size() == 0) {
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000740 new StoreInst(ConstantInt::get(Type::Int8Ty, 0), Dst, CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000741 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000742 }
743
Reid Spencere249a822005-04-27 07:54:40 +0000744 // We have enough information to now generate the memcpy call to
745 // do the concatenation for us.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000746 Value *MemcpyOps[] = {
Chris Lattner182a9452007-04-07 21:58:02 +0000747 Dst, Src, // Pass length including nul byte.
748 ConstantInt::get(SLC.getIntPtrType(), SrcStr.size()+1),
Chris Lattnerade1c2b2007-02-13 05:58:53 +0000749 ConstantInt::get(Type::Int32Ty, 1) // alignment
750 };
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000751 new CallInst(SLC.get_memcpy(), MemcpyOps, 4, "", CI);
Reid Spencere249a822005-04-27 07:54:40 +0000752
Chris Lattner485b6412007-04-07 00:42:32 +0000753 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000754 }
755} StrCpyOptimizer;
756
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000757/// This LibCallOptimization will simplify a call to the strlen library
758/// function by replacing it with a constant value if the string provided to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000759/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000760/// @brief Simplify the strlen library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000761struct VISIBILITY_HIDDEN StrLenOptimization : public LibCallOptimization {
Reid Spencer95d8efd2005-05-03 02:54:54 +0000762 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000763 "Number of 'strlen' calls simplified") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000764
765 /// @brief Make sure that the "strlen" function has the right prototype
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000766 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattnere8829aa2007-04-07 01:02:00 +0000767 const FunctionType *FT = F->getFunctionType();
768 return FT->getNumParams() == 1 &&
769 FT->getParamType(0) == PointerType::get(Type::Int8Ty) &&
770 isa<IntegerType>(FT->getReturnType());
Reid Spencer76dab9a2005-04-26 05:24:00 +0000771 }
772
773 /// @brief Perform the strlen optimization
Chris Lattnere8829aa2007-04-07 01:02:00 +0000774 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000775 // Make sure we're dealing with an sbyte* here.
Chris Lattner182a9452007-04-07 21:58:02 +0000776 Value *Src = CI->getOperand(1);
Reid Spencer170ae7f2005-05-07 20:15:59 +0000777
778 // Does the call to strlen have exactly one use?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000779 if (CI->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000780 // Is that single use a icmp operator?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000781 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CI->use_back()))
Reid Spencer170ae7f2005-05-07 20:15:59 +0000782 // Is it compared against a constant integer?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000783 if (ConstantInt *Cst = dyn_cast<ConstantInt>(Cmp->getOperand(1))) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000784 // If its compared against length 0 with == or !=
Chris Lattnere8829aa2007-04-07 01:02:00 +0000785 if (Cst->getZExtValue() == 0 && Cmp->isEquality()) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000786 // strlen(x) != 0 -> *x != 0
787 // strlen(x) == 0 -> *x == 0
Chris Lattner182a9452007-04-07 21:58:02 +0000788 Value *V = new LoadInst(Src, Src->getName()+".first", CI);
Chris Lattnere8829aa2007-04-07 01:02:00 +0000789 V = new ICmpInst(Cmp->getPredicate(), V,
790 ConstantInt::get(Type::Int8Ty, 0),
791 Cmp->getName()+".strlen", CI);
792 Cmp->replaceAllUsesWith(V);
793 Cmp->eraseFromParent();
794 return ReplaceCallWith(CI, 0); // no uses.
Reid Spencer170ae7f2005-05-07 20:15:59 +0000795 }
796 }
Chris Lattnere8829aa2007-04-07 01:02:00 +0000797 }
Reid Spencer170ae7f2005-05-07 20:15:59 +0000798
799 // Get the length of the constant string operand
Chris Lattner182a9452007-04-07 21:58:02 +0000800 std::string Str;
801 if (!GetConstantStringInfo(Src, Str))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000802 return false;
Chris Lattner182a9452007-04-07 21:58:02 +0000803
Reid Spencer170ae7f2005-05-07 20:15:59 +0000804 // strlen("xyz") -> 3 (for example)
Chris Lattner182a9452007-04-07 21:58:02 +0000805 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), Str.size()));
Reid Spencer76dab9a2005-04-26 05:24:00 +0000806 }
807} StrLenOptimizer;
808
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000809/// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
810/// is equal or not-equal to zero.
811static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
812 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
813 UI != E; ++UI) {
Chris Lattner6a36d632007-04-07 01:03:46 +0000814 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
815 if (IC->isEquality())
816 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
817 if (C->isNullValue())
818 continue;
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000819 // Unknown instruction.
820 return false;
821 }
822 return true;
823}
824
825/// This memcmpOptimization will simplify a call to the memcmp library
826/// function.
Reid Spencer557ab152007-02-05 23:32:05 +0000827struct VISIBILITY_HIDDEN memcmpOptimization : public LibCallOptimization {
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000828 /// @brief Default Constructor
829 memcmpOptimization()
830 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
831
832 /// @brief Make sure that the "memcmp" function has the right prototype
833 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
834 Function::const_arg_iterator AI = F->arg_begin();
835 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
836 if (!isa<PointerType>((++AI)->getType())) return false;
Chris Lattner03c49532007-01-15 02:27:26 +0000837 if (!(++AI)->getType()->isInteger()) return false;
838 if (!F->getReturnType()->isInteger()) return false;
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000839 return true;
840 }
841
842 /// Because of alignment and instruction information that we don't have, we
843 /// leave the bulk of this to the code generators.
844 ///
845 /// Note that we could do much more if we could force alignment on otherwise
846 /// small aligned allocas, or if we could indicate that loads have a small
847 /// alignment.
848 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
849 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
850
851 // If the two operands are the same, return zero.
852 if (LHS == RHS) {
853 // memcmp(s,s,x) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000854 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000855 }
856
857 // Make sure we have a constant length.
858 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
859 if (!LenC) return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000860 uint64_t Len = LenC->getZExtValue();
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000861
862 // If the length is zero, this returns 0.
863 switch (Len) {
864 case 0:
865 // memcmp(s1,s2,0) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000866 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000867 case 1: {
868 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
Reid Spencerc635f472006-12-31 05:48:39 +0000869 const Type *UCharPtr = PointerType::get(Type::Int8Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000870 CastInst *Op1Cast = CastInst::create(
871 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
872 CastInst *Op2Cast = CastInst::create(
873 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000874 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
875 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
876 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
877 if (RV->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +0000878 RV = CastInst::createIntegerCast(RV, CI->getType(), false,
879 RV->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000880 return ReplaceCallWith(CI, RV);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000881 }
882 case 2:
883 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
884 // TODO: IF both are aligned, use a short load/compare.
885
886 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
Reid Spencerc635f472006-12-31 05:48:39 +0000887 const Type *UCharPtr = PointerType::get(Type::Int8Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000888 CastInst *Op1Cast = CastInst::create(
889 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
890 CastInst *Op2Cast = CastInst::create(
891 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000892 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
893 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
894 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
895 CI->getName()+".d1", CI);
Reid Spencerc635f472006-12-31 05:48:39 +0000896 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000897 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
898 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
899 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
Chris Lattnercd60d382006-05-12 23:35:26 +0000900 Value *S2V2 = new LoadInst(G2, RHS->getName()+".val2", CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000901 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
902 CI->getName()+".d1", CI);
903 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
904 if (Or->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +0000905 Or = CastInst::createIntegerCast(Or, CI->getType(), false /*ZExt*/,
906 Or->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000907 return ReplaceCallWith(CI, Or);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000908 }
909 break;
910 default:
911 break;
912 }
913
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000914 return false;
915 }
916} memcmpOptimizer;
917
918
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000919/// This LibCallOptimization will simplify a call to the memcpy library
920/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000921/// bytes depending on the length of the string and the alignment. Additional
922/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +0000923/// @brief Simplify the memcpy library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000924struct VISIBILITY_HIDDEN LLVMMemCpyMoveOptzn : public LibCallOptimization {
Chris Lattnerea7986a2006-03-03 01:30:23 +0000925 LLVMMemCpyMoveOptzn(const char* fname, const char* desc)
926 : LibCallOptimization(fname, desc) {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000927
928 /// @brief Make sure that the "memcpy" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000929 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD) {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000930 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +0000931 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +0000932 }
933
Reid Spencerb4f7b832005-04-26 07:45:18 +0000934 /// Because of alignment and instruction information that we don't have, we
935 /// leave the bulk of this to the code generators. The optimization here just
936 /// deals with a few degenerate cases where the length of the string and the
937 /// alignment match the sizes of our intrinsic types so we can do a load and
938 /// store instead of the memcpy call.
939 /// @brief Perform the memcpy optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000940 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD) {
Reid Spencer4855ebf2005-04-26 19:55:57 +0000941 // Make sure we have constant int values to work with
942 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
943 if (!LEN)
944 return false;
945 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
946 if (!ALIGN)
947 return false;
948
949 // If the length is larger than the alignment, we can't optimize
Reid Spencere0fc4df2006-10-20 07:07:24 +0000950 uint64_t len = LEN->getZExtValue();
951 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +0000952 if (alignment == 0)
953 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000954 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +0000955 return false;
956
Reid Spencer08b49402005-04-27 17:46:54 +0000957 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +0000958 Value* dest = ci->getOperand(1);
959 Value* src = ci->getOperand(2);
Reid Spencer4f98e622007-01-07 21:45:41 +0000960 const Type* castType = 0;
Chris Lattner485b6412007-04-07 00:42:32 +0000961 switch (len) {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000962 case 0:
Chris Lattner485b6412007-04-07 00:42:32 +0000963 // memcpy(d,s,0,a) -> d
964 return ReplaceCallWith(ci, 0);
Reid Spencerc635f472006-12-31 05:48:39 +0000965 case 1: castType = Type::Int8Ty; break;
966 case 2: castType = Type::Int16Ty; break;
967 case 4: castType = Type::Int32Ty; break;
968 case 8: castType = Type::Int64Ty; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +0000969 default:
970 return false;
971 }
Reid Spencer08b49402005-04-27 17:46:54 +0000972
973 // Cast source and dest to the right sized primitive and then load/store
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000974 CastInst* SrcCast = CastInst::create(Instruction::BitCast,
975 src, PointerType::get(castType), src->getName()+".cast", ci);
976 CastInst* DestCast = CastInst::create(Instruction::BitCast,
977 dest, PointerType::get(castType),dest->getName()+".cast", ci);
Reid Spencer08b49402005-04-27 17:46:54 +0000978 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerde46e482006-11-02 20:25:50 +0000979 new StoreInst(LI, DestCast, ci);
Chris Lattner485b6412007-04-07 00:42:32 +0000980 return ReplaceCallWith(ci, 0);
Reid Spencerf2534c72005-04-25 21:11:48 +0000981 }
Chris Lattnerea7986a2006-03-03 01:30:23 +0000982};
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000983
Chris Lattnerea7986a2006-03-03 01:30:23 +0000984/// This LibCallOptimization will simplify a call to the memcpy/memmove library
985/// functions.
986LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer32("llvm.memcpy.i32",
987 "Number of 'llvm.memcpy' calls simplified");
988LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer64("llvm.memcpy.i64",
989 "Number of 'llvm.memcpy' calls simplified");
990LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer32("llvm.memmove.i32",
991 "Number of 'llvm.memmove' calls simplified");
992LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer64("llvm.memmove.i64",
993 "Number of 'llvm.memmove' calls simplified");
Reid Spencer38cabd72005-05-03 07:23:44 +0000994
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000995/// This LibCallOptimization will simplify a call to the memset library
996/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
997/// bytes depending on the length argument.
Reid Spencer557ab152007-02-05 23:32:05 +0000998struct VISIBILITY_HIDDEN LLVMMemSetOptimization : public LibCallOptimization {
Reid Spencer38cabd72005-05-03 07:23:44 +0000999 /// @brief Default Constructor
Chris Lattnerea7986a2006-03-03 01:30:23 +00001000 LLVMMemSetOptimization(const char *Name) : LibCallOptimization(Name,
Reid Spencer38cabd72005-05-03 07:23:44 +00001001 "Number of 'llvm.memset' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +00001002
1003 /// @brief Make sure that the "memset" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001004 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001005 // Just make sure this has 3 arguments per LLVM spec.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001006 return F->arg_size() == 4;
Reid Spencer38cabd72005-05-03 07:23:44 +00001007 }
1008
1009 /// Because of alignment and instruction information that we don't have, we
1010 /// leave the bulk of this to the code generators. The optimization here just
1011 /// deals with a few degenerate cases where the length parameter is constant
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001012 /// and the alignment matches the sizes of our intrinsic types so we can do
Reid Spencer38cabd72005-05-03 07:23:44 +00001013 /// store instead of the memcpy call. Other calls are transformed into the
1014 /// llvm.memset intrinsic.
1015 /// @brief Perform the memset optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001016 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &TD) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001017 // Make sure we have constant int values to work with
1018 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1019 if (!LEN)
1020 return false;
1021 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1022 if (!ALIGN)
1023 return false;
1024
1025 // Extract the length and alignment
Reid Spencere0fc4df2006-10-20 07:07:24 +00001026 uint64_t len = LEN->getZExtValue();
1027 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001028
1029 // Alignment 0 is identity for alignment 1
1030 if (alignment == 0)
1031 alignment = 1;
1032
1033 // If the length is zero, this is a no-op
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001034 if (len == 0) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001035 // memset(d,c,0,a) -> noop
Chris Lattner485b6412007-04-07 00:42:32 +00001036 return ReplaceCallWith(ci, 0);
Reid Spencer38cabd72005-05-03 07:23:44 +00001037 }
1038
1039 // If the length is larger than the alignment, we can't optimize
1040 if (len > alignment)
1041 return false;
1042
1043 // Make sure we have a constant ubyte to work with so we can extract
1044 // the value to be filled.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001045 ConstantInt* FILL = dyn_cast<ConstantInt>(ci->getOperand(2));
Reid Spencer38cabd72005-05-03 07:23:44 +00001046 if (!FILL)
1047 return false;
Reid Spencerc635f472006-12-31 05:48:39 +00001048 if (FILL->getType() != Type::Int8Ty)
Reid Spencer38cabd72005-05-03 07:23:44 +00001049 return false;
1050
1051 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001052
Reid Spencer38cabd72005-05-03 07:23:44 +00001053 // Extract the fill character
Reid Spencere0fc4df2006-10-20 07:07:24 +00001054 uint64_t fill_char = FILL->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001055 uint64_t fill_value = fill_char;
1056
1057 // Get the type we will cast to, based on size of memory area to fill, and
1058 // and the value we will store there.
1059 Value* dest = ci->getOperand(1);
Reid Spencer4f98e622007-01-07 21:45:41 +00001060 const Type* castType = 0;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001061 switch (len) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001062 case 1:
Reid Spencerc635f472006-12-31 05:48:39 +00001063 castType = Type::Int8Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001064 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001065 case 2:
Reid Spencerc635f472006-12-31 05:48:39 +00001066 castType = Type::Int16Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001067 fill_value |= fill_char << 8;
1068 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001069 case 4:
Reid Spencerc635f472006-12-31 05:48:39 +00001070 castType = Type::Int32Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001071 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1072 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001073 case 8:
Reid Spencerc635f472006-12-31 05:48:39 +00001074 castType = Type::Int64Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001075 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1076 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1077 fill_value |= fill_char << 56;
1078 break;
1079 default:
1080 return false;
1081 }
1082
1083 // Cast dest to the right sized primitive and then load/store
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001084 CastInst* DestCast = new BitCastInst(dest, PointerType::get(castType),
1085 dest->getName()+".cast", ci);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001086 new StoreInst(ConstantInt::get(castType,fill_value),DestCast, ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001087 return ReplaceCallWith(ci, 0);
Reid Spencer38cabd72005-05-03 07:23:44 +00001088 }
Chris Lattnerea7986a2006-03-03 01:30:23 +00001089};
1090
1091LLVMMemSetOptimization MemSet32Optimizer("llvm.memset.i32");
1092LLVMMemSetOptimization MemSet64Optimizer("llvm.memset.i64");
1093
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001094
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001095/// This LibCallOptimization will simplify calls to the "pow" library
1096/// function. It looks for cases where the result of pow is well known and
Reid Spencer93616972005-04-29 09:39:47 +00001097/// substitutes the appropriate value.
1098/// @brief Simplify the pow library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001099struct VISIBILITY_HIDDEN PowOptimization : public LibCallOptimization {
Reid Spencer93616972005-04-29 09:39:47 +00001100public:
1101 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001102 PowOptimization() : LibCallOptimization("pow",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001103 "Number of 'pow' calls simplified") {}
Reid Spencer95d8efd2005-05-03 02:54:54 +00001104
Reid Spencer93616972005-04-29 09:39:47 +00001105 /// @brief Make sure that the "pow" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001106 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer93616972005-04-29 09:39:47 +00001107 // Just make sure this has 2 arguments
1108 return (f->arg_size() == 2);
1109 }
1110
1111 /// @brief Perform the pow optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001112 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer93616972005-04-29 09:39:47 +00001113 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1114 Value* base = ci->getOperand(1);
1115 Value* expn = ci->getOperand(2);
1116 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1117 double Op1V = Op1->getValue();
Chris Lattner485b6412007-04-07 00:42:32 +00001118 if (Op1V == 1.0) // pow(1.0,x) -> 1.0
1119 return ReplaceCallWith(ci, ConstantFP::get(Ty, 1.0));
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001120 } else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) {
Reid Spencer93616972005-04-29 09:39:47 +00001121 double Op2V = Op2->getValue();
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001122 if (Op2V == 0.0) {
Reid Spencer93616972005-04-29 09:39:47 +00001123 // pow(x,0.0) -> 1.0
Chris Lattner485b6412007-04-07 00:42:32 +00001124 return ReplaceCallWith(ci, ConstantFP::get(Ty,1.0));
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001125 } else if (Op2V == 0.5) {
Reid Spencer93616972005-04-29 09:39:47 +00001126 // pow(x,0.5) -> sqrt(x)
1127 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1128 ci->getName()+".pow",ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001129 return ReplaceCallWith(ci, sqrt_inst);
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001130 } else if (Op2V == 1.0) {
Reid Spencer93616972005-04-29 09:39:47 +00001131 // pow(x,1.0) -> x
Chris Lattner485b6412007-04-07 00:42:32 +00001132 return ReplaceCallWith(ci, base);
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001133 } else if (Op2V == -1.0) {
Reid Spencer93616972005-04-29 09:39:47 +00001134 // pow(x,-1.0) -> 1.0/x
Chris Lattner485b6412007-04-07 00:42:32 +00001135 Value *div_inst =
1136 BinaryOperator::createFDiv(ConstantFP::get(Ty, 1.0), base,
1137 ci->getName()+".pow", ci);
1138 return ReplaceCallWith(ci, div_inst);
Reid Spencer93616972005-04-29 09:39:47 +00001139 }
1140 }
1141 return false; // opt failed
1142 }
1143} PowOptimizer;
1144
Evan Cheng1fc40252006-06-16 08:36:35 +00001145/// This LibCallOptimization will simplify calls to the "printf" library
1146/// function. It looks for cases where the result of printf is not used and the
1147/// operation can be reduced to something simpler.
1148/// @brief Simplify the printf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001149struct VISIBILITY_HIDDEN PrintfOptimization : public LibCallOptimization {
Evan Cheng1fc40252006-06-16 08:36:35 +00001150public:
1151 /// @brief Default Constructor
1152 PrintfOptimization() : LibCallOptimization("printf",
1153 "Number of 'printf' calls simplified") {}
1154
1155 /// @brief Make sure that the "printf" function has the right prototype
Chris Lattner0f150952007-04-07 01:18:36 +00001156 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Evan Cheng1fc40252006-06-16 08:36:35 +00001157 // Just make sure this has at least 1 arguments
Chris Lattner0f150952007-04-07 01:18:36 +00001158 return F->arg_size() >= 1;
Evan Cheng1fc40252006-06-16 08:36:35 +00001159 }
1160
1161 /// @brief Perform the printf optimization.
Chris Lattner0f150952007-04-07 01:18:36 +00001162 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Evan Cheng1fc40252006-06-16 08:36:35 +00001163 // If the call has more than 2 operands, we can't optimize it
Chris Lattner0f150952007-04-07 01:18:36 +00001164 if (CI->getNumOperands() != 3)
Evan Cheng1fc40252006-06-16 08:36:35 +00001165 return false;
1166
Evan Cheng1fc40252006-06-16 08:36:35 +00001167 // All the optimizations depend on the length of the first argument and the
1168 // fact that it is a constant string array. Check that now
Chris Lattner182a9452007-04-07 21:58:02 +00001169 std::string FormatStr;
1170 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
Evan Cheng1fc40252006-06-16 08:36:35 +00001171 return false;
1172
Chris Lattner182a9452007-04-07 21:58:02 +00001173 // Only support %c or "%s\n" for now.
1174 if (FormatStr.size() < 2 || FormatStr[0] != '%')
Chris Lattner0f150952007-04-07 01:18:36 +00001175 return false;
Evan Cheng1fc40252006-06-16 08:36:35 +00001176
1177 // Get the second character and switch on its value
Chris Lattner182a9452007-04-07 21:58:02 +00001178 switch (FormatStr[1]) {
Chris Lattner0f150952007-04-07 01:18:36 +00001179 default: return false;
Chris Lattner182a9452007-04-07 21:58:02 +00001180 case 's':
1181 if (FormatStr != "%s\n" ||
1182 // TODO: could insert strlen call to compute string length.
1183 !CI->use_empty())
Evan Cheng1fc40252006-06-16 08:36:35 +00001184 return false;
Chris Lattner0f150952007-04-07 01:18:36 +00001185
1186 // printf("%s\n",str) -> puts(str)
Chris Lattnerbed184c2007-04-07 21:04:50 +00001187 new CallInst(SLC.get_puts(), CastToCStr(CI->getOperand(2), CI),
Chris Lattner0f150952007-04-07 01:18:36 +00001188 CI->getName(), CI);
1189 return ReplaceCallWith(CI, 0);
Chris Lattner0f150952007-04-07 01:18:36 +00001190 case 'c': {
1191 // printf("%c",c) -> putchar(c)
Chris Lattner182a9452007-04-07 21:58:02 +00001192 if (FormatStr.size() != 2)
Chris Lattner0f150952007-04-07 01:18:36 +00001193 return false;
1194
1195 Value *V = CI->getOperand(2);
1196 if (!isa<IntegerType>(V->getType()) ||
Chris Lattner182a9452007-04-07 21:58:02 +00001197 cast<IntegerType>(V->getType())->getBitWidth() > 32)
Chris Lattner0f150952007-04-07 01:18:36 +00001198 return false;
1199
Chris Lattner182a9452007-04-07 21:58:02 +00001200 V = CastInst::createZExtOrBitCast(V, Type::Int32Ty, CI->getName()+".int",
Chris Lattner0f150952007-04-07 01:18:36 +00001201 CI);
1202 new CallInst(SLC.get_putchar(), V, "", CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001203 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
Chris Lattner0f150952007-04-07 01:18:36 +00001204 }
1205 }
Evan Cheng1fc40252006-06-16 08:36:35 +00001206 }
1207} PrintfOptimizer;
1208
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001209/// This LibCallOptimization will simplify calls to the "fprintf" library
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001210/// function. It looks for cases where the result of fprintf is not used and the
1211/// operation can be reduced to something simpler.
Evan Cheng1fc40252006-06-16 08:36:35 +00001212/// @brief Simplify the fprintf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001213struct VISIBILITY_HIDDEN FPrintFOptimization : public LibCallOptimization {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001214public:
1215 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001216 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001217 "Number of 'fprintf' calls simplified") {}
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001218
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001219 /// @brief Make sure that the "fprintf" function has the right prototype
Chris Lattnerbed184c2007-04-07 21:04:50 +00001220 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1221 const FunctionType *FT = F->getFunctionType();
1222 return FT->getNumParams() == 2 && // two fixed arguments.
1223 FT->getParamType(1) == PointerType::get(Type::Int8Ty) &&
1224 isa<PointerType>(FT->getParamType(0)) &&
1225 isa<IntegerType>(FT->getReturnType());
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001226 }
1227
1228 /// @brief Perform the fprintf optimization.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001229 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001230 // If the call has more than 3 operands, we can't optimize it
Chris Lattnerbed184c2007-04-07 21:04:50 +00001231 if (CI->getNumOperands() != 3 && CI->getNumOperands() != 4)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001232 return false;
1233
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001234 // All the optimizations depend on the format string.
Chris Lattner182a9452007-04-07 21:58:02 +00001235 std::string FormatStr;
1236 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001237 return false;
1238
Chris Lattner182a9452007-04-07 21:58:02 +00001239 // If this is just a format string, turn it into fwrite.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001240 if (CI->getNumOperands() == 3) {
Chris Lattner182a9452007-04-07 21:58:02 +00001241 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1242 if (FormatStr[i] == '%')
Chris Lattnerbed184c2007-04-07 21:04:50 +00001243 return false; // we found a format specifier
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001244
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001245 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
Chris Lattnerbed184c2007-04-07 21:04:50 +00001246 const Type *FILEty = CI->getOperand(1)->getType();
John Criswell4642afd2005-06-29 15:03:18 +00001247
Chris Lattnerbed184c2007-04-07 21:04:50 +00001248 Value *FWriteArgs[] = {
1249 CI->getOperand(2),
Chris Lattner182a9452007-04-07 21:58:02 +00001250 ConstantInt::get(SLC.getIntPtrType(), FormatStr.size()),
Chris Lattnerbed184c2007-04-07 21:04:50 +00001251 ConstantInt::get(SLC.getIntPtrType(), 1),
1252 CI->getOperand(1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001253 };
Chris Lattnerbed184c2007-04-07 21:04:50 +00001254 new CallInst(SLC.get_fwrite(FILEty), FWriteArgs, 4, CI->getName(), CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001255 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(),
1256 FormatStr.size()));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001257 }
Chris Lattnerbed184c2007-04-07 21:04:50 +00001258
1259 // The remaining optimizations require the format string to be length 2:
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001260 // "%s" or "%c".
Chris Lattner182a9452007-04-07 21:58:02 +00001261 if (FormatStr.size() != 2 || FormatStr[0] != '%')
Chris Lattnerbed184c2007-04-07 21:04:50 +00001262 return false;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001263
1264 // Get the second character and switch on its value
Chris Lattner182a9452007-04-07 21:58:02 +00001265 switch (FormatStr[1]) {
Chris Lattnerbed184c2007-04-07 21:04:50 +00001266 case 'c': {
1267 // fprintf(file,"%c",c) -> fputc(c,file)
1268 const Type *FILETy = CI->getOperand(1)->getType();
1269 Value *C = CastInst::createZExtOrBitCast(CI->getOperand(3), Type::Int32Ty,
1270 CI->getName()+".int", CI);
1271 new CallInst(SLC.get_fputc(FILETy), C, CI->getOperand(1), "", CI);
1272 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1273 }
1274 case 's': {
1275 const Type *FILETy = CI->getOperand(1)->getType();
Chris Lattnerbed184c2007-04-07 21:04:50 +00001276
1277 // If the result of the fprintf call is used, we can't do this.
Chris Lattner182a9452007-04-07 21:58:02 +00001278 // TODO: we should insert a strlen call.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001279 if (!CI->use_empty())
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001280 return false;
Chris Lattnerbed184c2007-04-07 21:04:50 +00001281
1282 // fprintf(file,"%s",str) -> fputs(str,file)
1283 new CallInst(SLC.get_fputs(FILETy), CastToCStr(CI->getOperand(3), CI),
1284 CI->getOperand(1), CI->getName(), CI);
1285 return ReplaceCallWith(CI, 0);
1286 }
1287 default:
1288 return false;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001289 }
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001290 }
1291} FPrintFOptimizer;
1292
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001293/// This LibCallOptimization will simplify calls to the "sprintf" library
Reid Spencer1e520fd2005-05-04 03:20:21 +00001294/// function. It looks for cases where the result of sprintf is not used and the
1295/// operation can be reduced to something simpler.
Evan Cheng1fc40252006-06-16 08:36:35 +00001296/// @brief Simplify the sprintf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001297struct VISIBILITY_HIDDEN SPrintFOptimization : public LibCallOptimization {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001298public:
1299 /// @brief Default Constructor
1300 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001301 "Number of 'sprintf' calls simplified") {}
Reid Spencer1e520fd2005-05-04 03:20:21 +00001302
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001303 /// @brief Make sure that the "sprintf" function has the right prototype
1304 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1305 const FunctionType *FT = F->getFunctionType();
1306 return FT->getNumParams() == 2 && // two fixed arguments.
1307 FT->getParamType(1) == PointerType::get(Type::Int8Ty) &&
1308 FT->getParamType(0) == FT->getParamType(1) &&
1309 isa<IntegerType>(FT->getReturnType());
Reid Spencer1e520fd2005-05-04 03:20:21 +00001310 }
1311
1312 /// @brief Perform the sprintf optimization.
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001313 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001314 // If the call has more than 3 operands, we can't optimize it
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001315 if (CI->getNumOperands() != 3 && CI->getNumOperands() != 4)
Reid Spencer1e520fd2005-05-04 03:20:21 +00001316 return false;
1317
Chris Lattner182a9452007-04-07 21:58:02 +00001318 std::string FormatStr;
1319 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Reid Spencer1e520fd2005-05-04 03:20:21 +00001320 return false;
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001321
1322 if (CI->getNumOperands() == 3) {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001323 // Make sure there's no % in the constant array
Chris Lattner182a9452007-04-07 21:58:02 +00001324 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1325 if (FormatStr[i] == '%')
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001326 return false; // we found a format specifier
1327
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001328 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001329 Value *MemCpyArgs[] = {
1330 CI->getOperand(1), CI->getOperand(2),
Chris Lattner182a9452007-04-07 21:58:02 +00001331 ConstantInt::get(SLC.getIntPtrType(),
1332 FormatStr.size()+1), // Copy the nul byte.
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001333 ConstantInt::get(Type::Int32Ty, 1)
1334 };
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001335 new CallInst(SLC.get_memcpy(), MemCpyArgs, 4, "", CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001336 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(),
1337 FormatStr.size()));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001338 }
1339
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001340 // The remaining optimizations require the format string to be "%s" or "%c".
Chris Lattner182a9452007-04-07 21:58:02 +00001341 if (FormatStr.size() != 2 || FormatStr[0] != '%')
Reid Spencer1e520fd2005-05-04 03:20:21 +00001342 return false;
1343
Reid Spencer1e520fd2005-05-04 03:20:21 +00001344 // Get the second character and switch on its value
Chris Lattner182a9452007-04-07 21:58:02 +00001345 switch (FormatStr[2]) {
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001346 case 'c': {
1347 // sprintf(dest,"%c",chr) -> store chr, dest
1348 Value *V = CastInst::createTruncOrBitCast(CI->getOperand(3),
1349 Type::Int8Ty, "char", CI);
1350 new StoreInst(V, CI->getOperand(1), CI);
1351 Value *Ptr = new GetElementPtrInst(CI->getOperand(1),
1352 ConstantInt::get(Type::Int32Ty, 1),
1353 CI->getOperand(1)->getName()+".end",
1354 CI);
1355 new StoreInst(ConstantInt::get(Type::Int8Ty,0), Ptr, CI);
1356 return ReplaceCallWith(CI, ConstantInt::get(Type::Int32Ty, 1));
1357 }
Chris Lattner175463a2005-09-24 22:17:06 +00001358 case 's': {
1359 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Chris Lattner34acba42007-01-07 08:12:01 +00001360 Value *Len = new CallInst(SLC.get_strlen(),
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001361 CastToCStr(CI->getOperand(3), CI),
1362 CI->getOperand(3)->getName()+".len", CI);
1363 Value *UnincLen = Len;
1364 Len = BinaryOperator::createAdd(Len, ConstantInt::get(Len->getType(), 1),
1365 Len->getName()+"1", CI);
1366 Value *MemcpyArgs[4] = {
1367 CI->getOperand(1),
1368 CastToCStr(CI->getOperand(3), CI),
1369 Len,
1370 ConstantInt::get(Type::Int32Ty, 1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001371 };
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001372 new CallInst(SLC.get_memcpy(), MemcpyArgs, 4, "", CI);
Chris Lattner175463a2005-09-24 22:17:06 +00001373
1374 // The strlen result is the unincremented number of bytes in the string.
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001375 if (!CI->use_empty()) {
1376 if (UnincLen->getType() != CI->getType())
1377 UnincLen = CastInst::createIntegerCast(UnincLen, CI->getType(), false,
1378 Len->getName(), CI);
1379 CI->replaceAllUsesWith(UnincLen);
Chris Lattnerf4877682005-09-25 07:06:48 +00001380 }
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001381 return ReplaceCallWith(CI, 0);
Chris Lattner175463a2005-09-24 22:17:06 +00001382 }
1383 }
1384 return false;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001385 }
1386} SPrintFOptimizer;
1387
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001388/// This LibCallOptimization will simplify calls to the "fputs" library
Reid Spencer93616972005-04-29 09:39:47 +00001389/// function. It looks for cases where the result of fputs is not used and the
1390/// operation can be reduced to something simpler.
Chris Lattner57179812007-04-08 07:00:35 +00001391/// @brief Simplify the fputs library function.
Chris Lattner182a9452007-04-07 21:58:02 +00001392struct VISIBILITY_HIDDEN FPutsOptimization : public LibCallOptimization {
Reid Spencer93616972005-04-29 09:39:47 +00001393public:
1394 /// @brief Default Constructor
Chris Lattner182a9452007-04-07 21:58:02 +00001395 FPutsOptimization() : LibCallOptimization("fputs",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001396 "Number of 'fputs' calls simplified") {}
Reid Spencer93616972005-04-29 09:39:47 +00001397
Reid Spencer93616972005-04-29 09:39:47 +00001398 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001399 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencer93616972005-04-29 09:39:47 +00001400 // Just make sure this has 2 arguments
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001401 return F->arg_size() == 2;
Reid Spencer93616972005-04-29 09:39:47 +00001402 }
1403
1404 /// @brief Perform the fputs optimization.
Chris Lattner182a9452007-04-07 21:58:02 +00001405 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1406 // If the result is used, none of these optimizations work.
1407 if (!CI->use_empty())
Reid Spencer93616972005-04-29 09:39:47 +00001408 return false;
1409
1410 // All the optimizations depend on the length of the first argument and the
1411 // fact that it is a constant string array. Check that now
Chris Lattner182a9452007-04-07 21:58:02 +00001412 std::string Str;
1413 if (!GetConstantStringInfo(CI->getOperand(1), Str))
Reid Spencer93616972005-04-29 09:39:47 +00001414 return false;
1415
Chris Lattner182a9452007-04-07 21:58:02 +00001416 const Type *FILETy = CI->getOperand(2)->getType();
Chris Lattner57179812007-04-08 07:00:35 +00001417 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1418 Value *FWriteParms[4] = {
1419 CI->getOperand(1),
1420 ConstantInt::get(SLC.getIntPtrType(), Str.size()),
1421 ConstantInt::get(SLC.getIntPtrType(), 1),
1422 CI->getOperand(2)
1423 };
1424 new CallInst(SLC.get_fwrite(FILETy), FWriteParms, 4, "", CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001425 return ReplaceCallWith(CI, 0); // Known to have no uses (see above).
Reid Spencer93616972005-04-29 09:39:47 +00001426 }
Chris Lattner57179812007-04-08 07:00:35 +00001427} FPutsOptimizer;
1428
1429/// This LibCallOptimization will simplify calls to the "fwrite" function.
1430struct VISIBILITY_HIDDEN FWriteOptimization : public LibCallOptimization {
1431public:
1432 /// @brief Default Constructor
1433 FWriteOptimization() : LibCallOptimization("fwrite",
1434 "Number of 'fwrite' calls simplified") {}
1435
1436 /// @brief Make sure that the "fputs" function has the right prototype
1437 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1438 const FunctionType *FT = F->getFunctionType();
1439 return FT->getNumParams() == 4 &&
1440 FT->getParamType(0) == PointerType::get(Type::Int8Ty) &&
1441 FT->getParamType(1) == FT->getParamType(2) &&
1442 isa<IntegerType>(FT->getParamType(1)) &&
1443 isa<PointerType>(FT->getParamType(3)) &&
1444 isa<IntegerType>(FT->getReturnType());
1445 }
1446
1447 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1448 // Get the element size and count.
1449 uint64_t EltSize, EltCount;
1450 if (ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(2)))
1451 EltSize = C->getZExtValue();
1452 else
1453 return false;
1454 if (ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(3)))
1455 EltCount = C->getZExtValue();
1456 else
1457 return false;
1458
1459 // If this is writing zero records, remove the call (it's a noop).
1460 if (EltSize * EltCount == 0)
1461 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
1462
1463 // If this is writing one byte, turn it into fputc.
1464 if (EltSize == 1 && EltCount == 1) {
1465 // fwrite(s,1,1,F) -> fputc(s[0],F)
1466 Value *Ptr = CI->getOperand(1);
1467 Value *Val = new LoadInst(Ptr, Ptr->getName()+".byte", CI);
1468 Val = new ZExtInst(Val, Type::Int32Ty, Val->getName()+".int", CI);
1469 const Type *FILETy = CI->getOperand(4)->getType();
1470 new CallInst(SLC.get_fputc(FILETy), Val, CI->getOperand(4), "", CI);
1471 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1472 }
1473 return false;
1474 }
1475} FWriteOptimizer;
Reid Spencer93616972005-04-29 09:39:47 +00001476
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001477/// This LibCallOptimization will simplify calls to the "isdigit" library
Reid Spencer282d0572005-05-04 18:58:28 +00001478/// function. It simply does range checks the parameter explicitly.
1479/// @brief Simplify the isdigit library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001480struct VISIBILITY_HIDDEN isdigitOptimization : public LibCallOptimization {
Reid Spencer282d0572005-05-04 18:58:28 +00001481public:
Chris Lattner5f6035f2005-09-29 06:16:11 +00001482 isdigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001483 "Number of 'isdigit' calls simplified") {}
Reid Spencer282d0572005-05-04 18:58:28 +00001484
Chris Lattner5f6035f2005-09-29 06:16:11 +00001485 /// @brief Make sure that the "isdigit" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001486 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer282d0572005-05-04 18:58:28 +00001487 // Just make sure this has 1 argument
1488 return (f->arg_size() == 1);
1489 }
1490
1491 /// @brief Perform the toascii optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001492 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1493 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1))) {
Reid Spencer282d0572005-05-04 18:58:28 +00001494 // isdigit(c) -> 0 or 1, if 'c' is constant
Reid Spencere0fc4df2006-10-20 07:07:24 +00001495 uint64_t val = CI->getZExtValue();
Chris Lattner485b6412007-04-07 00:42:32 +00001496 if (val >= '0' && val <= '9')
1497 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
Reid Spencer282d0572005-05-04 18:58:28 +00001498 else
Chris Lattner485b6412007-04-07 00:42:32 +00001499 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 0));
Reid Spencer282d0572005-05-04 18:58:28 +00001500 }
1501
1502 // isdigit(c) -> (unsigned)c - '0' <= 9
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001503 CastInst* cast = CastInst::createIntegerCast(ci->getOperand(1),
Reid Spencerc635f472006-12-31 05:48:39 +00001504 Type::Int32Ty, false/*ZExt*/, ci->getOperand(1)->getName()+".uint", ci);
Chris Lattner4201cd12005-08-24 17:22:17 +00001505 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
Reid Spencerc635f472006-12-31 05:48:39 +00001506 ConstantInt::get(Type::Int32Ty,0x30),
Reid Spencer282d0572005-05-04 18:58:28 +00001507 ci->getOperand(1)->getName()+".sub",ci);
Reid Spencer266e42b2006-12-23 06:05:41 +00001508 ICmpInst* setcond_inst = new ICmpInst(ICmpInst::ICMP_ULE,sub_inst,
Reid Spencerc635f472006-12-31 05:48:39 +00001509 ConstantInt::get(Type::Int32Ty,9),
Reid Spencer282d0572005-05-04 18:58:28 +00001510 ci->getOperand(1)->getName()+".cmp",ci);
Reid Spencerc635f472006-12-31 05:48:39 +00001511 CastInst* c2 = new ZExtInst(setcond_inst, Type::Int32Ty,
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001512 ci->getOperand(1)->getName()+".isdigit", ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001513 return ReplaceCallWith(ci, c2);
Reid Spencer282d0572005-05-04 18:58:28 +00001514 }
Chris Lattner5f6035f2005-09-29 06:16:11 +00001515} isdigitOptimizer;
1516
Reid Spencer557ab152007-02-05 23:32:05 +00001517struct VISIBILITY_HIDDEN isasciiOptimization : public LibCallOptimization {
Chris Lattner87ef9432005-09-29 06:17:27 +00001518public:
1519 isasciiOptimization()
1520 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1521
1522 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner03c49532007-01-15 02:27:26 +00001523 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1524 F->getReturnType()->isInteger();
Chris Lattner87ef9432005-09-29 06:17:27 +00001525 }
1526
1527 /// @brief Perform the isascii optimization.
1528 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1529 // isascii(c) -> (unsigned)c < 128
1530 Value *V = CI->getOperand(1);
Reid Spencer266e42b2006-12-23 06:05:41 +00001531 Value *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, V,
1532 ConstantInt::get(V->getType(), 128),
1533 V->getName()+".isascii", CI);
Chris Lattner87ef9432005-09-29 06:17:27 +00001534 if (Cmp->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001535 Cmp = new BitCastInst(Cmp, CI->getType(), Cmp->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +00001536 return ReplaceCallWith(CI, Cmp);
Chris Lattner87ef9432005-09-29 06:17:27 +00001537 }
1538} isasciiOptimizer;
Chris Lattner5f6035f2005-09-29 06:16:11 +00001539
Reid Spencer282d0572005-05-04 18:58:28 +00001540
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001541/// This LibCallOptimization will simplify calls to the "toascii" library
Reid Spencer4c444fe2005-04-30 03:17:54 +00001542/// function. It simply does the corresponding and operation to restrict the
1543/// range of values to the ASCII character set (0-127).
1544/// @brief Simplify the toascii library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001545struct VISIBILITY_HIDDEN ToAsciiOptimization : public LibCallOptimization {
Reid Spencer4c444fe2005-04-30 03:17:54 +00001546public:
1547 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001548 ToAsciiOptimization() : LibCallOptimization("toascii",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001549 "Number of 'toascii' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +00001550
Reid Spencer4c444fe2005-04-30 03:17:54 +00001551 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001552 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer4c444fe2005-04-30 03:17:54 +00001553 // Just make sure this has 2 arguments
1554 return (f->arg_size() == 1);
1555 }
1556
1557 /// @brief Perform the toascii optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001558 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer4c444fe2005-04-30 03:17:54 +00001559 // toascii(c) -> (c & 0x7f)
Chris Lattner485b6412007-04-07 00:42:32 +00001560 Value *chr = ci->getOperand(1);
1561 Value *and_inst = BinaryOperator::createAnd(chr,
Reid Spencer4c444fe2005-04-30 03:17:54 +00001562 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001563 return ReplaceCallWith(ci, and_inst);
Reid Spencer4c444fe2005-04-30 03:17:54 +00001564 }
1565} ToAsciiOptimizer;
1566
Reid Spencerb195fcd2005-05-14 16:42:52 +00001567/// This LibCallOptimization will simplify calls to the "ffs" library
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001568/// calls which find the first set bit in an int, long, or long long. The
Reid Spencerb195fcd2005-05-14 16:42:52 +00001569/// optimization is to compute the result at compile time if the argument is
1570/// a constant.
1571/// @brief Simplify the ffs library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001572struct VISIBILITY_HIDDEN FFSOptimization : public LibCallOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001573protected:
1574 /// @brief Subclass Constructor
1575 FFSOptimization(const char* funcName, const char* description)
Chris Lattner801f4752006-01-17 18:27:17 +00001576 : LibCallOptimization(funcName, description) {}
Reid Spencerb195fcd2005-05-14 16:42:52 +00001577
1578public:
1579 /// @brief Default Constructor
1580 FFSOptimization() : LibCallOptimization("ffs",
1581 "Number of 'ffs' calls simplified") {}
1582
Chris Lattner801f4752006-01-17 18:27:17 +00001583 /// @brief Make sure that the "ffs" function has the right prototype
1584 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencerb195fcd2005-05-14 16:42:52 +00001585 // Just make sure this has 2 arguments
Reid Spencerc635f472006-12-31 05:48:39 +00001586 return F->arg_size() == 1 && F->getReturnType() == Type::Int32Ty;
Reid Spencerb195fcd2005-05-14 16:42:52 +00001587 }
1588
1589 /// @brief Perform the ffs optimization.
Chris Lattner801f4752006-01-17 18:27:17 +00001590 virtual bool OptimizeCall(CallInst *TheCall, SimplifyLibCalls &SLC) {
1591 if (ConstantInt *CI = dyn_cast<ConstantInt>(TheCall->getOperand(1))) {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001592 // ffs(cnst) -> bit#
1593 // ffsl(cnst) -> bit#
Reid Spencer17f77842005-05-15 21:19:45 +00001594 // ffsll(cnst) -> bit#
Reid Spencere0fc4df2006-10-20 07:07:24 +00001595 uint64_t val = CI->getZExtValue();
Reid Spencer17f77842005-05-15 21:19:45 +00001596 int result = 0;
Chris Lattner801f4752006-01-17 18:27:17 +00001597 if (val) {
1598 ++result;
1599 while ((val & 1) == 0) {
1600 ++result;
1601 val >>= 1;
1602 }
Reid Spencer17f77842005-05-15 21:19:45 +00001603 }
Chris Lattner485b6412007-04-07 00:42:32 +00001604 return ReplaceCallWith(TheCall, ConstantInt::get(Type::Int32Ty, result));
Reid Spencerb195fcd2005-05-14 16:42:52 +00001605 }
Reid Spencer17f77842005-05-15 21:19:45 +00001606
Chris Lattner801f4752006-01-17 18:27:17 +00001607 // ffs(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1608 // ffsl(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1609 // ffsll(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1610 const Type *ArgType = TheCall->getOperand(1)->getType();
Chris Lattner801f4752006-01-17 18:27:17 +00001611 const char *CTTZName;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001612 assert(ArgType->getTypeID() == Type::IntegerTyID &&
1613 "llvm.cttz argument is not an integer?");
1614 unsigned BitWidth = cast<IntegerType>(ArgType)->getBitWidth();
Chris Lattner3b6058c2007-01-12 22:49:11 +00001615 if (BitWidth == 8)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001616 CTTZName = "llvm.cttz.i8";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001617 else if (BitWidth == 16)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001618 CTTZName = "llvm.cttz.i16";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001619 else if (BitWidth == 32)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001620 CTTZName = "llvm.cttz.i32";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001621 else {
1622 assert(BitWidth == 64 && "Unknown bitwidth");
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001623 CTTZName = "llvm.cttz.i64";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001624 }
Chris Lattner801f4752006-01-17 18:27:17 +00001625
Chris Lattner34acba42007-01-07 08:12:01 +00001626 Constant *F = SLC.getModule()->getOrInsertFunction(CTTZName, ArgType,
Chris Lattner801f4752006-01-17 18:27:17 +00001627 ArgType, NULL);
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001628 Value *V = CastInst::createIntegerCast(TheCall->getOperand(1), ArgType,
1629 false/*ZExt*/, "tmp", TheCall);
Chris Lattner801f4752006-01-17 18:27:17 +00001630 Value *V2 = new CallInst(F, V, "tmp", TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001631 V2 = CastInst::createIntegerCast(V2, Type::Int32Ty, false/*ZExt*/,
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001632 "tmp", TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001633 V2 = BinaryOperator::createAdd(V2, ConstantInt::get(Type::Int32Ty, 1),
Chris Lattner801f4752006-01-17 18:27:17 +00001634 "tmp", TheCall);
Reid Spencer266e42b2006-12-23 06:05:41 +00001635 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, V,
1636 Constant::getNullValue(V->getType()), "tmp",
1637 TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001638 V2 = new SelectInst(Cond, ConstantInt::get(Type::Int32Ty, 0), V2,
Chris Lattner801f4752006-01-17 18:27:17 +00001639 TheCall->getName(), TheCall);
Chris Lattner485b6412007-04-07 00:42:32 +00001640 return ReplaceCallWith(TheCall, V2);
Reid Spencerb195fcd2005-05-14 16:42:52 +00001641 }
1642} FFSOptimizer;
1643
1644/// This LibCallOptimization will simplify calls to the "ffsl" library
1645/// calls. It simply uses FFSOptimization for which the transformation is
1646/// identical.
1647/// @brief Simplify the ffsl library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001648struct VISIBILITY_HIDDEN FFSLOptimization : public FFSOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001649public:
1650 /// @brief Default Constructor
1651 FFSLOptimization() : FFSOptimization("ffsl",
1652 "Number of 'ffsl' calls simplified") {}
1653
1654} FFSLOptimizer;
1655
1656/// This LibCallOptimization will simplify calls to the "ffsll" library
1657/// calls. It simply uses FFSOptimization for which the transformation is
1658/// identical.
1659/// @brief Simplify the ffsl library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001660struct VISIBILITY_HIDDEN FFSLLOptimization : public FFSOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001661public:
1662 /// @brief Default Constructor
1663 FFSLLOptimization() : FFSOptimization("ffsll",
1664 "Number of 'ffsll' calls simplified") {}
1665
1666} FFSLLOptimizer;
1667
Chris Lattner57a28632006-01-23 05:57:36 +00001668/// This optimizes unary functions that take and return doubles.
1669struct UnaryDoubleFPOptimizer : public LibCallOptimization {
1670 UnaryDoubleFPOptimizer(const char *Fn, const char *Desc)
1671 : LibCallOptimization(Fn, Desc) {}
Chris Lattner4201cd12005-08-24 17:22:17 +00001672
Chris Lattner57a28632006-01-23 05:57:36 +00001673 // Make sure that this function has the right prototype
Chris Lattner4201cd12005-08-24 17:22:17 +00001674 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1675 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1676 F->getReturnType() == Type::DoubleTy;
1677 }
Chris Lattner57a28632006-01-23 05:57:36 +00001678
1679 /// ShrinkFunctionToFloatVersion - If the input to this function is really a
1680 /// float, strength reduce this to a float version of the function,
1681 /// e.g. floor((double)FLT) -> (double)floorf(FLT). This can only be called
1682 /// when the target supports the destination function and where there can be
1683 /// no precision loss.
1684 static bool ShrinkFunctionToFloatVersion(CallInst *CI, SimplifyLibCalls &SLC,
Chris Lattner34acba42007-01-07 08:12:01 +00001685 Constant *(SimplifyLibCalls::*FP)()){
Chris Lattner485b6412007-04-07 00:42:32 +00001686 if (FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1)))
Chris Lattner4201cd12005-08-24 17:22:17 +00001687 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
Chris Lattner57a28632006-01-23 05:57:36 +00001688 Value *New = new CallInst((SLC.*FP)(), Cast->getOperand(0),
Chris Lattner4201cd12005-08-24 17:22:17 +00001689 CI->getName(), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001690 New = new FPExtInst(New, Type::DoubleTy, CI->getName(), CI);
Chris Lattner4201cd12005-08-24 17:22:17 +00001691 CI->replaceAllUsesWith(New);
1692 CI->eraseFromParent();
1693 if (Cast->use_empty())
1694 Cast->eraseFromParent();
1695 return true;
1696 }
Chris Lattner57a28632006-01-23 05:57:36 +00001697 return false;
Chris Lattner4201cd12005-08-24 17:22:17 +00001698 }
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001699};
1700
Chris Lattner57a28632006-01-23 05:57:36 +00001701
Reid Spencer557ab152007-02-05 23:32:05 +00001702struct VISIBILITY_HIDDEN FloorOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57a28632006-01-23 05:57:36 +00001703 FloorOptimization()
1704 : UnaryDoubleFPOptimizer("floor", "Number of 'floor' calls simplified") {}
1705
1706 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001707#ifdef HAVE_FLOORF
Chris Lattner57a28632006-01-23 05:57:36 +00001708 // If this is a float argument passed in, convert to floorf.
1709 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_floorf))
1710 return true;
Reid Spencerade18212006-01-19 08:36:56 +00001711#endif
Chris Lattner57a28632006-01-23 05:57:36 +00001712 return false; // opt failed
1713 }
1714} FloorOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001715
Reid Spencer557ab152007-02-05 23:32:05 +00001716struct VISIBILITY_HIDDEN CeilOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001717 CeilOptimization()
1718 : UnaryDoubleFPOptimizer("ceil", "Number of 'ceil' calls simplified") {}
1719
1720 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1721#ifdef HAVE_CEILF
1722 // If this is a float argument passed in, convert to ceilf.
1723 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_ceilf))
1724 return true;
1725#endif
1726 return false; // opt failed
1727 }
1728} CeilOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001729
Reid Spencer557ab152007-02-05 23:32:05 +00001730struct VISIBILITY_HIDDEN RoundOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001731 RoundOptimization()
1732 : UnaryDoubleFPOptimizer("round", "Number of 'round' calls simplified") {}
1733
1734 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1735#ifdef HAVE_ROUNDF
1736 // If this is a float argument passed in, convert to roundf.
1737 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_roundf))
1738 return true;
1739#endif
1740 return false; // opt failed
1741 }
1742} RoundOptimizer;
1743
Reid Spencer557ab152007-02-05 23:32:05 +00001744struct VISIBILITY_HIDDEN RintOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001745 RintOptimization()
1746 : UnaryDoubleFPOptimizer("rint", "Number of 'rint' calls simplified") {}
1747
1748 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1749#ifdef HAVE_RINTF
1750 // If this is a float argument passed in, convert to rintf.
1751 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_rintf))
1752 return true;
1753#endif
1754 return false; // opt failed
1755 }
1756} RintOptimizer;
1757
Reid Spencer557ab152007-02-05 23:32:05 +00001758struct VISIBILITY_HIDDEN NearByIntOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001759 NearByIntOptimization()
1760 : UnaryDoubleFPOptimizer("nearbyint",
1761 "Number of 'nearbyint' calls simplified") {}
1762
1763 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1764#ifdef HAVE_NEARBYINTF
1765 // If this is a float argument passed in, convert to nearbyintf.
1766 if (ShrinkFunctionToFloatVersion(CI, SLC,&SimplifyLibCalls::get_nearbyintf))
1767 return true;
1768#endif
1769 return false; // opt failed
1770 }
1771} NearByIntOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001772
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001773/// GetConstantStringInfo - This function computes the length of a
1774/// null-terminated constant array of integers. This function can't rely on the
1775/// size of the constant array because there could be a null terminator in the
1776/// middle of the array.
1777///
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001778/// We also have to bail out if we find a non-integer constant initializer
1779/// of one of the elements or if there is no null-terminator. The logic
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001780/// below checks each of these conditions and will return true only if all
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001781/// conditions are met. If the conditions aren't met, this returns false.
1782///
1783/// If successful, the \p Array param is set to the constant array being
1784/// indexed, the \p Length parameter is set to the length of the null-terminated
1785/// string pointed to by V, the \p StartIdx value is set to the first
1786/// element of the Array that V points to, and true is returned.
Chris Lattner182a9452007-04-07 21:58:02 +00001787static bool GetConstantStringInfo(Value *V, std::string &Str) {
1788 // Look through noop bitcast instructions.
1789 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1790 if (BCI->getType() == BCI->getOperand(0)->getType())
1791 return GetConstantStringInfo(BCI->getOperand(0), Str);
1792 return false;
1793 }
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001794
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001795 // If the value is not a GEP instruction nor a constant expression with a
1796 // GEP instruction, then return false because ConstantArray can't occur
Reid Spencere249a822005-04-27 07:54:40 +00001797 // any other way
Chris Lattner182a9452007-04-07 21:58:02 +00001798 User *GEP = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001799 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Reid Spencere249a822005-04-27 07:54:40 +00001800 GEP = GEPI;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001801 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1802 if (CE->getOpcode() != Instruction::GetElementPtr)
Reid Spencere249a822005-04-27 07:54:40 +00001803 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001804 GEP = CE;
1805 } else {
Reid Spencere249a822005-04-27 07:54:40 +00001806 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001807 }
Reid Spencere249a822005-04-27 07:54:40 +00001808
1809 // Make sure the GEP has exactly three arguments.
1810 if (GEP->getNumOperands() != 3)
1811 return false;
1812
1813 // Check to make sure that the first operand of the GEP is an integer and
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001814 // has value 0 so that we are sure we're indexing into the initializer.
Chris Lattner182a9452007-04-07 21:58:02 +00001815 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1816 if (!Idx->isZero())
Reid Spencere249a822005-04-27 07:54:40 +00001817 return false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001818 } else
Reid Spencere249a822005-04-27 07:54:40 +00001819 return false;
1820
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001821 // If the second index isn't a ConstantInt, then this is a variable index
1822 // into the array. If this occurs, we can't say anything meaningful about
1823 // the string.
Chris Lattner182a9452007-04-07 21:58:02 +00001824 uint64_t StartIdx = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001825 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1826 StartIdx = CI->getZExtValue();
Reid Spencere249a822005-04-27 07:54:40 +00001827 else
1828 return false;
1829
1830 // The GEP instruction, constant or instruction, must reference a global
1831 // variable that is a constant and is initialized. The referenced constant
1832 // initializer is the array that we'll use for optimization.
1833 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1834 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1835 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001836 Constant *GlobalInit = GV->getInitializer();
Reid Spencere249a822005-04-27 07:54:40 +00001837
1838 // Handle the ConstantAggregateZero case
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001839 if (isa<ConstantAggregateZero>(GlobalInit)) {
Reid Spencere249a822005-04-27 07:54:40 +00001840 // This is a degenerate case. The initializer is constant zero so the
1841 // length of the string must be zero.
Chris Lattner182a9452007-04-07 21:58:02 +00001842 Str.clear();
Reid Spencere249a822005-04-27 07:54:40 +00001843 return true;
1844 }
1845
1846 // Must be a Constant Array
Chris Lattner182a9452007-04-07 21:58:02 +00001847 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001848 if (!Array) return false;
Reid Spencere249a822005-04-27 07:54:40 +00001849
1850 // Get the number of elements in the array
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001851 uint64_t NumElts = Array->getType()->getNumElements();
Reid Spencere249a822005-04-27 07:54:40 +00001852
Chris Lattner182a9452007-04-07 21:58:02 +00001853 // Traverse the constant array from StartIdx (derived above) which is
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001854 // the place the GEP refers to in the array.
Chris Lattner182a9452007-04-07 21:58:02 +00001855 for (unsigned i = StartIdx; i < NumElts; ++i) {
1856 Constant *Elt = Array->getOperand(i);
1857 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1858 if (!CI) // This array isn't suitable, non-int initializer.
1859 return false;
1860 if (CI->isZero())
1861 return true; // we found end of string, success!
1862 Str += (char)CI->getZExtValue();
Reid Spencere249a822005-04-27 07:54:40 +00001863 }
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001864
Chris Lattner182a9452007-04-07 21:58:02 +00001865 return false; // The array isn't null terminated.
Reid Spencere249a822005-04-27 07:54:40 +00001866}
1867
Reid Spencera7828ba2005-06-18 17:46:28 +00001868/// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
1869/// inserting the cast before IP, and return the cast.
1870/// @brief Cast a value to a "C" string.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001871static Value *CastToCStr(Value *V, Instruction *IP) {
Reid Spencera730cf82006-12-13 08:04:32 +00001872 assert(isa<PointerType>(V->getType()) &&
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001873 "Can't cast non-pointer type to C string type");
Reid Spencerc635f472006-12-31 05:48:39 +00001874 const Type *SBPTy = PointerType::get(Type::Int8Ty);
Reid Spencera7828ba2005-06-18 17:46:28 +00001875 if (V->getType() != SBPTy)
Chris Lattnerbed184c2007-04-07 21:04:50 +00001876 return new BitCastInst(V, SBPTy, V->getName(), IP);
Reid Spencera7828ba2005-06-18 17:46:28 +00001877 return V;
1878}
1879
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001880// TODO:
Reid Spencer649ac282005-04-28 04:40:06 +00001881// Additional cases that we need to add to this file:
1882//
Reid Spencer649ac282005-04-28 04:40:06 +00001883// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +00001884// * cbrt(expN(X)) -> expN(x/3)
1885// * cbrt(sqrt(x)) -> pow(x,1/6)
1886// * cbrt(sqrt(x)) -> pow(x,1/9)
1887//
Reid Spencer649ac282005-04-28 04:40:06 +00001888// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +00001889// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +00001890//
1891// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +00001892// * exp(log(x)) -> x
1893//
Reid Spencer649ac282005-04-28 04:40:06 +00001894// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +00001895// * log(exp(x)) -> x
1896// * log(x**y) -> y*log(x)
1897// * log(exp(y)) -> y*log(e)
1898// * log(exp2(y)) -> y*log(2)
1899// * log(exp10(y)) -> y*log(10)
1900// * log(sqrt(x)) -> 0.5*log(x)
1901// * log(pow(x,y)) -> y*log(x)
1902//
1903// lround, lroundf, lroundl:
1904// * lround(cnst) -> cnst'
1905//
1906// memcmp:
Reid Spencer649ac282005-04-28 04:40:06 +00001907// * memcmp(x,y,l) -> cnst
1908// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer649ac282005-04-28 04:40:06 +00001909//
Reid Spencer649ac282005-04-28 04:40:06 +00001910// memmove:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001911// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
Reid Spencer649ac282005-04-28 04:40:06 +00001912// (if s is a global constant array)
1913//
Reid Spencer649ac282005-04-28 04:40:06 +00001914// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00001915// * pow(exp(x),y) -> exp(x*y)
1916// * pow(sqrt(x),y) -> pow(x,y*0.5)
1917// * pow(pow(x,y),z)-> pow(x,y*z)
1918//
1919// puts:
1920// * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1921//
1922// round, roundf, roundl:
1923// * round(cnst) -> cnst'
1924//
1925// signbit:
1926// * signbit(cnst) -> cnst'
1927// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1928//
Reid Spencer649ac282005-04-28 04:40:06 +00001929// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00001930// * sqrt(expN(x)) -> expN(x*0.5)
1931// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1932// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1933//
Reid Spencer170ae7f2005-05-07 20:15:59 +00001934// stpcpy:
1935// * stpcpy(str, "literal") ->
1936// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer38cabd72005-05-03 07:23:44 +00001937// strrchr:
Reid Spencer649ac282005-04-28 04:40:06 +00001938// * strrchr(s,c) -> reverse_offset_of_in(c,s)
1939// (if c is a constant integer and s is a constant string)
1940// * strrchr(s1,0) -> strchr(s1,0)
1941//
Reid Spencer649ac282005-04-28 04:40:06 +00001942// strncat:
1943// * strncat(x,y,0) -> x
1944// * strncat(x,y,0) -> x (if strlen(y) = 0)
1945// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1946//
Reid Spencer649ac282005-04-28 04:40:06 +00001947// strncpy:
1948// * strncpy(d,s,0) -> d
1949// * strncpy(d,s,l) -> memcpy(d,s,l,1)
1950// (if s and l are constants)
1951//
1952// strpbrk:
1953// * strpbrk(s,a) -> offset_in_for(s,a)
1954// (if s and a are both constant strings)
1955// * strpbrk(s,"") -> 0
1956// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1957//
1958// strspn, strcspn:
1959// * strspn(s,a) -> const_int (if both args are constant)
1960// * strspn("",a) -> 0
1961// * strspn(s,"") -> 0
1962// * strcspn(s,a) -> const_int (if both args are constant)
1963// * strcspn("",a) -> 0
1964// * strcspn(s,"") -> strlen(a)
1965//
1966// strstr:
1967// * strstr(x,x) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001968// * strstr(s1,s2) -> offset_of_s2_in(s1)
Reid Spencer649ac282005-04-28 04:40:06 +00001969// (if s1 and s2 are constant strings)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001970//
Reid Spencer649ac282005-04-28 04:40:06 +00001971// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00001972// * tan(atan(x)) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001973//
Reid Spencer649ac282005-04-28 04:40:06 +00001974// trunc, truncf, truncl:
1975// * trunc(cnst) -> cnst'
1976//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001977//
Reid Spencer39a762d2005-04-25 02:53:12 +00001978}