eliminate temporary vectors
[oota-llvm.git] / lib / Transforms / IPO / SimplifyLibCalls.cpp
1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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
13 // occurs within the main() function can be transformed into a simple "return 3"
14 // 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.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "simplify-libcalls"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/hash_map"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Config/config.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/IPO.h"
32 using namespace llvm;
33
34 /// This statistic keeps track of the total number of library calls that have
35 /// been simplified regardless of which call it is.
36 STATISTIC(SimplifiedLibCalls, "Number of library calls simplified");
37
38 namespace {
39   // Forward declarations
40   class LibCallOptimization;
41   class SimplifyLibCalls;
42   
43 /// This list is populated by the constructor for LibCallOptimization class.
44 /// Therefore all subclasses are registered here at static initialization time
45 /// and this list is what the SimplifyLibCalls pass uses to apply the individual
46 /// optimizations to the call sites.
47 /// @brief The list of optimizations deriving from LibCallOptimization
48 static LibCallOptimization *OptList = 0;
49
50 /// This class is the abstract base class for the set of optimizations that
51 /// corresponds to one library call. The SimplifyLibCalls pass will call the
52 /// ValidateCalledFunction method to ask the optimization if a given Function
53 /// is the kind that the optimization can handle. If the subclass returns true,
54 /// then SImplifyLibCalls will also call the OptimizeCall method to perform,
55 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
56 /// OptimizeCall won't be called. Subclasses are responsible for providing the
57 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
58 /// constructor. This is used to efficiently select which call instructions to
59 /// optimize. The criteria for a "lib call" is "anything with well known
60 /// semantics", typically a library function that is defined by an international
61 /// standard. Because the semantics are well known, the optimizations can
62 /// generally short-circuit actually calling the function if there's a simpler
63 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
64 /// @brief Base class for library call optimizations
65 class LibCallOptimization {
66   LibCallOptimization **Prev, *Next;
67   const char *FunctionName; ///< Name of the library call we optimize
68 #ifndef NDEBUG
69   Statistic occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
70 #endif
71 public:
72   /// The \p fname argument must be the name of the library function being
73   /// optimized by the subclass.
74   /// @brief Constructor that registers the optimization.
75   LibCallOptimization(const char *FName, const char *Description)
76     : FunctionName(FName) {
77       
78 #ifndef NDEBUG
79     occurrences.construct("simplify-libcalls", Description);
80 #endif
81     // Register this optimizer in the list of optimizations.
82     Next = OptList;
83     OptList = this;
84     Prev = &OptList;
85     if (Next) Next->Prev = &Next;
86   }
87   
88   /// getNext - All libcall optimizations are chained together into a list,
89   /// return the next one in the list.
90   LibCallOptimization *getNext() { return Next; }
91
92   /// @brief Deregister from the optlist
93   virtual ~LibCallOptimization() {
94     *Prev = Next;
95     if (Next) Next->Prev = Prev;
96   }
97
98   /// The implementation of this function in subclasses should determine if
99   /// \p F is suitable for the optimization. This method is called by
100   /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
101   /// sites of such a function if that function is not suitable in the first
102   /// place.  If the called function is suitabe, this method should return true;
103   /// false, otherwise. This function should also perform any lazy
104   /// initialization that the LibCallOptimization needs to do, if its to return
105   /// true. This avoids doing initialization until the optimizer is actually
106   /// going to be called upon to do some optimization.
107   /// @brief Determine if the function is suitable for optimization
108   virtual bool ValidateCalledFunction(
109     const Function* F,    ///< The function that is the target of call sites
110     SimplifyLibCalls& SLC ///< The pass object invoking us
111   ) = 0;
112
113   /// The implementations of this function in subclasses is the heart of the
114   /// SimplifyLibCalls algorithm. Sublcasses of this class implement
115   /// OptimizeCall to determine if (a) the conditions are right for optimizing
116   /// the call and (b) to perform the optimization. If an action is taken
117   /// against ci, the subclass is responsible for returning true and ensuring
118   /// that ci is erased from its parent.
119   /// @brief Optimize a call, if possible.
120   virtual bool OptimizeCall(
121     CallInst* ci,          ///< The call instruction that should be optimized.
122     SimplifyLibCalls& SLC  ///< The pass object invoking us
123   ) = 0;
124
125   /// @brief Get the name of the library call being optimized
126   const char *getFunctionName() const { return FunctionName; }
127
128   /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
129   void succeeded() {
130 #ifndef NDEBUG
131     DEBUG(++occurrences);
132 #endif
133   }
134 };
135
136 /// This class is an LLVM Pass that applies each of the LibCallOptimization
137 /// instances to all the call sites in a module, relatively efficiently. The
138 /// purpose of this pass is to provide optimizations for calls to well-known
139 /// functions with well-known semantics, such as those in the c library. The
140 /// class provides the basic infrastructure for handling runOnModule.  Whenever
141 /// this pass finds a function call, it asks the appropriate optimizer to
142 /// validate the call (ValidateLibraryCall). If it is validated, then
143 /// the OptimizeCall method is also called.
144 /// @brief A ModulePass for optimizing well-known function calls.
145 class SimplifyLibCalls : public ModulePass {
146 public:
147   /// We need some target data for accurate signature details that are
148   /// target dependent. So we require target data in our AnalysisUsage.
149   /// @brief Require TargetData from AnalysisUsage.
150   virtual void getAnalysisUsage(AnalysisUsage& Info) const {
151     // Ask that the TargetData analysis be performed before us so we can use
152     // the target data.
153     Info.addRequired<TargetData>();
154   }
155
156   /// For this pass, process all of the function calls in the module, calling
157   /// ValidateLibraryCall and OptimizeCall as appropriate.
158   /// @brief Run all the lib call optimizations on a Module.
159   virtual bool runOnModule(Module &M) {
160     reset(M);
161
162     bool result = false;
163     hash_map<std::string, LibCallOptimization*> OptznMap;
164     for (LibCallOptimization *Optzn = OptList; Optzn; Optzn = Optzn->getNext())
165       OptznMap[Optzn->getFunctionName()] = Optzn;
166
167     // The call optimizations can be recursive. That is, the optimization might
168     // generate a call to another function which can also be optimized. This way
169     // we make the LibCallOptimization instances very specific to the case they
170     // handle. It also means we need to keep running over the function calls in
171     // the module until we don't get any more optimizations possible.
172     bool found_optimization = false;
173     do {
174       found_optimization = false;
175       for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
176         // All the "well-known" functions are external and have external linkage
177         // because they live in a runtime library somewhere and were (probably)
178         // not compiled by LLVM.  So, we only act on external functions that
179         // have external or dllimport linkage and non-empty uses.
180         if (!FI->isDeclaration() ||
181             !(FI->hasExternalLinkage() || FI->hasDLLImportLinkage()) ||
182             FI->use_empty())
183           continue;
184
185         // Get the optimization class that pertains to this function
186         hash_map<std::string, LibCallOptimization*>::iterator OMI =
187           OptznMap.find(FI->getName());
188         if (OMI == OptznMap.end()) continue;
189         
190         LibCallOptimization *CO = OMI->second;
191
192         // Make sure the called function is suitable for the optimization
193         if (!CO->ValidateCalledFunction(FI, *this))
194           continue;
195
196         // Loop over each of the uses of the function
197         for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
198              UI != UE ; ) {
199           // If the use of the function is a call instruction
200           if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
201             // Do the optimization on the LibCallOptimization.
202             if (CO->OptimizeCall(CI, *this)) {
203               ++SimplifiedLibCalls;
204               found_optimization = result = true;
205               CO->succeeded();
206             }
207           }
208         }
209       }
210     } while (found_optimization);
211     
212     return result;
213   }
214
215   /// @brief Return the *current* module we're working on.
216   Module* getModule() const { return M; }
217
218   /// @brief Return the *current* target data for the module we're working on.
219   TargetData* getTargetData() const { return TD; }
220
221   /// @brief Return the size_t type -- syntactic shortcut
222   const Type* getIntPtrType() const { return TD->getIntPtrType(); }
223
224   /// @brief Return a Function* for the putchar libcall
225   Constant *get_putchar() {
226     if (!putchar_func)
227       putchar_func = 
228         M->getOrInsertFunction("putchar", Type::Int32Ty, Type::Int32Ty, NULL);
229     return putchar_func;
230   }
231
232   /// @brief Return a Function* for the puts libcall
233   Constant *get_puts() {
234     if (!puts_func)
235       puts_func = M->getOrInsertFunction("puts", Type::Int32Ty,
236                                          PointerType::get(Type::Int8Ty),
237                                          NULL);
238     return puts_func;
239   }
240
241   /// @brief Return a Function* for the fputc libcall
242   Constant *get_fputc(const Type* FILEptr_type) {
243     if (!fputc_func)
244       fputc_func = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
245                                           FILEptr_type, NULL);
246     return fputc_func;
247   }
248
249   /// @brief Return a Function* for the fputs libcall
250   Constant *get_fputs(const Type* FILEptr_type) {
251     if (!fputs_func)
252       fputs_func = M->getOrInsertFunction("fputs", Type::Int32Ty,
253                                           PointerType::get(Type::Int8Ty),
254                                           FILEptr_type, NULL);
255     return fputs_func;
256   }
257
258   /// @brief Return a Function* for the fwrite libcall
259   Constant *get_fwrite(const Type* FILEptr_type) {
260     if (!fwrite_func)
261       fwrite_func = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
262                                            PointerType::get(Type::Int8Ty),
263                                            TD->getIntPtrType(),
264                                            TD->getIntPtrType(),
265                                            FILEptr_type, NULL);
266     return fwrite_func;
267   }
268
269   /// @brief Return a Function* for the sqrt libcall
270   Constant *get_sqrt() {
271     if (!sqrt_func)
272       sqrt_func = M->getOrInsertFunction("sqrt", Type::DoubleTy, 
273                                          Type::DoubleTy, NULL);
274     return sqrt_func;
275   }
276
277   /// @brief Return a Function* for the strcpy libcall
278   Constant *get_strcpy() {
279     if (!strcpy_func)
280       strcpy_func = M->getOrInsertFunction("strcpy",
281                                            PointerType::get(Type::Int8Ty),
282                                            PointerType::get(Type::Int8Ty),
283                                            PointerType::get(Type::Int8Ty),
284                                            NULL);
285     return strcpy_func;
286   }
287
288   /// @brief Return a Function* for the strlen libcall
289   Constant *get_strlen() {
290     if (!strlen_func)
291       strlen_func = M->getOrInsertFunction("strlen", TD->getIntPtrType(),
292                                            PointerType::get(Type::Int8Ty),
293                                            NULL);
294     return strlen_func;
295   }
296
297   /// @brief Return a Function* for the memchr libcall
298   Constant *get_memchr() {
299     if (!memchr_func)
300       memchr_func = M->getOrInsertFunction("memchr",
301                                            PointerType::get(Type::Int8Ty),
302                                            PointerType::get(Type::Int8Ty),
303                                            Type::Int32Ty, TD->getIntPtrType(),
304                                            NULL);
305     return memchr_func;
306   }
307
308   /// @brief Return a Function* for the memcpy libcall
309   Constant *get_memcpy() {
310     if (!memcpy_func) {
311       const Type *SBP = PointerType::get(Type::Int8Ty);
312       const char *N = TD->getIntPtrType() == Type::Int32Ty ?
313                             "llvm.memcpy.i32" : "llvm.memcpy.i64";
314       memcpy_func = M->getOrInsertFunction(N, Type::VoidTy, SBP, SBP,
315                                            TD->getIntPtrType(), Type::Int32Ty,
316                                            NULL);
317     }
318     return memcpy_func;
319   }
320
321   Constant *getUnaryFloatFunction(const char *Name, Constant *&Cache) {
322     if (!Cache)
323       Cache = M->getOrInsertFunction(Name, Type::FloatTy, Type::FloatTy, NULL);
324     return Cache;
325   }
326   
327   Constant *get_floorf() { return getUnaryFloatFunction("floorf", floorf_func);}
328   Constant *get_ceilf()  { return getUnaryFloatFunction( "ceilf",  ceilf_func);}
329   Constant *get_roundf() { return getUnaryFloatFunction("roundf", roundf_func);}
330   Constant *get_rintf()  { return getUnaryFloatFunction( "rintf",  rintf_func);}
331   Constant *get_nearbyintf() { return getUnaryFloatFunction("nearbyintf",
332                                                             nearbyintf_func); }
333 private:
334   /// @brief Reset our cached data for a new Module
335   void reset(Module& mod) {
336     M = &mod;
337     TD = &getAnalysis<TargetData>();
338     putchar_func = 0;
339     puts_func = 0;
340     fputc_func = 0;
341     fputs_func = 0;
342     fwrite_func = 0;
343     memcpy_func = 0;
344     memchr_func = 0;
345     sqrt_func   = 0;
346     strcpy_func = 0;
347     strlen_func = 0;
348     floorf_func = 0;
349     ceilf_func = 0;
350     roundf_func = 0;
351     rintf_func = 0;
352     nearbyintf_func = 0;
353   }
354
355 private:
356   /// Caches for function pointers.
357   Constant *putchar_func, *puts_func;
358   Constant *fputc_func, *fputs_func, *fwrite_func;
359   Constant *memcpy_func, *memchr_func;
360   Constant *sqrt_func;
361   Constant *strcpy_func, *strlen_func;
362   Constant *floorf_func, *ceilf_func, *roundf_func;
363   Constant *rintf_func, *nearbyintf_func;
364   Module *M;             ///< Cached Module
365   TargetData *TD;        ///< Cached TargetData
366 };
367
368 // Register the pass
369 RegisterPass<SimplifyLibCalls>
370 X("simplify-libcalls", "Simplify well-known library calls");
371
372 } // anonymous namespace
373
374 // The only public symbol in this file which just instantiates the pass object
375 ModulePass *llvm::createSimplifyLibCallsPass() {
376   return new SimplifyLibCalls();
377 }
378
379 // Classes below here, in the anonymous namespace, are all subclasses of the
380 // LibCallOptimization class, each implementing all optimizations possible for a
381 // single well-known library call. Each has a static singleton instance that
382 // auto registers it into the "optlist" global above.
383 namespace {
384
385 // Forward declare utility functions.
386 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
387 Value *CastToCStr(Value *V, Instruction &IP);
388
389 /// This LibCallOptimization will find instances of a call to "exit" that occurs
390 /// within the "main" function and change it to a simple "ret" instruction with
391 /// the same value passed to the exit function. When this is done, it splits the
392 /// basic block at the exit(3) call and deletes the call instruction.
393 /// @brief Replace calls to exit in main with a simple return
394 struct ExitInMainOptimization : public LibCallOptimization {
395   ExitInMainOptimization() : LibCallOptimization("exit",
396       "Number of 'exit' calls simplified") {}
397
398   // Make sure the called function looks like exit (int argument, int return
399   // type, external linkage, not varargs).
400   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
401     return F->arg_size() >= 1 && F->arg_begin()->getType()->isInteger();
402   }
403
404   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
405     // To be careful, we check that the call to exit is coming from "main", that
406     // main has external linkage, and the return type of main and the argument
407     // to exit have the same type.
408     Function *from = ci->getParent()->getParent();
409     if (from->hasExternalLinkage())
410       if (from->getReturnType() == ci->getOperand(1)->getType())
411         if (from->getName() == "main") {
412           // Okay, time to actually do the optimization. First, get the basic
413           // block of the call instruction
414           BasicBlock* bb = ci->getParent();
415
416           // Create a return instruction that we'll replace the call with.
417           // Note that the argument of the return is the argument of the call
418           // instruction.
419           new ReturnInst(ci->getOperand(1), ci);
420
421           // Split the block at the call instruction which places it in a new
422           // basic block.
423           bb->splitBasicBlock(ci);
424
425           // The block split caused a branch instruction to be inserted into
426           // the end of the original block, right after the return instruction
427           // that we put there. That's not a valid block, so delete the branch
428           // instruction.
429           bb->getInstList().pop_back();
430
431           // Now we can finally get rid of the call instruction which now lives
432           // in the new basic block.
433           ci->eraseFromParent();
434
435           // Optimization succeeded, return true.
436           return true;
437         }
438     // We didn't pass the criteria for this optimization so return false
439     return false;
440   }
441 } ExitInMainOptimizer;
442
443 /// This LibCallOptimization will simplify a call to the strcat library
444 /// function. The simplification is possible only if the string being
445 /// concatenated is a constant array or a constant expression that results in
446 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
447 /// of the constant string. Both of these calls are further reduced, if possible
448 /// on subsequent passes.
449 /// @brief Simplify the strcat library function.
450 struct StrCatOptimization : public LibCallOptimization {
451 public:
452   /// @brief Default constructor
453   StrCatOptimization() : LibCallOptimization("strcat",
454       "Number of 'strcat' calls simplified") {}
455
456 public:
457
458   /// @brief Make sure that the "strcat" function has the right prototype
459   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
460     if (f->getReturnType() == PointerType::get(Type::Int8Ty))
461       if (f->arg_size() == 2)
462       {
463         Function::const_arg_iterator AI = f->arg_begin();
464         if (AI++->getType() == PointerType::get(Type::Int8Ty))
465           if (AI->getType() == PointerType::get(Type::Int8Ty))
466           {
467             // Indicate this is a suitable call type.
468             return true;
469           }
470       }
471     return false;
472   }
473
474   /// @brief Optimize the strcat library function
475   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
476     // Extract some information from the instruction
477     Value* dest = ci->getOperand(1);
478     Value* src  = ci->getOperand(2);
479
480     // Extract the initializer (while making numerous checks) from the
481     // source operand of the call to strcat. If we get null back, one of
482     // a variety of checks in get_GVInitializer failed
483     uint64_t len = 0;
484     if (!getConstantStringLength(src,len))
485       return false;
486
487     // Handle the simple, do-nothing case
488     if (len == 0) {
489       ci->replaceAllUsesWith(dest);
490       ci->eraseFromParent();
491       return true;
492     }
493
494     // Increment the length because we actually want to memcpy the null
495     // terminator as well.
496     len++;
497
498     // We need to find the end of the destination string.  That's where the
499     // memory is to be moved to. We just generate a call to strlen (further
500     // optimized in another pass).  Note that the SLC.get_strlen() call
501     // caches the Function* for us.
502     CallInst* strlen_inst =
503       new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
504
505     // Now that we have the destination's length, we must index into the
506     // destination's pointer to get the actual memcpy destination (end of
507     // the string .. we're concatenating).
508     GetElementPtrInst* gep =
509       new GetElementPtrInst(dest, strlen_inst, dest->getName()+".indexed", ci);
510
511     // We have enough information to now generate the memcpy call to
512     // do the concatenation for us.
513     std::vector<Value*> vals;
514     vals.push_back(gep); // destination
515     vals.push_back(ci->getOperand(2)); // source
516     vals.push_back(ConstantInt::get(SLC.getIntPtrType(),len)); // length
517     vals.push_back(ConstantInt::get(Type::Int32Ty,1)); // alignment
518     new CallInst(SLC.get_memcpy(), vals, "", ci);
519
520     // Finally, substitute the first operand of the strcat call for the
521     // strcat call itself since strcat returns its first operand; and,
522     // kill the strcat CallInst.
523     ci->replaceAllUsesWith(dest);
524     ci->eraseFromParent();
525     return true;
526   }
527 } StrCatOptimizer;
528
529 /// This LibCallOptimization will simplify a call to the strchr library
530 /// function.  It optimizes out cases where the arguments are both constant
531 /// and the result can be determined statically.
532 /// @brief Simplify the strcmp library function.
533 struct StrChrOptimization : public LibCallOptimization {
534 public:
535   StrChrOptimization() : LibCallOptimization("strchr",
536       "Number of 'strchr' calls simplified") {}
537
538   /// @brief Make sure that the "strchr" function has the right prototype
539   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
540     if (f->getReturnType() == PointerType::get(Type::Int8Ty) &&
541         f->arg_size() == 2)
542       return true;
543     return false;
544   }
545
546   /// @brief Perform the strchr optimizations
547   virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
548     // If there aren't three operands, bail
549     if (ci->getNumOperands() != 3)
550       return false;
551
552     // Check that the first argument to strchr is a constant array of sbyte.
553     // If it is, get the length and data, otherwise return false.
554     uint64_t len = 0;
555     ConstantArray* CA = 0;
556     if (!getConstantStringLength(ci->getOperand(1), len, &CA))
557       return false;
558
559     // Check that the second argument to strchr is a constant int. If it isn't
560     // a constant signed integer, we can try an alternate optimization
561     ConstantInt* CSI = dyn_cast<ConstantInt>(ci->getOperand(2));
562     if (!CSI) {
563       // The second operand is not constant, or not signed. Just lower this to 
564       // memchr since we know the length of the string since it is constant.
565       Constant *f = SLC.get_memchr();
566       std::vector<Value*> args;
567       args.push_back(ci->getOperand(1));
568       args.push_back(ci->getOperand(2));
569       args.push_back(ConstantInt::get(SLC.getIntPtrType(), len));
570       ci->replaceAllUsesWith(new CallInst(f, args, ci->getName(), ci));
571       ci->eraseFromParent();
572       return true;
573     }
574
575     // Get the character we're looking for
576     int64_t chr = CSI->getSExtValue();
577
578     // Compute the offset
579     uint64_t offset = 0;
580     bool char_found = false;
581     for (uint64_t i = 0; i < len; ++i) {
582       if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i))) {
583         // Check for the null terminator
584         if (CI->isNullValue())
585           break; // we found end of string
586         else if (CI->getSExtValue() == chr) {
587           char_found = true;
588           offset = i;
589           break;
590         }
591       }
592     }
593
594     // strchr(s,c)  -> offset_of_in(c,s)
595     //    (if c is a constant integer and s is a constant string)
596     if (char_found) {
597       Value* Idx = ConstantInt::get(Type::Int64Ty,offset);
598       GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1), Idx, 
599           ci->getOperand(1)->getName()+".strchr",ci);
600       ci->replaceAllUsesWith(GEP);
601     } else {
602       ci->replaceAllUsesWith(
603           ConstantPointerNull::get(PointerType::get(Type::Int8Ty)));
604     }
605     ci->eraseFromParent();
606     return true;
607   }
608 } StrChrOptimizer;
609
610 /// This LibCallOptimization will simplify a call to the strcmp library
611 /// function.  It optimizes out cases where one or both arguments are constant
612 /// and the result can be determined statically.
613 /// @brief Simplify the strcmp library function.
614 struct StrCmpOptimization : public LibCallOptimization {
615 public:
616   StrCmpOptimization() : LibCallOptimization("strcmp",
617       "Number of 'strcmp' calls simplified") {}
618
619   /// @brief Make sure that the "strcmp" function has the right prototype
620   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
621     return F->getReturnType() == Type::Int32Ty && F->arg_size() == 2;
622   }
623
624   /// @brief Perform the strcmp optimization
625   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
626     // First, check to see if src and destination are the same. If they are,
627     // then the optimization is to replace the CallInst with a constant 0
628     // because the call is a no-op.
629     Value* s1 = ci->getOperand(1);
630     Value* s2 = ci->getOperand(2);
631     if (s1 == s2) {
632       // strcmp(x,x)  -> 0
633       ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,0));
634       ci->eraseFromParent();
635       return true;
636     }
637
638     bool isstr_1 = false;
639     uint64_t len_1 = 0;
640     ConstantArray* A1;
641     if (getConstantStringLength(s1,len_1,&A1)) {
642       isstr_1 = true;
643       if (len_1 == 0) {
644         // strcmp("",x) -> *x
645         LoadInst* load =
646           new LoadInst(CastToCStr(s2,*ci), ci->getName()+".load",ci);
647         CastInst* cast =
648           CastInst::create(Instruction::SExt, load, Type::Int32Ty, 
649                            ci->getName()+".int", ci);
650         ci->replaceAllUsesWith(cast);
651         ci->eraseFromParent();
652         return true;
653       }
654     }
655
656     bool isstr_2 = false;
657     uint64_t len_2 = 0;
658     ConstantArray* A2;
659     if (getConstantStringLength(s2, len_2, &A2)) {
660       isstr_2 = true;
661       if (len_2 == 0) {
662         // strcmp(x,"") -> *x
663         LoadInst* load =
664           new LoadInst(CastToCStr(s1,*ci),ci->getName()+".val",ci);
665         CastInst* cast =
666           CastInst::create(Instruction::SExt, load, Type::Int32Ty, 
667                            ci->getName()+".int", ci);
668         ci->replaceAllUsesWith(cast);
669         ci->eraseFromParent();
670         return true;
671       }
672     }
673
674     if (isstr_1 && isstr_2) {
675       // strcmp(x,y)  -> cnst  (if both x and y are constant strings)
676       std::string str1 = A1->getAsString();
677       std::string str2 = A2->getAsString();
678       int result = strcmp(str1.c_str(), str2.c_str());
679       ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,result));
680       ci->eraseFromParent();
681       return true;
682     }
683     return false;
684   }
685 } StrCmpOptimizer;
686
687 /// This LibCallOptimization will simplify a call to the strncmp library
688 /// function.  It optimizes out cases where one or both arguments are constant
689 /// and the result can be determined statically.
690 /// @brief Simplify the strncmp library function.
691 struct StrNCmpOptimization : public LibCallOptimization {
692 public:
693   StrNCmpOptimization() : LibCallOptimization("strncmp",
694       "Number of 'strncmp' calls simplified") {}
695
696   /// @brief Make sure that the "strncmp" function has the right prototype
697   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
698     if (f->getReturnType() == Type::Int32Ty && f->arg_size() == 3)
699       return true;
700     return false;
701   }
702
703   /// @brief Perform the strncpy optimization
704   virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
705     // First, check to see if src and destination are the same. If they are,
706     // then the optimization is to replace the CallInst with a constant 0
707     // because the call is a no-op.
708     Value* s1 = ci->getOperand(1);
709     Value* s2 = ci->getOperand(2);
710     if (s1 == s2) {
711       // strncmp(x,x,l)  -> 0
712       ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,0));
713       ci->eraseFromParent();
714       return true;
715     }
716
717     // Check the length argument, if it is Constant zero then the strings are
718     // considered equal.
719     uint64_t len_arg = 0;
720     bool len_arg_is_const = false;
721     if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3))) {
722       len_arg_is_const = true;
723       len_arg = len_CI->getZExtValue();
724       if (len_arg == 0) {
725         // strncmp(x,y,0)   -> 0
726         ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,0));
727         ci->eraseFromParent();
728         return true;
729       }
730     }
731
732     bool isstr_1 = false;
733     uint64_t len_1 = 0;
734     ConstantArray* A1;
735     if (getConstantStringLength(s1, len_1, &A1)) {
736       isstr_1 = true;
737       if (len_1 == 0) {
738         // strncmp("",x) -> *x
739         LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
740         CastInst* cast =
741           CastInst::create(Instruction::SExt, load, Type::Int32Ty, 
742                            ci->getName()+".int", ci);
743         ci->replaceAllUsesWith(cast);
744         ci->eraseFromParent();
745         return true;
746       }
747     }
748
749     bool isstr_2 = false;
750     uint64_t len_2 = 0;
751     ConstantArray* A2;
752     if (getConstantStringLength(s2,len_2,&A2)) {
753       isstr_2 = true;
754       if (len_2 == 0) {
755         // strncmp(x,"") -> *x
756         LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
757         CastInst* cast =
758           CastInst::create(Instruction::SExt, load, Type::Int32Ty, 
759                            ci->getName()+".int", ci);
760         ci->replaceAllUsesWith(cast);
761         ci->eraseFromParent();
762         return true;
763       }
764     }
765
766     if (isstr_1 && isstr_2 && len_arg_is_const) {
767       // strncmp(x,y,const) -> constant
768       std::string str1 = A1->getAsString();
769       std::string str2 = A2->getAsString();
770       int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
771       ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,result));
772       ci->eraseFromParent();
773       return true;
774     }
775     return false;
776   }
777 } StrNCmpOptimizer;
778
779 /// This LibCallOptimization will simplify a call to the strcpy library
780 /// function.  Two optimizations are possible:
781 /// (1) If src and dest are the same and not volatile, just return dest
782 /// (2) If the src is a constant then we can convert to llvm.memmove
783 /// @brief Simplify the strcpy library function.
784 struct StrCpyOptimization : public LibCallOptimization {
785 public:
786   StrCpyOptimization() : LibCallOptimization("strcpy",
787       "Number of 'strcpy' calls simplified") {}
788
789   /// @brief Make sure that the "strcpy" function has the right prototype
790   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
791     if (f->getReturnType() == PointerType::get(Type::Int8Ty))
792       if (f->arg_size() == 2) {
793         Function::const_arg_iterator AI = f->arg_begin();
794         if (AI++->getType() == PointerType::get(Type::Int8Ty))
795           if (AI->getType() == PointerType::get(Type::Int8Ty)) {
796             // Indicate this is a suitable call type.
797             return true;
798           }
799       }
800     return false;
801   }
802
803   /// @brief Perform the strcpy optimization
804   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
805     // First, check to see if src and destination are the same. If they are,
806     // then the optimization is to replace the CallInst with the destination
807     // because the call is a no-op. Note that this corresponds to the
808     // degenerate strcpy(X,X) case which should have "undefined" results
809     // according to the C specification. However, it occurs sometimes and
810     // we optimize it as a no-op.
811     Value* dest = ci->getOperand(1);
812     Value* src = ci->getOperand(2);
813     if (dest == src) {
814       ci->replaceAllUsesWith(dest);
815       ci->eraseFromParent();
816       return true;
817     }
818
819     // Get the length of the constant string referenced by the second operand,
820     // the "src" parameter. Fail the optimization if we can't get the length
821     // (note that getConstantStringLength does lots of checks to make sure this
822     // is valid).
823     uint64_t len = 0;
824     if (!getConstantStringLength(ci->getOperand(2),len))
825       return false;
826
827     // If the constant string's length is zero we can optimize this by just
828     // doing a store of 0 at the first byte of the destination
829     if (len == 0) {
830       new StoreInst(ConstantInt::get(Type::Int8Ty,0),ci->getOperand(1),ci);
831       ci->replaceAllUsesWith(dest);
832       ci->eraseFromParent();
833       return true;
834     }
835
836     // Increment the length because we actually want to memcpy the null
837     // terminator as well.
838     len++;
839
840     // We have enough information to now generate the memcpy call to
841     // do the concatenation for us.
842     std::vector<Value*> vals;
843     vals.push_back(dest); // destination
844     vals.push_back(src); // source
845     vals.push_back(ConstantInt::get(SLC.getIntPtrType(),len)); // length
846     vals.push_back(ConstantInt::get(Type::Int32Ty,1)); // alignment
847     new CallInst(SLC.get_memcpy(), vals, "", ci);
848
849     // Finally, substitute the first operand of the strcat call for the
850     // strcat call itself since strcat returns its first operand; and,
851     // kill the strcat CallInst.
852     ci->replaceAllUsesWith(dest);
853     ci->eraseFromParent();
854     return true;
855   }
856 } StrCpyOptimizer;
857
858 /// This LibCallOptimization will simplify a call to the strlen library
859 /// function by replacing it with a constant value if the string provided to
860 /// it is a constant array.
861 /// @brief Simplify the strlen library function.
862 struct StrLenOptimization : public LibCallOptimization {
863   StrLenOptimization() : LibCallOptimization("strlen",
864       "Number of 'strlen' calls simplified") {}
865
866   /// @brief Make sure that the "strlen" function has the right prototype
867   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
868   {
869     if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
870       if (f->arg_size() == 1)
871         if (Function::const_arg_iterator AI = f->arg_begin())
872           if (AI->getType() == PointerType::get(Type::Int8Ty))
873             return true;
874     return false;
875   }
876
877   /// @brief Perform the strlen optimization
878   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
879   {
880     // Make sure we're dealing with an sbyte* here.
881     Value* str = ci->getOperand(1);
882     if (str->getType() != PointerType::get(Type::Int8Ty))
883       return false;
884
885     // Does the call to strlen have exactly one use?
886     if (ci->hasOneUse())
887       // Is that single use a icmp operator?
888       if (ICmpInst* bop = dyn_cast<ICmpInst>(ci->use_back()))
889         // Is it compared against a constant integer?
890         if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
891         {
892           // Get the value the strlen result is compared to
893           uint64_t val = CI->getZExtValue();
894
895           // If its compared against length 0 with == or !=
896           if (val == 0 &&
897               (bop->getPredicate() == ICmpInst::ICMP_EQ ||
898                bop->getPredicate() == ICmpInst::ICMP_NE))
899           {
900             // strlen(x) != 0 -> *x != 0
901             // strlen(x) == 0 -> *x == 0
902             LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
903             ICmpInst* rbop = new ICmpInst(bop->getPredicate(), load, 
904                                           ConstantInt::get(Type::Int8Ty,0),
905                                           bop->getName()+".strlen", ci);
906             bop->replaceAllUsesWith(rbop);
907             bop->eraseFromParent();
908             ci->eraseFromParent();
909             return true;
910           }
911         }
912
913     // Get the length of the constant string operand
914     uint64_t len = 0;
915     if (!getConstantStringLength(ci->getOperand(1),len))
916       return false;
917
918     // strlen("xyz") -> 3 (for example)
919     const Type *Ty = SLC.getTargetData()->getIntPtrType();
920     ci->replaceAllUsesWith(ConstantInt::get(Ty, len));
921      
922     ci->eraseFromParent();
923     return true;
924   }
925 } StrLenOptimizer;
926
927 /// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
928 /// is equal or not-equal to zero. 
929 static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
930   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
931        UI != E; ++UI) {
932     Instruction *User = cast<Instruction>(*UI);
933     if (ICmpInst *IC = dyn_cast<ICmpInst>(User)) {
934       if ((IC->getPredicate() == ICmpInst::ICMP_NE ||
935            IC->getPredicate() == ICmpInst::ICMP_EQ) &&
936           isa<Constant>(IC->getOperand(1)) &&
937           cast<Constant>(IC->getOperand(1))->isNullValue())
938         continue;
939     } else if (CastInst *CI = dyn_cast<CastInst>(User))
940       if (CI->getType() == Type::Int1Ty)
941         continue;
942     // Unknown instruction.
943     return false;
944   }
945   return true;
946 }
947
948 /// This memcmpOptimization will simplify a call to the memcmp library
949 /// function.
950 struct memcmpOptimization : public LibCallOptimization {
951   /// @brief Default Constructor
952   memcmpOptimization()
953     : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
954   
955   /// @brief Make sure that the "memcmp" function has the right prototype
956   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
957     Function::const_arg_iterator AI = F->arg_begin();
958     if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
959     if (!isa<PointerType>((++AI)->getType())) return false;
960     if (!(++AI)->getType()->isInteger()) return false;
961     if (!F->getReturnType()->isInteger()) return false;
962     return true;
963   }
964   
965   /// Because of alignment and instruction information that we don't have, we
966   /// leave the bulk of this to the code generators.
967   ///
968   /// Note that we could do much more if we could force alignment on otherwise
969   /// small aligned allocas, or if we could indicate that loads have a small
970   /// alignment.
971   virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
972     Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
973
974     // If the two operands are the same, return zero.
975     if (LHS == RHS) {
976       // memcmp(s,s,x) -> 0
977       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
978       CI->eraseFromParent();
979       return true;
980     }
981     
982     // Make sure we have a constant length.
983     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
984     if (!LenC) return false;
985     uint64_t Len = LenC->getZExtValue();
986       
987     // If the length is zero, this returns 0.
988     switch (Len) {
989     case 0:
990       // memcmp(s1,s2,0) -> 0
991       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
992       CI->eraseFromParent();
993       return true;
994     case 1: {
995       // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
996       const Type *UCharPtr = PointerType::get(Type::Int8Ty);
997       CastInst *Op1Cast = CastInst::create(
998           Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
999       CastInst *Op2Cast = CastInst::create(
1000           Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
1001       Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
1002       Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
1003       Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
1004       if (RV->getType() != CI->getType())
1005         RV = CastInst::createIntegerCast(RV, CI->getType(), false, 
1006                                          RV->getName(), CI);
1007       CI->replaceAllUsesWith(RV);
1008       CI->eraseFromParent();
1009       return true;
1010     }
1011     case 2:
1012       if (IsOnlyUsedInEqualsZeroComparison(CI)) {
1013         // TODO: IF both are aligned, use a short load/compare.
1014       
1015         // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
1016         const Type *UCharPtr = PointerType::get(Type::Int8Ty);
1017         CastInst *Op1Cast = CastInst::create(
1018             Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
1019         CastInst *Op2Cast = CastInst::create(
1020             Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
1021         Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
1022         Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
1023         Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
1024                                               CI->getName()+".d1", CI);
1025         Constant *One = ConstantInt::get(Type::Int32Ty, 1);
1026         Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
1027         Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
1028         Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
1029         Value *S2V2 = new LoadInst(G2, RHS->getName()+".val2", CI);
1030         Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
1031                                               CI->getName()+".d1", CI);
1032         Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
1033         if (Or->getType() != CI->getType())
1034           Or = CastInst::createIntegerCast(Or, CI->getType(), false /*ZExt*/, 
1035                                            Or->getName(), CI);
1036         CI->replaceAllUsesWith(Or);
1037         CI->eraseFromParent();
1038         return true;
1039       }
1040       break;
1041     default:
1042       break;
1043     }
1044     
1045     return false;
1046   }
1047 } memcmpOptimizer;
1048
1049
1050 /// This LibCallOptimization will simplify a call to the memcpy library
1051 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1052 /// bytes depending on the length of the string and the alignment. Additional
1053 /// optimizations are possible in code generation (sequence of immediate store)
1054 /// @brief Simplify the memcpy library function.
1055 struct LLVMMemCpyMoveOptzn : public LibCallOptimization {
1056   LLVMMemCpyMoveOptzn(const char* fname, const char* desc)
1057   : LibCallOptimization(fname, desc) {}
1058
1059   /// @brief Make sure that the "memcpy" function has the right prototype
1060   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD) {
1061     // Just make sure this has 4 arguments per LLVM spec.
1062     return (f->arg_size() == 4);
1063   }
1064
1065   /// Because of alignment and instruction information that we don't have, we
1066   /// leave the bulk of this to the code generators. The optimization here just
1067   /// deals with a few degenerate cases where the length of the string and the
1068   /// alignment match the sizes of our intrinsic types so we can do a load and
1069   /// store instead of the memcpy call.
1070   /// @brief Perform the memcpy optimization.
1071   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD) {
1072     // Make sure we have constant int values to work with
1073     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1074     if (!LEN)
1075       return false;
1076     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1077     if (!ALIGN)
1078       return false;
1079
1080     // If the length is larger than the alignment, we can't optimize
1081     uint64_t len = LEN->getZExtValue();
1082     uint64_t alignment = ALIGN->getZExtValue();
1083     if (alignment == 0)
1084       alignment = 1; // Alignment 0 is identity for alignment 1
1085     if (len > alignment)
1086       return false;
1087
1088     // Get the type we will cast to, based on size of the string
1089     Value* dest = ci->getOperand(1);
1090     Value* src = ci->getOperand(2);
1091     const Type* castType = 0;
1092     switch (len)
1093     {
1094       case 0:
1095         // memcpy(d,s,0,a) -> noop
1096         ci->eraseFromParent();
1097         return true;
1098       case 1: castType = Type::Int8Ty; break;
1099       case 2: castType = Type::Int16Ty; break;
1100       case 4: castType = Type::Int32Ty; break;
1101       case 8: castType = Type::Int64Ty; break;
1102       default:
1103         return false;
1104     }
1105
1106     // Cast source and dest to the right sized primitive and then load/store
1107     CastInst* SrcCast = CastInst::create(Instruction::BitCast,
1108         src, PointerType::get(castType), src->getName()+".cast", ci);
1109     CastInst* DestCast = CastInst::create(Instruction::BitCast,
1110         dest, PointerType::get(castType),dest->getName()+".cast", ci);
1111     LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
1112     new StoreInst(LI, DestCast, ci);
1113     ci->eraseFromParent();
1114     return true;
1115   }
1116 };
1117
1118 /// This LibCallOptimization will simplify a call to the memcpy/memmove library
1119 /// functions.
1120 LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer32("llvm.memcpy.i32",
1121                                     "Number of 'llvm.memcpy' calls simplified");
1122 LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer64("llvm.memcpy.i64",
1123                                    "Number of 'llvm.memcpy' calls simplified");
1124 LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer32("llvm.memmove.i32",
1125                                    "Number of 'llvm.memmove' calls simplified");
1126 LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer64("llvm.memmove.i64",
1127                                    "Number of 'llvm.memmove' calls simplified");
1128
1129 /// This LibCallOptimization will simplify a call to the memset library
1130 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1131 /// bytes depending on the length argument.
1132 struct LLVMMemSetOptimization : public LibCallOptimization {
1133   /// @brief Default Constructor
1134   LLVMMemSetOptimization(const char *Name) : LibCallOptimization(Name,
1135       "Number of 'llvm.memset' calls simplified") {}
1136
1137   /// @brief Make sure that the "memset" function has the right prototype
1138   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
1139     // Just make sure this has 3 arguments per LLVM spec.
1140     return F->arg_size() == 4;
1141   }
1142
1143   /// Because of alignment and instruction information that we don't have, we
1144   /// leave the bulk of this to the code generators. The optimization here just
1145   /// deals with a few degenerate cases where the length parameter is constant
1146   /// and the alignment matches the sizes of our intrinsic types so we can do
1147   /// store instead of the memcpy call. Other calls are transformed into the
1148   /// llvm.memset intrinsic.
1149   /// @brief Perform the memset optimization.
1150   virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &TD) {
1151     // Make sure we have constant int values to work with
1152     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1153     if (!LEN)
1154       return false;
1155     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1156     if (!ALIGN)
1157       return false;
1158
1159     // Extract the length and alignment
1160     uint64_t len = LEN->getZExtValue();
1161     uint64_t alignment = ALIGN->getZExtValue();
1162
1163     // Alignment 0 is identity for alignment 1
1164     if (alignment == 0)
1165       alignment = 1;
1166
1167     // If the length is zero, this is a no-op
1168     if (len == 0) {
1169       // memset(d,c,0,a) -> noop
1170       ci->eraseFromParent();
1171       return true;
1172     }
1173
1174     // If the length is larger than the alignment, we can't optimize
1175     if (len > alignment)
1176       return false;
1177
1178     // Make sure we have a constant ubyte to work with so we can extract
1179     // the value to be filled.
1180     ConstantInt* FILL = dyn_cast<ConstantInt>(ci->getOperand(2));
1181     if (!FILL)
1182       return false;
1183     if (FILL->getType() != Type::Int8Ty)
1184       return false;
1185
1186     // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1187
1188     // Extract the fill character
1189     uint64_t fill_char = FILL->getZExtValue();
1190     uint64_t fill_value = fill_char;
1191
1192     // Get the type we will cast to, based on size of memory area to fill, and
1193     // and the value we will store there.
1194     Value* dest = ci->getOperand(1);
1195     const Type* castType = 0;
1196     switch (len) {
1197       case 1:
1198         castType = Type::Int8Ty;
1199         break;
1200       case 2:
1201         castType = Type::Int16Ty;
1202         fill_value |= fill_char << 8;
1203         break;
1204       case 4:
1205         castType = Type::Int32Ty;
1206         fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1207         break;
1208       case 8:
1209         castType = Type::Int64Ty;
1210         fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1211         fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1212         fill_value |= fill_char << 56;
1213         break;
1214       default:
1215         return false;
1216     }
1217
1218     // Cast dest to the right sized primitive and then load/store
1219     CastInst* DestCast = new BitCastInst(dest, PointerType::get(castType), 
1220                                          dest->getName()+".cast", ci);
1221     new StoreInst(ConstantInt::get(castType,fill_value),DestCast, ci);
1222     ci->eraseFromParent();
1223     return true;
1224   }
1225 };
1226
1227 LLVMMemSetOptimization MemSet32Optimizer("llvm.memset.i32");
1228 LLVMMemSetOptimization MemSet64Optimizer("llvm.memset.i64");
1229
1230
1231 /// This LibCallOptimization will simplify calls to the "pow" library
1232 /// function. It looks for cases where the result of pow is well known and
1233 /// substitutes the appropriate value.
1234 /// @brief Simplify the pow library function.
1235 struct PowOptimization : public LibCallOptimization {
1236 public:
1237   /// @brief Default Constructor
1238   PowOptimization() : LibCallOptimization("pow",
1239       "Number of 'pow' calls simplified") {}
1240
1241   /// @brief Make sure that the "pow" function has the right prototype
1242   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1243     // Just make sure this has 2 arguments
1244     return (f->arg_size() == 2);
1245   }
1246
1247   /// @brief Perform the pow optimization.
1248   virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1249     const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1250     Value* base = ci->getOperand(1);
1251     Value* expn = ci->getOperand(2);
1252     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1253       double Op1V = Op1->getValue();
1254       if (Op1V == 1.0) {
1255         // pow(1.0,x) -> 1.0
1256         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1257         ci->eraseFromParent();
1258         return true;
1259       }
1260     }  else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) {
1261       double Op2V = Op2->getValue();
1262       if (Op2V == 0.0) {
1263         // pow(x,0.0) -> 1.0
1264         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1265         ci->eraseFromParent();
1266         return true;
1267       } else if (Op2V == 0.5) {
1268         // pow(x,0.5) -> sqrt(x)
1269         CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1270             ci->getName()+".pow",ci);
1271         ci->replaceAllUsesWith(sqrt_inst);
1272         ci->eraseFromParent();
1273         return true;
1274       } else if (Op2V == 1.0) {
1275         // pow(x,1.0) -> x
1276         ci->replaceAllUsesWith(base);
1277         ci->eraseFromParent();
1278         return true;
1279       } else if (Op2V == -1.0) {
1280         // pow(x,-1.0)    -> 1.0/x
1281         BinaryOperator* div_inst= BinaryOperator::createFDiv(
1282           ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1283         ci->replaceAllUsesWith(div_inst);
1284         ci->eraseFromParent();
1285         return true;
1286       }
1287     }
1288     return false; // opt failed
1289   }
1290 } PowOptimizer;
1291
1292 /// This LibCallOptimization will simplify calls to the "printf" library
1293 /// function. It looks for cases where the result of printf is not used and the
1294 /// operation can be reduced to something simpler.
1295 /// @brief Simplify the printf library function.
1296 struct PrintfOptimization : public LibCallOptimization {
1297 public:
1298   /// @brief Default Constructor
1299   PrintfOptimization() : LibCallOptimization("printf",
1300       "Number of 'printf' calls simplified") {}
1301
1302   /// @brief Make sure that the "printf" function has the right prototype
1303   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1304     // Just make sure this has at least 1 arguments
1305     return (f->arg_size() >= 1);
1306   }
1307
1308   /// @brief Perform the printf optimization.
1309   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
1310     // If the call has more than 2 operands, we can't optimize it
1311     if (ci->getNumOperands() > 3 || ci->getNumOperands() <= 2)
1312       return false;
1313
1314     // If the result of the printf call is used, none of these optimizations
1315     // can be made.
1316     if (!ci->use_empty())
1317       return false;
1318
1319     // All the optimizations depend on the length of the first argument and the
1320     // fact that it is a constant string array. Check that now
1321     uint64_t len = 0;
1322     ConstantArray* CA = 0;
1323     if (!getConstantStringLength(ci->getOperand(1), len, &CA))
1324       return false;
1325
1326     if (len != 2 && len != 3)
1327       return false;
1328
1329     // The first character has to be a %
1330     if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1331       if (CI->getZExtValue() != '%')
1332         return false;
1333
1334     // Get the second character and switch on its value
1335     ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1336     switch (CI->getZExtValue()) {
1337       case 's':
1338       {
1339         if (len != 3 ||
1340             dyn_cast<ConstantInt>(CA->getOperand(2))->getZExtValue() != '\n')
1341           return false;
1342
1343         // printf("%s\n",str) -> puts(str)
1344         std::vector<Value*> args;
1345         new CallInst(SLC.get_puts(), CastToCStr(ci->getOperand(2), *ci),
1346                      ci->getName(), ci);
1347         ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty, len));
1348         break;
1349       }
1350       case 'c':
1351       {
1352         // printf("%c",c) -> putchar(c)
1353         if (len != 2)
1354           return false;
1355
1356         CastInst *Char = CastInst::createSExtOrBitCast(
1357             ci->getOperand(2), Type::Int32Ty, CI->getName()+".int", ci);
1358         new CallInst(SLC.get_putchar(), Char, "", ci);
1359         ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty, 1));
1360         break;
1361       }
1362       default:
1363         return false;
1364     }
1365     ci->eraseFromParent();
1366     return true;
1367   }
1368 } PrintfOptimizer;
1369
1370 /// This LibCallOptimization will simplify calls to the "fprintf" library
1371 /// function. It looks for cases where the result of fprintf is not used and the
1372 /// operation can be reduced to something simpler.
1373 /// @brief Simplify the fprintf library function.
1374 struct FPrintFOptimization : public LibCallOptimization {
1375 public:
1376   /// @brief Default Constructor
1377   FPrintFOptimization() : LibCallOptimization("fprintf",
1378       "Number of 'fprintf' calls simplified") {}
1379
1380   /// @brief Make sure that the "fprintf" function has the right prototype
1381   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1382     // Just make sure this has at least 2 arguments
1383     return (f->arg_size() >= 2);
1384   }
1385
1386   /// @brief Perform the fprintf optimization.
1387   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
1388     // If the call has more than 3 operands, we can't optimize it
1389     if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1390       return false;
1391
1392     // If the result of the fprintf call is used, none of these optimizations
1393     // can be made.
1394     if (!ci->use_empty())
1395       return false;
1396
1397     // All the optimizations depend on the length of the second argument and the
1398     // fact that it is a constant string array. Check that now
1399     uint64_t len = 0;
1400     ConstantArray* CA = 0;
1401     if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1402       return false;
1403
1404     if (ci->getNumOperands() == 3) {
1405       // Make sure there's no % in the constant array
1406       for (unsigned i = 0; i < len; ++i) {
1407         if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i))) {
1408           // Check for the null terminator
1409           if (CI->getZExtValue() == '%')
1410             return false; // we found end of string
1411         } else {
1412           return false;
1413         }
1414       }
1415
1416       // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
1417       const Type* FILEptr_type = ci->getOperand(1)->getType();
1418
1419       // Make sure that the fprintf() and fwrite() functions both take the
1420       // same type of char pointer.
1421       if (ci->getOperand(2)->getType() != PointerType::get(Type::Int8Ty))
1422         return false;
1423
1424       std::vector<Value*> args;
1425       args.push_back(ci->getOperand(2));
1426       args.push_back(ConstantInt::get(SLC.getIntPtrType(),len));
1427       args.push_back(ConstantInt::get(SLC.getIntPtrType(),1));
1428       args.push_back(ci->getOperand(1));
1429       new CallInst(SLC.get_fwrite(FILEptr_type), args, ci->getName(), ci);
1430       ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,len));
1431       ci->eraseFromParent();
1432       return true;
1433     }
1434
1435     // The remaining optimizations require the format string to be length 2
1436     // "%s" or "%c".
1437     if (len != 2)
1438       return false;
1439
1440     // The first character has to be a %
1441     if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1442       if (CI->getZExtValue() != '%')
1443         return false;
1444
1445     // Get the second character and switch on its value
1446     ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1447     switch (CI->getZExtValue()) {
1448       case 's':
1449       {
1450         uint64_t len = 0;
1451         ConstantArray* CA = 0;
1452         if (getConstantStringLength(ci->getOperand(3), len, &CA)) {
1453           // fprintf(file,"%s",str) -> fwrite(str,strlen(str),1,file)
1454           const Type* FILEptr_type = ci->getOperand(1)->getType();
1455           std::vector<Value*> args;
1456           args.push_back(CastToCStr(ci->getOperand(3), *ci));
1457           args.push_back(ConstantInt::get(SLC.getIntPtrType(), len));
1458           args.push_back(ConstantInt::get(SLC.getIntPtrType(), 1));
1459           args.push_back(ci->getOperand(1));
1460           new CallInst(SLC.get_fwrite(FILEptr_type), args, ci->getName(), ci);
1461           ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty, len));
1462         } else {
1463           // fprintf(file,"%s",str) -> fputs(str,file)
1464           const Type* FILEptr_type = ci->getOperand(1)->getType();
1465           new CallInst(SLC.get_fputs(FILEptr_type),
1466                        CastToCStr(ci->getOperand(3), *ci),
1467                        ci->getOperand(1), ci->getName(),ci);
1468           ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,len));
1469         }
1470         break;
1471       }
1472       case 'c':
1473       {
1474         // fprintf(file,"%c",c) -> fputc(c,file)
1475         const Type* FILEptr_type = ci->getOperand(1)->getType();
1476         CastInst* cast = CastInst::createSExtOrBitCast(
1477             ci->getOperand(3), Type::Int32Ty, CI->getName()+".int", ci);
1478         new CallInst(SLC.get_fputc(FILEptr_type), cast,ci->getOperand(1),"",ci);
1479         ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,1));
1480         break;
1481       }
1482       default:
1483         return false;
1484     }
1485     ci->eraseFromParent();
1486     return true;
1487   }
1488 } FPrintFOptimizer;
1489
1490 /// This LibCallOptimization will simplify calls to the "sprintf" library
1491 /// function. It looks for cases where the result of sprintf is not used and the
1492 /// operation can be reduced to something simpler.
1493 /// @brief Simplify the sprintf library function.
1494 struct SPrintFOptimization : public LibCallOptimization {
1495 public:
1496   /// @brief Default Constructor
1497   SPrintFOptimization() : LibCallOptimization("sprintf",
1498       "Number of 'sprintf' calls simplified") {}
1499
1500   /// @brief Make sure that the "fprintf" function has the right prototype
1501   virtual bool ValidateCalledFunction(const Function *f, SimplifyLibCalls &SLC){
1502     // Just make sure this has at least 2 arguments
1503     return (f->getReturnType() == Type::Int32Ty && f->arg_size() >= 2);
1504   }
1505
1506   /// @brief Perform the sprintf optimization.
1507   virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1508     // If the call has more than 3 operands, we can't optimize it
1509     if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1510       return false;
1511
1512     // All the optimizations depend on the length of the second argument and the
1513     // fact that it is a constant string array. Check that now
1514     uint64_t len = 0;
1515     ConstantArray* CA = 0;
1516     if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1517       return false;
1518
1519     if (ci->getNumOperands() == 3) {
1520       if (len == 0) {
1521         // If the length is 0, we just need to store a null byte
1522         new StoreInst(ConstantInt::get(Type::Int8Ty,0),ci->getOperand(1),ci);
1523         ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,0));
1524         ci->eraseFromParent();
1525         return true;
1526       }
1527
1528       // Make sure there's no % in the constant array
1529       for (unsigned i = 0; i < len; ++i) {
1530         if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i))) {
1531           // Check for the null terminator
1532           if (CI->getZExtValue() == '%')
1533             return false; // we found a %, can't optimize
1534         } else {
1535           return false; // initializer is not constant int, can't optimize
1536         }
1537       }
1538
1539       // Increment length because we want to copy the null byte too
1540       len++;
1541
1542       // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
1543       std::vector<Value*> args;
1544       args.push_back(ci->getOperand(1));
1545       args.push_back(ci->getOperand(2));
1546       args.push_back(ConstantInt::get(SLC.getIntPtrType(),len));
1547       args.push_back(ConstantInt::get(Type::Int32Ty,1));
1548       new CallInst(SLC.get_memcpy(), args, "", ci);
1549       ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,len));
1550       ci->eraseFromParent();
1551       return true;
1552     }
1553
1554     // The remaining optimizations require the format string to be length 2
1555     // "%s" or "%c".
1556     if (len != 2)
1557       return false;
1558
1559     // The first character has to be a %
1560     if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1561       if (CI->getZExtValue() != '%')
1562         return false;
1563
1564     // Get the second character and switch on its value
1565     ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1566     switch (CI->getZExtValue()) {
1567     case 's': {
1568       // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1569       Value *Len = new CallInst(SLC.get_strlen(),
1570                                 CastToCStr(ci->getOperand(3), *ci),
1571                                 ci->getOperand(3)->getName()+".len", ci);
1572       Value *Len1 = BinaryOperator::createAdd(Len,
1573                                             ConstantInt::get(Len->getType(), 1),
1574                                               Len->getName()+"1", ci);
1575       if (Len1->getType() != SLC.getIntPtrType())
1576         Len1 = CastInst::createIntegerCast(Len1, SLC.getIntPtrType(), false,
1577                                            Len1->getName(), ci);
1578       std::vector<Value*> args;
1579       args.push_back(CastToCStr(ci->getOperand(1), *ci));
1580       args.push_back(CastToCStr(ci->getOperand(3), *ci));
1581       args.push_back(Len1);
1582       args.push_back(ConstantInt::get(Type::Int32Ty,1));
1583       new CallInst(SLC.get_memcpy(), args, "", ci);
1584       
1585       // The strlen result is the unincremented number of bytes in the string.
1586       if (!ci->use_empty()) {
1587         if (Len->getType() != ci->getType())
1588           Len = CastInst::createIntegerCast(Len, ci->getType(), false, 
1589                                             Len->getName(), ci);
1590         ci->replaceAllUsesWith(Len);
1591       }
1592       ci->eraseFromParent();
1593       return true;
1594     }
1595     case 'c': {
1596       // sprintf(dest,"%c",chr) -> store chr, dest
1597       CastInst* cast = CastInst::createTruncOrBitCast(
1598           ci->getOperand(3), Type::Int8Ty, "char", ci);
1599       new StoreInst(cast, ci->getOperand(1), ci);
1600       GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1601         ConstantInt::get(Type::Int32Ty,1),ci->getOperand(1)->getName()+".end",
1602         ci);
1603       new StoreInst(ConstantInt::get(Type::Int8Ty,0),gep,ci);
1604       ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,1));
1605       ci->eraseFromParent();
1606       return true;
1607     }
1608     }
1609     return false;
1610   }
1611 } SPrintFOptimizer;
1612
1613 /// This LibCallOptimization will simplify calls to the "fputs" library
1614 /// function. It looks for cases where the result of fputs is not used and the
1615 /// operation can be reduced to something simpler.
1616 /// @brief Simplify the puts library function.
1617 struct PutsOptimization : public LibCallOptimization {
1618 public:
1619   /// @brief Default Constructor
1620   PutsOptimization() : LibCallOptimization("fputs",
1621       "Number of 'fputs' calls simplified") {}
1622
1623   /// @brief Make sure that the "fputs" function has the right prototype
1624   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1625     // Just make sure this has 2 arguments
1626     return F->arg_size() == 2;
1627   }
1628
1629   /// @brief Perform the fputs optimization.
1630   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
1631     // If the result is used, none of these optimizations work
1632     if (!ci->use_empty())
1633       return false;
1634
1635     // All the optimizations depend on the length of the first argument and the
1636     // fact that it is a constant string array. Check that now
1637     uint64_t len = 0;
1638     if (!getConstantStringLength(ci->getOperand(1), len))
1639       return false;
1640
1641     switch (len) {
1642       case 0:
1643         // fputs("",F) -> noop
1644         break;
1645       case 1:
1646       {
1647         // fputs(s,F)  -> fputc(s[0],F)  (if s is constant and strlen(s) == 1)
1648         const Type* FILEptr_type = ci->getOperand(2)->getType();
1649         LoadInst* loadi = new LoadInst(ci->getOperand(1),
1650           ci->getOperand(1)->getName()+".byte",ci);
1651         CastInst* casti = new SExtInst(loadi, Type::Int32Ty, 
1652                                        loadi->getName()+".int", ci);
1653         new CallInst(SLC.get_fputc(FILEptr_type), casti,
1654                      ci->getOperand(2), "", ci);
1655         break;
1656       }
1657       default:
1658       {
1659         // fputs(s,F)  -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1660         const Type* FILEptr_type = ci->getOperand(2)->getType();
1661         std::vector<Value*> parms;
1662         parms.push_back(ci->getOperand(1));
1663         parms.push_back(ConstantInt::get(SLC.getIntPtrType(),len));
1664         parms.push_back(ConstantInt::get(SLC.getIntPtrType(),1));
1665         parms.push_back(ci->getOperand(2));
1666         new CallInst(SLC.get_fwrite(FILEptr_type), parms, "", ci);
1667         break;
1668       }
1669     }
1670     ci->eraseFromParent();
1671     return true; // success
1672   }
1673 } PutsOptimizer;
1674
1675 /// This LibCallOptimization will simplify calls to the "isdigit" library
1676 /// function. It simply does range checks the parameter explicitly.
1677 /// @brief Simplify the isdigit library function.
1678 struct isdigitOptimization : public LibCallOptimization {
1679 public:
1680   isdigitOptimization() : LibCallOptimization("isdigit",
1681       "Number of 'isdigit' calls simplified") {}
1682
1683   /// @brief Make sure that the "isdigit" function has the right prototype
1684   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1685     // Just make sure this has 1 argument
1686     return (f->arg_size() == 1);
1687   }
1688
1689   /// @brief Perform the toascii optimization.
1690   virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1691     if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1))) {
1692       // isdigit(c)   -> 0 or 1, if 'c' is constant
1693       uint64_t val = CI->getZExtValue();
1694       if (val >= '0' && val <='9')
1695         ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,1));
1696       else
1697         ci->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty,0));
1698       ci->eraseFromParent();
1699       return true;
1700     }
1701
1702     // isdigit(c)   -> (unsigned)c - '0' <= 9
1703     CastInst* cast = CastInst::createIntegerCast(ci->getOperand(1),
1704         Type::Int32Ty, false/*ZExt*/, ci->getOperand(1)->getName()+".uint", ci);
1705     BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
1706         ConstantInt::get(Type::Int32Ty,0x30),
1707         ci->getOperand(1)->getName()+".sub",ci);
1708     ICmpInst* setcond_inst = new ICmpInst(ICmpInst::ICMP_ULE,sub_inst,
1709         ConstantInt::get(Type::Int32Ty,9),
1710         ci->getOperand(1)->getName()+".cmp",ci);
1711     CastInst* c2 = new ZExtInst(setcond_inst, Type::Int32Ty, 
1712         ci->getOperand(1)->getName()+".isdigit", ci);
1713     ci->replaceAllUsesWith(c2);
1714     ci->eraseFromParent();
1715     return true;
1716   }
1717 } isdigitOptimizer;
1718
1719 struct isasciiOptimization : public LibCallOptimization {
1720 public:
1721   isasciiOptimization()
1722     : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1723   
1724   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1725     return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() && 
1726            F->getReturnType()->isInteger();
1727   }
1728   
1729   /// @brief Perform the isascii optimization.
1730   virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1731     // isascii(c)   -> (unsigned)c < 128
1732     Value *V = CI->getOperand(1);
1733     Value *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, V, 
1734                               ConstantInt::get(V->getType(), 128), 
1735                               V->getName()+".isascii", CI);
1736     if (Cmp->getType() != CI->getType())
1737       Cmp = new BitCastInst(Cmp, CI->getType(), Cmp->getName(), CI);
1738     CI->replaceAllUsesWith(Cmp);
1739     CI->eraseFromParent();
1740     return true;
1741   }
1742 } isasciiOptimizer;
1743
1744
1745 /// This LibCallOptimization will simplify calls to the "toascii" library
1746 /// function. It simply does the corresponding and operation to restrict the
1747 /// range of values to the ASCII character set (0-127).
1748 /// @brief Simplify the toascii library function.
1749 struct ToAsciiOptimization : public LibCallOptimization {
1750 public:
1751   /// @brief Default Constructor
1752   ToAsciiOptimization() : LibCallOptimization("toascii",
1753       "Number of 'toascii' calls simplified") {}
1754
1755   /// @brief Make sure that the "fputs" function has the right prototype
1756   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1757     // Just make sure this has 2 arguments
1758     return (f->arg_size() == 1);
1759   }
1760
1761   /// @brief Perform the toascii optimization.
1762   virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1763     // toascii(c)   -> (c & 0x7f)
1764     Value* chr = ci->getOperand(1);
1765     BinaryOperator* and_inst = BinaryOperator::createAnd(chr,
1766         ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1767     ci->replaceAllUsesWith(and_inst);
1768     ci->eraseFromParent();
1769     return true;
1770   }
1771 } ToAsciiOptimizer;
1772
1773 /// This LibCallOptimization will simplify calls to the "ffs" library
1774 /// calls which find the first set bit in an int, long, or long long. The
1775 /// optimization is to compute the result at compile time if the argument is
1776 /// a constant.
1777 /// @brief Simplify the ffs library function.
1778 struct FFSOptimization : public LibCallOptimization {
1779 protected:
1780   /// @brief Subclass Constructor
1781   FFSOptimization(const char* funcName, const char* description)
1782     : LibCallOptimization(funcName, description) {}
1783
1784 public:
1785   /// @brief Default Constructor
1786   FFSOptimization() : LibCallOptimization("ffs",
1787       "Number of 'ffs' calls simplified") {}
1788
1789   /// @brief Make sure that the "ffs" function has the right prototype
1790   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1791     // Just make sure this has 2 arguments
1792     return F->arg_size() == 1 && F->getReturnType() == Type::Int32Ty;
1793   }
1794
1795   /// @brief Perform the ffs optimization.
1796   virtual bool OptimizeCall(CallInst *TheCall, SimplifyLibCalls &SLC) {
1797     if (ConstantInt *CI = dyn_cast<ConstantInt>(TheCall->getOperand(1))) {
1798       // ffs(cnst)  -> bit#
1799       // ffsl(cnst) -> bit#
1800       // ffsll(cnst) -> bit#
1801       uint64_t val = CI->getZExtValue();
1802       int result = 0;
1803       if (val) {
1804         ++result;
1805         while ((val & 1) == 0) {
1806           ++result;
1807           val >>= 1;
1808         }
1809       }
1810       TheCall->replaceAllUsesWith(ConstantInt::get(Type::Int32Ty, result));
1811       TheCall->eraseFromParent();
1812       return true;
1813     }
1814
1815     // ffs(x)   -> x == 0 ? 0 : llvm.cttz(x)+1
1816     // ffsl(x)  -> x == 0 ? 0 : llvm.cttz(x)+1
1817     // ffsll(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1818     const Type *ArgType = TheCall->getOperand(1)->getType();
1819     const char *CTTZName;
1820     assert(ArgType->getTypeID() == Type::IntegerTyID &&
1821            "llvm.cttz argument is not an integer?");
1822     unsigned BitWidth = cast<IntegerType>(ArgType)->getBitWidth();
1823     if (BitWidth == 8)
1824       CTTZName = "llvm.cttz.i8";
1825     else if (BitWidth == 16)
1826       CTTZName = "llvm.cttz.i16"; 
1827     else if (BitWidth == 32)
1828       CTTZName = "llvm.cttz.i32";
1829     else {
1830       assert(BitWidth == 64 && "Unknown bitwidth");
1831       CTTZName = "llvm.cttz.i64";
1832     }
1833     
1834     Constant *F = SLC.getModule()->getOrInsertFunction(CTTZName, ArgType,
1835                                                        ArgType, NULL);
1836     Value *V = CastInst::createIntegerCast(TheCall->getOperand(1), ArgType, 
1837                                            false/*ZExt*/, "tmp", TheCall);
1838     Value *V2 = new CallInst(F, V, "tmp", TheCall);
1839     V2 = CastInst::createIntegerCast(V2, Type::Int32Ty, false/*ZExt*/, 
1840                                      "tmp", TheCall);
1841     V2 = BinaryOperator::createAdd(V2, ConstantInt::get(Type::Int32Ty, 1),
1842                                    "tmp", TheCall);
1843     Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, V, 
1844                                Constant::getNullValue(V->getType()), "tmp", 
1845                                TheCall);
1846     V2 = new SelectInst(Cond, ConstantInt::get(Type::Int32Ty, 0), V2,
1847                         TheCall->getName(), TheCall);
1848     TheCall->replaceAllUsesWith(V2);
1849     TheCall->eraseFromParent();
1850     return true;
1851   }
1852 } FFSOptimizer;
1853
1854 /// This LibCallOptimization will simplify calls to the "ffsl" library
1855 /// calls. It simply uses FFSOptimization for which the transformation is
1856 /// identical.
1857 /// @brief Simplify the ffsl library function.
1858 struct FFSLOptimization : public FFSOptimization {
1859 public:
1860   /// @brief Default Constructor
1861   FFSLOptimization() : FFSOptimization("ffsl",
1862       "Number of 'ffsl' calls simplified") {}
1863
1864 } FFSLOptimizer;
1865
1866 /// This LibCallOptimization will simplify calls to the "ffsll" library
1867 /// calls. It simply uses FFSOptimization for which the transformation is
1868 /// identical.
1869 /// @brief Simplify the ffsl library function.
1870 struct FFSLLOptimization : public FFSOptimization {
1871 public:
1872   /// @brief Default Constructor
1873   FFSLLOptimization() : FFSOptimization("ffsll",
1874       "Number of 'ffsll' calls simplified") {}
1875
1876 } FFSLLOptimizer;
1877
1878 /// This optimizes unary functions that take and return doubles.
1879 struct UnaryDoubleFPOptimizer : public LibCallOptimization {
1880   UnaryDoubleFPOptimizer(const char *Fn, const char *Desc)
1881   : LibCallOptimization(Fn, Desc) {}
1882   
1883   // Make sure that this function has the right prototype
1884   virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1885     return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1886            F->getReturnType() == Type::DoubleTy;
1887   }
1888
1889   /// ShrinkFunctionToFloatVersion - If the input to this function is really a
1890   /// float, strength reduce this to a float version of the function,
1891   /// e.g. floor((double)FLT) -> (double)floorf(FLT).  This can only be called
1892   /// when the target supports the destination function and where there can be
1893   /// no precision loss.
1894   static bool ShrinkFunctionToFloatVersion(CallInst *CI, SimplifyLibCalls &SLC,
1895                                            Constant *(SimplifyLibCalls::*FP)()){
1896     if (CastInst *Cast = dyn_cast<CastInst>(CI->getOperand(1)))
1897       if (Cast->getOperand(0)->getType() == Type::FloatTy) {
1898         Value *New = new CallInst((SLC.*FP)(), Cast->getOperand(0),
1899                                   CI->getName(), CI);
1900         New = new FPExtInst(New, Type::DoubleTy, CI->getName(), CI);
1901         CI->replaceAllUsesWith(New);
1902         CI->eraseFromParent();
1903         if (Cast->use_empty())
1904           Cast->eraseFromParent();
1905         return true;
1906       }
1907     return false;
1908   }
1909 };
1910
1911
1912 struct FloorOptimization : public UnaryDoubleFPOptimizer {
1913   FloorOptimization()
1914     : UnaryDoubleFPOptimizer("floor", "Number of 'floor' calls simplified") {}
1915   
1916   virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1917 #ifdef HAVE_FLOORF
1918     // If this is a float argument passed in, convert to floorf.
1919     if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_floorf))
1920       return true;
1921 #endif
1922     return false; // opt failed
1923   }
1924 } FloorOptimizer;
1925
1926 struct CeilOptimization : public UnaryDoubleFPOptimizer {
1927   CeilOptimization()
1928   : UnaryDoubleFPOptimizer("ceil", "Number of 'ceil' calls simplified") {}
1929   
1930   virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1931 #ifdef HAVE_CEILF
1932     // If this is a float argument passed in, convert to ceilf.
1933     if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_ceilf))
1934       return true;
1935 #endif
1936     return false; // opt failed
1937   }
1938 } CeilOptimizer;
1939
1940 struct RoundOptimization : public UnaryDoubleFPOptimizer {
1941   RoundOptimization()
1942   : UnaryDoubleFPOptimizer("round", "Number of 'round' calls simplified") {}
1943   
1944   virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1945 #ifdef HAVE_ROUNDF
1946     // If this is a float argument passed in, convert to roundf.
1947     if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_roundf))
1948       return true;
1949 #endif
1950     return false; // opt failed
1951   }
1952 } RoundOptimizer;
1953
1954 struct RintOptimization : public UnaryDoubleFPOptimizer {
1955   RintOptimization()
1956   : UnaryDoubleFPOptimizer("rint", "Number of 'rint' calls simplified") {}
1957   
1958   virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1959 #ifdef HAVE_RINTF
1960     // If this is a float argument passed in, convert to rintf.
1961     if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_rintf))
1962       return true;
1963 #endif
1964     return false; // opt failed
1965   }
1966 } RintOptimizer;
1967
1968 struct NearByIntOptimization : public UnaryDoubleFPOptimizer {
1969   NearByIntOptimization()
1970   : UnaryDoubleFPOptimizer("nearbyint",
1971                            "Number of 'nearbyint' calls simplified") {}
1972   
1973   virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1974 #ifdef HAVE_NEARBYINTF
1975     // If this is a float argument passed in, convert to nearbyintf.
1976     if (ShrinkFunctionToFloatVersion(CI, SLC,&SimplifyLibCalls::get_nearbyintf))
1977       return true;
1978 #endif
1979     return false; // opt failed
1980   }
1981 } NearByIntOptimizer;
1982
1983 /// A function to compute the length of a null-terminated constant array of
1984 /// integers.  This function can't rely on the size of the constant array
1985 /// because there could be a null terminator in the middle of the array.
1986 /// We also have to bail out if we find a non-integer constant initializer
1987 /// of one of the elements or if there is no null-terminator. The logic
1988 /// below checks each of these conditions and will return true only if all
1989 /// conditions are met. In that case, the \p len parameter is set to the length
1990 /// of the null-terminated string. If false is returned, the conditions were
1991 /// not met and len is set to 0.
1992 /// @brief Get the length of a constant string (null-terminated array).
1993 bool getConstantStringLength(Value *V, uint64_t &len, ConstantArray **CA) {
1994   assert(V != 0 && "Invalid args to getConstantStringLength");
1995   len = 0; // make sure we initialize this
1996   User* GEP = 0;
1997   // If the value is not a GEP instruction nor a constant expression with a
1998   // GEP instruction, then return false because ConstantArray can't occur
1999   // any other way
2000   if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
2001     GEP = GEPI;
2002   else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
2003     if (CE->getOpcode() == Instruction::GetElementPtr)
2004       GEP = CE;
2005     else
2006       return false;
2007   else
2008     return false;
2009
2010   // Make sure the GEP has exactly three arguments.
2011   if (GEP->getNumOperands() != 3)
2012     return false;
2013
2014   // Check to make sure that the first operand of the GEP is an integer and
2015   // has value 0 so that we are sure we're indexing into the initializer.
2016   if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
2017     if (!op1->isNullValue())
2018       return false;
2019   } else
2020     return false;
2021
2022   // Ensure that the second operand is a ConstantInt. If it isn't then this
2023   // GEP is wonky and we're not really sure what were referencing into and
2024   // better of not optimizing it. While we're at it, get the second index
2025   // value. We'll need this later for indexing the ConstantArray.
2026   uint64_t start_idx = 0;
2027   if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2028     start_idx = CI->getZExtValue();
2029   else
2030     return false;
2031
2032   // The GEP instruction, constant or instruction, must reference a global
2033   // variable that is a constant and is initialized. The referenced constant
2034   // initializer is the array that we'll use for optimization.
2035   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2036   if (!GV || !GV->isConstant() || !GV->hasInitializer())
2037     return false;
2038
2039   // Get the initializer.
2040   Constant* INTLZR = GV->getInitializer();
2041
2042   // Handle the ConstantAggregateZero case
2043   if (isa<ConstantAggregateZero>(INTLZR)) {
2044     // This is a degenerate case. The initializer is constant zero so the
2045     // length of the string must be zero.
2046     len = 0;
2047     return true;
2048   }
2049
2050   // Must be a Constant Array
2051   ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
2052   if (!A)
2053     return false;
2054
2055   // Get the number of elements in the array
2056   uint64_t max_elems = A->getType()->getNumElements();
2057
2058   // Traverse the constant array from start_idx (derived above) which is
2059   // the place the GEP refers to in the array.
2060   for (len = start_idx; len < max_elems; len++) {
2061     if (ConstantInt *CI = dyn_cast<ConstantInt>(A->getOperand(len))) {
2062       // Check for the null terminator
2063       if (CI->isNullValue())
2064         break; // we found end of string
2065     } else
2066       return false; // This array isn't suitable, non-int initializer
2067   }
2068   
2069   if (len >= max_elems)
2070     return false; // This array isn't null terminated
2071
2072   // Subtract out the initial value from the length
2073   len -= start_idx;
2074   if (CA)
2075     *CA = A;
2076   return true; // success!
2077 }
2078
2079 /// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
2080 /// inserting the cast before IP, and return the cast.
2081 /// @brief Cast a value to a "C" string.
2082 Value *CastToCStr(Value *V, Instruction &IP) {
2083   assert(isa<PointerType>(V->getType()) && 
2084          "Can't cast non-pointer type to C string type");
2085   const Type *SBPTy = PointerType::get(Type::Int8Ty);
2086   if (V->getType() != SBPTy)
2087     return new BitCastInst(V, SBPTy, V->getName(), &IP);
2088   return V;
2089 }
2090
2091 // TODO:
2092 //   Additional cases that we need to add to this file:
2093 //
2094 // cbrt:
2095 //   * cbrt(expN(X))  -> expN(x/3)
2096 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2097 //   * cbrt(sqrt(x))  -> pow(x,1/9)
2098 //
2099 // cos, cosf, cosl:
2100 //   * cos(-x)  -> cos(x)
2101 //
2102 // exp, expf, expl:
2103 //   * exp(log(x))  -> x
2104 //
2105 // log, logf, logl:
2106 //   * log(exp(x))   -> x
2107 //   * log(x**y)     -> y*log(x)
2108 //   * log(exp(y))   -> y*log(e)
2109 //   * log(exp2(y))  -> y*log(2)
2110 //   * log(exp10(y)) -> y*log(10)
2111 //   * log(sqrt(x))  -> 0.5*log(x)
2112 //   * log(pow(x,y)) -> y*log(x)
2113 //
2114 // lround, lroundf, lroundl:
2115 //   * lround(cnst) -> cnst'
2116 //
2117 // memcmp:
2118 //   * memcmp(x,y,l)   -> cnst
2119 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2120 //
2121 // memmove:
2122 //   * memmove(d,s,l,a) -> memcpy(d,s,l,a)
2123 //       (if s is a global constant array)
2124 //
2125 // pow, powf, powl:
2126 //   * pow(exp(x),y)  -> exp(x*y)
2127 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2128 //   * pow(pow(x,y),z)-> pow(x,y*z)
2129 //
2130 // puts:
2131 //   * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
2132 //
2133 // round, roundf, roundl:
2134 //   * round(cnst) -> cnst'
2135 //
2136 // signbit:
2137 //   * signbit(cnst) -> cnst'
2138 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2139 //
2140 // sqrt, sqrtf, sqrtl:
2141 //   * sqrt(expN(x))  -> expN(x*0.5)
2142 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2143 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2144 //
2145 // stpcpy:
2146 //   * stpcpy(str, "literal") ->
2147 //           llvm.memcpy(str,"literal",strlen("literal")+1,1)
2148 // strrchr:
2149 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
2150 //      (if c is a constant integer and s is a constant string)
2151 //   * strrchr(s1,0) -> strchr(s1,0)
2152 //
2153 // strncat:
2154 //   * strncat(x,y,0) -> x
2155 //   * strncat(x,y,0) -> x (if strlen(y) = 0)
2156 //   * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2157 //
2158 // strncpy:
2159 //   * strncpy(d,s,0) -> d
2160 //   * strncpy(d,s,l) -> memcpy(d,s,l,1)
2161 //      (if s and l are constants)
2162 //
2163 // strpbrk:
2164 //   * strpbrk(s,a) -> offset_in_for(s,a)
2165 //      (if s and a are both constant strings)
2166 //   * strpbrk(s,"") -> 0
2167 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2168 //
2169 // strspn, strcspn:
2170 //   * strspn(s,a)   -> const_int (if both args are constant)
2171 //   * strspn("",a)  -> 0
2172 //   * strspn(s,"")  -> 0
2173 //   * strcspn(s,a)  -> const_int (if both args are constant)
2174 //   * strcspn("",a) -> 0
2175 //   * strcspn(s,"") -> strlen(a)
2176 //
2177 // strstr:
2178 //   * strstr(x,x)  -> x
2179 //   * strstr(s1,s2) -> offset_of_s2_in(s1)
2180 //       (if s1 and s2 are constant strings)
2181 //
2182 // tan, tanf, tanl:
2183 //   * tan(atan(x)) -> x
2184 //
2185 // trunc, truncf, truncl:
2186 //   * trunc(cnst) -> cnst'
2187 //
2188 //
2189 }