blob: 96b5f3d77b5d72102954e4a63ebb1f3802ac6a92 [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 Lattner9b2b8ab2007-04-06 22:54:17 +0000394static bool GetConstantStringInfo(Value *V, ConstantArray *&Array,
395 uint64_t &Length, uint64_t &StartIdx);
Reid Spencer557ab152007-02-05 23:32:05 +0000396static Value *CastToCStr(Value *V, Instruction &IP);
Reid Spencere249a822005-04-27 07:54:40 +0000397
398/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000399/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000400/// the same value passed to the exit function. When this is done, it splits the
401/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000402/// @brief Replace calls to exit in main with a simple return
Reid Spencer557ab152007-02-05 23:32:05 +0000403struct VISIBILITY_HIDDEN ExitInMainOptimization : public LibCallOptimization {
Reid Spencer95d8efd2005-05-03 02:54:54 +0000404 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000405 "Number of 'exit' calls simplified") {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000406
407 // Make sure the called function looks like exit (int argument, int return
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000408 // type, external linkage, not varargs).
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000409 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner03c49532007-01-15 02:27:26 +0000410 return F->arg_size() >= 1 && F->arg_begin()->getType()->isInteger();
Reid Spencerf2534c72005-04-25 21:11:48 +0000411 }
412
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000413 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
Reid Spencerf2534c72005-04-25 21:11:48 +0000414 // To be careful, we check that the call to exit is coming from "main", that
415 // main has external linkage, and the return type of main and the argument
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000416 // to exit have the same type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000417 Function *from = ci->getParent()->getParent();
418 if (from->hasExternalLinkage())
419 if (from->getReturnType() == ci->getOperand(1)->getType())
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000420 if (from->getName() == "main") {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000421 // Okay, time to actually do the optimization. First, get the basic
Reid Spencerf2534c72005-04-25 21:11:48 +0000422 // block of the call instruction
423 BasicBlock* bb = ci->getParent();
Reid Spencer39a762d2005-04-25 02:53:12 +0000424
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000425 // Create a return instruction that we'll replace the call with.
426 // Note that the argument of the return is the argument of the call
Reid Spencerf2534c72005-04-25 21:11:48 +0000427 // instruction.
Chris Lattnercd60d382006-05-12 23:35:26 +0000428 new ReturnInst(ci->getOperand(1), ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000429
Reid Spencerf2534c72005-04-25 21:11:48 +0000430 // Split the block at the call instruction which places it in a new
431 // basic block.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000432 bb->splitBasicBlock(ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000433
Reid Spencerf2534c72005-04-25 21:11:48 +0000434 // The block split caused a branch instruction to be inserted into
435 // the end of the original block, right after the return instruction
436 // that we put there. That's not a valid block, so delete the branch
437 // instruction.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000438 bb->getInstList().pop_back();
Reid Spencer39a762d2005-04-25 02:53:12 +0000439
Reid Spencerf2534c72005-04-25 21:11:48 +0000440 // Now we can finally get rid of the call instruction which now lives
441 // in the new basic block.
442 ci->eraseFromParent();
443
444 // Optimization succeeded, return true.
445 return true;
446 }
447 // We didn't pass the criteria for this optimization so return false
448 return false;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000449 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000450} ExitInMainOptimizer;
451
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000452/// This LibCallOptimization will simplify a call to the strcat library
453/// function. The simplification is possible only if the string being
454/// concatenated is a constant array or a constant expression that results in
455/// a constant string. In this case we can replace it with strlen + llvm.memcpy
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000456/// of the constant string. Both of these calls are further reduced, if possible
457/// on subsequent passes.
Reid Spencerf2534c72005-04-25 21:11:48 +0000458/// @brief Simplify the strcat library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000459struct VISIBILITY_HIDDEN StrCatOptimization : public LibCallOptimization {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000460public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000461 /// @brief Default constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +0000462 StrCatOptimization() : LibCallOptimization("strcat",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000463 "Number of 'strcat' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000464
465public:
Reid Spencerf2534c72005-04-25 21:11:48 +0000466
467 /// @brief Make sure that the "strcat" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000468 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencerc635f472006-12-31 05:48:39 +0000469 if (f->getReturnType() == PointerType::get(Type::Int8Ty))
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000470 if (f->arg_size() == 2)
Reid Spencerf2534c72005-04-25 21:11:48 +0000471 {
472 Function::const_arg_iterator AI = f->arg_begin();
Reid Spencerc635f472006-12-31 05:48:39 +0000473 if (AI++->getType() == PointerType::get(Type::Int8Ty))
474 if (AI->getType() == PointerType::get(Type::Int8Ty))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000475 {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000476 // Indicate this is a suitable call type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000477 return true;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000478 }
Reid Spencerf2534c72005-04-25 21:11:48 +0000479 }
480 return false;
481 }
482
Reid Spencere249a822005-04-27 07:54:40 +0000483 /// @brief Optimize the strcat library function
Chris Lattner56b7fc72007-04-06 22:59:33 +0000484 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer08b49402005-04-27 17:46:54 +0000485 // Extract some information from the instruction
Chris Lattner56b7fc72007-04-06 22:59:33 +0000486 Value *Dst = CI->getOperand(1);
487 Value *Src = CI->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +0000488
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000489 // Extract the initializer (while making numerous checks) from the
Chris Lattner56b7fc72007-04-06 22:59:33 +0000490 // source operand of the call to strcat.
491 uint64_t SrcLength, StartIdx;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +0000492 ConstantArray *Arr;
Chris Lattner56b7fc72007-04-06 22:59:33 +0000493 if (!GetConstantStringInfo(Src, Arr, SrcLength, StartIdx))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000494 return false;
495
Reid Spencerb4f7b832005-04-26 07:45:18 +0000496 // Handle the simple, do-nothing case
Chris Lattner485b6412007-04-07 00:42:32 +0000497 if (SrcLength == 0)
498 return ReplaceCallWith(CI, Dst);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000499
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000500 // We need to find the end of the destination string. That's where the
501 // memory is to be moved to. We just generate a call to strlen (further
Chris Lattner56b7fc72007-04-06 22:59:33 +0000502 // optimized in another pass).
503 CallInst *DstLen = new CallInst(SLC.get_strlen(), Dst,
504 Dst->getName()+".len", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000505
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000506 // Now that we have the destination's length, we must index into the
Reid Spencerb4f7b832005-04-26 07:45:18 +0000507 // destination's pointer to get the actual memcpy destination (end of
508 // the string .. we're concatenating).
Chris Lattner56b7fc72007-04-06 22:59:33 +0000509 Dst = new GetElementPtrInst(Dst, DstLen, Dst->getName()+".indexed", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000510
511 // We have enough information to now generate the memcpy call to
512 // do the concatenation for us.
Chris Lattner56b7fc72007-04-06 22:59:33 +0000513 Value *Vals[] = {
514 Dst, Src,
515 ConstantInt::get(SLC.getIntPtrType(), SrcLength+1), // copy nul term.
516 ConstantInt::get(Type::Int32Ty, 1) // alignment
517 };
518 new CallInst(SLC.get_memcpy(), Vals, 4, "", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000519
Chris Lattner485b6412007-04-07 00:42:32 +0000520 return ReplaceCallWith(CI, Dst);
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000521 }
522} StrCatOptimizer;
523
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000524/// This LibCallOptimization will simplify a call to the strchr library
Reid Spencer38cabd72005-05-03 07:23:44 +0000525/// function. It optimizes out cases where the arguments are both constant
526/// and the result can be determined statically.
527/// @brief Simplify the strcmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000528struct VISIBILITY_HIDDEN StrChrOptimization : public LibCallOptimization {
Reid Spencer38cabd72005-05-03 07:23:44 +0000529public:
530 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000531 "Number of 'strchr' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +0000532
533 /// @brief Make sure that the "strchr" function has the right prototype
Chris Lattner39f0bb92007-04-06 23:38:55 +0000534 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
535 const FunctionType *FT = F->getFunctionType();
536 return FT->getNumParams() == 2 &&
537 FT->getReturnType() == PointerType::get(Type::Int8Ty) &&
538 FT->getParamType(0) == FT->getReturnType() &&
539 isa<IntegerType>(FT->getParamType(1));
Reid Spencer38cabd72005-05-03 07:23:44 +0000540 }
541
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000542 /// @brief Perform the strchr optimizations
Chris Lattner39f0bb92007-04-06 23:38:55 +0000543 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer38cabd72005-05-03 07:23:44 +0000544 // Check that the first argument to strchr is a constant array of sbyte.
545 // If it is, get the length and data, otherwise return false.
Chris Lattner39f0bb92007-04-06 23:38:55 +0000546 uint64_t StrLength, StartIdx;
547 ConstantArray *CA = 0;
548 if (!GetConstantStringInfo(CI->getOperand(1), CA, StrLength, StartIdx))
Reid Spencer38cabd72005-05-03 07:23:44 +0000549 return false;
550
Chris Lattner39f0bb92007-04-06 23:38:55 +0000551 // If the second operand is not constant, just lower this to memchr since we
552 // know the length of the input string.
553 ConstantInt *CSI = dyn_cast<ConstantInt>(CI->getOperand(2));
Reid Spencerc635f472006-12-31 05:48:39 +0000554 if (!CSI) {
Chris Lattner39f0bb92007-04-06 23:38:55 +0000555 Value *Args[3] = {
556 CI->getOperand(1),
557 CI->getOperand(2),
558 ConstantInt::get(SLC.getIntPtrType(), StrLength+1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +0000559 };
Chris Lattner485b6412007-04-07 00:42:32 +0000560 return ReplaceCallWith(CI, new CallInst(SLC.get_memchr(), Args, 3,
561 CI->getName(), CI));
Reid Spencer38cabd72005-05-03 07:23:44 +0000562 }
563
564 // Get the character we're looking for
Chris Lattner39f0bb92007-04-06 23:38:55 +0000565 int64_t CharValue = CSI->getSExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +0000566
Chris Lattner39f0bb92007-04-06 23:38:55 +0000567 if (StrLength == 0) {
568 // If the length of the string is zero, and we are searching for zero,
569 // return the input pointer.
Chris Lattner485b6412007-04-07 00:42:32 +0000570 if (CharValue == 0)
571 return ReplaceCallWith(CI, CI->getOperand(1));
572 // Otherwise, char wasn't found.
573 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattner39f0bb92007-04-06 23:38:55 +0000574 }
575
Reid Spencer38cabd72005-05-03 07:23:44 +0000576 // Compute the offset
Chris Lattner39f0bb92007-04-06 23:38:55 +0000577 uint64_t i = 0;
578 while (1) {
579 assert(i <= StrLength && "Didn't find null terminator?");
580 if (ConstantInt *C = dyn_cast<ConstantInt>(CA->getOperand(i+StartIdx))) {
581 // Did we find our match?
582 if (C->getSExtValue() == CharValue)
Reid Spencer38cabd72005-05-03 07:23:44 +0000583 break;
Chris Lattner485b6412007-04-07 00:42:32 +0000584 if (C->isZero()) // We found the end of the string. strchr returns null.
585 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Reid Spencer38cabd72005-05-03 07:23:44 +0000586 }
Chris Lattner39f0bb92007-04-06 23:38:55 +0000587 ++i;
Reid Spencer38cabd72005-05-03 07:23:44 +0000588 }
589
Chris Lattner39f0bb92007-04-06 23:38:55 +0000590 // strchr(s+n,c) -> gep(s+n+i,c)
Reid Spencer38cabd72005-05-03 07:23:44 +0000591 // (if c is a constant integer and s is a constant string)
Chris Lattner39f0bb92007-04-06 23:38:55 +0000592 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
593 Value *GEP = new GetElementPtrInst(CI->getOperand(1), Idx,
594 CI->getOperand(1)->getName() +
595 ".strchr", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000596 return ReplaceCallWith(CI, GEP);
Reid Spencer38cabd72005-05-03 07:23:44 +0000597 }
598} StrChrOptimizer;
599
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000600/// This LibCallOptimization will simplify a call to the strcmp library
Reid Spencer4c444fe2005-04-30 03:17:54 +0000601/// function. It optimizes out cases where one or both arguments are constant
602/// and the result can be determined statically.
603/// @brief Simplify the strcmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000604struct VISIBILITY_HIDDEN StrCmpOptimization : public LibCallOptimization {
Reid Spencer4c444fe2005-04-30 03:17:54 +0000605public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000606 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000607 "Number of 'strcmp' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +0000608
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000609 /// @brief Make sure that the "strcmp" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000610 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000611 const FunctionType *FT = F->getFunctionType();
612 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 2 &&
613 FT->getParamType(0) == FT->getParamType(1) &&
614 FT->getParamType(0) == PointerType::get(Type::Int8Ty);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000615 }
616
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000617 /// @brief Perform the strcmp optimization
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000618 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer4c444fe2005-04-30 03:17:54 +0000619 // First, check to see if src and destination are the same. If they are,
Reid Spencer16449a92005-04-30 06:45:47 +0000620 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000621 // because the call is a no-op.
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000622 Value *Str1P = CI->getOperand(1);
623 Value *Str2P = CI->getOperand(2);
Chris Lattner485b6412007-04-07 00:42:32 +0000624 if (Str1P == Str2P) // strcmp(x,x) -> 0
625 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Reid Spencer4c444fe2005-04-30 03:17:54 +0000626
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000627 uint64_t Str1Len, Str1StartIdx;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +0000628 ConstantArray *A1;
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000629 bool Str1IsCst = GetConstantStringInfo(Str1P, A1, Str1Len, Str1StartIdx);
630 if (Str1IsCst && Str1Len == 0) {
631 // strcmp("", x) -> *x
632 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
633 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000634 return ReplaceCallWith(CI, V);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000635 }
636
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000637 uint64_t Str2Len, Str2StartIdx;
Reid Spencer4c444fe2005-04-30 03:17:54 +0000638 ConstantArray* A2;
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000639 bool Str2IsCst = GetConstantStringInfo(Str2P, A2, Str2Len, Str2StartIdx);
640 if (Str2IsCst && Str2Len == 0) {
641 // strcmp(x,"") -> *x
642 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
643 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000644 return ReplaceCallWith(CI, V);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000645 }
646
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000647 if (Str1IsCst && Str2IsCst && A1->isCString() && A2->isCString()) {
648 // strcmp(x, y) -> cnst (if both x and y are constant strings)
649 std::string S1 = A1->getAsString();
650 std::string S2 = A2->getAsString();
651 int R = strcmp(S1.c_str()+Str1StartIdx, S2.c_str()+Str2StartIdx);
Chris Lattner485b6412007-04-07 00:42:32 +0000652 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencer4c444fe2005-04-30 03:17:54 +0000653 }
654 return false;
655 }
656} StrCmpOptimizer;
657
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000658/// This LibCallOptimization will simplify a call to the strncmp library
Reid Spencer49fa07042005-05-03 01:43:45 +0000659/// function. It optimizes out cases where one or both arguments are constant
660/// and the result can be determined statically.
661/// @brief Simplify the strncmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000662struct VISIBILITY_HIDDEN StrNCmpOptimization : public LibCallOptimization {
Reid Spencer49fa07042005-05-03 01:43:45 +0000663public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000664 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000665 "Number of 'strncmp' calls simplified") {}
Reid Spencer49fa07042005-05-03 01:43:45 +0000666
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000667 /// @brief Make sure that the "strncmp" function has the right prototype
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000668 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
669 const FunctionType *FT = F->getFunctionType();
670 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 3 &&
671 FT->getParamType(0) == FT->getParamType(1) &&
672 FT->getParamType(0) == PointerType::get(Type::Int8Ty) &&
673 isa<IntegerType>(FT->getParamType(2));
Reid Spencer49fa07042005-05-03 01:43:45 +0000674 return false;
675 }
676
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000677 /// @brief Perform the strncmp optimization
678 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer49fa07042005-05-03 01:43:45 +0000679 // First, check to see if src and destination are the same. If they are,
680 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000681 // because the call is a no-op.
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000682 Value *Str1P = CI->getOperand(1);
683 Value *Str2P = CI->getOperand(2);
Chris Lattner485b6412007-04-07 00:42:32 +0000684 if (Str1P == Str2P) // strncmp(x,x) -> 0
685 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000686
Reid Spencer49fa07042005-05-03 01:43:45 +0000687 // Check the length argument, if it is Constant zero then the strings are
688 // considered equal.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000689 uint64_t Length;
690 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
691 Length = LengthArg->getZExtValue();
692 else
693 return false;
694
695 if (Length == 0) {
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000696 // strncmp(x,y,0) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000697 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Reid Spencer49fa07042005-05-03 01:43:45 +0000698 }
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000699
700 uint64_t Str1Len, Str1StartIdx;
701 ConstantArray *A1;
702 bool Str1IsCst = GetConstantStringInfo(Str1P, A1, Str1Len, Str1StartIdx);
703 if (Str1IsCst && Str1Len == 0) {
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000704 // strncmp("", x) -> *x
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000705 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
706 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000707 return ReplaceCallWith(CI, V);
Reid Spencer49fa07042005-05-03 01:43:45 +0000708 }
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000709
710 uint64_t Str2Len, Str2StartIdx;
Reid Spencer49fa07042005-05-03 01:43:45 +0000711 ConstantArray* A2;
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000712 bool Str2IsCst = GetConstantStringInfo(Str2P, A2, Str2Len, Str2StartIdx);
713 if (Str2IsCst && Str2Len == 0) {
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000714 // strncmp(x,"") -> *x
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000715 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
716 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000717 return ReplaceCallWith(CI, V);
Reid Spencer49fa07042005-05-03 01:43:45 +0000718 }
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000719
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000720 if (Str1IsCst && Str2IsCst && A1->isCString() &&
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000721 A2->isCString()) {
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000722 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000723 std::string S1 = A1->getAsString();
724 std::string S2 = A2->getAsString();
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000725 int R = strncmp(S1.c_str()+Str1StartIdx, S2.c_str()+Str2StartIdx, Length);
Chris Lattner485b6412007-04-07 00:42:32 +0000726 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencer49fa07042005-05-03 01:43:45 +0000727 }
728 return false;
729 }
730} StrNCmpOptimizer;
731
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000732/// This LibCallOptimization will simplify a call to the strcpy library
733/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000734/// (1) If src and dest are the same and not volatile, just return dest
735/// (2) If the src is a constant then we can convert to llvm.memmove
736/// @brief Simplify the strcpy library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000737struct VISIBILITY_HIDDEN StrCpyOptimization : public LibCallOptimization {
Reid Spencere249a822005-04-27 07:54:40 +0000738public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000739 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000740 "Number of 'strcpy' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000741
742 /// @brief Make sure that the "strcpy" function has the right prototype
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000743 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
744 const FunctionType *FT = F->getFunctionType();
745 return FT->getNumParams() == 2 &&
746 FT->getParamType(0) == FT->getParamType(1) &&
747 FT->getReturnType() == FT->getParamType(0) &&
748 FT->getParamType(0) == PointerType::get(Type::Int8Ty);
Reid Spencere249a822005-04-27 07:54:40 +0000749 }
750
751 /// @brief Perform the strcpy optimization
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000752 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencere249a822005-04-27 07:54:40 +0000753 // First, check to see if src and destination are the same. If they are,
754 // then the optimization is to replace the CallInst with the destination
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000755 // because the call is a no-op. Note that this corresponds to the
Reid Spencere249a822005-04-27 07:54:40 +0000756 // degenerate strcpy(X,X) case which should have "undefined" results
757 // according to the C specification. However, it occurs sometimes and
758 // we optimize it as a no-op.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000759 Value *Dst = CI->getOperand(1);
760 Value *Src = CI->getOperand(2);
761 if (Dst == Src) {
762 // strcpy(x, x) -> x
Chris Lattner485b6412007-04-07 00:42:32 +0000763 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000764 }
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000765
766 // Get the length of the constant string referenced by the Src operand.
767 uint64_t SrcLen, SrcStartIdx;
768 ConstantArray *SrcArr;
769 if (!GetConstantStringInfo(Src, SrcArr, SrcLen, SrcStartIdx))
Reid Spencere249a822005-04-27 07:54:40 +0000770 return false;
771
772 // If the constant string's length is zero we can optimize this by just
773 // doing a store of 0 at the first byte of the destination
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000774 if (SrcLen == 0) {
775 new StoreInst(ConstantInt::get(Type::Int8Ty, 0), Dst, CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000776 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000777 }
778
Reid Spencere249a822005-04-27 07:54:40 +0000779 // We have enough information to now generate the memcpy call to
780 // do the concatenation for us.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000781 Value *MemcpyOps[] = {
782 Dst, Src,
783 ConstantInt::get(SLC.getIntPtrType(), SrcLen), // length including nul.
Chris Lattnerade1c2b2007-02-13 05:58:53 +0000784 ConstantInt::get(Type::Int32Ty, 1) // alignment
785 };
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000786 new CallInst(SLC.get_memcpy(), MemcpyOps, 4, "", CI);
Reid Spencere249a822005-04-27 07:54:40 +0000787
Chris Lattner485b6412007-04-07 00:42:32 +0000788 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000789 }
790} StrCpyOptimizer;
791
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000792/// This LibCallOptimization will simplify a call to the strlen library
793/// function by replacing it with a constant value if the string provided to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000794/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000795/// @brief Simplify the strlen library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000796struct VISIBILITY_HIDDEN StrLenOptimization : public LibCallOptimization {
Reid Spencer95d8efd2005-05-03 02:54:54 +0000797 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000798 "Number of 'strlen' calls simplified") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000799
800 /// @brief Make sure that the "strlen" function has the right prototype
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000801 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattnere8829aa2007-04-07 01:02:00 +0000802 const FunctionType *FT = F->getFunctionType();
803 return FT->getNumParams() == 1 &&
804 FT->getParamType(0) == PointerType::get(Type::Int8Ty) &&
805 isa<IntegerType>(FT->getReturnType());
Reid Spencer76dab9a2005-04-26 05:24:00 +0000806 }
807
808 /// @brief Perform the strlen optimization
Chris Lattnere8829aa2007-04-07 01:02:00 +0000809 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000810 // Make sure we're dealing with an sbyte* here.
Chris Lattnere8829aa2007-04-07 01:02:00 +0000811 Value *Str = CI->getOperand(1);
Reid Spencer170ae7f2005-05-07 20:15:59 +0000812
813 // Does the call to strlen have exactly one use?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000814 if (CI->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000815 // Is that single use a icmp operator?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000816 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CI->use_back()))
Reid Spencer170ae7f2005-05-07 20:15:59 +0000817 // Is it compared against a constant integer?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000818 if (ConstantInt *Cst = dyn_cast<ConstantInt>(Cmp->getOperand(1))) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000819 // If its compared against length 0 with == or !=
Chris Lattnere8829aa2007-04-07 01:02:00 +0000820 if (Cst->getZExtValue() == 0 && Cmp->isEquality()) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000821 // strlen(x) != 0 -> *x != 0
822 // strlen(x) == 0 -> *x == 0
Chris Lattnere8829aa2007-04-07 01:02:00 +0000823 Value *V = new LoadInst(Str, Str->getName()+".first", CI);
824 V = new ICmpInst(Cmp->getPredicate(), V,
825 ConstantInt::get(Type::Int8Ty, 0),
826 Cmp->getName()+".strlen", CI);
827 Cmp->replaceAllUsesWith(V);
828 Cmp->eraseFromParent();
829 return ReplaceCallWith(CI, 0); // no uses.
Reid Spencer170ae7f2005-05-07 20:15:59 +0000830 }
831 }
Chris Lattnere8829aa2007-04-07 01:02:00 +0000832 }
Reid Spencer170ae7f2005-05-07 20:15:59 +0000833
834 // Get the length of the constant string operand
Chris Lattnere8829aa2007-04-07 01:02:00 +0000835 uint64_t StrLen = 0, StartIdx;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +0000836 ConstantArray *A;
Chris Lattnere8829aa2007-04-07 01:02:00 +0000837 if (!GetConstantStringInfo(CI->getOperand(1), A, StrLen, StartIdx))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000838 return false;
839
Reid Spencer170ae7f2005-05-07 20:15:59 +0000840 // strlen("xyz") -> 3 (for example)
Chris Lattnere8829aa2007-04-07 01:02:00 +0000841 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), StrLen));
Reid Spencer76dab9a2005-04-26 05:24:00 +0000842 }
843} StrLenOptimizer;
844
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000845/// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
846/// is equal or not-equal to zero.
847static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
848 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
849 UI != E; ++UI) {
Chris Lattner6a36d632007-04-07 01:03:46 +0000850 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
851 if (IC->isEquality())
852 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
853 if (C->isNullValue())
854 continue;
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000855 // Unknown instruction.
856 return false;
857 }
858 return true;
859}
860
861/// This memcmpOptimization will simplify a call to the memcmp library
862/// function.
Reid Spencer557ab152007-02-05 23:32:05 +0000863struct VISIBILITY_HIDDEN memcmpOptimization : public LibCallOptimization {
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000864 /// @brief Default Constructor
865 memcmpOptimization()
866 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
867
868 /// @brief Make sure that the "memcmp" function has the right prototype
869 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
870 Function::const_arg_iterator AI = F->arg_begin();
871 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
872 if (!isa<PointerType>((++AI)->getType())) return false;
Chris Lattner03c49532007-01-15 02:27:26 +0000873 if (!(++AI)->getType()->isInteger()) return false;
874 if (!F->getReturnType()->isInteger()) return false;
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000875 return true;
876 }
877
878 /// Because of alignment and instruction information that we don't have, we
879 /// leave the bulk of this to the code generators.
880 ///
881 /// Note that we could do much more if we could force alignment on otherwise
882 /// small aligned allocas, or if we could indicate that loads have a small
883 /// alignment.
884 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
885 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
886
887 // If the two operands are the same, return zero.
888 if (LHS == RHS) {
889 // memcmp(s,s,x) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000890 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000891 }
892
893 // Make sure we have a constant length.
894 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
895 if (!LenC) return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000896 uint64_t Len = LenC->getZExtValue();
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000897
898 // If the length is zero, this returns 0.
899 switch (Len) {
900 case 0:
901 // memcmp(s1,s2,0) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000902 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000903 case 1: {
904 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
Reid Spencerc635f472006-12-31 05:48:39 +0000905 const Type *UCharPtr = PointerType::get(Type::Int8Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000906 CastInst *Op1Cast = CastInst::create(
907 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
908 CastInst *Op2Cast = CastInst::create(
909 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000910 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
911 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
912 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
913 if (RV->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +0000914 RV = CastInst::createIntegerCast(RV, CI->getType(), false,
915 RV->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000916 return ReplaceCallWith(CI, RV);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000917 }
918 case 2:
919 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
920 // TODO: IF both are aligned, use a short load/compare.
921
922 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
Reid Spencerc635f472006-12-31 05:48:39 +0000923 const Type *UCharPtr = PointerType::get(Type::Int8Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000924 CastInst *Op1Cast = CastInst::create(
925 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
926 CastInst *Op2Cast = CastInst::create(
927 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000928 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
929 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
930 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
931 CI->getName()+".d1", CI);
Reid Spencerc635f472006-12-31 05:48:39 +0000932 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000933 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
934 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
935 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
Chris Lattnercd60d382006-05-12 23:35:26 +0000936 Value *S2V2 = new LoadInst(G2, RHS->getName()+".val2", CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000937 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
938 CI->getName()+".d1", CI);
939 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
940 if (Or->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +0000941 Or = CastInst::createIntegerCast(Or, CI->getType(), false /*ZExt*/,
942 Or->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000943 return ReplaceCallWith(CI, Or);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000944 }
945 break;
946 default:
947 break;
948 }
949
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000950 return false;
951 }
952} memcmpOptimizer;
953
954
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000955/// This LibCallOptimization will simplify a call to the memcpy library
956/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000957/// bytes depending on the length of the string and the alignment. Additional
958/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +0000959/// @brief Simplify the memcpy library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000960struct VISIBILITY_HIDDEN LLVMMemCpyMoveOptzn : public LibCallOptimization {
Chris Lattnerea7986a2006-03-03 01:30:23 +0000961 LLVMMemCpyMoveOptzn(const char* fname, const char* desc)
962 : LibCallOptimization(fname, desc) {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000963
964 /// @brief Make sure that the "memcpy" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000965 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD) {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000966 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +0000967 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +0000968 }
969
Reid Spencerb4f7b832005-04-26 07:45:18 +0000970 /// Because of alignment and instruction information that we don't have, we
971 /// leave the bulk of this to the code generators. The optimization here just
972 /// deals with a few degenerate cases where the length of the string and the
973 /// alignment match the sizes of our intrinsic types so we can do a load and
974 /// store instead of the memcpy call.
975 /// @brief Perform the memcpy optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000976 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD) {
Reid Spencer4855ebf2005-04-26 19:55:57 +0000977 // Make sure we have constant int values to work with
978 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
979 if (!LEN)
980 return false;
981 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
982 if (!ALIGN)
983 return false;
984
985 // If the length is larger than the alignment, we can't optimize
Reid Spencere0fc4df2006-10-20 07:07:24 +0000986 uint64_t len = LEN->getZExtValue();
987 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +0000988 if (alignment == 0)
989 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000990 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +0000991 return false;
992
Reid Spencer08b49402005-04-27 17:46:54 +0000993 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +0000994 Value* dest = ci->getOperand(1);
995 Value* src = ci->getOperand(2);
Reid Spencer4f98e622007-01-07 21:45:41 +0000996 const Type* castType = 0;
Chris Lattner485b6412007-04-07 00:42:32 +0000997 switch (len) {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000998 case 0:
Chris Lattner485b6412007-04-07 00:42:32 +0000999 // memcpy(d,s,0,a) -> d
1000 return ReplaceCallWith(ci, 0);
Reid Spencerc635f472006-12-31 05:48:39 +00001001 case 1: castType = Type::Int8Ty; break;
1002 case 2: castType = Type::Int16Ty; break;
1003 case 4: castType = Type::Int32Ty; break;
1004 case 8: castType = Type::Int64Ty; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001005 default:
1006 return false;
1007 }
Reid Spencer08b49402005-04-27 17:46:54 +00001008
1009 // Cast source and dest to the right sized primitive and then load/store
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001010 CastInst* SrcCast = CastInst::create(Instruction::BitCast,
1011 src, PointerType::get(castType), src->getName()+".cast", ci);
1012 CastInst* DestCast = CastInst::create(Instruction::BitCast,
1013 dest, PointerType::get(castType),dest->getName()+".cast", ci);
Reid Spencer08b49402005-04-27 17:46:54 +00001014 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerde46e482006-11-02 20:25:50 +00001015 new StoreInst(LI, DestCast, ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001016 return ReplaceCallWith(ci, 0);
Reid Spencerf2534c72005-04-25 21:11:48 +00001017 }
Chris Lattnerea7986a2006-03-03 01:30:23 +00001018};
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001019
Chris Lattnerea7986a2006-03-03 01:30:23 +00001020/// This LibCallOptimization will simplify a call to the memcpy/memmove library
1021/// functions.
1022LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer32("llvm.memcpy.i32",
1023 "Number of 'llvm.memcpy' calls simplified");
1024LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer64("llvm.memcpy.i64",
1025 "Number of 'llvm.memcpy' calls simplified");
1026LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer32("llvm.memmove.i32",
1027 "Number of 'llvm.memmove' calls simplified");
1028LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer64("llvm.memmove.i64",
1029 "Number of 'llvm.memmove' calls simplified");
Reid Spencer38cabd72005-05-03 07:23:44 +00001030
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001031/// This LibCallOptimization will simplify a call to the memset library
1032/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1033/// bytes depending on the length argument.
Reid Spencer557ab152007-02-05 23:32:05 +00001034struct VISIBILITY_HIDDEN LLVMMemSetOptimization : public LibCallOptimization {
Reid Spencer38cabd72005-05-03 07:23:44 +00001035 /// @brief Default Constructor
Chris Lattnerea7986a2006-03-03 01:30:23 +00001036 LLVMMemSetOptimization(const char *Name) : LibCallOptimization(Name,
Reid Spencer38cabd72005-05-03 07:23:44 +00001037 "Number of 'llvm.memset' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +00001038
1039 /// @brief Make sure that the "memset" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001040 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001041 // Just make sure this has 3 arguments per LLVM spec.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001042 return F->arg_size() == 4;
Reid Spencer38cabd72005-05-03 07:23:44 +00001043 }
1044
1045 /// Because of alignment and instruction information that we don't have, we
1046 /// leave the bulk of this to the code generators. The optimization here just
1047 /// deals with a few degenerate cases where the length parameter is constant
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001048 /// and the alignment matches the sizes of our intrinsic types so we can do
Reid Spencer38cabd72005-05-03 07:23:44 +00001049 /// store instead of the memcpy call. Other calls are transformed into the
1050 /// llvm.memset intrinsic.
1051 /// @brief Perform the memset optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001052 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &TD) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001053 // Make sure we have constant int values to work with
1054 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1055 if (!LEN)
1056 return false;
1057 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1058 if (!ALIGN)
1059 return false;
1060
1061 // Extract the length and alignment
Reid Spencere0fc4df2006-10-20 07:07:24 +00001062 uint64_t len = LEN->getZExtValue();
1063 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001064
1065 // Alignment 0 is identity for alignment 1
1066 if (alignment == 0)
1067 alignment = 1;
1068
1069 // If the length is zero, this is a no-op
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001070 if (len == 0) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001071 // memset(d,c,0,a) -> noop
Chris Lattner485b6412007-04-07 00:42:32 +00001072 return ReplaceCallWith(ci, 0);
Reid Spencer38cabd72005-05-03 07:23:44 +00001073 }
1074
1075 // If the length is larger than the alignment, we can't optimize
1076 if (len > alignment)
1077 return false;
1078
1079 // Make sure we have a constant ubyte to work with so we can extract
1080 // the value to be filled.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001081 ConstantInt* FILL = dyn_cast<ConstantInt>(ci->getOperand(2));
Reid Spencer38cabd72005-05-03 07:23:44 +00001082 if (!FILL)
1083 return false;
Reid Spencerc635f472006-12-31 05:48:39 +00001084 if (FILL->getType() != Type::Int8Ty)
Reid Spencer38cabd72005-05-03 07:23:44 +00001085 return false;
1086
1087 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001088
Reid Spencer38cabd72005-05-03 07:23:44 +00001089 // Extract the fill character
Reid Spencere0fc4df2006-10-20 07:07:24 +00001090 uint64_t fill_char = FILL->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001091 uint64_t fill_value = fill_char;
1092
1093 // Get the type we will cast to, based on size of memory area to fill, and
1094 // and the value we will store there.
1095 Value* dest = ci->getOperand(1);
Reid Spencer4f98e622007-01-07 21:45:41 +00001096 const Type* castType = 0;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001097 switch (len) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001098 case 1:
Reid Spencerc635f472006-12-31 05:48:39 +00001099 castType = Type::Int8Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001100 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001101 case 2:
Reid Spencerc635f472006-12-31 05:48:39 +00001102 castType = Type::Int16Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001103 fill_value |= fill_char << 8;
1104 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001105 case 4:
Reid Spencerc635f472006-12-31 05:48:39 +00001106 castType = Type::Int32Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001107 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1108 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001109 case 8:
Reid Spencerc635f472006-12-31 05:48:39 +00001110 castType = Type::Int64Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001111 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1112 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1113 fill_value |= fill_char << 56;
1114 break;
1115 default:
1116 return false;
1117 }
1118
1119 // Cast dest to the right sized primitive and then load/store
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001120 CastInst* DestCast = new BitCastInst(dest, PointerType::get(castType),
1121 dest->getName()+".cast", ci);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001122 new StoreInst(ConstantInt::get(castType,fill_value),DestCast, ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001123 return ReplaceCallWith(ci, 0);
Reid Spencer38cabd72005-05-03 07:23:44 +00001124 }
Chris Lattnerea7986a2006-03-03 01:30:23 +00001125};
1126
1127LLVMMemSetOptimization MemSet32Optimizer("llvm.memset.i32");
1128LLVMMemSetOptimization MemSet64Optimizer("llvm.memset.i64");
1129
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001130
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001131/// This LibCallOptimization will simplify calls to the "pow" library
1132/// function. It looks for cases where the result of pow is well known and
Reid Spencer93616972005-04-29 09:39:47 +00001133/// substitutes the appropriate value.
1134/// @brief Simplify the pow library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001135struct VISIBILITY_HIDDEN PowOptimization : public LibCallOptimization {
Reid Spencer93616972005-04-29 09:39:47 +00001136public:
1137 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001138 PowOptimization() : LibCallOptimization("pow",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001139 "Number of 'pow' calls simplified") {}
Reid Spencer95d8efd2005-05-03 02:54:54 +00001140
Reid Spencer93616972005-04-29 09:39:47 +00001141 /// @brief Make sure that the "pow" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001142 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer93616972005-04-29 09:39:47 +00001143 // Just make sure this has 2 arguments
1144 return (f->arg_size() == 2);
1145 }
1146
1147 /// @brief Perform the pow optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001148 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer93616972005-04-29 09:39:47 +00001149 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1150 Value* base = ci->getOperand(1);
1151 Value* expn = ci->getOperand(2);
1152 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1153 double Op1V = Op1->getValue();
Chris Lattner485b6412007-04-07 00:42:32 +00001154 if (Op1V == 1.0) // pow(1.0,x) -> 1.0
1155 return ReplaceCallWith(ci, ConstantFP::get(Ty, 1.0));
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001156 } else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) {
Reid Spencer93616972005-04-29 09:39:47 +00001157 double Op2V = Op2->getValue();
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001158 if (Op2V == 0.0) {
Reid Spencer93616972005-04-29 09:39:47 +00001159 // pow(x,0.0) -> 1.0
Chris Lattner485b6412007-04-07 00:42:32 +00001160 return ReplaceCallWith(ci, ConstantFP::get(Ty,1.0));
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001161 } else if (Op2V == 0.5) {
Reid Spencer93616972005-04-29 09:39:47 +00001162 // pow(x,0.5) -> sqrt(x)
1163 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1164 ci->getName()+".pow",ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001165 return ReplaceCallWith(ci, sqrt_inst);
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001166 } else if (Op2V == 1.0) {
Reid Spencer93616972005-04-29 09:39:47 +00001167 // pow(x,1.0) -> x
Chris Lattner485b6412007-04-07 00:42:32 +00001168 return ReplaceCallWith(ci, base);
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001169 } else if (Op2V == -1.0) {
Reid Spencer93616972005-04-29 09:39:47 +00001170 // pow(x,-1.0) -> 1.0/x
Chris Lattner485b6412007-04-07 00:42:32 +00001171 Value *div_inst =
1172 BinaryOperator::createFDiv(ConstantFP::get(Ty, 1.0), base,
1173 ci->getName()+".pow", ci);
1174 return ReplaceCallWith(ci, div_inst);
Reid Spencer93616972005-04-29 09:39:47 +00001175 }
1176 }
1177 return false; // opt failed
1178 }
1179} PowOptimizer;
1180
Evan Cheng1fc40252006-06-16 08:36:35 +00001181/// This LibCallOptimization will simplify calls to the "printf" library
1182/// function. It looks for cases where the result of printf is not used and the
1183/// operation can be reduced to something simpler.
1184/// @brief Simplify the printf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001185struct VISIBILITY_HIDDEN PrintfOptimization : public LibCallOptimization {
Evan Cheng1fc40252006-06-16 08:36:35 +00001186public:
1187 /// @brief Default Constructor
1188 PrintfOptimization() : LibCallOptimization("printf",
1189 "Number of 'printf' calls simplified") {}
1190
1191 /// @brief Make sure that the "printf" function has the right prototype
1192 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1193 // Just make sure this has at least 1 arguments
1194 return (f->arg_size() >= 1);
1195 }
1196
1197 /// @brief Perform the printf optimization.
1198 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
1199 // If the call has more than 2 operands, we can't optimize it
1200 if (ci->getNumOperands() > 3 || ci->getNumOperands() <= 2)
1201 return false;
1202
1203 // If the result of the printf call is used, none of these optimizations
1204 // can be made.
1205 if (!ci->use_empty())
1206 return false;
1207
1208 // All the optimizations depend on the length of the first argument and the
1209 // fact that it is a constant string array. Check that now
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001210 uint64_t len, StartIdx;
Evan Cheng1fc40252006-06-16 08:36:35 +00001211 ConstantArray* CA = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001212 if (!GetConstantStringInfo(ci->getOperand(1), CA, len, StartIdx))
Evan Cheng1fc40252006-06-16 08:36:35 +00001213 return false;
1214
1215 if (len != 2 && len != 3)
1216 return false;
1217
1218 // The first character has to be a %
1219 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
Reid Spencere0fc4df2006-10-20 07:07:24 +00001220 if (CI->getZExtValue() != '%')
Evan Cheng1fc40252006-06-16 08:36:35 +00001221 return false;
1222
1223 // Get the second character and switch on its value
1224 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00001225 switch (CI->getZExtValue()) {
Evan Cheng1fc40252006-06-16 08:36:35 +00001226 case 's':
1227 {
1228 if (len != 3 ||
Reid Spencere0fc4df2006-10-20 07:07:24 +00001229 dyn_cast<ConstantInt>(CA->getOperand(2))->getZExtValue() != '\n')
Evan Cheng1fc40252006-06-16 08:36:35 +00001230 return false;
1231
1232 // printf("%s\n",str) -> puts(str)
Evan Cheng1fc40252006-06-16 08:36:35 +00001233 std::vector<Value*> args;
Chris Lattner34acba42007-01-07 08:12:01 +00001234 new CallInst(SLC.get_puts(), CastToCStr(ci->getOperand(2), *ci),
1235 ci->getName(), ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001236 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, len));
Evan Cheng1fc40252006-06-16 08:36:35 +00001237 }
1238 case 'c':
1239 {
1240 // printf("%c",c) -> putchar(c)
1241 if (len != 2)
1242 return false;
1243
Chris Lattner34acba42007-01-07 08:12:01 +00001244 CastInst *Char = CastInst::createSExtOrBitCast(
Reid Spencerc635f472006-12-31 05:48:39 +00001245 ci->getOperand(2), Type::Int32Ty, CI->getName()+".int", ci);
Chris Lattner34acba42007-01-07 08:12:01 +00001246 new CallInst(SLC.get_putchar(), Char, "", ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001247 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
Evan Cheng1fc40252006-06-16 08:36:35 +00001248 }
1249 default:
1250 return false;
1251 }
Chris Lattner485b6412007-04-07 00:42:32 +00001252 return false;
Evan Cheng1fc40252006-06-16 08:36:35 +00001253 }
1254} PrintfOptimizer;
1255
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001256/// This LibCallOptimization will simplify calls to the "fprintf" library
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001257/// function. It looks for cases where the result of fprintf is not used and the
1258/// operation can be reduced to something simpler.
Evan Cheng1fc40252006-06-16 08:36:35 +00001259/// @brief Simplify the fprintf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001260struct VISIBILITY_HIDDEN FPrintFOptimization : public LibCallOptimization {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001261public:
1262 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001263 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001264 "Number of 'fprintf' calls simplified") {}
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001265
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001266 /// @brief Make sure that the "fprintf" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001267 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001268 // Just make sure this has at least 2 arguments
1269 return (f->arg_size() >= 2);
1270 }
1271
1272 /// @brief Perform the fprintf optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001273 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001274 // If the call has more than 3 operands, we can't optimize it
1275 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1276 return false;
1277
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001278 // If the result of the fprintf call is used, none of these optimizations
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001279 // can be made.
Chris Lattner175463a2005-09-24 22:17:06 +00001280 if (!ci->use_empty())
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001281 return false;
1282
1283 // All the optimizations depend on the length of the second argument and the
1284 // fact that it is a constant string array. Check that now
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001285 uint64_t len, StartIdx;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001286 ConstantArray* CA = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001287 if (!GetConstantStringInfo(ci->getOperand(2), CA, len, StartIdx))
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001288 return false;
1289
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001290 if (ci->getNumOperands() == 3) {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001291 // Make sure there's no % in the constant array
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001292 for (unsigned i = 0; i < len; ++i) {
1293 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i))) {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001294 // Check for the null terminator
Reid Spencere0fc4df2006-10-20 07:07:24 +00001295 if (CI->getZExtValue() == '%')
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001296 return false; // we found end of string
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001297 } else {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001298 return false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001299 }
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001300 }
1301
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001302 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001303 const Type* FILEptr_type = ci->getOperand(1)->getType();
John Criswell4642afd2005-06-29 15:03:18 +00001304
1305 // Make sure that the fprintf() and fwrite() functions both take the
1306 // same type of char pointer.
Chris Lattner34acba42007-01-07 08:12:01 +00001307 if (ci->getOperand(2)->getType() != PointerType::get(Type::Int8Ty))
John Criswell4642afd2005-06-29 15:03:18 +00001308 return false;
John Criswell4642afd2005-06-29 15:03:18 +00001309
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001310 Value* args[4] = {
1311 ci->getOperand(2),
1312 ConstantInt::get(SLC.getIntPtrType(),len),
1313 ConstantInt::get(SLC.getIntPtrType(),1),
1314 ci->getOperand(1)
1315 };
1316 new CallInst(SLC.get_fwrite(FILEptr_type), args, 4, ci->getName(), ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001317 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001318 }
1319
1320 // The remaining optimizations require the format string to be length 2
1321 // "%s" or "%c".
1322 if (len != 2)
1323 return false;
1324
1325 // The first character has to be a %
1326 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
Reid Spencere0fc4df2006-10-20 07:07:24 +00001327 if (CI->getZExtValue() != '%')
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001328 return false;
1329
1330 // Get the second character and switch on its value
1331 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00001332 switch (CI->getZExtValue()) {
Chris Lattner485b6412007-04-07 00:42:32 +00001333 case 's': {
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001334 uint64_t len, StartIdx;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001335 ConstantArray* CA = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001336 if (GetConstantStringInfo(ci->getOperand(3), CA, len, StartIdx)) {
Evan Chengf2ea5872006-06-16 04:52:30 +00001337 // fprintf(file,"%s",str) -> fwrite(str,strlen(str),1,file)
1338 const Type* FILEptr_type = ci->getOperand(1)->getType();
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001339 Value* args[4] = {
1340 CastToCStr(ci->getOperand(3), *ci),
1341 ConstantInt::get(SLC.getIntPtrType(), len),
1342 ConstantInt::get(SLC.getIntPtrType(), 1),
1343 ci->getOperand(1)
1344 };
1345 new CallInst(SLC.get_fwrite(FILEptr_type), args, 4,ci->getName(), ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001346 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, len));
Evan Chengf2ea5872006-06-16 04:52:30 +00001347 }
Chris Lattner485b6412007-04-07 00:42:32 +00001348 // fprintf(file,"%s",str) -> fputs(str,file)
1349 const Type* FILEptr_type = ci->getOperand(1)->getType();
1350 new CallInst(SLC.get_fputs(FILEptr_type),
1351 CastToCStr(ci->getOperand(3), *ci),
1352 ci->getOperand(1), ci->getName(),ci);
1353 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001354 }
Chris Lattner485b6412007-04-07 00:42:32 +00001355 case 'c': {
Evan Cheng1fc40252006-06-16 08:36:35 +00001356 // fprintf(file,"%c",c) -> fputc(c,file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001357 const Type* FILEptr_type = ci->getOperand(1)->getType();
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001358 CastInst* cast = CastInst::createSExtOrBitCast(
Reid Spencerc635f472006-12-31 05:48:39 +00001359 ci->getOperand(3), Type::Int32Ty, CI->getName()+".int", ci);
Chris Lattner34acba42007-01-07 08:12:01 +00001360 new CallInst(SLC.get_fputc(FILEptr_type), cast,ci->getOperand(1),"",ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001361 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty,1));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001362 }
1363 default:
1364 return false;
1365 }
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001366 }
1367} FPrintFOptimizer;
1368
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001369/// This LibCallOptimization will simplify calls to the "sprintf" library
Reid Spencer1e520fd2005-05-04 03:20:21 +00001370/// function. It looks for cases where the result of sprintf is not used and the
1371/// operation can be reduced to something simpler.
Evan Cheng1fc40252006-06-16 08:36:35 +00001372/// @brief Simplify the sprintf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001373struct VISIBILITY_HIDDEN SPrintFOptimization : public LibCallOptimization {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001374public:
1375 /// @brief Default Constructor
1376 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001377 "Number of 'sprintf' calls simplified") {}
Reid Spencer1e520fd2005-05-04 03:20:21 +00001378
Reid Spencer1e520fd2005-05-04 03:20:21 +00001379 /// @brief Make sure that the "fprintf" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001380 virtual bool ValidateCalledFunction(const Function *f, SimplifyLibCalls &SLC){
Reid Spencer1e520fd2005-05-04 03:20:21 +00001381 // Just make sure this has at least 2 arguments
Reid Spencerc635f472006-12-31 05:48:39 +00001382 return (f->getReturnType() == Type::Int32Ty && f->arg_size() >= 2);
Reid Spencer1e520fd2005-05-04 03:20:21 +00001383 }
1384
1385 /// @brief Perform the sprintf optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001386 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001387 // If the call has more than 3 operands, we can't optimize it
1388 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1389 return false;
1390
1391 // All the optimizations depend on the length of the second argument and the
1392 // fact that it is a constant string array. Check that now
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001393 uint64_t len, StartIdx;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001394 ConstantArray* CA = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001395 if (!GetConstantStringInfo(ci->getOperand(2), CA, len, StartIdx))
Reid Spencer1e520fd2005-05-04 03:20:21 +00001396 return false;
1397
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001398 if (ci->getNumOperands() == 3) {
1399 if (len == 0) {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001400 // If the length is 0, we just need to store a null byte
Reid Spencerc635f472006-12-31 05:48:39 +00001401 new StoreInst(ConstantInt::get(Type::Int8Ty,0),ci->getOperand(1),ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001402 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty,0));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001403 }
1404
1405 // Make sure there's no % in the constant array
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001406 for (unsigned i = 0; i < len; ++i) {
1407 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i))) {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001408 // Check for the null terminator
Reid Spencere0fc4df2006-10-20 07:07:24 +00001409 if (CI->getZExtValue() == '%')
Reid Spencer1e520fd2005-05-04 03:20:21 +00001410 return false; // we found a %, can't optimize
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001411 } else {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001412 return false; // initializer is not constant int, can't optimize
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001413 }
Reid Spencer1e520fd2005-05-04 03:20:21 +00001414 }
1415
1416 // Increment length because we want to copy the null byte too
1417 len++;
1418
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001419 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001420 Value *args[4] = {
1421 ci->getOperand(1),
1422 ci->getOperand(2),
1423 ConstantInt::get(SLC.getIntPtrType(),len),
1424 ConstantInt::get(Type::Int32Ty, 1)
1425 };
1426 new CallInst(SLC.get_memcpy(), args, 4, "", ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001427 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty,len));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001428 }
1429
1430 // The remaining optimizations require the format string to be length 2
1431 // "%s" or "%c".
1432 if (len != 2)
1433 return false;
1434
1435 // The first character has to be a %
1436 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
Reid Spencere0fc4df2006-10-20 07:07:24 +00001437 if (CI->getZExtValue() != '%')
Reid Spencer1e520fd2005-05-04 03:20:21 +00001438 return false;
1439
1440 // Get the second character and switch on its value
1441 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00001442 switch (CI->getZExtValue()) {
Chris Lattner175463a2005-09-24 22:17:06 +00001443 case 's': {
1444 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Chris Lattner34acba42007-01-07 08:12:01 +00001445 Value *Len = new CallInst(SLC.get_strlen(),
1446 CastToCStr(ci->getOperand(3), *ci),
Chris Lattner175463a2005-09-24 22:17:06 +00001447 ci->getOperand(3)->getName()+".len", ci);
1448 Value *Len1 = BinaryOperator::createAdd(Len,
1449 ConstantInt::get(Len->getType(), 1),
1450 Len->getName()+"1", ci);
Andrew Lenharth47da6012006-02-15 21:13:37 +00001451 if (Len1->getType() != SLC.getIntPtrType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001452 Len1 = CastInst::createIntegerCast(Len1, SLC.getIntPtrType(), false,
1453 Len1->getName(), ci);
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001454 Value *args[4] = {
1455 CastToCStr(ci->getOperand(1), *ci),
1456 CastToCStr(ci->getOperand(3), *ci),
1457 Len1,
1458 ConstantInt::get(Type::Int32Ty,1)
1459 };
1460 new CallInst(SLC.get_memcpy(), args, 4, "", ci);
Chris Lattner175463a2005-09-24 22:17:06 +00001461
1462 // The strlen result is the unincremented number of bytes in the string.
Chris Lattnerf4877682005-09-25 07:06:48 +00001463 if (!ci->use_empty()) {
1464 if (Len->getType() != ci->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001465 Len = CastInst::createIntegerCast(Len, ci->getType(), false,
1466 Len->getName(), ci);
Chris Lattnerf4877682005-09-25 07:06:48 +00001467 ci->replaceAllUsesWith(Len);
1468 }
Chris Lattner485b6412007-04-07 00:42:32 +00001469 return ReplaceCallWith(ci, 0);
Reid Spencer1e520fd2005-05-04 03:20:21 +00001470 }
Chris Lattner175463a2005-09-24 22:17:06 +00001471 case 'c': {
1472 // sprintf(dest,"%c",chr) -> store chr, dest
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001473 CastInst* cast = CastInst::createTruncOrBitCast(
Reid Spencerc635f472006-12-31 05:48:39 +00001474 ci->getOperand(3), Type::Int8Ty, "char", ci);
Chris Lattner175463a2005-09-24 22:17:06 +00001475 new StoreInst(cast, ci->getOperand(1), ci);
1476 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
Reid Spencerc635f472006-12-31 05:48:39 +00001477 ConstantInt::get(Type::Int32Ty,1),ci->getOperand(1)->getName()+".end",
Chris Lattner175463a2005-09-24 22:17:06 +00001478 ci);
Reid Spencerc635f472006-12-31 05:48:39 +00001479 new StoreInst(ConstantInt::get(Type::Int8Ty,0),gep,ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001480 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
Chris Lattner175463a2005-09-24 22:17:06 +00001481 }
1482 }
1483 return false;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001484 }
1485} SPrintFOptimizer;
1486
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001487/// This LibCallOptimization will simplify calls to the "fputs" library
Reid Spencer93616972005-04-29 09:39:47 +00001488/// function. It looks for cases where the result of fputs is not used and the
1489/// operation can be reduced to something simpler.
Evan Cheng1fc40252006-06-16 08:36:35 +00001490/// @brief Simplify the puts library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001491struct VISIBILITY_HIDDEN PutsOptimization : public LibCallOptimization {
Reid Spencer93616972005-04-29 09:39:47 +00001492public:
1493 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001494 PutsOptimization() : LibCallOptimization("fputs",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001495 "Number of 'fputs' calls simplified") {}
Reid Spencer93616972005-04-29 09:39:47 +00001496
Reid Spencer93616972005-04-29 09:39:47 +00001497 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001498 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencer93616972005-04-29 09:39:47 +00001499 // Just make sure this has 2 arguments
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001500 return F->arg_size() == 2;
Reid Spencer93616972005-04-29 09:39:47 +00001501 }
1502
1503 /// @brief Perform the fputs optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001504 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
Reid Spencer93616972005-04-29 09:39:47 +00001505 // If the result is used, none of these optimizations work
Chris Lattner175463a2005-09-24 22:17:06 +00001506 if (!ci->use_empty())
Reid Spencer93616972005-04-29 09:39:47 +00001507 return false;
1508
1509 // All the optimizations depend on the length of the first argument and the
1510 // fact that it is a constant string array. Check that now
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001511 uint64_t len, StartIdx;
1512 ConstantArray *CA;
1513 if (!GetConstantStringInfo(ci->getOperand(1), CA, len, StartIdx))
Reid Spencer93616972005-04-29 09:39:47 +00001514 return false;
1515
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001516 switch (len) {
Reid Spencer93616972005-04-29 09:39:47 +00001517 case 0:
1518 // fputs("",F) -> noop
1519 break;
1520 case 1:
1521 {
1522 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001523 const Type* FILEptr_type = ci->getOperand(2)->getType();
Reid Spencer93616972005-04-29 09:39:47 +00001524 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1525 ci->getOperand(1)->getName()+".byte",ci);
Reid Spencerc635f472006-12-31 05:48:39 +00001526 CastInst* casti = new SExtInst(loadi, Type::Int32Ty,
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001527 loadi->getName()+".int", ci);
Chris Lattner34acba42007-01-07 08:12:01 +00001528 new CallInst(SLC.get_fputc(FILEptr_type), casti,
1529 ci->getOperand(2), "", ci);
Reid Spencer93616972005-04-29 09:39:47 +00001530 break;
1531 }
1532 default:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001533 {
Reid Spencer93616972005-04-29 09:39:47 +00001534 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001535 const Type* FILEptr_type = ci->getOperand(2)->getType();
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001536 Value *parms[4] = {
1537 ci->getOperand(1),
1538 ConstantInt::get(SLC.getIntPtrType(),len),
1539 ConstantInt::get(SLC.getIntPtrType(),1),
1540 ci->getOperand(2)
1541 };
1542 new CallInst(SLC.get_fwrite(FILEptr_type), parms, 4, "", ci);
Reid Spencer93616972005-04-29 09:39:47 +00001543 break;
1544 }
1545 }
Chris Lattner485b6412007-04-07 00:42:32 +00001546 return ReplaceCallWith(ci, 0); // Known to have no uses (see above).
Reid Spencer93616972005-04-29 09:39:47 +00001547 }
1548} PutsOptimizer;
1549
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001550/// This LibCallOptimization will simplify calls to the "isdigit" library
Reid Spencer282d0572005-05-04 18:58:28 +00001551/// function. It simply does range checks the parameter explicitly.
1552/// @brief Simplify the isdigit library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001553struct VISIBILITY_HIDDEN isdigitOptimization : public LibCallOptimization {
Reid Spencer282d0572005-05-04 18:58:28 +00001554public:
Chris Lattner5f6035f2005-09-29 06:16:11 +00001555 isdigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001556 "Number of 'isdigit' calls simplified") {}
Reid Spencer282d0572005-05-04 18:58:28 +00001557
Chris Lattner5f6035f2005-09-29 06:16:11 +00001558 /// @brief Make sure that the "isdigit" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001559 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer282d0572005-05-04 18:58:28 +00001560 // Just make sure this has 1 argument
1561 return (f->arg_size() == 1);
1562 }
1563
1564 /// @brief Perform the toascii optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001565 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1566 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1))) {
Reid Spencer282d0572005-05-04 18:58:28 +00001567 // isdigit(c) -> 0 or 1, if 'c' is constant
Reid Spencere0fc4df2006-10-20 07:07:24 +00001568 uint64_t val = CI->getZExtValue();
Chris Lattner485b6412007-04-07 00:42:32 +00001569 if (val >= '0' && val <= '9')
1570 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
Reid Spencer282d0572005-05-04 18:58:28 +00001571 else
Chris Lattner485b6412007-04-07 00:42:32 +00001572 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 0));
Reid Spencer282d0572005-05-04 18:58:28 +00001573 }
1574
1575 // isdigit(c) -> (unsigned)c - '0' <= 9
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001576 CastInst* cast = CastInst::createIntegerCast(ci->getOperand(1),
Reid Spencerc635f472006-12-31 05:48:39 +00001577 Type::Int32Ty, false/*ZExt*/, ci->getOperand(1)->getName()+".uint", ci);
Chris Lattner4201cd12005-08-24 17:22:17 +00001578 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
Reid Spencerc635f472006-12-31 05:48:39 +00001579 ConstantInt::get(Type::Int32Ty,0x30),
Reid Spencer282d0572005-05-04 18:58:28 +00001580 ci->getOperand(1)->getName()+".sub",ci);
Reid Spencer266e42b2006-12-23 06:05:41 +00001581 ICmpInst* setcond_inst = new ICmpInst(ICmpInst::ICMP_ULE,sub_inst,
Reid Spencerc635f472006-12-31 05:48:39 +00001582 ConstantInt::get(Type::Int32Ty,9),
Reid Spencer282d0572005-05-04 18:58:28 +00001583 ci->getOperand(1)->getName()+".cmp",ci);
Reid Spencerc635f472006-12-31 05:48:39 +00001584 CastInst* c2 = new ZExtInst(setcond_inst, Type::Int32Ty,
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001585 ci->getOperand(1)->getName()+".isdigit", ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001586 return ReplaceCallWith(ci, c2);
Reid Spencer282d0572005-05-04 18:58:28 +00001587 }
Chris Lattner5f6035f2005-09-29 06:16:11 +00001588} isdigitOptimizer;
1589
Reid Spencer557ab152007-02-05 23:32:05 +00001590struct VISIBILITY_HIDDEN isasciiOptimization : public LibCallOptimization {
Chris Lattner87ef9432005-09-29 06:17:27 +00001591public:
1592 isasciiOptimization()
1593 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1594
1595 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner03c49532007-01-15 02:27:26 +00001596 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1597 F->getReturnType()->isInteger();
Chris Lattner87ef9432005-09-29 06:17:27 +00001598 }
1599
1600 /// @brief Perform the isascii optimization.
1601 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1602 // isascii(c) -> (unsigned)c < 128
1603 Value *V = CI->getOperand(1);
Reid Spencer266e42b2006-12-23 06:05:41 +00001604 Value *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, V,
1605 ConstantInt::get(V->getType(), 128),
1606 V->getName()+".isascii", CI);
Chris Lattner87ef9432005-09-29 06:17:27 +00001607 if (Cmp->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001608 Cmp = new BitCastInst(Cmp, CI->getType(), Cmp->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +00001609 return ReplaceCallWith(CI, Cmp);
Chris Lattner87ef9432005-09-29 06:17:27 +00001610 }
1611} isasciiOptimizer;
Chris Lattner5f6035f2005-09-29 06:16:11 +00001612
Reid Spencer282d0572005-05-04 18:58:28 +00001613
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001614/// This LibCallOptimization will simplify calls to the "toascii" library
Reid Spencer4c444fe2005-04-30 03:17:54 +00001615/// function. It simply does the corresponding and operation to restrict the
1616/// range of values to the ASCII character set (0-127).
1617/// @brief Simplify the toascii library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001618struct VISIBILITY_HIDDEN ToAsciiOptimization : public LibCallOptimization {
Reid Spencer4c444fe2005-04-30 03:17:54 +00001619public:
1620 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001621 ToAsciiOptimization() : LibCallOptimization("toascii",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001622 "Number of 'toascii' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +00001623
Reid Spencer4c444fe2005-04-30 03:17:54 +00001624 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001625 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer4c444fe2005-04-30 03:17:54 +00001626 // Just make sure this has 2 arguments
1627 return (f->arg_size() == 1);
1628 }
1629
1630 /// @brief Perform the toascii optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001631 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer4c444fe2005-04-30 03:17:54 +00001632 // toascii(c) -> (c & 0x7f)
Chris Lattner485b6412007-04-07 00:42:32 +00001633 Value *chr = ci->getOperand(1);
1634 Value *and_inst = BinaryOperator::createAnd(chr,
Reid Spencer4c444fe2005-04-30 03:17:54 +00001635 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001636 return ReplaceCallWith(ci, and_inst);
Reid Spencer4c444fe2005-04-30 03:17:54 +00001637 }
1638} ToAsciiOptimizer;
1639
Reid Spencerb195fcd2005-05-14 16:42:52 +00001640/// This LibCallOptimization will simplify calls to the "ffs" library
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001641/// calls which find the first set bit in an int, long, or long long. The
Reid Spencerb195fcd2005-05-14 16:42:52 +00001642/// optimization is to compute the result at compile time if the argument is
1643/// a constant.
1644/// @brief Simplify the ffs library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001645struct VISIBILITY_HIDDEN FFSOptimization : public LibCallOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001646protected:
1647 /// @brief Subclass Constructor
1648 FFSOptimization(const char* funcName, const char* description)
Chris Lattner801f4752006-01-17 18:27:17 +00001649 : LibCallOptimization(funcName, description) {}
Reid Spencerb195fcd2005-05-14 16:42:52 +00001650
1651public:
1652 /// @brief Default Constructor
1653 FFSOptimization() : LibCallOptimization("ffs",
1654 "Number of 'ffs' calls simplified") {}
1655
Chris Lattner801f4752006-01-17 18:27:17 +00001656 /// @brief Make sure that the "ffs" function has the right prototype
1657 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencerb195fcd2005-05-14 16:42:52 +00001658 // Just make sure this has 2 arguments
Reid Spencerc635f472006-12-31 05:48:39 +00001659 return F->arg_size() == 1 && F->getReturnType() == Type::Int32Ty;
Reid Spencerb195fcd2005-05-14 16:42:52 +00001660 }
1661
1662 /// @brief Perform the ffs optimization.
Chris Lattner801f4752006-01-17 18:27:17 +00001663 virtual bool OptimizeCall(CallInst *TheCall, SimplifyLibCalls &SLC) {
1664 if (ConstantInt *CI = dyn_cast<ConstantInt>(TheCall->getOperand(1))) {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001665 // ffs(cnst) -> bit#
1666 // ffsl(cnst) -> bit#
Reid Spencer17f77842005-05-15 21:19:45 +00001667 // ffsll(cnst) -> bit#
Reid Spencere0fc4df2006-10-20 07:07:24 +00001668 uint64_t val = CI->getZExtValue();
Reid Spencer17f77842005-05-15 21:19:45 +00001669 int result = 0;
Chris Lattner801f4752006-01-17 18:27:17 +00001670 if (val) {
1671 ++result;
1672 while ((val & 1) == 0) {
1673 ++result;
1674 val >>= 1;
1675 }
Reid Spencer17f77842005-05-15 21:19:45 +00001676 }
Chris Lattner485b6412007-04-07 00:42:32 +00001677 return ReplaceCallWith(TheCall, ConstantInt::get(Type::Int32Ty, result));
Reid Spencerb195fcd2005-05-14 16:42:52 +00001678 }
Reid Spencer17f77842005-05-15 21:19:45 +00001679
Chris Lattner801f4752006-01-17 18:27:17 +00001680 // ffs(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1681 // ffsl(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1682 // ffsll(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1683 const Type *ArgType = TheCall->getOperand(1)->getType();
Chris Lattner801f4752006-01-17 18:27:17 +00001684 const char *CTTZName;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001685 assert(ArgType->getTypeID() == Type::IntegerTyID &&
1686 "llvm.cttz argument is not an integer?");
1687 unsigned BitWidth = cast<IntegerType>(ArgType)->getBitWidth();
Chris Lattner3b6058c2007-01-12 22:49:11 +00001688 if (BitWidth == 8)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001689 CTTZName = "llvm.cttz.i8";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001690 else if (BitWidth == 16)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001691 CTTZName = "llvm.cttz.i16";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001692 else if (BitWidth == 32)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001693 CTTZName = "llvm.cttz.i32";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001694 else {
1695 assert(BitWidth == 64 && "Unknown bitwidth");
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001696 CTTZName = "llvm.cttz.i64";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001697 }
Chris Lattner801f4752006-01-17 18:27:17 +00001698
Chris Lattner34acba42007-01-07 08:12:01 +00001699 Constant *F = SLC.getModule()->getOrInsertFunction(CTTZName, ArgType,
Chris Lattner801f4752006-01-17 18:27:17 +00001700 ArgType, NULL);
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001701 Value *V = CastInst::createIntegerCast(TheCall->getOperand(1), ArgType,
1702 false/*ZExt*/, "tmp", TheCall);
Chris Lattner801f4752006-01-17 18:27:17 +00001703 Value *V2 = new CallInst(F, V, "tmp", TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001704 V2 = CastInst::createIntegerCast(V2, Type::Int32Ty, false/*ZExt*/,
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001705 "tmp", TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001706 V2 = BinaryOperator::createAdd(V2, ConstantInt::get(Type::Int32Ty, 1),
Chris Lattner801f4752006-01-17 18:27:17 +00001707 "tmp", TheCall);
Reid Spencer266e42b2006-12-23 06:05:41 +00001708 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, V,
1709 Constant::getNullValue(V->getType()), "tmp",
1710 TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001711 V2 = new SelectInst(Cond, ConstantInt::get(Type::Int32Ty, 0), V2,
Chris Lattner801f4752006-01-17 18:27:17 +00001712 TheCall->getName(), TheCall);
Chris Lattner485b6412007-04-07 00:42:32 +00001713 return ReplaceCallWith(TheCall, V2);
Reid Spencerb195fcd2005-05-14 16:42:52 +00001714 }
1715} FFSOptimizer;
1716
1717/// This LibCallOptimization will simplify calls to the "ffsl" library
1718/// calls. It simply uses FFSOptimization for which the transformation is
1719/// identical.
1720/// @brief Simplify the ffsl library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001721struct VISIBILITY_HIDDEN FFSLOptimization : public FFSOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001722public:
1723 /// @brief Default Constructor
1724 FFSLOptimization() : FFSOptimization("ffsl",
1725 "Number of 'ffsl' calls simplified") {}
1726
1727} FFSLOptimizer;
1728
1729/// This LibCallOptimization will simplify calls to the "ffsll" library
1730/// calls. It simply uses FFSOptimization for which the transformation is
1731/// identical.
1732/// @brief Simplify the ffsl library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001733struct VISIBILITY_HIDDEN FFSLLOptimization : public FFSOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001734public:
1735 /// @brief Default Constructor
1736 FFSLLOptimization() : FFSOptimization("ffsll",
1737 "Number of 'ffsll' calls simplified") {}
1738
1739} FFSLLOptimizer;
1740
Chris Lattner57a28632006-01-23 05:57:36 +00001741/// This optimizes unary functions that take and return doubles.
1742struct UnaryDoubleFPOptimizer : public LibCallOptimization {
1743 UnaryDoubleFPOptimizer(const char *Fn, const char *Desc)
1744 : LibCallOptimization(Fn, Desc) {}
Chris Lattner4201cd12005-08-24 17:22:17 +00001745
Chris Lattner57a28632006-01-23 05:57:36 +00001746 // Make sure that this function has the right prototype
Chris Lattner4201cd12005-08-24 17:22:17 +00001747 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1748 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1749 F->getReturnType() == Type::DoubleTy;
1750 }
Chris Lattner57a28632006-01-23 05:57:36 +00001751
1752 /// ShrinkFunctionToFloatVersion - If the input to this function is really a
1753 /// float, strength reduce this to a float version of the function,
1754 /// e.g. floor((double)FLT) -> (double)floorf(FLT). This can only be called
1755 /// when the target supports the destination function and where there can be
1756 /// no precision loss.
1757 static bool ShrinkFunctionToFloatVersion(CallInst *CI, SimplifyLibCalls &SLC,
Chris Lattner34acba42007-01-07 08:12:01 +00001758 Constant *(SimplifyLibCalls::*FP)()){
Chris Lattner485b6412007-04-07 00:42:32 +00001759 if (FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1)))
Chris Lattner4201cd12005-08-24 17:22:17 +00001760 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
Chris Lattner57a28632006-01-23 05:57:36 +00001761 Value *New = new CallInst((SLC.*FP)(), Cast->getOperand(0),
Chris Lattner4201cd12005-08-24 17:22:17 +00001762 CI->getName(), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001763 New = new FPExtInst(New, Type::DoubleTy, CI->getName(), CI);
Chris Lattner4201cd12005-08-24 17:22:17 +00001764 CI->replaceAllUsesWith(New);
1765 CI->eraseFromParent();
1766 if (Cast->use_empty())
1767 Cast->eraseFromParent();
1768 return true;
1769 }
Chris Lattner57a28632006-01-23 05:57:36 +00001770 return false;
Chris Lattner4201cd12005-08-24 17:22:17 +00001771 }
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001772};
1773
Chris Lattner57a28632006-01-23 05:57:36 +00001774
Reid Spencer557ab152007-02-05 23:32:05 +00001775struct VISIBILITY_HIDDEN FloorOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57a28632006-01-23 05:57:36 +00001776 FloorOptimization()
1777 : UnaryDoubleFPOptimizer("floor", "Number of 'floor' calls simplified") {}
1778
1779 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001780#ifdef HAVE_FLOORF
Chris Lattner57a28632006-01-23 05:57:36 +00001781 // If this is a float argument passed in, convert to floorf.
1782 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_floorf))
1783 return true;
Reid Spencerade18212006-01-19 08:36:56 +00001784#endif
Chris Lattner57a28632006-01-23 05:57:36 +00001785 return false; // opt failed
1786 }
1787} FloorOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001788
Reid Spencer557ab152007-02-05 23:32:05 +00001789struct VISIBILITY_HIDDEN CeilOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001790 CeilOptimization()
1791 : UnaryDoubleFPOptimizer("ceil", "Number of 'ceil' calls simplified") {}
1792
1793 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1794#ifdef HAVE_CEILF
1795 // If this is a float argument passed in, convert to ceilf.
1796 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_ceilf))
1797 return true;
1798#endif
1799 return false; // opt failed
1800 }
1801} CeilOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001802
Reid Spencer557ab152007-02-05 23:32:05 +00001803struct VISIBILITY_HIDDEN RoundOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001804 RoundOptimization()
1805 : UnaryDoubleFPOptimizer("round", "Number of 'round' calls simplified") {}
1806
1807 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1808#ifdef HAVE_ROUNDF
1809 // If this is a float argument passed in, convert to roundf.
1810 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_roundf))
1811 return true;
1812#endif
1813 return false; // opt failed
1814 }
1815} RoundOptimizer;
1816
Reid Spencer557ab152007-02-05 23:32:05 +00001817struct VISIBILITY_HIDDEN RintOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001818 RintOptimization()
1819 : UnaryDoubleFPOptimizer("rint", "Number of 'rint' calls simplified") {}
1820
1821 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1822#ifdef HAVE_RINTF
1823 // If this is a float argument passed in, convert to rintf.
1824 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_rintf))
1825 return true;
1826#endif
1827 return false; // opt failed
1828 }
1829} RintOptimizer;
1830
Reid Spencer557ab152007-02-05 23:32:05 +00001831struct VISIBILITY_HIDDEN NearByIntOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001832 NearByIntOptimization()
1833 : UnaryDoubleFPOptimizer("nearbyint",
1834 "Number of 'nearbyint' calls simplified") {}
1835
1836 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1837#ifdef HAVE_NEARBYINTF
1838 // If this is a float argument passed in, convert to nearbyintf.
1839 if (ShrinkFunctionToFloatVersion(CI, SLC,&SimplifyLibCalls::get_nearbyintf))
1840 return true;
1841#endif
1842 return false; // opt failed
1843 }
1844} NearByIntOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001845
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001846/// GetConstantStringInfo - This function computes the length of a
1847/// null-terminated constant array of integers. This function can't rely on the
1848/// size of the constant array because there could be a null terminator in the
1849/// middle of the array.
1850///
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001851/// We also have to bail out if we find a non-integer constant initializer
1852/// of one of the elements or if there is no null-terminator. The logic
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001853/// below checks each of these conditions and will return true only if all
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001854/// conditions are met. If the conditions aren't met, this returns false.
1855///
1856/// If successful, the \p Array param is set to the constant array being
1857/// indexed, the \p Length parameter is set to the length of the null-terminated
1858/// string pointed to by V, the \p StartIdx value is set to the first
1859/// element of the Array that V points to, and true is returned.
1860static bool GetConstantStringInfo(Value *V, ConstantArray *&Array,
1861 uint64_t &Length, uint64_t &StartIdx) {
1862 assert(V != 0 && "Invalid args to GetConstantStringInfo");
1863 // Initialize results.
1864 Length = 0;
1865 StartIdx = 0;
1866 Array = 0;
1867
1868 User *GEP = 0;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001869 // If the value is not a GEP instruction nor a constant expression with a
1870 // GEP instruction, then return false because ConstantArray can't occur
Reid Spencere249a822005-04-27 07:54:40 +00001871 // any other way
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001872 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Reid Spencere249a822005-04-27 07:54:40 +00001873 GEP = GEPI;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001874 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1875 if (CE->getOpcode() != Instruction::GetElementPtr)
Reid Spencere249a822005-04-27 07:54:40 +00001876 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001877 GEP = CE;
1878 } else {
Reid Spencere249a822005-04-27 07:54:40 +00001879 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001880 }
Reid Spencere249a822005-04-27 07:54:40 +00001881
1882 // Make sure the GEP has exactly three arguments.
1883 if (GEP->getNumOperands() != 3)
1884 return false;
1885
1886 // Check to make sure that the first operand of the GEP is an integer and
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001887 // has value 0 so that we are sure we're indexing into the initializer.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001888 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
Reid Spencer2e54a152007-03-02 00:28:52 +00001889 if (!op1->isZero())
Reid Spencere249a822005-04-27 07:54:40 +00001890 return false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001891 } else
Reid Spencere249a822005-04-27 07:54:40 +00001892 return false;
1893
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001894 // If the second index isn't a ConstantInt, then this is a variable index
1895 // into the array. If this occurs, we can't say anything meaningful about
1896 // the string.
1897 StartIdx = 0;
1898 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1899 StartIdx = CI->getZExtValue();
Reid Spencere249a822005-04-27 07:54:40 +00001900 else
1901 return false;
1902
1903 // The GEP instruction, constant or instruction, must reference a global
1904 // variable that is a constant and is initialized. The referenced constant
1905 // initializer is the array that we'll use for optimization.
1906 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1907 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1908 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001909 Constant *GlobalInit = GV->getInitializer();
Reid Spencere249a822005-04-27 07:54:40 +00001910
1911 // Handle the ConstantAggregateZero case
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001912 if (isa<ConstantAggregateZero>(GlobalInit)) {
Reid Spencere249a822005-04-27 07:54:40 +00001913 // This is a degenerate case. The initializer is constant zero so the
1914 // length of the string must be zero.
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001915 Length = 0;
Reid Spencere249a822005-04-27 07:54:40 +00001916 return true;
1917 }
1918
1919 // Must be a Constant Array
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001920 Array = dyn_cast<ConstantArray>(GlobalInit);
1921 if (!Array) return false;
Reid Spencere249a822005-04-27 07:54:40 +00001922
1923 // Get the number of elements in the array
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001924 uint64_t NumElts = Array->getType()->getNumElements();
Reid Spencere249a822005-04-27 07:54:40 +00001925
1926 // Traverse the constant array from start_idx (derived above) which is
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001927 // the place the GEP refers to in the array.
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001928 Length = StartIdx;
1929 while (1) {
1930 if (Length >= NumElts)
1931 return false; // The array isn't null terminated.
1932
1933 Constant *Elt = Array->getOperand(Length);
1934 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
1935 // Check for the null terminator.
Reid Spencer2e54a152007-03-02 00:28:52 +00001936 if (CI->isZero())
Reid Spencere249a822005-04-27 07:54:40 +00001937 break; // we found end of string
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001938 } else
Reid Spencere249a822005-04-27 07:54:40 +00001939 return false; // This array isn't suitable, non-int initializer
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001940 ++Length;
Reid Spencere249a822005-04-27 07:54:40 +00001941 }
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001942
Reid Spencere249a822005-04-27 07:54:40 +00001943 // Subtract out the initial value from the length
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001944 Length -= StartIdx;
Reid Spencere249a822005-04-27 07:54:40 +00001945 return true; // success!
1946}
1947
Reid Spencera7828ba2005-06-18 17:46:28 +00001948/// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
1949/// inserting the cast before IP, and return the cast.
1950/// @brief Cast a value to a "C" string.
Reid Spencer557ab152007-02-05 23:32:05 +00001951static Value *CastToCStr(Value *V, Instruction &IP) {
Reid Spencera730cf82006-12-13 08:04:32 +00001952 assert(isa<PointerType>(V->getType()) &&
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001953 "Can't cast non-pointer type to C string type");
Reid Spencerc635f472006-12-31 05:48:39 +00001954 const Type *SBPTy = PointerType::get(Type::Int8Ty);
Reid Spencera7828ba2005-06-18 17:46:28 +00001955 if (V->getType() != SBPTy)
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001956 return new BitCastInst(V, SBPTy, V->getName(), &IP);
Reid Spencera7828ba2005-06-18 17:46:28 +00001957 return V;
1958}
1959
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001960// TODO:
Reid Spencer649ac282005-04-28 04:40:06 +00001961// Additional cases that we need to add to this file:
1962//
Reid Spencer649ac282005-04-28 04:40:06 +00001963// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +00001964// * cbrt(expN(X)) -> expN(x/3)
1965// * cbrt(sqrt(x)) -> pow(x,1/6)
1966// * cbrt(sqrt(x)) -> pow(x,1/9)
1967//
Reid Spencer649ac282005-04-28 04:40:06 +00001968// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +00001969// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +00001970//
1971// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +00001972// * exp(log(x)) -> x
1973//
Reid Spencer649ac282005-04-28 04:40:06 +00001974// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +00001975// * log(exp(x)) -> x
1976// * log(x**y) -> y*log(x)
1977// * log(exp(y)) -> y*log(e)
1978// * log(exp2(y)) -> y*log(2)
1979// * log(exp10(y)) -> y*log(10)
1980// * log(sqrt(x)) -> 0.5*log(x)
1981// * log(pow(x,y)) -> y*log(x)
1982//
1983// lround, lroundf, lroundl:
1984// * lround(cnst) -> cnst'
1985//
1986// memcmp:
Reid Spencer649ac282005-04-28 04:40:06 +00001987// * memcmp(x,y,l) -> cnst
1988// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer649ac282005-04-28 04:40:06 +00001989//
Reid Spencer649ac282005-04-28 04:40:06 +00001990// memmove:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001991// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
Reid Spencer649ac282005-04-28 04:40:06 +00001992// (if s is a global constant array)
1993//
Reid Spencer649ac282005-04-28 04:40:06 +00001994// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00001995// * pow(exp(x),y) -> exp(x*y)
1996// * pow(sqrt(x),y) -> pow(x,y*0.5)
1997// * pow(pow(x,y),z)-> pow(x,y*z)
1998//
1999// puts:
2000// * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
2001//
2002// round, roundf, roundl:
2003// * round(cnst) -> cnst'
2004//
2005// signbit:
2006// * signbit(cnst) -> cnst'
2007// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2008//
Reid Spencer649ac282005-04-28 04:40:06 +00002009// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00002010// * sqrt(expN(x)) -> expN(x*0.5)
2011// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2012// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2013//
Reid Spencer170ae7f2005-05-07 20:15:59 +00002014// stpcpy:
2015// * stpcpy(str, "literal") ->
2016// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer38cabd72005-05-03 07:23:44 +00002017// strrchr:
Reid Spencer649ac282005-04-28 04:40:06 +00002018// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2019// (if c is a constant integer and s is a constant string)
2020// * strrchr(s1,0) -> strchr(s1,0)
2021//
Reid Spencer649ac282005-04-28 04:40:06 +00002022// strncat:
2023// * strncat(x,y,0) -> x
2024// * strncat(x,y,0) -> x (if strlen(y) = 0)
2025// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2026//
Reid Spencer649ac282005-04-28 04:40:06 +00002027// strncpy:
2028// * strncpy(d,s,0) -> d
2029// * strncpy(d,s,l) -> memcpy(d,s,l,1)
2030// (if s and l are constants)
2031//
2032// strpbrk:
2033// * strpbrk(s,a) -> offset_in_for(s,a)
2034// (if s and a are both constant strings)
2035// * strpbrk(s,"") -> 0
2036// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2037//
2038// strspn, strcspn:
2039// * strspn(s,a) -> const_int (if both args are constant)
2040// * strspn("",a) -> 0
2041// * strspn(s,"") -> 0
2042// * strcspn(s,a) -> const_int (if both args are constant)
2043// * strcspn("",a) -> 0
2044// * strcspn(s,"") -> strlen(a)
2045//
2046// strstr:
2047// * strstr(x,x) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002048// * strstr(s1,s2) -> offset_of_s2_in(s1)
Reid Spencer649ac282005-04-28 04:40:06 +00002049// (if s1 and s2 are constant strings)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002050//
Reid Spencer649ac282005-04-28 04:40:06 +00002051// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00002052// * tan(atan(x)) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002053//
Reid Spencer649ac282005-04-28 04:40:06 +00002054// trunc, truncf, truncl:
2055// * trunc(cnst) -> cnst'
2056//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002057//
Reid Spencer39a762d2005-04-25 02:53:12 +00002058}