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