blob: 0bd3f84c5e1aa410f00ceaa95e90590eac7c1808 [file] [log] [blame]
Reid Spencerb7c11e32005-04-25 03:59:26 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
Reid Spencera7c049b2005-04-25 02:53:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencera7c049b2005-04-25 02:53:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Jeff Cohen00b168892005-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 Spencer0660f752005-05-21 00:57:44 +000013// occurs within the main() function can be transformed into a simple "return 3"
Jeff Cohen00b168892005-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 Spencera7c049b2005-04-25 02:53:12 +000017//
18//===----------------------------------------------------------------------===//
19
Reid Spenceref99ea32005-04-26 23:05:17 +000020#define DEBUG_TYPE "simplify-libcalls"
Reid Spencer8f132612005-04-26 23:02:16 +000021#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Instructions.h"
Reid Spencera7c049b2005-04-25 02:53:12 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Reid Spencerb7c11e32005-04-25 03:59:26 +000026#include "llvm/ADT/hash_map"
Reid Spencer8f132612005-04-26 23:02:16 +000027#include "llvm/ADT/Statistic.h"
Reid Spenceraa87e052006-01-19 08:36:56 +000028#include "llvm/Config/config.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Reid Spencer8f132612005-04-26 23:02:16 +000030#include "llvm/Support/Debug.h"
Reid Spencerfcbdb9c2005-04-26 19:13:17 +000031#include "llvm/Target/TargetData.h"
Reid Spencer8f132612005-04-26 23:02:16 +000032#include "llvm/Transforms/IPO.h"
Reid Spencera7c049b2005-04-25 02:53:12 +000033using namespace llvm;
34
Reid Spencera16d5a52005-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 Lattner86453c52006-12-19 22:09:18 +000037STATISTIC(SimplifiedLibCalls, "Number of library calls simplified");
Reid Spencera7c049b2005-04-25 02:53:12 +000038
Chris Lattner86453c52006-12-19 22:09:18 +000039namespace {
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
43
Chris Lattnere05cf712006-01-22 23:10:26 +000044/// This list is populated by the constructor for LibCallOptimization class.
Reid Spencer89026022005-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 Spencer716f49e2005-04-27 21:29:20 +000048/// @brief The list of optimizations deriving from LibCallOptimization
Chris Lattnere05cf712006-01-22 23:10:26 +000049static LibCallOptimization *OptList = 0;
Reid Spencera7c049b2005-04-25 02:53:12 +000050
Reid Spencera16d5a52005-04-27 07:54:40 +000051/// This class is the abstract base class for the set of optimizations that
Reid Spencer716f49e2005-04-27 21:29:20 +000052/// corresponds to one library call. The SimplifyLibCalls pass will call the
Reid Spencera16d5a52005-04-27 07:54:40 +000053/// ValidateCalledFunction method to ask the optimization if a given Function
Reid Spencer716f49e2005-04-27 21:29:20 +000054/// is the kind that the optimization can handle. If the subclass returns true,
Jeff Cohen00b168892005-07-27 06:12:32 +000055/// then SImplifyLibCalls will also call the OptimizeCall method to perform,
Reid Spencer716f49e2005-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 Cohen00b168892005-07-27 06:12:32 +000060/// optimize. The criteria for a "lib call" is "anything with well known
Reid Spencer716f49e2005-04-27 21:29:20 +000061/// semantics", typically a library function that is defined by an international
Jeff Cohen00b168892005-07-27 06:12:32 +000062/// standard. Because the semantics are well known, the optimizations can
Reid Spencer716f49e2005-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 Spencera16d5a52005-04-27 07:54:40 +000065/// @brief Base class for library call optimizations
Reid Spencer9133fe22007-02-05 23:32:05 +000066class VISIBILITY_HIDDEN LibCallOptimization {
Chris Lattnere05cf712006-01-22 23:10:26 +000067 LibCallOptimization **Prev, *Next;
68 const char *FunctionName; ///< Name of the library call we optimize
69#ifndef NDEBUG
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000070 Statistic occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
Chris Lattnere05cf712006-01-22 23:10:26 +000071#endif
Jeff Cohen5882b922005-04-29 03:05:44 +000072public:
Jeff Cohen00b168892005-07-27 06:12:32 +000073 /// The \p fname argument must be the name of the library function being
Reid Spencer716f49e2005-04-27 21:29:20 +000074 /// optimized by the subclass.
75 /// @brief Constructor that registers the optimization.
Chris Lattnere05cf712006-01-22 23:10:26 +000076 LibCallOptimization(const char *FName, const char *Description)
Chris Lattner1c560ad2006-12-19 23:16:47 +000077 : FunctionName(FName) {
78
Reid Spencer1ea099c2005-04-27 00:05:45 +000079#ifndef NDEBUG
Chris Lattner1c560ad2006-12-19 23:16:47 +000080 occurrences.construct("simplify-libcalls", Description);
Reid Spencer1ea099c2005-04-27 00:05:45 +000081#endif
Chris Lattnere05cf712006-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 Spencera7c049b2005-04-25 02:53:12 +000087 }
Chris Lattnere05cf712006-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 Spencera7c049b2005-04-25 02:53:12 +000092
Reid Spencer716f49e2005-04-27 21:29:20 +000093 /// @brief Deregister from the optlist
Chris Lattnere05cf712006-01-22 23:10:26 +000094 virtual ~LibCallOptimization() {
95 *Prev = Next;
96 if (Next) Next->Prev = Prev;
97 }
Reid Spencer43e0bae2005-04-26 03:26:15 +000098
Reid Spencera16d5a52005-04-27 07:54:40 +000099 /// The implementation of this function in subclasses should determine if
Jeff Cohen00b168892005-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 Spencer716f49e2005-04-27 21:29:20 +0000103 /// place. If the called function is suitabe, this method should return true;
Jeff Cohen00b168892005-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 Spencera16d5a52005-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 Spencer716f49e2005-04-27 21:29:20 +0000108 /// @brief Determine if the function is suitable for optimization
Reid Spencera16d5a52005-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 Spencerfcbdb9c2005-04-26 19:13:17 +0000113
Jeff Cohen00b168892005-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 Spencera16d5a52005-04-27 07:54:40 +0000116 /// OptimizeCall to determine if (a) the conditions are right for optimizing
Jeff Cohen00b168892005-07-27 06:12:32 +0000117 /// the call and (b) to perform the optimization. If an action is taken
Reid Spencera16d5a52005-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 Spencera16d5a52005-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 Spencerfcbdb9c2005-04-26 19:13:17 +0000125
Reid Spencera16d5a52005-04-27 07:54:40 +0000126 /// @brief Get the name of the library call being optimized
Chris Lattnere05cf712006-01-22 23:10:26 +0000127 const char *getFunctionName() const { return FunctionName; }
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000128
Chris Lattner679d7182007-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 Spencer716f49e2005-04-27 21:29:20 +0000136 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
Chris Lattnere05cf712006-01-22 23:10:26 +0000137 void succeeded() {
Reid Spencera16d5a52005-04-27 07:54:40 +0000138#ifndef NDEBUG
Chris Lattnere05cf712006-01-22 23:10:26 +0000139 DEBUG(++occurrences);
Reid Spencera16d5a52005-04-27 07:54:40 +0000140#endif
Chris Lattnere05cf712006-01-22 23:10:26 +0000141 }
Reid Spencera16d5a52005-04-27 07:54:40 +0000142};
143
Jeff Cohen00b168892005-07-27 06:12:32 +0000144/// This class is an LLVM Pass that applies each of the LibCallOptimization
Reid Spencera16d5a52005-04-27 07:54:40 +0000145/// instances to all the call sites in a module, relatively efficiently. The
Jeff Cohen00b168892005-07-27 06:12:32 +0000146/// purpose of this pass is to provide optimizations for calls to well-known
Reid Spencera16d5a52005-04-27 07:54:40 +0000147/// functions with well-known semantics, such as those in the c library. The
Chris Lattner53249862005-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 Spencer716f49e2005-04-27 21:29:20 +0000150/// validate the call (ValidateLibraryCall). If it is validated, then
151/// the OptimizeCall method is also called.
Reid Spencera16d5a52005-04-27 07:54:40 +0000152/// @brief A ModulePass for optimizing well-known function calls.
Reid Spencer9133fe22007-02-05 23:32:05 +0000153class VISIBILITY_HIDDEN SimplifyLibCalls : public ModulePass {
Jeff Cohen5882b922005-04-29 03:05:44 +0000154public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000155 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +0000156 SimplifyLibCalls() : ModulePass((intptr_t)&ID) {}
157
Reid Spencera16d5a52005-04-27 07:54:40 +0000158 /// We need some target data for accurate signature details that are
159 /// target dependent. So we require target data in our AnalysisUsage.
Reid Spencer716f49e2005-04-27 21:29:20 +0000160 /// @brief Require TargetData from AnalysisUsage.
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000161 virtual void getAnalysisUsage(AnalysisUsage& Info) const {
Reid Spencera16d5a52005-04-27 07:54:40 +0000162 // Ask that the TargetData analysis be performed before us so we can use
163 // the target data.
164 Info.addRequired<TargetData>();
165 }
166
167 /// For this pass, process all of the function calls in the module, calling
168 /// ValidateLibraryCall and OptimizeCall as appropriate.
Reid Spencer716f49e2005-04-27 21:29:20 +0000169 /// @brief Run all the lib call optimizations on a Module.
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000170 virtual bool runOnModule(Module &M) {
Reid Spencera16d5a52005-04-27 07:54:40 +0000171 reset(M);
172
173 bool result = false;
Chris Lattnere05cf712006-01-22 23:10:26 +0000174 hash_map<std::string, LibCallOptimization*> OptznMap;
175 for (LibCallOptimization *Optzn = OptList; Optzn; Optzn = Optzn->getNext())
176 OptznMap[Optzn->getFunctionName()] = Optzn;
Reid Spencera16d5a52005-04-27 07:54:40 +0000177
178 // The call optimizations can be recursive. That is, the optimization might
179 // generate a call to another function which can also be optimized. This way
Jeff Cohen00b168892005-07-27 06:12:32 +0000180 // we make the LibCallOptimization instances very specific to the case they
181 // handle. It also means we need to keep running over the function calls in
Reid Spencera16d5a52005-04-27 07:54:40 +0000182 // the module until we don't get any more optimizations possible.
183 bool found_optimization = false;
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000184 do {
Reid Spencera16d5a52005-04-27 07:54:40 +0000185 found_optimization = false;
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000186 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Reid Spencera16d5a52005-04-27 07:54:40 +0000187 // All the "well-known" functions are external and have external linkage
Jeff Cohen00b168892005-07-27 06:12:32 +0000188 // because they live in a runtime library somewhere and were (probably)
189 // not compiled by LLVM. So, we only act on external functions that
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000190 // have external or dllimport linkage and non-empty uses.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000191 if (!FI->isDeclaration() ||
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000192 !(FI->hasExternalLinkage() || FI->hasDLLImportLinkage()) ||
193 FI->use_empty())
Reid Spencera16d5a52005-04-27 07:54:40 +0000194 continue;
195
196 // Get the optimization class that pertains to this function
Chris Lattnere05cf712006-01-22 23:10:26 +0000197 hash_map<std::string, LibCallOptimization*>::iterator OMI =
198 OptznMap.find(FI->getName());
199 if (OMI == OptznMap.end()) continue;
200
201 LibCallOptimization *CO = OMI->second;
Reid Spencera16d5a52005-04-27 07:54:40 +0000202
203 // Make sure the called function is suitable for the optimization
Chris Lattnere05cf712006-01-22 23:10:26 +0000204 if (!CO->ValidateCalledFunction(FI, *this))
Reid Spencera16d5a52005-04-27 07:54:40 +0000205 continue;
206
207 // Loop over each of the uses of the function
Jeff Cohen00b168892005-07-27 06:12:32 +0000208 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000209 UI != UE ; ) {
Reid Spencera16d5a52005-04-27 07:54:40 +0000210 // If the use of the function is a call instruction
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000211 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
Reid Spencera16d5a52005-04-27 07:54:40 +0000212 // Do the optimization on the LibCallOptimization.
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000213 if (CO->OptimizeCall(CI, *this)) {
Reid Spencera16d5a52005-04-27 07:54:40 +0000214 ++SimplifiedLibCalls;
215 found_optimization = result = true;
Reid Spencer716f49e2005-04-27 21:29:20 +0000216 CO->succeeded();
Reid Spencera16d5a52005-04-27 07:54:40 +0000217 }
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000218 }
219 }
220 }
Reid Spencera16d5a52005-04-27 07:54:40 +0000221 } while (found_optimization);
Chris Lattnere05cf712006-01-22 23:10:26 +0000222
Reid Spencera16d5a52005-04-27 07:54:40 +0000223 return result;
224 }
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000225
Reid Spencera16d5a52005-04-27 07:54:40 +0000226 /// @brief Return the *current* module we're working on.
Reid Spencerff5525d2005-04-29 09:39:47 +0000227 Module* getModule() const { return M; }
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000228
Reid Spencera16d5a52005-04-27 07:54:40 +0000229 /// @brief Return the *current* target data for the module we're working on.
Reid Spencerff5525d2005-04-29 09:39:47 +0000230 TargetData* getTargetData() const { return TD; }
231
232 /// @brief Return the size_t type -- syntactic shortcut
233 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
234
Evan Cheng21abac22006-06-16 08:36:35 +0000235 /// @brief Return a Function* for the putchar libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000236 Constant *get_putchar() {
Evan Cheng21abac22006-06-16 08:36:35 +0000237 if (!putchar_func)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000238 putchar_func =
239 M->getOrInsertFunction("putchar", Type::Int32Ty, Type::Int32Ty, NULL);
Evan Cheng21abac22006-06-16 08:36:35 +0000240 return putchar_func;
241 }
242
243 /// @brief Return a Function* for the puts libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000244 Constant *get_puts() {
Evan Cheng21abac22006-06-16 08:36:35 +0000245 if (!puts_func)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000246 puts_func = M->getOrInsertFunction("puts", Type::Int32Ty,
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000247 PointerType::getUnqual(Type::Int8Ty),
Evan Cheng21abac22006-06-16 08:36:35 +0000248 NULL);
249 return puts_func;
250 }
251
Reid Spencerff5525d2005-04-29 09:39:47 +0000252 /// @brief Return a Function* for the fputc libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000253 Constant *get_fputc(const Type* FILEptr_type) {
Reid Spencerff5525d2005-04-29 09:39:47 +0000254 if (!fputc_func)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000255 fputc_func = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000256 FILEptr_type, NULL);
Reid Spencerff5525d2005-04-29 09:39:47 +0000257 return fputc_func;
258 }
259
Evan Cheng95289522006-06-16 04:52:30 +0000260 /// @brief Return a Function* for the fputs libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000261 Constant *get_fputs(const Type* FILEptr_type) {
Evan Cheng95289522006-06-16 04:52:30 +0000262 if (!fputs_func)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000263 fputs_func = M->getOrInsertFunction("fputs", Type::Int32Ty,
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000264 PointerType::getUnqual(Type::Int8Ty),
Evan Cheng95289522006-06-16 04:52:30 +0000265 FILEptr_type, NULL);
266 return fputs_func;
267 }
268
Reid Spencerff5525d2005-04-29 09:39:47 +0000269 /// @brief Return a Function* for the fwrite libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000270 Constant *get_fwrite(const Type* FILEptr_type) {
Reid Spencerff5525d2005-04-29 09:39:47 +0000271 if (!fwrite_func)
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000272 fwrite_func = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000273 PointerType::getUnqual(Type::Int8Ty),
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000274 TD->getIntPtrType(),
275 TD->getIntPtrType(),
276 FILEptr_type, NULL);
Reid Spencerff5525d2005-04-29 09:39:47 +0000277 return fwrite_func;
278 }
279
280 /// @brief Return a Function* for the sqrt libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000281 Constant *get_sqrt() {
Reid Spencerff5525d2005-04-29 09:39:47 +0000282 if (!sqrt_func)
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000283 sqrt_func = M->getOrInsertFunction("sqrt", Type::DoubleTy,
284 Type::DoubleTy, NULL);
Reid Spencerff5525d2005-04-29 09:39:47 +0000285 return sqrt_func;
286 }
Reid Spencera16d5a52005-04-27 07:54:40 +0000287
Owen Andersonf4d5de42007-01-20 10:07:23 +0000288 /// @brief Return a Function* for the strcpy libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000289 Constant *get_strcpy() {
Reid Spencer58b563c2005-05-04 03:20:21 +0000290 if (!strcpy_func)
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000291 strcpy_func = M->getOrInsertFunction("strcpy",
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000292 PointerType::getUnqual(Type::Int8Ty),
293 PointerType::getUnqual(Type::Int8Ty),
294 PointerType::getUnqual(Type::Int8Ty),
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000295 NULL);
Reid Spencer58b563c2005-05-04 03:20:21 +0000296 return strcpy_func;
297 }
298
299 /// @brief Return a Function* for the strlen libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000300 Constant *get_strlen() {
Reid Spencera16d5a52005-04-27 07:54:40 +0000301 if (!strlen_func)
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000302 strlen_func = M->getOrInsertFunction("strlen", TD->getIntPtrType(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000303 PointerType::getUnqual(Type::Int8Ty),
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000304 NULL);
Reid Spencera16d5a52005-04-27 07:54:40 +0000305 return strlen_func;
Reid Spencer43e0bae2005-04-26 03:26:15 +0000306 }
307
Reid Spencer21506ff2005-05-03 07:23:44 +0000308 /// @brief Return a Function* for the memchr libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000309 Constant *get_memchr() {
Reid Spencer21506ff2005-05-03 07:23:44 +0000310 if (!memchr_func)
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000311 memchr_func = M->getOrInsertFunction("memchr",
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000312 PointerType::getUnqual(Type::Int8Ty),
313 PointerType::getUnqual(Type::Int8Ty),
Reid Spencerc5b206b2006-12-31 05:48:39 +0000314 Type::Int32Ty, TD->getIntPtrType(),
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000315 NULL);
Reid Spencer21506ff2005-05-03 07:23:44 +0000316 return memchr_func;
317 }
318
Reid Spencera16d5a52005-04-27 07:54:40 +0000319 /// @brief Return a Function* for the memcpy libcall
Chris Lattnerb76efb72007-01-07 08:12:01 +0000320 Constant *get_memcpy() {
Chris Lattner53249862005-08-24 17:22:17 +0000321 if (!memcpy_func) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000322 const Type *SBP = PointerType::getUnqual(Type::Int8Ty);
Reid Spencerc5b206b2006-12-31 05:48:39 +0000323 const char *N = TD->getIntPtrType() == Type::Int32Ty ?
Chris Lattneraecb0622006-03-03 01:30:23 +0000324 "llvm.memcpy.i32" : "llvm.memcpy.i64";
325 memcpy_func = M->getOrInsertFunction(N, Type::VoidTy, SBP, SBP,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000326 TD->getIntPtrType(), Type::Int32Ty,
Chris Lattneraecb0622006-03-03 01:30:23 +0000327 NULL);
Reid Spencer43e0bae2005-04-26 03:26:15 +0000328 }
Reid Spencera16d5a52005-04-27 07:54:40 +0000329 return memcpy_func;
Reid Spencer43e0bae2005-04-26 03:26:15 +0000330 }
Reid Spencer912401c2005-04-26 05:24:00 +0000331
Chris Lattnerb76efb72007-01-07 08:12:01 +0000332 Constant *getUnaryFloatFunction(const char *Name, Constant *&Cache) {
Chris Lattnere46f6e92006-01-23 06:24:46 +0000333 if (!Cache)
334 Cache = M->getOrInsertFunction(Name, Type::FloatTy, Type::FloatTy, NULL);
335 return Cache;
Chris Lattner53249862005-08-24 17:22:17 +0000336 }
337
Chris Lattnerb76efb72007-01-07 08:12:01 +0000338 Constant *get_floorf() { return getUnaryFloatFunction("floorf", floorf_func);}
339 Constant *get_ceilf() { return getUnaryFloatFunction( "ceilf", ceilf_func);}
340 Constant *get_roundf() { return getUnaryFloatFunction("roundf", roundf_func);}
341 Constant *get_rintf() { return getUnaryFloatFunction( "rintf", rintf_func);}
342 Constant *get_nearbyintf() { return getUnaryFloatFunction("nearbyintf",
Chris Lattnere46f6e92006-01-23 06:24:46 +0000343 nearbyintf_func); }
Reid Spencera16d5a52005-04-27 07:54:40 +0000344private:
Reid Spencer716f49e2005-04-27 21:29:20 +0000345 /// @brief Reset our cached data for a new Module
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000346 void reset(Module& mod) {
Reid Spencera16d5a52005-04-27 07:54:40 +0000347 M = &mod;
348 TD = &getAnalysis<TargetData>();
Evan Cheng21abac22006-06-16 08:36:35 +0000349 putchar_func = 0;
350 puts_func = 0;
Reid Spencerff5525d2005-04-29 09:39:47 +0000351 fputc_func = 0;
Evan Cheng95289522006-06-16 04:52:30 +0000352 fputs_func = 0;
Reid Spencerff5525d2005-04-29 09:39:47 +0000353 fwrite_func = 0;
Reid Spencera16d5a52005-04-27 07:54:40 +0000354 memcpy_func = 0;
Reid Spencer21506ff2005-05-03 07:23:44 +0000355 memchr_func = 0;
Reid Spencerff5525d2005-04-29 09:39:47 +0000356 sqrt_func = 0;
Reid Spencer58b563c2005-05-04 03:20:21 +0000357 strcpy_func = 0;
Reid Spencera16d5a52005-04-27 07:54:40 +0000358 strlen_func = 0;
Chris Lattner53249862005-08-24 17:22:17 +0000359 floorf_func = 0;
Chris Lattnere46f6e92006-01-23 06:24:46 +0000360 ceilf_func = 0;
361 roundf_func = 0;
362 rintf_func = 0;
363 nearbyintf_func = 0;
Reid Spencer912401c2005-04-26 05:24:00 +0000364 }
Reid Spencera7c049b2005-04-25 02:53:12 +0000365
Reid Spencera16d5a52005-04-27 07:54:40 +0000366private:
Chris Lattnere46f6e92006-01-23 06:24:46 +0000367 /// Caches for function pointers.
Chris Lattnerb76efb72007-01-07 08:12:01 +0000368 Constant *putchar_func, *puts_func;
369 Constant *fputc_func, *fputs_func, *fwrite_func;
370 Constant *memcpy_func, *memchr_func;
371 Constant *sqrt_func;
372 Constant *strcpy_func, *strlen_func;
373 Constant *floorf_func, *ceilf_func, *roundf_func;
374 Constant *rintf_func, *nearbyintf_func;
Chris Lattnere46f6e92006-01-23 06:24:46 +0000375 Module *M; ///< Cached Module
376 TargetData *TD; ///< Cached TargetData
Reid Spencera16d5a52005-04-27 07:54:40 +0000377};
378
Devang Patel19974732007-05-03 01:11:54 +0000379char SimplifyLibCalls::ID = 0;
Reid Spencera16d5a52005-04-27 07:54:40 +0000380// Register the pass
Chris Lattner7f8897f2006-08-27 22:42:52 +0000381RegisterPass<SimplifyLibCalls>
382X("simplify-libcalls", "Simplify well-known library calls");
Reid Spencera16d5a52005-04-27 07:54:40 +0000383
384} // anonymous namespace
385
386// The only public symbol in this file which just instantiates the pass object
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000387ModulePass *llvm::createSimplifyLibCallsPass() {
Jeff Cohen00b168892005-07-27 06:12:32 +0000388 return new SimplifyLibCalls();
Reid Spencera16d5a52005-04-27 07:54:40 +0000389}
390
391// Classes below here, in the anonymous namespace, are all subclasses of the
392// LibCallOptimization class, each implementing all optimizations possible for a
393// single well-known library call. Each has a static singleton instance that
Jeff Cohen00b168892005-07-27 06:12:32 +0000394// auto registers it into the "optlist" global above.
Reid Spencera16d5a52005-04-27 07:54:40 +0000395namespace {
396
Reid Spencer134d2e42005-06-18 17:46:28 +0000397// Forward declare utility functions.
Chris Lattner0cd3a232007-04-07 21:58:02 +0000398static bool GetConstantStringInfo(Value *V, std::string &Str);
Chris Lattner3492cda2007-04-07 21:04:50 +0000399static Value *CastToCStr(Value *V, Instruction *IP);
Reid Spencera16d5a52005-04-27 07:54:40 +0000400
401/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencera7c049b2005-04-25 02:53:12 +0000402/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer716f49e2005-04-27 21:29:20 +0000403/// the same value passed to the exit function. When this is done, it splits the
404/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencera7c049b2005-04-25 02:53:12 +0000405/// @brief Replace calls to exit in main with a simple return
Reid Spencer9133fe22007-02-05 23:32:05 +0000406struct VISIBILITY_HIDDEN ExitInMainOptimization : public LibCallOptimization {
Reid Spencer9974dda2005-05-03 02:54:54 +0000407 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer789082a2005-05-07 20:15:59 +0000408 "Number of 'exit' calls simplified") {}
Reid Spencer6cc03112005-04-25 21:11:48 +0000409
410 // Make sure the called function looks like exit (int argument, int return
Jeff Cohen00b168892005-07-27 06:12:32 +0000411 // type, external linkage, not varargs).
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000412 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner42a75512007-01-15 02:27:26 +0000413 return F->arg_size() >= 1 && F->arg_begin()->getType()->isInteger();
Reid Spencer6cc03112005-04-25 21:11:48 +0000414 }
415
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000416 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
Reid Spencer6cc03112005-04-25 21:11:48 +0000417 // To be careful, we check that the call to exit is coming from "main", that
418 // main has external linkage, and the return type of main and the argument
Jeff Cohen00b168892005-07-27 06:12:32 +0000419 // to exit have the same type.
Reid Spencer6cc03112005-04-25 21:11:48 +0000420 Function *from = ci->getParent()->getParent();
421 if (from->hasExternalLinkage())
422 if (from->getReturnType() == ci->getOperand(1)->getType())
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000423 if (from->getName() == "main") {
Jeff Cohen00b168892005-07-27 06:12:32 +0000424 // Okay, time to actually do the optimization. First, get the basic
Reid Spencer6cc03112005-04-25 21:11:48 +0000425 // block of the call instruction
426 BasicBlock* bb = ci->getParent();
Reid Spencera7c049b2005-04-25 02:53:12 +0000427
Jeff Cohen00b168892005-07-27 06:12:32 +0000428 // Create a return instruction that we'll replace the call with.
429 // Note that the argument of the return is the argument of the call
Reid Spencer6cc03112005-04-25 21:11:48 +0000430 // instruction.
Chris Lattner2144c252006-05-12 23:35:26 +0000431 new ReturnInst(ci->getOperand(1), ci);
Reid Spencera7c049b2005-04-25 02:53:12 +0000432
Reid Spencer6cc03112005-04-25 21:11:48 +0000433 // Split the block at the call instruction which places it in a new
434 // basic block.
Reid Spencer43e0bae2005-04-26 03:26:15 +0000435 bb->splitBasicBlock(ci);
Reid Spencera7c049b2005-04-25 02:53:12 +0000436
Reid Spencer6cc03112005-04-25 21:11:48 +0000437 // The block split caused a branch instruction to be inserted into
438 // the end of the original block, right after the return instruction
439 // that we put there. That's not a valid block, so delete the branch
440 // instruction.
Reid Spencer43e0bae2005-04-26 03:26:15 +0000441 bb->getInstList().pop_back();
Reid Spencera7c049b2005-04-25 02:53:12 +0000442
Reid Spencer6cc03112005-04-25 21:11:48 +0000443 // Now we can finally get rid of the call instruction which now lives
444 // in the new basic block.
445 ci->eraseFromParent();
446
447 // Optimization succeeded, return true.
448 return true;
449 }
450 // We didn't pass the criteria for this optimization so return false
451 return false;
Reid Spencerb7c11e32005-04-25 03:59:26 +0000452 }
Reid Spencera7c049b2005-04-25 02:53:12 +0000453} ExitInMainOptimizer;
454
Jeff Cohen00b168892005-07-27 06:12:32 +0000455/// This LibCallOptimization will simplify a call to the strcat library
456/// function. The simplification is possible only if the string being
457/// concatenated is a constant array or a constant expression that results in
458/// a constant string. In this case we can replace it with strlen + llvm.memcpy
Reid Spencer716f49e2005-04-27 21:29:20 +0000459/// of the constant string. Both of these calls are further reduced, if possible
460/// on subsequent passes.
Reid Spencer6cc03112005-04-25 21:11:48 +0000461/// @brief Simplify the strcat library function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000462struct VISIBILITY_HIDDEN StrCatOptimization : public LibCallOptimization {
Reid Spencer43e0bae2005-04-26 03:26:15 +0000463public:
Reid Spencer716f49e2005-04-27 21:29:20 +0000464 /// @brief Default constructor
Reid Spencer9974dda2005-05-03 02:54:54 +0000465 StrCatOptimization() : LibCallOptimization("strcat",
Reid Spencer789082a2005-05-07 20:15:59 +0000466 "Number of 'strcat' calls simplified") {}
Reid Spencera16d5a52005-04-27 07:54:40 +0000467
468public:
Reid Spencer6cc03112005-04-25 21:11:48 +0000469
470 /// @brief Make sure that the "strcat" function has the right prototype
Chris Lattner0cd3a232007-04-07 21:58:02 +0000471 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
472 const FunctionType *FT = F->getFunctionType();
473 return FT->getNumParams() == 2 &&
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000474 FT->getReturnType() == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner0cd3a232007-04-07 21:58:02 +0000475 FT->getParamType(0) == FT->getReturnType() &&
476 FT->getParamType(1) == FT->getReturnType();
Reid Spencer6cc03112005-04-25 21:11:48 +0000477 }
478
Reid Spencera16d5a52005-04-27 07:54:40 +0000479 /// @brief Optimize the strcat library function
Chris Lattner09c11aa2007-04-06 22:59:33 +0000480 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer3f7d8c62005-04-27 17:46:54 +0000481 // Extract some information from the instruction
Chris Lattner09c11aa2007-04-06 22:59:33 +0000482 Value *Dst = CI->getOperand(1);
483 Value *Src = CI->getOperand(2);
Reid Spencer3f7d8c62005-04-27 17:46:54 +0000484
Jeff Cohen00b168892005-07-27 06:12:32 +0000485 // Extract the initializer (while making numerous checks) from the
Chris Lattner09c11aa2007-04-06 22:59:33 +0000486 // source operand of the call to strcat.
Chris Lattner0cd3a232007-04-07 21:58:02 +0000487 std::string SrcStr;
488 if (!GetConstantStringInfo(Src, SrcStr))
Reid Spencer43e0bae2005-04-26 03:26:15 +0000489 return false;
490
Reid Spencer20754ac2005-04-26 07:45:18 +0000491 // Handle the simple, do-nothing case
Chris Lattner0cd3a232007-04-07 21:58:02 +0000492 if (SrcStr.empty())
Chris Lattner679d7182007-04-07 00:42:32 +0000493 return ReplaceCallWith(CI, Dst);
Reid Spencer43e0bae2005-04-26 03:26:15 +0000494
Jeff Cohen00b168892005-07-27 06:12:32 +0000495 // We need to find the end of the destination string. That's where the
Chris Lattner0cd3a232007-04-07 21:58:02 +0000496 // memory is to be moved to. We just generate a call to strlen.
Chris Lattner09c11aa2007-04-06 22:59:33 +0000497 CallInst *DstLen = new CallInst(SLC.get_strlen(), Dst,
498 Dst->getName()+".len", CI);
Reid Spencer20754ac2005-04-26 07:45:18 +0000499
Jeff Cohen00b168892005-07-27 06:12:32 +0000500 // Now that we have the destination's length, we must index into the
Reid Spencer20754ac2005-04-26 07:45:18 +0000501 // destination's pointer to get the actual memcpy destination (end of
502 // the string .. we're concatenating).
Chris Lattner09c11aa2007-04-06 22:59:33 +0000503 Dst = new GetElementPtrInst(Dst, DstLen, Dst->getName()+".indexed", CI);
Reid Spencer20754ac2005-04-26 07:45:18 +0000504
505 // We have enough information to now generate the memcpy call to
506 // do the concatenation for us.
Chris Lattner09c11aa2007-04-06 22:59:33 +0000507 Value *Vals[] = {
508 Dst, Src,
Chris Lattner0cd3a232007-04-07 21:58:02 +0000509 ConstantInt::get(SLC.getIntPtrType(), SrcStr.size()+1), // copy nul byte.
Chris Lattner09c11aa2007-04-06 22:59:33 +0000510 ConstantInt::get(Type::Int32Ty, 1) // alignment
511 };
David Greene52eec542007-08-01 03:43:44 +0000512 new CallInst(SLC.get_memcpy(), Vals, Vals + 4, "", CI);
Reid Spencer20754ac2005-04-26 07:45:18 +0000513
Chris Lattner679d7182007-04-07 00:42:32 +0000514 return ReplaceCallWith(CI, Dst);
Reid Spencerb7c11e32005-04-25 03:59:26 +0000515 }
516} StrCatOptimizer;
517
Jeff Cohen00b168892005-07-27 06:12:32 +0000518/// This LibCallOptimization will simplify a call to the strchr library
Reid Spencer21506ff2005-05-03 07:23:44 +0000519/// function. It optimizes out cases where the arguments are both constant
520/// and the result can be determined statically.
521/// @brief Simplify the strcmp library function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000522struct VISIBILITY_HIDDEN StrChrOptimization : public LibCallOptimization {
Reid Spencer21506ff2005-05-03 07:23:44 +0000523public:
524 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer789082a2005-05-07 20:15:59 +0000525 "Number of 'strchr' calls simplified") {}
Reid Spencer21506ff2005-05-03 07:23:44 +0000526
527 /// @brief Make sure that the "strchr" function has the right prototype
Chris Lattner6897fe52007-04-06 23:38:55 +0000528 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
529 const FunctionType *FT = F->getFunctionType();
530 return FT->getNumParams() == 2 &&
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000531 FT->getReturnType() == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner6897fe52007-04-06 23:38:55 +0000532 FT->getParamType(0) == FT->getReturnType() &&
533 isa<IntegerType>(FT->getParamType(1));
Reid Spencer21506ff2005-05-03 07:23:44 +0000534 }
535
Chris Lattner93751352005-05-20 22:22:25 +0000536 /// @brief Perform the strchr optimizations
Chris Lattner6897fe52007-04-06 23:38:55 +0000537 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer21506ff2005-05-03 07:23:44 +0000538 // Check that the first argument to strchr is a constant array of sbyte.
Chris Lattner0cd3a232007-04-07 21:58:02 +0000539 std::string Str;
540 if (!GetConstantStringInfo(CI->getOperand(1), Str))
Reid Spencer21506ff2005-05-03 07:23:44 +0000541 return false;
542
Chris Lattner6897fe52007-04-06 23:38:55 +0000543 // If the second operand is not constant, just lower this to memchr since we
544 // know the length of the input string.
545 ConstantInt *CSI = dyn_cast<ConstantInt>(CI->getOperand(2));
Reid Spencerc5b206b2006-12-31 05:48:39 +0000546 if (!CSI) {
Chris Lattner6897fe52007-04-06 23:38:55 +0000547 Value *Args[3] = {
548 CI->getOperand(1),
549 CI->getOperand(2),
Chris Lattner0cd3a232007-04-07 21:58:02 +0000550 ConstantInt::get(SLC.getIntPtrType(), Str.size()+1)
Chris Lattnerc18470c2007-02-13 05:58:53 +0000551 };
David Greene52eec542007-08-01 03:43:44 +0000552 return ReplaceCallWith(CI, new CallInst(SLC.get_memchr(), Args, Args + 3,
Chris Lattner679d7182007-04-07 00:42:32 +0000553 CI->getName(), CI));
Reid Spencer21506ff2005-05-03 07:23:44 +0000554 }
555
Chris Lattner0cd3a232007-04-07 21:58:02 +0000556 // strchr can find the nul character.
557 Str += '\0';
Chris Lattner6897fe52007-04-06 23:38:55 +0000558
Chris Lattner0cd3a232007-04-07 21:58:02 +0000559 // Get the character we're looking for
560 char CharValue = CSI->getSExtValue();
561
Reid Spencer21506ff2005-05-03 07:23:44 +0000562 // Compute the offset
Chris Lattner6897fe52007-04-06 23:38:55 +0000563 uint64_t i = 0;
564 while (1) {
Chris Lattner0cd3a232007-04-07 21:58:02 +0000565 if (i == Str.size()) // Didn't find the char. strchr returns null.
566 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
567 // Did we find our match?
568 if (Str[i] == CharValue)
569 break;
Chris Lattner6897fe52007-04-06 23:38:55 +0000570 ++i;
Reid Spencer21506ff2005-05-03 07:23:44 +0000571 }
572
Chris Lattner6897fe52007-04-06 23:38:55 +0000573 // strchr(s+n,c) -> gep(s+n+i,c)
Reid Spencer21506ff2005-05-03 07:23:44 +0000574 // (if c is a constant integer and s is a constant string)
Chris Lattner6897fe52007-04-06 23:38:55 +0000575 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
576 Value *GEP = new GetElementPtrInst(CI->getOperand(1), Idx,
577 CI->getOperand(1)->getName() +
578 ".strchr", CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000579 return ReplaceCallWith(CI, GEP);
Reid Spencer21506ff2005-05-03 07:23:44 +0000580 }
581} StrChrOptimizer;
582
Jeff Cohen00b168892005-07-27 06:12:32 +0000583/// This LibCallOptimization will simplify a call to the strcmp library
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000584/// function. It optimizes out cases where one or both arguments are constant
585/// and the result can be determined statically.
586/// @brief Simplify the strcmp library function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000587struct VISIBILITY_HIDDEN StrCmpOptimization : public LibCallOptimization {
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000588public:
Reid Spencer9974dda2005-05-03 02:54:54 +0000589 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer789082a2005-05-07 20:15:59 +0000590 "Number of 'strcmp' calls simplified") {}
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000591
Chris Lattner93751352005-05-20 22:22:25 +0000592 /// @brief Make sure that the "strcmp" function has the right prototype
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000593 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattnerceb375e2007-04-07 00:01:51 +0000594 const FunctionType *FT = F->getFunctionType();
595 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 2 &&
596 FT->getParamType(0) == FT->getParamType(1) &&
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000597 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty);
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000598 }
599
Chris Lattner93751352005-05-20 22:22:25 +0000600 /// @brief Perform the strcmp optimization
Chris Lattnerceb375e2007-04-07 00:01:51 +0000601 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000602 // First, check to see if src and destination are the same. If they are,
Reid Spencer63a75132005-04-30 06:45:47 +0000603 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen00b168892005-07-27 06:12:32 +0000604 // because the call is a no-op.
Chris Lattnerceb375e2007-04-07 00:01:51 +0000605 Value *Str1P = CI->getOperand(1);
606 Value *Str2P = CI->getOperand(2);
Chris Lattner679d7182007-04-07 00:42:32 +0000607 if (Str1P == Str2P) // strcmp(x,x) -> 0
608 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000609
Chris Lattner0cd3a232007-04-07 21:58:02 +0000610 std::string Str1;
611 if (!GetConstantStringInfo(Str1P, Str1))
612 return false;
613 if (Str1.empty()) {
Chris Lattnerceb375e2007-04-07 00:01:51 +0000614 // strcmp("", x) -> *x
615 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
616 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000617 return ReplaceCallWith(CI, V);
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000618 }
619
Chris Lattner0cd3a232007-04-07 21:58:02 +0000620 std::string Str2;
621 if (!GetConstantStringInfo(Str2P, Str2))
622 return false;
623 if (Str2.empty()) {
Chris Lattnerceb375e2007-04-07 00:01:51 +0000624 // strcmp(x,"") -> *x
625 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
626 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000627 return ReplaceCallWith(CI, V);
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000628 }
629
Chris Lattner0cd3a232007-04-07 21:58:02 +0000630 // strcmp(x, y) -> cnst (if both x and y are constant strings)
631 int R = strcmp(Str1.c_str(), Str2.c_str());
632 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencer9f56b1f2005-04-30 03:17:54 +0000633 }
634} StrCmpOptimizer;
635
Jeff Cohen00b168892005-07-27 06:12:32 +0000636/// This LibCallOptimization will simplify a call to the strncmp library
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000637/// function. It optimizes out cases where one or both arguments are constant
638/// and the result can be determined statically.
639/// @brief Simplify the strncmp library function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000640struct VISIBILITY_HIDDEN StrNCmpOptimization : public LibCallOptimization {
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000641public:
Reid Spencer9974dda2005-05-03 02:54:54 +0000642 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer789082a2005-05-07 20:15:59 +0000643 "Number of 'strncmp' calls simplified") {}
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000644
Chris Lattner93751352005-05-20 22:22:25 +0000645 /// @brief Make sure that the "strncmp" function has the right prototype
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000646 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
647 const FunctionType *FT = F->getFunctionType();
648 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 3 &&
649 FT->getParamType(0) == FT->getParamType(1) &&
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000650 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000651 isa<IntegerType>(FT->getParamType(2));
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000652 return false;
653 }
654
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000655 /// @brief Perform the strncmp optimization
656 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000657 // First, check to see if src and destination are the same. If they are,
658 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen00b168892005-07-27 06:12:32 +0000659 // because the call is a no-op.
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000660 Value *Str1P = CI->getOperand(1);
661 Value *Str2P = CI->getOperand(2);
Chris Lattner0cd3a232007-04-07 21:58:02 +0000662 if (Str1P == Str2P) // strncmp(x,x, n) -> 0
Chris Lattner679d7182007-04-07 00:42:32 +0000663 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000664
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000665 // Check the length argument, if it is Constant zero then the strings are
666 // considered equal.
Chris Lattnerdb895b82007-04-07 00:26:18 +0000667 uint64_t Length;
668 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
669 Length = LengthArg->getZExtValue();
670 else
671 return false;
672
Chris Lattner0cd3a232007-04-07 21:58:02 +0000673 if (Length == 0) // strncmp(x,y,0) -> 0
Chris Lattner679d7182007-04-07 00:42:32 +0000674 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000675
Chris Lattner0cd3a232007-04-07 21:58:02 +0000676 std::string Str1;
677 if (!GetConstantStringInfo(Str1P, Str1))
678 return false;
679 if (Str1.empty()) {
680 // strncmp("", x, n) -> *x
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000681 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
682 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000683 return ReplaceCallWith(CI, V);
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000684 }
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000685
Chris Lattner0cd3a232007-04-07 21:58:02 +0000686 std::string Str2;
687 if (!GetConstantStringInfo(Str2P, Str2))
688 return false;
689 if (Str2.empty()) {
690 // strncmp(x, "", n) -> *x
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000691 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
692 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000693 return ReplaceCallWith(CI, V);
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000694 }
Chris Lattner7b50c8f2007-04-07 00:06:57 +0000695
Chris Lattner0cd3a232007-04-07 21:58:02 +0000696 // strncmp(x, y, n) -> cnst (if both x and y are constant strings)
697 int R = strncmp(Str1.c_str(), Str2.c_str(), Length);
698 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencere6ec8cc2005-05-03 01:43:45 +0000699 }
700} StrNCmpOptimizer;
701
Jeff Cohen00b168892005-07-27 06:12:32 +0000702/// This LibCallOptimization will simplify a call to the strcpy library
703/// function. Two optimizations are possible:
Reid Spencera16d5a52005-04-27 07:54:40 +0000704/// (1) If src and dest are the same and not volatile, just return dest
705/// (2) If the src is a constant then we can convert to llvm.memmove
706/// @brief Simplify the strcpy library function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000707struct VISIBILITY_HIDDEN StrCpyOptimization : public LibCallOptimization {
Reid Spencera16d5a52005-04-27 07:54:40 +0000708public:
Reid Spencer9974dda2005-05-03 02:54:54 +0000709 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer789082a2005-05-07 20:15:59 +0000710 "Number of 'strcpy' calls simplified") {}
Reid Spencera16d5a52005-04-27 07:54:40 +0000711
712 /// @brief Make sure that the "strcpy" function has the right prototype
Chris Lattnerdb895b82007-04-07 00:26:18 +0000713 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
714 const FunctionType *FT = F->getFunctionType();
715 return FT->getNumParams() == 2 &&
716 FT->getParamType(0) == FT->getParamType(1) &&
717 FT->getReturnType() == FT->getParamType(0) &&
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000718 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty);
Reid Spencera16d5a52005-04-27 07:54:40 +0000719 }
720
721 /// @brief Perform the strcpy optimization
Chris Lattnerdb895b82007-04-07 00:26:18 +0000722 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencera16d5a52005-04-27 07:54:40 +0000723 // First, check to see if src and destination are the same. If they are,
724 // then the optimization is to replace the CallInst with the destination
Jeff Cohen00b168892005-07-27 06:12:32 +0000725 // because the call is a no-op. Note that this corresponds to the
Reid Spencera16d5a52005-04-27 07:54:40 +0000726 // degenerate strcpy(X,X) case which should have "undefined" results
727 // according to the C specification. However, it occurs sometimes and
728 // we optimize it as a no-op.
Chris Lattnerdb895b82007-04-07 00:26:18 +0000729 Value *Dst = CI->getOperand(1);
730 Value *Src = CI->getOperand(2);
731 if (Dst == Src) {
732 // strcpy(x, x) -> x
Chris Lattner679d7182007-04-07 00:42:32 +0000733 return ReplaceCallWith(CI, Dst);
Reid Spencera16d5a52005-04-27 07:54:40 +0000734 }
Chris Lattnerdb895b82007-04-07 00:26:18 +0000735
736 // Get the length of the constant string referenced by the Src operand.
Chris Lattner0cd3a232007-04-07 21:58:02 +0000737 std::string SrcStr;
738 if (!GetConstantStringInfo(Src, SrcStr))
Reid Spencera16d5a52005-04-27 07:54:40 +0000739 return false;
Chris Lattner0cd3a232007-04-07 21:58:02 +0000740
Reid Spencera16d5a52005-04-27 07:54:40 +0000741 // If the constant string's length is zero we can optimize this by just
742 // doing a store of 0 at the first byte of the destination
Chris Lattner0cd3a232007-04-07 21:58:02 +0000743 if (SrcStr.size() == 0) {
Chris Lattnerdb895b82007-04-07 00:26:18 +0000744 new StoreInst(ConstantInt::get(Type::Int8Ty, 0), Dst, CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000745 return ReplaceCallWith(CI, Dst);
Reid Spencera16d5a52005-04-27 07:54:40 +0000746 }
747
Reid Spencera16d5a52005-04-27 07:54:40 +0000748 // We have enough information to now generate the memcpy call to
749 // do the concatenation for us.
Chris Lattnerdb895b82007-04-07 00:26:18 +0000750 Value *MemcpyOps[] = {
Chris Lattner0cd3a232007-04-07 21:58:02 +0000751 Dst, Src, // Pass length including nul byte.
752 ConstantInt::get(SLC.getIntPtrType(), SrcStr.size()+1),
Chris Lattnerc18470c2007-02-13 05:58:53 +0000753 ConstantInt::get(Type::Int32Ty, 1) // alignment
754 };
David Greene52eec542007-08-01 03:43:44 +0000755 new CallInst(SLC.get_memcpy(), MemcpyOps, MemcpyOps + 4, "", CI);
Reid Spencera16d5a52005-04-27 07:54:40 +0000756
Chris Lattner679d7182007-04-07 00:42:32 +0000757 return ReplaceCallWith(CI, Dst);
Reid Spencera16d5a52005-04-27 07:54:40 +0000758 }
759} StrCpyOptimizer;
760
Jeff Cohen00b168892005-07-27 06:12:32 +0000761/// This LibCallOptimization will simplify a call to the strlen library
762/// function by replacing it with a constant value if the string provided to
Reid Spencer716f49e2005-04-27 21:29:20 +0000763/// it is a constant array.
Reid Spencer912401c2005-04-26 05:24:00 +0000764/// @brief Simplify the strlen library function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000765struct VISIBILITY_HIDDEN StrLenOptimization : public LibCallOptimization {
Reid Spencer9974dda2005-05-03 02:54:54 +0000766 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer789082a2005-05-07 20:15:59 +0000767 "Number of 'strlen' calls simplified") {}
Reid Spencer912401c2005-04-26 05:24:00 +0000768
769 /// @brief Make sure that the "strlen" function has the right prototype
Chris Lattnerdb895b82007-04-07 00:26:18 +0000770 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner71bf3e22007-04-07 01:02:00 +0000771 const FunctionType *FT = F->getFunctionType();
772 return FT->getNumParams() == 1 &&
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000773 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner71bf3e22007-04-07 01:02:00 +0000774 isa<IntegerType>(FT->getReturnType());
Reid Spencer912401c2005-04-26 05:24:00 +0000775 }
776
777 /// @brief Perform the strlen optimization
Chris Lattner71bf3e22007-04-07 01:02:00 +0000778 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer789082a2005-05-07 20:15:59 +0000779 // Make sure we're dealing with an sbyte* here.
Chris Lattner0cd3a232007-04-07 21:58:02 +0000780 Value *Src = CI->getOperand(1);
Reid Spencer789082a2005-05-07 20:15:59 +0000781
782 // Does the call to strlen have exactly one use?
Chris Lattner71bf3e22007-04-07 01:02:00 +0000783 if (CI->hasOneUse()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000784 // Is that single use a icmp operator?
Chris Lattner71bf3e22007-04-07 01:02:00 +0000785 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CI->use_back()))
Reid Spencer789082a2005-05-07 20:15:59 +0000786 // Is it compared against a constant integer?
Chris Lattner71bf3e22007-04-07 01:02:00 +0000787 if (ConstantInt *Cst = dyn_cast<ConstantInt>(Cmp->getOperand(1))) {
Reid Spencer789082a2005-05-07 20:15:59 +0000788 // If its compared against length 0 with == or !=
Chris Lattner71bf3e22007-04-07 01:02:00 +0000789 if (Cst->getZExtValue() == 0 && Cmp->isEquality()) {
Reid Spencer789082a2005-05-07 20:15:59 +0000790 // strlen(x) != 0 -> *x != 0
791 // strlen(x) == 0 -> *x == 0
Chris Lattner0cd3a232007-04-07 21:58:02 +0000792 Value *V = new LoadInst(Src, Src->getName()+".first", CI);
Chris Lattner71bf3e22007-04-07 01:02:00 +0000793 V = new ICmpInst(Cmp->getPredicate(), V,
794 ConstantInt::get(Type::Int8Ty, 0),
795 Cmp->getName()+".strlen", CI);
796 Cmp->replaceAllUsesWith(V);
797 Cmp->eraseFromParent();
798 return ReplaceCallWith(CI, 0); // no uses.
Reid Spencer789082a2005-05-07 20:15:59 +0000799 }
800 }
Chris Lattner71bf3e22007-04-07 01:02:00 +0000801 }
Reid Spencer789082a2005-05-07 20:15:59 +0000802
803 // Get the length of the constant string operand
Chris Lattner0cd3a232007-04-07 21:58:02 +0000804 std::string Str;
805 if (!GetConstantStringInfo(Src, Str))
Reid Spencer912401c2005-04-26 05:24:00 +0000806 return false;
Chris Lattner0cd3a232007-04-07 21:58:02 +0000807
Reid Spencer789082a2005-05-07 20:15:59 +0000808 // strlen("xyz") -> 3 (for example)
Chris Lattner0cd3a232007-04-07 21:58:02 +0000809 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), Str.size()));
Reid Spencer912401c2005-04-26 05:24:00 +0000810 }
811} StrLenOptimizer;
812
Chris Lattnerc3300692005-09-29 04:54:20 +0000813/// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
814/// is equal or not-equal to zero.
815static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
816 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
817 UI != E; ++UI) {
Chris Lattneref4fd352007-04-07 01:03:46 +0000818 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
819 if (IC->isEquality())
820 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
821 if (C->isNullValue())
822 continue;
Chris Lattnerc3300692005-09-29 04:54:20 +0000823 // Unknown instruction.
824 return false;
825 }
826 return true;
827}
828
829/// This memcmpOptimization will simplify a call to the memcmp library
830/// function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000831struct VISIBILITY_HIDDEN memcmpOptimization : public LibCallOptimization {
Chris Lattnerc3300692005-09-29 04:54:20 +0000832 /// @brief Default Constructor
833 memcmpOptimization()
834 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
835
836 /// @brief Make sure that the "memcmp" function has the right prototype
837 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
838 Function::const_arg_iterator AI = F->arg_begin();
839 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
840 if (!isa<PointerType>((++AI)->getType())) return false;
Chris Lattner42a75512007-01-15 02:27:26 +0000841 if (!(++AI)->getType()->isInteger()) return false;
842 if (!F->getReturnType()->isInteger()) return false;
Chris Lattnerc3300692005-09-29 04:54:20 +0000843 return true;
844 }
845
846 /// Because of alignment and instruction information that we don't have, we
847 /// leave the bulk of this to the code generators.
848 ///
849 /// Note that we could do much more if we could force alignment on otherwise
850 /// small aligned allocas, or if we could indicate that loads have a small
851 /// alignment.
852 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
853 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
854
855 // If the two operands are the same, return zero.
856 if (LHS == RHS) {
857 // memcmp(s,s,x) -> 0
Chris Lattner679d7182007-04-07 00:42:32 +0000858 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc3300692005-09-29 04:54:20 +0000859 }
860
861 // Make sure we have a constant length.
862 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
863 if (!LenC) return false;
Reid Spencerb83eb642006-10-20 07:07:24 +0000864 uint64_t Len = LenC->getZExtValue();
Chris Lattnerc3300692005-09-29 04:54:20 +0000865
866 // If the length is zero, this returns 0.
867 switch (Len) {
868 case 0:
869 // memcmp(s1,s2,0) -> 0
Chris Lattner679d7182007-04-07 00:42:32 +0000870 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc3300692005-09-29 04:54:20 +0000871 case 1: {
872 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000873 const Type *UCharPtr = PointerType::getUnqual(Type::Int8Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +0000874 CastInst *Op1Cast = CastInst::create(
875 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
876 CastInst *Op2Cast = CastInst::create(
877 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc3300692005-09-29 04:54:20 +0000878 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
879 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
880 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
881 if (RV->getType() != CI->getType())
Reid Spencer7b06bd52006-12-13 00:50:17 +0000882 RV = CastInst::createIntegerCast(RV, CI->getType(), false,
883 RV->getName(), CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000884 return ReplaceCallWith(CI, RV);
Chris Lattnerc3300692005-09-29 04:54:20 +0000885 }
886 case 2:
887 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
888 // TODO: IF both are aligned, use a short load/compare.
889
890 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000891 const Type *UCharPtr = PointerType::getUnqual(Type::Int8Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +0000892 CastInst *Op1Cast = CastInst::create(
893 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
894 CastInst *Op2Cast = CastInst::create(
895 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc3300692005-09-29 04:54:20 +0000896 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
897 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
898 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
899 CI->getName()+".d1", CI);
Reid Spencerc5b206b2006-12-31 05:48:39 +0000900 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnerc3300692005-09-29 04:54:20 +0000901 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
902 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
903 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
Chris Lattner2144c252006-05-12 23:35:26 +0000904 Value *S2V2 = new LoadInst(G2, RHS->getName()+".val2", CI);
Chris Lattnerc3300692005-09-29 04:54:20 +0000905 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
906 CI->getName()+".d1", CI);
907 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
908 if (Or->getType() != CI->getType())
Reid Spencer7b06bd52006-12-13 00:50:17 +0000909 Or = CastInst::createIntegerCast(Or, CI->getType(), false /*ZExt*/,
910 Or->getName(), CI);
Chris Lattner679d7182007-04-07 00:42:32 +0000911 return ReplaceCallWith(CI, Or);
Chris Lattnerc3300692005-09-29 04:54:20 +0000912 }
913 break;
914 default:
915 break;
916 }
917
Chris Lattnerc3300692005-09-29 04:54:20 +0000918 return false;
919 }
920} memcmpOptimizer;
921
922
Jeff Cohen00b168892005-07-27 06:12:32 +0000923/// This LibCallOptimization will simplify a call to the memcpy library
924/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
Reid Spencer716f49e2005-04-27 21:29:20 +0000925/// bytes depending on the length of the string and the alignment. Additional
926/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencer6cc03112005-04-25 21:11:48 +0000927/// @brief Simplify the memcpy library function.
Reid Spencer9133fe22007-02-05 23:32:05 +0000928struct VISIBILITY_HIDDEN LLVMMemCpyMoveOptzn : public LibCallOptimization {
Chris Lattneraecb0622006-03-03 01:30:23 +0000929 LLVMMemCpyMoveOptzn(const char* fname, const char* desc)
930 : LibCallOptimization(fname, desc) {}
Reid Spencer6cc03112005-04-25 21:11:48 +0000931
932 /// @brief Make sure that the "memcpy" function has the right prototype
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000933 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD) {
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000934 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer8f132612005-04-26 23:02:16 +0000935 return (f->arg_size() == 4);
Reid Spencer6cc03112005-04-25 21:11:48 +0000936 }
937
Reid Spencer20754ac2005-04-26 07:45:18 +0000938 /// Because of alignment and instruction information that we don't have, we
939 /// leave the bulk of this to the code generators. The optimization here just
940 /// deals with a few degenerate cases where the length of the string and the
941 /// alignment match the sizes of our intrinsic types so we can do a load and
942 /// store instead of the memcpy call.
943 /// @brief Perform the memcpy optimization.
Chris Lattner0f9f8c32006-01-22 22:35:08 +0000944 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD) {
Reid Spencer43fd4d02005-04-26 19:55:57 +0000945 // Make sure we have constant int values to work with
946 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
947 if (!LEN)
948 return false;
949 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
950 if (!ALIGN)
951 return false;
952
953 // If the length is larger than the alignment, we can't optimize
Reid Spencerb83eb642006-10-20 07:07:24 +0000954 uint64_t len = LEN->getZExtValue();
955 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer21506ff2005-05-03 07:23:44 +0000956 if (alignment == 0)
957 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000958 if (len > alignment)
Reid Spencer20754ac2005-04-26 07:45:18 +0000959 return false;
960
Reid Spencer3f7d8c62005-04-27 17:46:54 +0000961 // Get the type we will cast to, based on size of the string
Reid Spencer20754ac2005-04-26 07:45:18 +0000962 Value* dest = ci->getOperand(1);
963 Value* src = ci->getOperand(2);
Reid Spencer3c628622007-01-07 21:45:41 +0000964 const Type* castType = 0;
Chris Lattner679d7182007-04-07 00:42:32 +0000965 switch (len) {
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000966 case 0:
Chris Lattner679d7182007-04-07 00:42:32 +0000967 // memcpy(d,s,0,a) -> d
968 return ReplaceCallWith(ci, 0);
Reid Spencerc5b206b2006-12-31 05:48:39 +0000969 case 1: castType = Type::Int8Ty; break;
970 case 2: castType = Type::Int16Ty; break;
971 case 4: castType = Type::Int32Ty; break;
972 case 8: castType = Type::Int64Ty; break;
Reid Spencer20754ac2005-04-26 07:45:18 +0000973 default:
974 return false;
975 }
Reid Spencer3f7d8c62005-04-27 17:46:54 +0000976
977 // Cast source and dest to the right sized primitive and then load/store
Reid Spencer3da59db2006-11-27 01:05:10 +0000978 CastInst* SrcCast = CastInst::create(Instruction::BitCast,
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000979 src, PointerType::getUnqual(castType), src->getName()+".cast", ci);
Reid Spencer3da59db2006-11-27 01:05:10 +0000980 CastInst* DestCast = CastInst::create(Instruction::BitCast,
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000981 dest, PointerType::getUnqual(castType),dest->getName()+".cast", ci);
Reid Spencer3f7d8c62005-04-27 17:46:54 +0000982 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencer3ed469c2006-11-02 20:25:50 +0000983 new StoreInst(LI, DestCast, ci);
Chris Lattner679d7182007-04-07 00:42:32 +0000984 return ReplaceCallWith(ci, 0);
Reid Spencer6cc03112005-04-25 21:11:48 +0000985 }
Chris Lattneraecb0622006-03-03 01:30:23 +0000986};
Reid Spencerfcbdb9c2005-04-26 19:13:17 +0000987
Chris Lattneraecb0622006-03-03 01:30:23 +0000988/// This LibCallOptimization will simplify a call to the memcpy/memmove library
989/// functions.
990LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer32("llvm.memcpy.i32",
991 "Number of 'llvm.memcpy' calls simplified");
992LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer64("llvm.memcpy.i64",
993 "Number of 'llvm.memcpy' calls simplified");
994LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer32("llvm.memmove.i32",
995 "Number of 'llvm.memmove' calls simplified");
996LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer64("llvm.memmove.i64",
997 "Number of 'llvm.memmove' calls simplified");
Reid Spencer21506ff2005-05-03 07:23:44 +0000998
Jeff Cohen00b168892005-07-27 06:12:32 +0000999/// This LibCallOptimization will simplify a call to the memset library
1000/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1001/// bytes depending on the length argument.
Reid Spencer9133fe22007-02-05 23:32:05 +00001002struct VISIBILITY_HIDDEN LLVMMemSetOptimization : public LibCallOptimization {
Reid Spencer21506ff2005-05-03 07:23:44 +00001003 /// @brief Default Constructor
Chris Lattneraecb0622006-03-03 01:30:23 +00001004 LLVMMemSetOptimization(const char *Name) : LibCallOptimization(Name,
Reid Spencer21506ff2005-05-03 07:23:44 +00001005 "Number of 'llvm.memset' calls simplified") {}
Reid Spencer21506ff2005-05-03 07:23:44 +00001006
1007 /// @brief Make sure that the "memset" function has the right prototype
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001008 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
Reid Spencer21506ff2005-05-03 07:23:44 +00001009 // Just make sure this has 3 arguments per LLVM spec.
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001010 return F->arg_size() == 4;
Reid Spencer21506ff2005-05-03 07:23:44 +00001011 }
1012
1013 /// Because of alignment and instruction information that we don't have, we
1014 /// leave the bulk of this to the code generators. The optimization here just
1015 /// deals with a few degenerate cases where the length parameter is constant
Jeff Cohen00b168892005-07-27 06:12:32 +00001016 /// and the alignment matches the sizes of our intrinsic types so we can do
Reid Spencer21506ff2005-05-03 07:23:44 +00001017 /// store instead of the memcpy call. Other calls are transformed into the
1018 /// llvm.memset intrinsic.
1019 /// @brief Perform the memset optimization.
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001020 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &TD) {
Reid Spencer21506ff2005-05-03 07:23:44 +00001021 // Make sure we have constant int values to work with
1022 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1023 if (!LEN)
1024 return false;
1025 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1026 if (!ALIGN)
1027 return false;
1028
1029 // Extract the length and alignment
Reid Spencerb83eb642006-10-20 07:07:24 +00001030 uint64_t len = LEN->getZExtValue();
1031 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer21506ff2005-05-03 07:23:44 +00001032
1033 // Alignment 0 is identity for alignment 1
1034 if (alignment == 0)
1035 alignment = 1;
1036
1037 // If the length is zero, this is a no-op
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001038 if (len == 0) {
Reid Spencer21506ff2005-05-03 07:23:44 +00001039 // memset(d,c,0,a) -> noop
Chris Lattner679d7182007-04-07 00:42:32 +00001040 return ReplaceCallWith(ci, 0);
Reid Spencer21506ff2005-05-03 07:23:44 +00001041 }
1042
1043 // If the length is larger than the alignment, we can't optimize
1044 if (len > alignment)
1045 return false;
1046
1047 // Make sure we have a constant ubyte to work with so we can extract
1048 // the value to be filled.
Reid Spencerb83eb642006-10-20 07:07:24 +00001049 ConstantInt* FILL = dyn_cast<ConstantInt>(ci->getOperand(2));
Reid Spencer21506ff2005-05-03 07:23:44 +00001050 if (!FILL)
1051 return false;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001052 if (FILL->getType() != Type::Int8Ty)
Reid Spencer21506ff2005-05-03 07:23:44 +00001053 return false;
1054
1055 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
Jeff Cohen00b168892005-07-27 06:12:32 +00001056
Reid Spencer21506ff2005-05-03 07:23:44 +00001057 // Extract the fill character
Reid Spencerb83eb642006-10-20 07:07:24 +00001058 uint64_t fill_char = FILL->getZExtValue();
Reid Spencer21506ff2005-05-03 07:23:44 +00001059 uint64_t fill_value = fill_char;
1060
1061 // Get the type we will cast to, based on size of memory area to fill, and
1062 // and the value we will store there.
1063 Value* dest = ci->getOperand(1);
Reid Spencer3c628622007-01-07 21:45:41 +00001064 const Type* castType = 0;
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001065 switch (len) {
Jeff Cohen00b168892005-07-27 06:12:32 +00001066 case 1:
Reid Spencerc5b206b2006-12-31 05:48:39 +00001067 castType = Type::Int8Ty;
Reid Spencer21506ff2005-05-03 07:23:44 +00001068 break;
Jeff Cohen00b168892005-07-27 06:12:32 +00001069 case 2:
Reid Spencerc5b206b2006-12-31 05:48:39 +00001070 castType = Type::Int16Ty;
Reid Spencer21506ff2005-05-03 07:23:44 +00001071 fill_value |= fill_char << 8;
1072 break;
Jeff Cohen00b168892005-07-27 06:12:32 +00001073 case 4:
Reid Spencerc5b206b2006-12-31 05:48:39 +00001074 castType = Type::Int32Ty;
Reid Spencer21506ff2005-05-03 07:23:44 +00001075 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1076 break;
Jeff Cohen00b168892005-07-27 06:12:32 +00001077 case 8:
Reid Spencerc5b206b2006-12-31 05:48:39 +00001078 castType = Type::Int64Ty;
Reid Spencer21506ff2005-05-03 07:23:44 +00001079 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1080 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1081 fill_value |= fill_char << 56;
1082 break;
1083 default:
1084 return false;
1085 }
1086
1087 // Cast dest to the right sized primitive and then load/store
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001088 CastInst* DestCast = new BitCastInst(dest, PointerType::getUnqual(castType),
Reid Spencer7b06bd52006-12-13 00:50:17 +00001089 dest->getName()+".cast", ci);
Reid Spencerb83eb642006-10-20 07:07:24 +00001090 new StoreInst(ConstantInt::get(castType,fill_value),DestCast, ci);
Chris Lattner679d7182007-04-07 00:42:32 +00001091 return ReplaceCallWith(ci, 0);
Reid Spencer21506ff2005-05-03 07:23:44 +00001092 }
Chris Lattneraecb0622006-03-03 01:30:23 +00001093};
1094
1095LLVMMemSetOptimization MemSet32Optimizer("llvm.memset.i32");
1096LLVMMemSetOptimization MemSet64Optimizer("llvm.memset.i64");
1097
Reid Spencerfcbdb9c2005-04-26 19:13:17 +00001098
Jeff Cohen00b168892005-07-27 06:12:32 +00001099/// This LibCallOptimization will simplify calls to the "pow" library
1100/// function. It looks for cases where the result of pow is well known and
Reid Spencerff5525d2005-04-29 09:39:47 +00001101/// substitutes the appropriate value.
1102/// @brief Simplify the pow library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001103struct VISIBILITY_HIDDEN PowOptimization : public LibCallOptimization {
Reid Spencerff5525d2005-04-29 09:39:47 +00001104public:
1105 /// @brief Default Constructor
Reid Spencer9974dda2005-05-03 02:54:54 +00001106 PowOptimization() : LibCallOptimization("pow",
Reid Spencer789082a2005-05-07 20:15:59 +00001107 "Number of 'pow' calls simplified") {}
Reid Spencer9974dda2005-05-03 02:54:54 +00001108
Reid Spencerff5525d2005-04-29 09:39:47 +00001109 /// @brief Make sure that the "pow" function has the right prototype
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001110 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencerff5525d2005-04-29 09:39:47 +00001111 // Just make sure this has 2 arguments
1112 return (f->arg_size() == 2);
1113 }
1114
1115 /// @brief Perform the pow optimization.
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001116 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencerff5525d2005-04-29 09:39:47 +00001117 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
Dale Johannesen4292d1c2007-09-28 18:06:58 +00001118 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
1119 return false; // FIXME long double not yet supported
Reid Spencerff5525d2005-04-29 09:39:47 +00001120 Value* base = ci->getOperand(1);
1121 Value* expn = ci->getOperand(2);
1122 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
Dale Johannesen43421b32007-09-06 18:13:44 +00001123 if (Op1->isExactlyValue(1.0)) // pow(1.0,x) -> 1.0
1124 return ReplaceCallWith(ci, ConstantFP::get(Ty,
1125 Ty==Type::FloatTy ? APFloat(1.0f) : APFloat(1.0)));
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001126 } else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) {
Dale Johannesen43421b32007-09-06 18:13:44 +00001127 if (Op2->getValueAPF().isZero()) {
Reid Spencerff5525d2005-04-29 09:39:47 +00001128 // pow(x,0.0) -> 1.0
Dale Johannesen43421b32007-09-06 18:13:44 +00001129 return ReplaceCallWith(ci, ConstantFP::get(Ty,
1130 Ty==Type::FloatTy ? APFloat(1.0f) : APFloat(1.0)));
1131 } else if (Op2->isExactlyValue(0.5)) {
Reid Spencerff5525d2005-04-29 09:39:47 +00001132 // pow(x,0.5) -> sqrt(x)
1133 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1134 ci->getName()+".pow",ci);
Chris Lattner679d7182007-04-07 00:42:32 +00001135 return ReplaceCallWith(ci, sqrt_inst);
Dale Johannesen43421b32007-09-06 18:13:44 +00001136 } else if (Op2->isExactlyValue(1.0)) {
Reid Spencerff5525d2005-04-29 09:39:47 +00001137 // pow(x,1.0) -> x
Chris Lattner679d7182007-04-07 00:42:32 +00001138 return ReplaceCallWith(ci, base);
Dale Johannesen43421b32007-09-06 18:13:44 +00001139 } else if (Op2->isExactlyValue(-1.0)) {
Reid Spencerff5525d2005-04-29 09:39:47 +00001140 // pow(x,-1.0) -> 1.0/x
Chris Lattner679d7182007-04-07 00:42:32 +00001141 Value *div_inst =
Dale Johannesen43421b32007-09-06 18:13:44 +00001142 BinaryOperator::createFDiv(ConstantFP::get(Ty,
1143 Ty==Type::FloatTy ? APFloat(1.0f) : APFloat(1.0)),
1144 base, ci->getName()+".pow", ci);
Chris Lattner679d7182007-04-07 00:42:32 +00001145 return ReplaceCallWith(ci, div_inst);
Reid Spencerff5525d2005-04-29 09:39:47 +00001146 }
1147 }
1148 return false; // opt failed
1149 }
1150} PowOptimizer;
1151
Evan Cheng21abac22006-06-16 08:36:35 +00001152/// This LibCallOptimization will simplify calls to the "printf" library
1153/// function. It looks for cases where the result of printf is not used and the
1154/// operation can be reduced to something simpler.
1155/// @brief Simplify the printf library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001156struct VISIBILITY_HIDDEN PrintfOptimization : public LibCallOptimization {
Evan Cheng21abac22006-06-16 08:36:35 +00001157public:
1158 /// @brief Default Constructor
1159 PrintfOptimization() : LibCallOptimization("printf",
1160 "Number of 'printf' calls simplified") {}
1161
1162 /// @brief Make sure that the "printf" function has the right prototype
Chris Lattner045af542007-04-07 01:18:36 +00001163 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner35b9b492007-04-14 01:17:48 +00001164 // Just make sure this has at least 1 argument and returns an integer or
1165 // void type.
1166 const FunctionType *FT = F->getFunctionType();
1167 return FT->getNumParams() >= 1 &&
1168 (isa<IntegerType>(FT->getReturnType()) ||
1169 FT->getReturnType() == Type::VoidTy);
Evan Cheng21abac22006-06-16 08:36:35 +00001170 }
1171
1172 /// @brief Perform the printf optimization.
Chris Lattner045af542007-04-07 01:18:36 +00001173 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Evan Cheng21abac22006-06-16 08:36:35 +00001174 // All the optimizations depend on the length of the first argument and the
1175 // fact that it is a constant string array. Check that now
Chris Lattner0cd3a232007-04-07 21:58:02 +00001176 std::string FormatStr;
1177 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
Evan Cheng21abac22006-06-16 08:36:35 +00001178 return false;
Chris Lattner35b9b492007-04-14 01:17:48 +00001179
1180 // If this is a simple constant string with no format specifiers that ends
1181 // with a \n, turn it into a puts call.
1182 if (FormatStr.empty()) {
1183 // Tolerate printf's declared void.
1184 if (CI->use_empty()) return ReplaceCallWith(CI, 0);
1185 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
1186 }
1187
1188 if (FormatStr.size() == 1) {
1189 // Turn this into a putchar call, even if it is a %.
1190 Value *V = ConstantInt::get(Type::Int32Ty, FormatStr[0]);
1191 new CallInst(SLC.get_putchar(), V, "", CI);
1192 if (CI->use_empty()) return ReplaceCallWith(CI, 0);
1193 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1194 }
Evan Cheng21abac22006-06-16 08:36:35 +00001195
Chris Lattner35b9b492007-04-14 01:17:48 +00001196 // Check to see if the format str is something like "foo\n", in which case
1197 // we convert it to a puts call. We don't allow it to contain any format
1198 // characters.
1199 if (FormatStr[FormatStr.size()-1] == '\n' &&
1200 FormatStr.find('%') == std::string::npos) {
1201 // Create a string literal with no \n on it. We expect the constant merge
1202 // pass to be run after this pass, to merge duplicate strings.
1203 FormatStr.erase(FormatStr.end()-1);
1204 Constant *Init = ConstantArray::get(FormatStr, true);
1205 Constant *GV = new GlobalVariable(Init->getType(), true,
1206 GlobalVariable::InternalLinkage,
1207 Init, "str",
1208 CI->getParent()->getParent()->getParent());
1209 // Cast GV to be a pointer to char.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001210 GV = ConstantExpr::getBitCast(GV, PointerType::getUnqual(Type::Int8Ty));
Chris Lattner35b9b492007-04-14 01:17:48 +00001211 new CallInst(SLC.get_puts(), GV, "", CI);
1212
1213 if (CI->use_empty()) return ReplaceCallWith(CI, 0);
Dale Johannesen0fcee062007-10-24 20:14:50 +00001214 // The return value from printf includes the \n we just removed, so +1.
Chris Lattner35b9b492007-04-14 01:17:48 +00001215 return ReplaceCallWith(CI,
Dale Johannesen0fcee062007-10-24 20:14:50 +00001216 ConstantInt::get(CI->getType(),
1217 FormatStr.size()+1));
Chris Lattner35b9b492007-04-14 01:17:48 +00001218 }
1219
1220
Chris Lattner0cd3a232007-04-07 21:58:02 +00001221 // Only support %c or "%s\n" for now.
1222 if (FormatStr.size() < 2 || FormatStr[0] != '%')
Chris Lattner045af542007-04-07 01:18:36 +00001223 return false;
Evan Cheng21abac22006-06-16 08:36:35 +00001224
1225 // Get the second character and switch on its value
Chris Lattner0cd3a232007-04-07 21:58:02 +00001226 switch (FormatStr[1]) {
Chris Lattner045af542007-04-07 01:18:36 +00001227 default: return false;
Chris Lattner0cd3a232007-04-07 21:58:02 +00001228 case 's':
Chris Lattner35b9b492007-04-14 01:17:48 +00001229 if (FormatStr != "%s\n" || CI->getNumOperands() < 3 ||
Chris Lattner0cd3a232007-04-07 21:58:02 +00001230 // TODO: could insert strlen call to compute string length.
1231 !CI->use_empty())
Evan Cheng21abac22006-06-16 08:36:35 +00001232 return false;
Chris Lattner045af542007-04-07 01:18:36 +00001233
1234 // printf("%s\n",str) -> puts(str)
Chris Lattner3492cda2007-04-07 21:04:50 +00001235 new CallInst(SLC.get_puts(), CastToCStr(CI->getOperand(2), CI),
Chris Lattner045af542007-04-07 01:18:36 +00001236 CI->getName(), CI);
1237 return ReplaceCallWith(CI, 0);
Chris Lattner045af542007-04-07 01:18:36 +00001238 case 'c': {
1239 // printf("%c",c) -> putchar(c)
Chris Lattner35b9b492007-04-14 01:17:48 +00001240 if (FormatStr.size() != 2 || CI->getNumOperands() < 3)
Chris Lattner045af542007-04-07 01:18:36 +00001241 return false;
1242
1243 Value *V = CI->getOperand(2);
1244 if (!isa<IntegerType>(V->getType()) ||
Chris Lattner0cd3a232007-04-07 21:58:02 +00001245 cast<IntegerType>(V->getType())->getBitWidth() > 32)
Chris Lattner045af542007-04-07 01:18:36 +00001246 return false;
1247
Chris Lattner0cd3a232007-04-07 21:58:02 +00001248 V = CastInst::createZExtOrBitCast(V, Type::Int32Ty, CI->getName()+".int",
Chris Lattner045af542007-04-07 01:18:36 +00001249 CI);
1250 new CallInst(SLC.get_putchar(), V, "", CI);
Chris Lattner0cd3a232007-04-07 21:58:02 +00001251 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
Chris Lattner045af542007-04-07 01:18:36 +00001252 }
1253 }
Evan Cheng21abac22006-06-16 08:36:35 +00001254 }
1255} PrintfOptimizer;
1256
Jeff Cohen00b168892005-07-27 06:12:32 +00001257/// This LibCallOptimization will simplify calls to the "fprintf" library
Reid Spencera1b43902005-05-02 23:59:26 +00001258/// function. It looks for cases where the result of fprintf is not used and the
1259/// operation can be reduced to something simpler.
Evan Cheng21abac22006-06-16 08:36:35 +00001260/// @brief Simplify the fprintf library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001261struct VISIBILITY_HIDDEN FPrintFOptimization : public LibCallOptimization {
Reid Spencera1b43902005-05-02 23:59:26 +00001262public:
1263 /// @brief Default Constructor
Reid Spencer9974dda2005-05-03 02:54:54 +00001264 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer789082a2005-05-07 20:15:59 +00001265 "Number of 'fprintf' calls simplified") {}
Reid Spencera1b43902005-05-02 23:59:26 +00001266
Reid Spencera1b43902005-05-02 23:59:26 +00001267 /// @brief Make sure that the "fprintf" function has the right prototype
Chris Lattner3492cda2007-04-07 21:04:50 +00001268 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1269 const FunctionType *FT = F->getFunctionType();
1270 return FT->getNumParams() == 2 && // two fixed arguments.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001271 FT->getParamType(1) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner3492cda2007-04-07 21:04:50 +00001272 isa<PointerType>(FT->getParamType(0)) &&
1273 isa<IntegerType>(FT->getReturnType());
Reid Spencera1b43902005-05-02 23:59:26 +00001274 }
1275
1276 /// @brief Perform the fprintf optimization.
Chris Lattner3492cda2007-04-07 21:04:50 +00001277 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencera1b43902005-05-02 23:59:26 +00001278 // If the call has more than 3 operands, we can't optimize it
Chris Lattner3492cda2007-04-07 21:04:50 +00001279 if (CI->getNumOperands() != 3 && CI->getNumOperands() != 4)
Reid Spencera1b43902005-05-02 23:59:26 +00001280 return false;
1281
Chris Lattner73f5d422007-04-07 21:17:51 +00001282 // All the optimizations depend on the format string.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001283 std::string FormatStr;
1284 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Reid Spencera1b43902005-05-02 23:59:26 +00001285 return false;
1286
Chris Lattner0cd3a232007-04-07 21:58:02 +00001287 // If this is just a format string, turn it into fwrite.
Chris Lattner3492cda2007-04-07 21:04:50 +00001288 if (CI->getNumOperands() == 3) {
Chris Lattner0cd3a232007-04-07 21:58:02 +00001289 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1290 if (FormatStr[i] == '%')
Chris Lattner3492cda2007-04-07 21:04:50 +00001291 return false; // we found a format specifier
Reid Spencera1b43902005-05-02 23:59:26 +00001292
Jeff Cohen00b168892005-07-27 06:12:32 +00001293 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
Chris Lattner3492cda2007-04-07 21:04:50 +00001294 const Type *FILEty = CI->getOperand(1)->getType();
John Criswell1d231ec2005-06-29 15:03:18 +00001295
Chris Lattner3492cda2007-04-07 21:04:50 +00001296 Value *FWriteArgs[] = {
1297 CI->getOperand(2),
Chris Lattner0cd3a232007-04-07 21:58:02 +00001298 ConstantInt::get(SLC.getIntPtrType(), FormatStr.size()),
Chris Lattner3492cda2007-04-07 21:04:50 +00001299 ConstantInt::get(SLC.getIntPtrType(), 1),
1300 CI->getOperand(1)
Chris Lattnerc18470c2007-02-13 05:58:53 +00001301 };
David Greene52eec542007-08-01 03:43:44 +00001302 new CallInst(SLC.get_fwrite(FILEty), FWriteArgs, FWriteArgs + 4, CI->getName(), CI);
Chris Lattner0cd3a232007-04-07 21:58:02 +00001303 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(),
1304 FormatStr.size()));
Reid Spencera1b43902005-05-02 23:59:26 +00001305 }
Chris Lattner3492cda2007-04-07 21:04:50 +00001306
1307 // The remaining optimizations require the format string to be length 2:
Reid Spencera1b43902005-05-02 23:59:26 +00001308 // "%s" or "%c".
Chris Lattner0cd3a232007-04-07 21:58:02 +00001309 if (FormatStr.size() != 2 || FormatStr[0] != '%')
Chris Lattner3492cda2007-04-07 21:04:50 +00001310 return false;
Reid Spencera1b43902005-05-02 23:59:26 +00001311
1312 // Get the second character and switch on its value
Chris Lattner0cd3a232007-04-07 21:58:02 +00001313 switch (FormatStr[1]) {
Chris Lattner3492cda2007-04-07 21:04:50 +00001314 case 'c': {
1315 // fprintf(file,"%c",c) -> fputc(c,file)
1316 const Type *FILETy = CI->getOperand(1)->getType();
1317 Value *C = CastInst::createZExtOrBitCast(CI->getOperand(3), Type::Int32Ty,
1318 CI->getName()+".int", CI);
David Greene52eec542007-08-01 03:43:44 +00001319 SmallVector<Value *, 2> Args;
1320 Args.push_back(C);
1321 Args.push_back(CI->getOperand(1));
1322 new CallInst(SLC.get_fputc(FILETy), Args.begin(), Args.end(), "", CI);
Chris Lattner3492cda2007-04-07 21:04:50 +00001323 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1324 }
1325 case 's': {
1326 const Type *FILETy = CI->getOperand(1)->getType();
Chris Lattner3492cda2007-04-07 21:04:50 +00001327
1328 // If the result of the fprintf call is used, we can't do this.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001329 // TODO: we should insert a strlen call.
Chris Lattner3492cda2007-04-07 21:04:50 +00001330 if (!CI->use_empty())
Reid Spencera1b43902005-05-02 23:59:26 +00001331 return false;
Chris Lattner3492cda2007-04-07 21:04:50 +00001332
1333 // fprintf(file,"%s",str) -> fputs(str,file)
David Greene52eec542007-08-01 03:43:44 +00001334 SmallVector<Value *, 2> Args;
1335 Args.push_back(CastToCStr(CI->getOperand(3), CI));
1336 Args.push_back(CI->getOperand(1));
1337 new CallInst(SLC.get_fputs(FILETy), Args.begin(),
1338 Args.end(), CI->getName(), CI);
Chris Lattner3492cda2007-04-07 21:04:50 +00001339 return ReplaceCallWith(CI, 0);
1340 }
1341 default:
1342 return false;
Reid Spencera1b43902005-05-02 23:59:26 +00001343 }
Reid Spencera1b43902005-05-02 23:59:26 +00001344 }
1345} FPrintFOptimizer;
1346
Jeff Cohen00b168892005-07-27 06:12:32 +00001347/// This LibCallOptimization will simplify calls to the "sprintf" library
Reid Spencer58b563c2005-05-04 03:20:21 +00001348/// function. It looks for cases where the result of sprintf is not used and the
1349/// operation can be reduced to something simpler.
Evan Cheng21abac22006-06-16 08:36:35 +00001350/// @brief Simplify the sprintf library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001351struct VISIBILITY_HIDDEN SPrintFOptimization : public LibCallOptimization {
Reid Spencer58b563c2005-05-04 03:20:21 +00001352public:
1353 /// @brief Default Constructor
1354 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer789082a2005-05-07 20:15:59 +00001355 "Number of 'sprintf' calls simplified") {}
Reid Spencer58b563c2005-05-04 03:20:21 +00001356
Chris Lattner73f5d422007-04-07 21:17:51 +00001357 /// @brief Make sure that the "sprintf" function has the right prototype
1358 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1359 const FunctionType *FT = F->getFunctionType();
1360 return FT->getNumParams() == 2 && // two fixed arguments.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001361 FT->getParamType(1) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner73f5d422007-04-07 21:17:51 +00001362 FT->getParamType(0) == FT->getParamType(1) &&
1363 isa<IntegerType>(FT->getReturnType());
Reid Spencer58b563c2005-05-04 03:20:21 +00001364 }
1365
1366 /// @brief Perform the sprintf optimization.
Chris Lattner73f5d422007-04-07 21:17:51 +00001367 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer58b563c2005-05-04 03:20:21 +00001368 // If the call has more than 3 operands, we can't optimize it
Chris Lattner73f5d422007-04-07 21:17:51 +00001369 if (CI->getNumOperands() != 3 && CI->getNumOperands() != 4)
Reid Spencer58b563c2005-05-04 03:20:21 +00001370 return false;
1371
Chris Lattner0cd3a232007-04-07 21:58:02 +00001372 std::string FormatStr;
1373 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Reid Spencer58b563c2005-05-04 03:20:21 +00001374 return false;
Chris Lattner73f5d422007-04-07 21:17:51 +00001375
1376 if (CI->getNumOperands() == 3) {
Reid Spencer58b563c2005-05-04 03:20:21 +00001377 // Make sure there's no % in the constant array
Chris Lattner0cd3a232007-04-07 21:58:02 +00001378 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1379 if (FormatStr[i] == '%')
Chris Lattner73f5d422007-04-07 21:17:51 +00001380 return false; // we found a format specifier
1381
Jeff Cohen00b168892005-07-27 06:12:32 +00001382 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
Chris Lattner73f5d422007-04-07 21:17:51 +00001383 Value *MemCpyArgs[] = {
1384 CI->getOperand(1), CI->getOperand(2),
Chris Lattner0cd3a232007-04-07 21:58:02 +00001385 ConstantInt::get(SLC.getIntPtrType(),
1386 FormatStr.size()+1), // Copy the nul byte.
Chris Lattnerc18470c2007-02-13 05:58:53 +00001387 ConstantInt::get(Type::Int32Ty, 1)
1388 };
David Greene52eec542007-08-01 03:43:44 +00001389 new CallInst(SLC.get_memcpy(), MemCpyArgs, MemCpyArgs + 4, "", CI);
Chris Lattner0cd3a232007-04-07 21:58:02 +00001390 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(),
1391 FormatStr.size()));
Reid Spencer58b563c2005-05-04 03:20:21 +00001392 }
1393
Chris Lattner73f5d422007-04-07 21:17:51 +00001394 // The remaining optimizations require the format string to be "%s" or "%c".
Chris Lattner0cd3a232007-04-07 21:58:02 +00001395 if (FormatStr.size() != 2 || FormatStr[0] != '%')
Reid Spencer58b563c2005-05-04 03:20:21 +00001396 return false;
1397
Reid Spencer58b563c2005-05-04 03:20:21 +00001398 // Get the second character and switch on its value
Chris Lattner51047852007-04-08 18:11:26 +00001399 switch (FormatStr[1]) {
Chris Lattner73f5d422007-04-07 21:17:51 +00001400 case 'c': {
1401 // sprintf(dest,"%c",chr) -> store chr, dest
1402 Value *V = CastInst::createTruncOrBitCast(CI->getOperand(3),
1403 Type::Int8Ty, "char", CI);
1404 new StoreInst(V, CI->getOperand(1), CI);
1405 Value *Ptr = new GetElementPtrInst(CI->getOperand(1),
1406 ConstantInt::get(Type::Int32Ty, 1),
1407 CI->getOperand(1)->getName()+".end",
1408 CI);
1409 new StoreInst(ConstantInt::get(Type::Int8Ty,0), Ptr, CI);
1410 return ReplaceCallWith(CI, ConstantInt::get(Type::Int32Ty, 1));
1411 }
Chris Lattner5d735bf2005-09-24 22:17:06 +00001412 case 's': {
1413 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Chris Lattnerb76efb72007-01-07 08:12:01 +00001414 Value *Len = new CallInst(SLC.get_strlen(),
Chris Lattner73f5d422007-04-07 21:17:51 +00001415 CastToCStr(CI->getOperand(3), CI),
1416 CI->getOperand(3)->getName()+".len", CI);
1417 Value *UnincLen = Len;
1418 Len = BinaryOperator::createAdd(Len, ConstantInt::get(Len->getType(), 1),
1419 Len->getName()+"1", CI);
1420 Value *MemcpyArgs[4] = {
1421 CI->getOperand(1),
1422 CastToCStr(CI->getOperand(3), CI),
1423 Len,
1424 ConstantInt::get(Type::Int32Ty, 1)
Chris Lattnerc18470c2007-02-13 05:58:53 +00001425 };
David Greene52eec542007-08-01 03:43:44 +00001426 new CallInst(SLC.get_memcpy(), MemcpyArgs, MemcpyArgs + 4, "", CI);
Chris Lattner5d735bf2005-09-24 22:17:06 +00001427
1428 // The strlen result is the unincremented number of bytes in the string.
Chris Lattner73f5d422007-04-07 21:17:51 +00001429 if (!CI->use_empty()) {
1430 if (UnincLen->getType() != CI->getType())
1431 UnincLen = CastInst::createIntegerCast(UnincLen, CI->getType(), false,
1432 Len->getName(), CI);
1433 CI->replaceAllUsesWith(UnincLen);
Chris Lattneraebac502005-09-25 07:06:48 +00001434 }
Chris Lattner73f5d422007-04-07 21:17:51 +00001435 return ReplaceCallWith(CI, 0);
Chris Lattner5d735bf2005-09-24 22:17:06 +00001436 }
1437 }
1438 return false;
Reid Spencer58b563c2005-05-04 03:20:21 +00001439 }
1440} SPrintFOptimizer;
1441
Jeff Cohen00b168892005-07-27 06:12:32 +00001442/// This LibCallOptimization will simplify calls to the "fputs" library
Reid Spencerff5525d2005-04-29 09:39:47 +00001443/// function. It looks for cases where the result of fputs is not used and the
1444/// operation can be reduced to something simpler.
Chris Lattner5cef3c62007-04-08 07:00:35 +00001445/// @brief Simplify the fputs library function.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001446struct VISIBILITY_HIDDEN FPutsOptimization : public LibCallOptimization {
Reid Spencerff5525d2005-04-29 09:39:47 +00001447public:
1448 /// @brief Default Constructor
Chris Lattner0cd3a232007-04-07 21:58:02 +00001449 FPutsOptimization() : LibCallOptimization("fputs",
Reid Spencer789082a2005-05-07 20:15:59 +00001450 "Number of 'fputs' calls simplified") {}
Reid Spencerff5525d2005-04-29 09:39:47 +00001451
Reid Spencerff5525d2005-04-29 09:39:47 +00001452 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001453 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencerff5525d2005-04-29 09:39:47 +00001454 // Just make sure this has 2 arguments
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001455 return F->arg_size() == 2;
Reid Spencerff5525d2005-04-29 09:39:47 +00001456 }
1457
1458 /// @brief Perform the fputs optimization.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001459 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1460 // If the result is used, none of these optimizations work.
1461 if (!CI->use_empty())
Reid Spencerff5525d2005-04-29 09:39:47 +00001462 return false;
1463
1464 // All the optimizations depend on the length of the first argument and the
1465 // fact that it is a constant string array. Check that now
Chris Lattner0cd3a232007-04-07 21:58:02 +00001466 std::string Str;
1467 if (!GetConstantStringInfo(CI->getOperand(1), Str))
Reid Spencerff5525d2005-04-29 09:39:47 +00001468 return false;
1469
Chris Lattner0cd3a232007-04-07 21:58:02 +00001470 const Type *FILETy = CI->getOperand(2)->getType();
Chris Lattner5cef3c62007-04-08 07:00:35 +00001471 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1472 Value *FWriteParms[4] = {
1473 CI->getOperand(1),
1474 ConstantInt::get(SLC.getIntPtrType(), Str.size()),
1475 ConstantInt::get(SLC.getIntPtrType(), 1),
1476 CI->getOperand(2)
1477 };
David Greene52eec542007-08-01 03:43:44 +00001478 new CallInst(SLC.get_fwrite(FILETy), FWriteParms, FWriteParms + 4, "", CI);
Chris Lattner0cd3a232007-04-07 21:58:02 +00001479 return ReplaceCallWith(CI, 0); // Known to have no uses (see above).
Reid Spencerff5525d2005-04-29 09:39:47 +00001480 }
Chris Lattner5cef3c62007-04-08 07:00:35 +00001481} FPutsOptimizer;
1482
1483/// This LibCallOptimization will simplify calls to the "fwrite" function.
1484struct VISIBILITY_HIDDEN FWriteOptimization : public LibCallOptimization {
1485public:
1486 /// @brief Default Constructor
1487 FWriteOptimization() : LibCallOptimization("fwrite",
1488 "Number of 'fwrite' calls simplified") {}
1489
1490 /// @brief Make sure that the "fputs" function has the right prototype
1491 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1492 const FunctionType *FT = F->getFunctionType();
1493 return FT->getNumParams() == 4 &&
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001494 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner5cef3c62007-04-08 07:00:35 +00001495 FT->getParamType(1) == FT->getParamType(2) &&
1496 isa<IntegerType>(FT->getParamType(1)) &&
1497 isa<PointerType>(FT->getParamType(3)) &&
1498 isa<IntegerType>(FT->getReturnType());
1499 }
1500
1501 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1502 // Get the element size and count.
1503 uint64_t EltSize, EltCount;
1504 if (ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(2)))
1505 EltSize = C->getZExtValue();
1506 else
1507 return false;
1508 if (ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(3)))
1509 EltCount = C->getZExtValue();
1510 else
1511 return false;
1512
1513 // If this is writing zero records, remove the call (it's a noop).
1514 if (EltSize * EltCount == 0)
1515 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
1516
1517 // If this is writing one byte, turn it into fputc.
1518 if (EltSize == 1 && EltCount == 1) {
David Greene52eec542007-08-01 03:43:44 +00001519 SmallVector<Value *, 2> Args;
Chris Lattner5cef3c62007-04-08 07:00:35 +00001520 // fwrite(s,1,1,F) -> fputc(s[0],F)
1521 Value *Ptr = CI->getOperand(1);
1522 Value *Val = new LoadInst(Ptr, Ptr->getName()+".byte", CI);
David Greene52eec542007-08-01 03:43:44 +00001523 Args.push_back(new ZExtInst(Val, Type::Int32Ty, Val->getName()+".int", CI));
1524 Args.push_back(CI->getOperand(4));
Chris Lattner5cef3c62007-04-08 07:00:35 +00001525 const Type *FILETy = CI->getOperand(4)->getType();
David Greene52eec542007-08-01 03:43:44 +00001526 new CallInst(SLC.get_fputc(FILETy), Args.begin(), Args.end(), "", CI);
Chris Lattner5cef3c62007-04-08 07:00:35 +00001527 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1528 }
1529 return false;
1530 }
1531} FWriteOptimizer;
Reid Spencerff5525d2005-04-29 09:39:47 +00001532
Jeff Cohen00b168892005-07-27 06:12:32 +00001533/// This LibCallOptimization will simplify calls to the "isdigit" library
Reid Spencercea65592005-05-04 18:58:28 +00001534/// function. It simply does range checks the parameter explicitly.
1535/// @brief Simplify the isdigit library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001536struct VISIBILITY_HIDDEN isdigitOptimization : public LibCallOptimization {
Reid Spencercea65592005-05-04 18:58:28 +00001537public:
Chris Lattnere9b62422005-09-29 06:16:11 +00001538 isdigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer789082a2005-05-07 20:15:59 +00001539 "Number of 'isdigit' calls simplified") {}
Reid Spencercea65592005-05-04 18:58:28 +00001540
Chris Lattnere9b62422005-09-29 06:16:11 +00001541 /// @brief Make sure that the "isdigit" function has the right prototype
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001542 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencercea65592005-05-04 18:58:28 +00001543 // Just make sure this has 1 argument
1544 return (f->arg_size() == 1);
1545 }
1546
1547 /// @brief Perform the toascii optimization.
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001548 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1549 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1))) {
Reid Spencercea65592005-05-04 18:58:28 +00001550 // isdigit(c) -> 0 or 1, if 'c' is constant
Reid Spencerb83eb642006-10-20 07:07:24 +00001551 uint64_t val = CI->getZExtValue();
Chris Lattner679d7182007-04-07 00:42:32 +00001552 if (val >= '0' && val <= '9')
1553 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
Reid Spencercea65592005-05-04 18:58:28 +00001554 else
Chris Lattner679d7182007-04-07 00:42:32 +00001555 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 0));
Reid Spencercea65592005-05-04 18:58:28 +00001556 }
1557
1558 // isdigit(c) -> (unsigned)c - '0' <= 9
Reid Spencer7b06bd52006-12-13 00:50:17 +00001559 CastInst* cast = CastInst::createIntegerCast(ci->getOperand(1),
Reid Spencerc5b206b2006-12-31 05:48:39 +00001560 Type::Int32Ty, false/*ZExt*/, ci->getOperand(1)->getName()+".uint", ci);
Chris Lattner53249862005-08-24 17:22:17 +00001561 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
Reid Spencerc5b206b2006-12-31 05:48:39 +00001562 ConstantInt::get(Type::Int32Ty,0x30),
Reid Spencercea65592005-05-04 18:58:28 +00001563 ci->getOperand(1)->getName()+".sub",ci);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001564 ICmpInst* setcond_inst = new ICmpInst(ICmpInst::ICMP_ULE,sub_inst,
Reid Spencerc5b206b2006-12-31 05:48:39 +00001565 ConstantInt::get(Type::Int32Ty,9),
Reid Spencercea65592005-05-04 18:58:28 +00001566 ci->getOperand(1)->getName()+".cmp",ci);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001567 CastInst* c2 = new ZExtInst(setcond_inst, Type::Int32Ty,
Reid Spencer7b06bd52006-12-13 00:50:17 +00001568 ci->getOperand(1)->getName()+".isdigit", ci);
Chris Lattner679d7182007-04-07 00:42:32 +00001569 return ReplaceCallWith(ci, c2);
Reid Spencercea65592005-05-04 18:58:28 +00001570 }
Chris Lattnere9b62422005-09-29 06:16:11 +00001571} isdigitOptimizer;
1572
Reid Spencer9133fe22007-02-05 23:32:05 +00001573struct VISIBILITY_HIDDEN isasciiOptimization : public LibCallOptimization {
Chris Lattnera48bc532005-09-29 06:17:27 +00001574public:
1575 isasciiOptimization()
1576 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1577
1578 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner42a75512007-01-15 02:27:26 +00001579 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1580 F->getReturnType()->isInteger();
Chris Lattnera48bc532005-09-29 06:17:27 +00001581 }
1582
1583 /// @brief Perform the isascii optimization.
1584 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1585 // isascii(c) -> (unsigned)c < 128
1586 Value *V = CI->getOperand(1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001587 Value *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, V,
1588 ConstantInt::get(V->getType(), 128),
1589 V->getName()+".isascii", CI);
Chris Lattnera48bc532005-09-29 06:17:27 +00001590 if (Cmp->getType() != CI->getType())
Chris Lattner83ae2fc2007-04-15 05:38:40 +00001591 Cmp = new ZExtInst(Cmp, CI->getType(), Cmp->getName(), CI);
Chris Lattner679d7182007-04-07 00:42:32 +00001592 return ReplaceCallWith(CI, Cmp);
Chris Lattnera48bc532005-09-29 06:17:27 +00001593 }
1594} isasciiOptimizer;
Chris Lattnere9b62422005-09-29 06:16:11 +00001595
Reid Spencercea65592005-05-04 18:58:28 +00001596
Jeff Cohen00b168892005-07-27 06:12:32 +00001597/// This LibCallOptimization will simplify calls to the "toascii" library
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001598/// function. It simply does the corresponding and operation to restrict the
1599/// range of values to the ASCII character set (0-127).
1600/// @brief Simplify the toascii library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001601struct VISIBILITY_HIDDEN ToAsciiOptimization : public LibCallOptimization {
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001602public:
1603 /// @brief Default Constructor
Reid Spencer9974dda2005-05-03 02:54:54 +00001604 ToAsciiOptimization() : LibCallOptimization("toascii",
Reid Spencer789082a2005-05-07 20:15:59 +00001605 "Number of 'toascii' calls simplified") {}
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001606
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001607 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001608 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001609 // Just make sure this has 2 arguments
1610 return (f->arg_size() == 1);
1611 }
1612
1613 /// @brief Perform the toascii optimization.
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001614 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001615 // toascii(c) -> (c & 0x7f)
Chris Lattner679d7182007-04-07 00:42:32 +00001616 Value *chr = ci->getOperand(1);
1617 Value *and_inst = BinaryOperator::createAnd(chr,
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001618 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
Chris Lattner679d7182007-04-07 00:42:32 +00001619 return ReplaceCallWith(ci, and_inst);
Reid Spencer9f56b1f2005-04-30 03:17:54 +00001620 }
1621} ToAsciiOptimizer;
1622
Reid Spencerc29b13d2005-05-14 16:42:52 +00001623/// This LibCallOptimization will simplify calls to the "ffs" library
Jeff Cohen00b168892005-07-27 06:12:32 +00001624/// calls which find the first set bit in an int, long, or long long. The
Reid Spencerc29b13d2005-05-14 16:42:52 +00001625/// optimization is to compute the result at compile time if the argument is
1626/// a constant.
1627/// @brief Simplify the ffs library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001628struct VISIBILITY_HIDDEN FFSOptimization : public LibCallOptimization {
Reid Spencerc29b13d2005-05-14 16:42:52 +00001629protected:
1630 /// @brief Subclass Constructor
1631 FFSOptimization(const char* funcName, const char* description)
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001632 : LibCallOptimization(funcName, description) {}
Reid Spencerc29b13d2005-05-14 16:42:52 +00001633
1634public:
1635 /// @brief Default Constructor
1636 FFSOptimization() : LibCallOptimization("ffs",
1637 "Number of 'ffs' calls simplified") {}
1638
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001639 /// @brief Make sure that the "ffs" function has the right prototype
1640 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencerc29b13d2005-05-14 16:42:52 +00001641 // Just make sure this has 2 arguments
Reid Spencerc5b206b2006-12-31 05:48:39 +00001642 return F->arg_size() == 1 && F->getReturnType() == Type::Int32Ty;
Reid Spencerc29b13d2005-05-14 16:42:52 +00001643 }
1644
1645 /// @brief Perform the ffs optimization.
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001646 virtual bool OptimizeCall(CallInst *TheCall, SimplifyLibCalls &SLC) {
1647 if (ConstantInt *CI = dyn_cast<ConstantInt>(TheCall->getOperand(1))) {
Reid Spencerc29b13d2005-05-14 16:42:52 +00001648 // ffs(cnst) -> bit#
1649 // ffsl(cnst) -> bit#
Reid Spencerf74eb3f2005-05-15 21:19:45 +00001650 // ffsll(cnst) -> bit#
Reid Spencerb83eb642006-10-20 07:07:24 +00001651 uint64_t val = CI->getZExtValue();
Reid Spencerf74eb3f2005-05-15 21:19:45 +00001652 int result = 0;
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001653 if (val) {
1654 ++result;
1655 while ((val & 1) == 0) {
1656 ++result;
1657 val >>= 1;
1658 }
Reid Spencerf74eb3f2005-05-15 21:19:45 +00001659 }
Chris Lattner679d7182007-04-07 00:42:32 +00001660 return ReplaceCallWith(TheCall, ConstantInt::get(Type::Int32Ty, result));
Reid Spencerc29b13d2005-05-14 16:42:52 +00001661 }
Reid Spencerf74eb3f2005-05-15 21:19:45 +00001662
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001663 // ffs(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1664 // ffsl(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1665 // ffsll(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1666 const Type *ArgType = TheCall->getOperand(1)->getType();
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001667 const char *CTTZName;
Reid Spencera54b7cb2007-01-12 07:05:14 +00001668 assert(ArgType->getTypeID() == Type::IntegerTyID &&
1669 "llvm.cttz argument is not an integer?");
1670 unsigned BitWidth = cast<IntegerType>(ArgType)->getBitWidth();
Chris Lattner720922f2007-01-12 22:49:11 +00001671 if (BitWidth == 8)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001672 CTTZName = "llvm.cttz.i8";
Chris Lattner720922f2007-01-12 22:49:11 +00001673 else if (BitWidth == 16)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001674 CTTZName = "llvm.cttz.i16";
Chris Lattner720922f2007-01-12 22:49:11 +00001675 else if (BitWidth == 32)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001676 CTTZName = "llvm.cttz.i32";
Chris Lattner720922f2007-01-12 22:49:11 +00001677 else {
1678 assert(BitWidth == 64 && "Unknown bitwidth");
Reid Spencera54b7cb2007-01-12 07:05:14 +00001679 CTTZName = "llvm.cttz.i64";
Chris Lattner720922f2007-01-12 22:49:11 +00001680 }
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001681
Chris Lattnerb76efb72007-01-07 08:12:01 +00001682 Constant *F = SLC.getModule()->getOrInsertFunction(CTTZName, ArgType,
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001683 ArgType, NULL);
Reid Spencer7b06bd52006-12-13 00:50:17 +00001684 Value *V = CastInst::createIntegerCast(TheCall->getOperand(1), ArgType,
1685 false/*ZExt*/, "tmp", TheCall);
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001686 Value *V2 = new CallInst(F, V, "tmp", TheCall);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001687 V2 = CastInst::createIntegerCast(V2, Type::Int32Ty, false/*ZExt*/,
Reid Spencer7b06bd52006-12-13 00:50:17 +00001688 "tmp", TheCall);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001689 V2 = BinaryOperator::createAdd(V2, ConstantInt::get(Type::Int32Ty, 1),
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001690 "tmp", TheCall);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001691 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, V,
1692 Constant::getNullValue(V->getType()), "tmp",
1693 TheCall);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001694 V2 = new SelectInst(Cond, ConstantInt::get(Type::Int32Ty, 0), V2,
Chris Lattnerf91e97a2006-01-17 18:27:17 +00001695 TheCall->getName(), TheCall);
Chris Lattner679d7182007-04-07 00:42:32 +00001696 return ReplaceCallWith(TheCall, V2);
Reid Spencerc29b13d2005-05-14 16:42:52 +00001697 }
1698} FFSOptimizer;
1699
1700/// This LibCallOptimization will simplify calls to the "ffsl" library
1701/// calls. It simply uses FFSOptimization for which the transformation is
1702/// identical.
1703/// @brief Simplify the ffsl library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001704struct VISIBILITY_HIDDEN FFSLOptimization : public FFSOptimization {
Reid Spencerc29b13d2005-05-14 16:42:52 +00001705public:
1706 /// @brief Default Constructor
1707 FFSLOptimization() : FFSOptimization("ffsl",
1708 "Number of 'ffsl' calls simplified") {}
1709
1710} FFSLOptimizer;
1711
1712/// This LibCallOptimization will simplify calls to the "ffsll" library
1713/// calls. It simply uses FFSOptimization for which the transformation is
1714/// identical.
1715/// @brief Simplify the ffsl library function.
Reid Spencer9133fe22007-02-05 23:32:05 +00001716struct VISIBILITY_HIDDEN FFSLLOptimization : public FFSOptimization {
Reid Spencerc29b13d2005-05-14 16:42:52 +00001717public:
1718 /// @brief Default Constructor
1719 FFSLLOptimization() : FFSOptimization("ffsll",
1720 "Number of 'ffsll' calls simplified") {}
1721
1722} FFSLLOptimizer;
1723
Chris Lattner7070c5f2006-01-23 05:57:36 +00001724/// This optimizes unary functions that take and return doubles.
1725struct UnaryDoubleFPOptimizer : public LibCallOptimization {
1726 UnaryDoubleFPOptimizer(const char *Fn, const char *Desc)
1727 : LibCallOptimization(Fn, Desc) {}
Chris Lattner53249862005-08-24 17:22:17 +00001728
Chris Lattner7070c5f2006-01-23 05:57:36 +00001729 // Make sure that this function has the right prototype
Chris Lattner53249862005-08-24 17:22:17 +00001730 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1731 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1732 F->getReturnType() == Type::DoubleTy;
1733 }
Chris Lattner7070c5f2006-01-23 05:57:36 +00001734
1735 /// ShrinkFunctionToFloatVersion - If the input to this function is really a
1736 /// float, strength reduce this to a float version of the function,
1737 /// e.g. floor((double)FLT) -> (double)floorf(FLT). This can only be called
1738 /// when the target supports the destination function and where there can be
1739 /// no precision loss.
1740 static bool ShrinkFunctionToFloatVersion(CallInst *CI, SimplifyLibCalls &SLC,
Chris Lattnerb76efb72007-01-07 08:12:01 +00001741 Constant *(SimplifyLibCalls::*FP)()){
Chris Lattner679d7182007-04-07 00:42:32 +00001742 if (FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1)))
Chris Lattner53249862005-08-24 17:22:17 +00001743 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
Chris Lattner7070c5f2006-01-23 05:57:36 +00001744 Value *New = new CallInst((SLC.*FP)(), Cast->getOperand(0),
Chris Lattner53249862005-08-24 17:22:17 +00001745 CI->getName(), CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00001746 New = new FPExtInst(New, Type::DoubleTy, CI->getName(), CI);
Chris Lattner53249862005-08-24 17:22:17 +00001747 CI->replaceAllUsesWith(New);
1748 CI->eraseFromParent();
1749 if (Cast->use_empty())
1750 Cast->eraseFromParent();
1751 return true;
1752 }
Chris Lattner7070c5f2006-01-23 05:57:36 +00001753 return false;
Chris Lattner53249862005-08-24 17:22:17 +00001754 }
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001755};
1756
Chris Lattner7070c5f2006-01-23 05:57:36 +00001757
Reid Spencer9133fe22007-02-05 23:32:05 +00001758struct VISIBILITY_HIDDEN FloorOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner7070c5f2006-01-23 05:57:36 +00001759 FloorOptimization()
1760 : UnaryDoubleFPOptimizer("floor", "Number of 'floor' calls simplified") {}
1761
1762 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001763#ifdef HAVE_FLOORF
Chris Lattner7070c5f2006-01-23 05:57:36 +00001764 // If this is a float argument passed in, convert to floorf.
1765 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_floorf))
1766 return true;
Reid Spenceraa87e052006-01-19 08:36:56 +00001767#endif
Chris Lattner7070c5f2006-01-23 05:57:36 +00001768 return false; // opt failed
1769 }
1770} FloorOptimizer;
Chris Lattner53249862005-08-24 17:22:17 +00001771
Reid Spencer9133fe22007-02-05 23:32:05 +00001772struct VISIBILITY_HIDDEN CeilOptimization : public UnaryDoubleFPOptimizer {
Chris Lattnere46f6e92006-01-23 06:24:46 +00001773 CeilOptimization()
1774 : UnaryDoubleFPOptimizer("ceil", "Number of 'ceil' calls simplified") {}
1775
1776 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1777#ifdef HAVE_CEILF
1778 // If this is a float argument passed in, convert to ceilf.
1779 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_ceilf))
1780 return true;
1781#endif
1782 return false; // opt failed
1783 }
1784} CeilOptimizer;
Chris Lattner53249862005-08-24 17:22:17 +00001785
Reid Spencer9133fe22007-02-05 23:32:05 +00001786struct VISIBILITY_HIDDEN RoundOptimization : public UnaryDoubleFPOptimizer {
Chris Lattnere46f6e92006-01-23 06:24:46 +00001787 RoundOptimization()
1788 : UnaryDoubleFPOptimizer("round", "Number of 'round' calls simplified") {}
1789
1790 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1791#ifdef HAVE_ROUNDF
1792 // If this is a float argument passed in, convert to roundf.
1793 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_roundf))
1794 return true;
1795#endif
1796 return false; // opt failed
1797 }
1798} RoundOptimizer;
1799
Reid Spencer9133fe22007-02-05 23:32:05 +00001800struct VISIBILITY_HIDDEN RintOptimization : public UnaryDoubleFPOptimizer {
Chris Lattnere46f6e92006-01-23 06:24:46 +00001801 RintOptimization()
1802 : UnaryDoubleFPOptimizer("rint", "Number of 'rint' calls simplified") {}
1803
1804 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1805#ifdef HAVE_RINTF
1806 // If this is a float argument passed in, convert to rintf.
1807 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_rintf))
1808 return true;
1809#endif
1810 return false; // opt failed
1811 }
1812} RintOptimizer;
1813
Reid Spencer9133fe22007-02-05 23:32:05 +00001814struct VISIBILITY_HIDDEN NearByIntOptimization : public UnaryDoubleFPOptimizer {
Chris Lattnere46f6e92006-01-23 06:24:46 +00001815 NearByIntOptimization()
1816 : UnaryDoubleFPOptimizer("nearbyint",
1817 "Number of 'nearbyint' calls simplified") {}
1818
1819 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1820#ifdef HAVE_NEARBYINTF
1821 // If this is a float argument passed in, convert to nearbyintf.
1822 if (ShrinkFunctionToFloatVersion(CI, SLC,&SimplifyLibCalls::get_nearbyintf))
1823 return true;
1824#endif
1825 return false; // opt failed
1826 }
1827} NearByIntOptimizer;
Chris Lattner53249862005-08-24 17:22:17 +00001828
Chris Lattnerc8e17412007-04-06 22:54:17 +00001829/// GetConstantStringInfo - This function computes the length of a
1830/// null-terminated constant array of integers. This function can't rely on the
1831/// size of the constant array because there could be a null terminator in the
1832/// middle of the array.
1833///
Jeff Cohen00b168892005-07-27 06:12:32 +00001834/// We also have to bail out if we find a non-integer constant initializer
1835/// of one of the elements or if there is no null-terminator. The logic
Reid Spencer716f49e2005-04-27 21:29:20 +00001836/// below checks each of these conditions and will return true only if all
Chris Lattnerc8e17412007-04-06 22:54:17 +00001837/// conditions are met. If the conditions aren't met, this returns false.
1838///
1839/// If successful, the \p Array param is set to the constant array being
1840/// indexed, the \p Length parameter is set to the length of the null-terminated
1841/// string pointed to by V, the \p StartIdx value is set to the first
1842/// element of the Array that V points to, and true is returned.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001843static bool GetConstantStringInfo(Value *V, std::string &Str) {
1844 // Look through noop bitcast instructions.
1845 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1846 if (BCI->getType() == BCI->getOperand(0)->getType())
1847 return GetConstantStringInfo(BCI->getOperand(0), Str);
1848 return false;
1849 }
Chris Lattnerc8e17412007-04-06 22:54:17 +00001850
Jeff Cohen00b168892005-07-27 06:12:32 +00001851 // If the value is not a GEP instruction nor a constant expression with a
1852 // GEP instruction, then return false because ConstantArray can't occur
Reid Spencera16d5a52005-04-27 07:54:40 +00001853 // any other way
Chris Lattner0cd3a232007-04-07 21:58:02 +00001854 User *GEP = 0;
Chris Lattnerc8e17412007-04-06 22:54:17 +00001855 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Reid Spencera16d5a52005-04-27 07:54:40 +00001856 GEP = GEPI;
Chris Lattnerc8e17412007-04-06 22:54:17 +00001857 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1858 if (CE->getOpcode() != Instruction::GetElementPtr)
Reid Spencera16d5a52005-04-27 07:54:40 +00001859 return false;
Chris Lattnerc8e17412007-04-06 22:54:17 +00001860 GEP = CE;
1861 } else {
Reid Spencera16d5a52005-04-27 07:54:40 +00001862 return false;
Chris Lattnerc8e17412007-04-06 22:54:17 +00001863 }
Reid Spencera16d5a52005-04-27 07:54:40 +00001864
1865 // Make sure the GEP has exactly three arguments.
1866 if (GEP->getNumOperands() != 3)
1867 return false;
1868
1869 // Check to make sure that the first operand of the GEP is an integer and
Jeff Cohen00b168892005-07-27 06:12:32 +00001870 // has value 0 so that we are sure we're indexing into the initializer.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001871 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1872 if (!Idx->isZero())
Reid Spencera16d5a52005-04-27 07:54:40 +00001873 return false;
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001874 } else
Reid Spencera16d5a52005-04-27 07:54:40 +00001875 return false;
1876
Chris Lattnerc8e17412007-04-06 22:54:17 +00001877 // If the second index isn't a ConstantInt, then this is a variable index
1878 // into the array. If this occurs, we can't say anything meaningful about
1879 // the string.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001880 uint64_t StartIdx = 0;
Chris Lattnerc8e17412007-04-06 22:54:17 +00001881 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1882 StartIdx = CI->getZExtValue();
Reid Spencera16d5a52005-04-27 07:54:40 +00001883 else
1884 return false;
1885
1886 // The GEP instruction, constant or instruction, must reference a global
1887 // variable that is a constant and is initialized. The referenced constant
1888 // initializer is the array that we'll use for optimization.
1889 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1890 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1891 return false;
Chris Lattnerc8e17412007-04-06 22:54:17 +00001892 Constant *GlobalInit = GV->getInitializer();
Reid Spencera16d5a52005-04-27 07:54:40 +00001893
1894 // Handle the ConstantAggregateZero case
Chris Lattnerc8e17412007-04-06 22:54:17 +00001895 if (isa<ConstantAggregateZero>(GlobalInit)) {
Reid Spencera16d5a52005-04-27 07:54:40 +00001896 // This is a degenerate case. The initializer is constant zero so the
1897 // length of the string must be zero.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001898 Str.clear();
Reid Spencera16d5a52005-04-27 07:54:40 +00001899 return true;
1900 }
1901
1902 // Must be a Constant Array
Chris Lattner0cd3a232007-04-07 21:58:02 +00001903 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Chris Lattnerc8e17412007-04-06 22:54:17 +00001904 if (!Array) return false;
Reid Spencera16d5a52005-04-27 07:54:40 +00001905
1906 // Get the number of elements in the array
Chris Lattnerc8e17412007-04-06 22:54:17 +00001907 uint64_t NumElts = Array->getType()->getNumElements();
Reid Spencera16d5a52005-04-27 07:54:40 +00001908
Chris Lattner0cd3a232007-04-07 21:58:02 +00001909 // Traverse the constant array from StartIdx (derived above) which is
Jeff Cohen00b168892005-07-27 06:12:32 +00001910 // the place the GEP refers to in the array.
Chris Lattner0cd3a232007-04-07 21:58:02 +00001911 for (unsigned i = StartIdx; i < NumElts; ++i) {
1912 Constant *Elt = Array->getOperand(i);
1913 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1914 if (!CI) // This array isn't suitable, non-int initializer.
1915 return false;
1916 if (CI->isZero())
1917 return true; // we found end of string, success!
1918 Str += (char)CI->getZExtValue();
Reid Spencera16d5a52005-04-27 07:54:40 +00001919 }
Chris Lattner0f9f8c32006-01-22 22:35:08 +00001920
Chris Lattner0cd3a232007-04-07 21:58:02 +00001921 return false; // The array isn't null terminated.
Reid Spencera16d5a52005-04-27 07:54:40 +00001922}
1923
Reid Spencer134d2e42005-06-18 17:46:28 +00001924/// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
1925/// inserting the cast before IP, and return the cast.
1926/// @brief Cast a value to a "C" string.
Chris Lattner3492cda2007-04-07 21:04:50 +00001927static Value *CastToCStr(Value *V, Instruction *IP) {
Reid Spencerdccd9fe2006-12-13 08:04:32 +00001928 assert(isa<PointerType>(V->getType()) &&
Reid Spencer7b06bd52006-12-13 00:50:17 +00001929 "Can't cast non-pointer type to C string type");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001930 const Type *SBPTy = PointerType::getUnqual(Type::Int8Ty);
Reid Spencer134d2e42005-06-18 17:46:28 +00001931 if (V->getType() != SBPTy)
Chris Lattner3492cda2007-04-07 21:04:50 +00001932 return new BitCastInst(V, SBPTy, V->getName(), IP);
Reid Spencer134d2e42005-06-18 17:46:28 +00001933 return V;
1934}
1935
Jeff Cohen00b168892005-07-27 06:12:32 +00001936// TODO:
Reid Spencer8441a012005-04-28 04:40:06 +00001937// Additional cases that we need to add to this file:
1938//
Reid Spencer8441a012005-04-28 04:40:06 +00001939// cbrt:
Reid Spencer8441a012005-04-28 04:40:06 +00001940// * cbrt(expN(X)) -> expN(x/3)
1941// * cbrt(sqrt(x)) -> pow(x,1/6)
1942// * cbrt(sqrt(x)) -> pow(x,1/9)
1943//
Reid Spencer8441a012005-04-28 04:40:06 +00001944// cos, cosf, cosl:
Reid Spencer5624c752005-04-28 18:05:16 +00001945// * cos(-x) -> cos(x)
Reid Spencer8441a012005-04-28 04:40:06 +00001946//
1947// exp, expf, expl:
Reid Spencer8441a012005-04-28 04:40:06 +00001948// * exp(log(x)) -> x
1949//
Reid Spencer8441a012005-04-28 04:40:06 +00001950// log, logf, logl:
Reid Spencer8441a012005-04-28 04:40:06 +00001951// * log(exp(x)) -> x
1952// * log(x**y) -> y*log(x)
1953// * log(exp(y)) -> y*log(e)
1954// * log(exp2(y)) -> y*log(2)
1955// * log(exp10(y)) -> y*log(10)
1956// * log(sqrt(x)) -> 0.5*log(x)
1957// * log(pow(x,y)) -> y*log(x)
1958//
1959// lround, lroundf, lroundl:
1960// * lround(cnst) -> cnst'
1961//
1962// memcmp:
Reid Spencer8441a012005-04-28 04:40:06 +00001963// * memcmp(x,y,l) -> cnst
1964// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer8441a012005-04-28 04:40:06 +00001965//
Reid Spencer8441a012005-04-28 04:40:06 +00001966// memmove:
Jeff Cohen00b168892005-07-27 06:12:32 +00001967// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
Reid Spencer8441a012005-04-28 04:40:06 +00001968// (if s is a global constant array)
1969//
Reid Spencer8441a012005-04-28 04:40:06 +00001970// pow, powf, powl:
Reid Spencer8441a012005-04-28 04:40:06 +00001971// * pow(exp(x),y) -> exp(x*y)
1972// * pow(sqrt(x),y) -> pow(x,y*0.5)
1973// * pow(pow(x,y),z)-> pow(x,y*z)
1974//
1975// puts:
Chris Lattner35b9b492007-04-14 01:17:48 +00001976// * puts("") -> putchar("\n")
Reid Spencer8441a012005-04-28 04:40:06 +00001977//
1978// round, roundf, roundl:
1979// * round(cnst) -> cnst'
1980//
1981// signbit:
1982// * signbit(cnst) -> cnst'
1983// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1984//
Reid Spencer8441a012005-04-28 04:40:06 +00001985// sqrt, sqrtf, sqrtl:
Reid Spencer8441a012005-04-28 04:40:06 +00001986// * sqrt(expN(x)) -> expN(x*0.5)
1987// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1988// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1989//
Reid Spencer789082a2005-05-07 20:15:59 +00001990// stpcpy:
1991// * stpcpy(str, "literal") ->
1992// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer21506ff2005-05-03 07:23:44 +00001993// strrchr:
Reid Spencer8441a012005-04-28 04:40:06 +00001994// * strrchr(s,c) -> reverse_offset_of_in(c,s)
1995// (if c is a constant integer and s is a constant string)
1996// * strrchr(s1,0) -> strchr(s1,0)
1997//
Reid Spencer8441a012005-04-28 04:40:06 +00001998// strncat:
1999// * strncat(x,y,0) -> x
2000// * strncat(x,y,0) -> x (if strlen(y) = 0)
2001// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2002//
Reid Spencer8441a012005-04-28 04:40:06 +00002003// strncpy:
2004// * strncpy(d,s,0) -> d
2005// * strncpy(d,s,l) -> memcpy(d,s,l,1)
2006// (if s and l are constants)
2007//
2008// strpbrk:
2009// * strpbrk(s,a) -> offset_in_for(s,a)
2010// (if s and a are both constant strings)
2011// * strpbrk(s,"") -> 0
2012// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2013//
2014// strspn, strcspn:
2015// * strspn(s,a) -> const_int (if both args are constant)
2016// * strspn("",a) -> 0
2017// * strspn(s,"") -> 0
2018// * strcspn(s,a) -> const_int (if both args are constant)
2019// * strcspn("",a) -> 0
2020// * strcspn(s,"") -> strlen(a)
2021//
2022// strstr:
2023// * strstr(x,x) -> x
Jeff Cohen00b168892005-07-27 06:12:32 +00002024// * strstr(s1,s2) -> offset_of_s2_in(s1)
Reid Spencer8441a012005-04-28 04:40:06 +00002025// (if s1 and s2 are constant strings)
Jeff Cohen00b168892005-07-27 06:12:32 +00002026//
Reid Spencer8441a012005-04-28 04:40:06 +00002027// tan, tanf, tanl:
Reid Spencer8441a012005-04-28 04:40:06 +00002028// * tan(atan(x)) -> x
Jeff Cohen00b168892005-07-27 06:12:32 +00002029//
Reid Spencer8441a012005-04-28 04:40:06 +00002030// trunc, truncf, truncl:
2031// * trunc(cnst) -> cnst'
2032//
Jeff Cohen00b168892005-07-27 06:12:32 +00002033//
Reid Spencera7c049b2005-04-25 02:53:12 +00002034}