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