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