Add the StrNCmpOptimization which is similar to strcmp.
[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 variety of small optimizations for calls to specific
11 // well-known (e.g. runtime library) function calls. For example, a call to the
12 // function "exit(3)" that occurs within the main() function can be transformed
13 // into a simple "return 3" instruction. Any optimization that takes this form
14 // (replace call to library function with simpler code that provides same 
15 // result) belongs in this file. 
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "simplify-libcalls"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/ADT/hash_map"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include <iostream>
31 using namespace llvm;
32
33 namespace {
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("simplify-libcalls", 
38   "Number of well-known library calls simplified");
39
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
43
44 /// @brief The list of optimizations deriving from LibCallOptimization
45 hash_map<std::string,LibCallOptimization*> optlist;
46
47 /// This class is the abstract base class for the set of optimizations that
48 /// corresponds to one library call. The SimplifyLibCalls pass will call the
49 /// ValidateCalledFunction method to ask the optimization if a given Function
50 /// is the kind that the optimization can handle. If the subclass returns true,
51 /// then SImplifyLibCalls will also call the OptimizeCall method to perform, 
52 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
53 /// OptimizeCall won't be called. Subclasses are responsible for providing the
54 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
55 /// constructor. This is used to efficiently select which call instructions to
56 /// optimize. The criteria for a "lib call" is "anything with well known 
57 /// semantics", typically a library function that is defined by an international
58 /// standard. Because the semantics are well known, the optimizations can 
59 /// generally short-circuit actually calling the function if there's a simpler
60 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
61 /// @brief Base class for library call optimizations
62 class LibCallOptimization
63 {
64 public:
65   /// The \p fname argument must be the name of the library function being 
66   /// optimized by the subclass.
67   /// @brief Constructor that registers the optimization.
68   LibCallOptimization(const char * fname )
69     : func_name(fname)
70 #ifndef NDEBUG
71     , stat_name(std::string("simplify-libcalls:")+fname)
72     , stat_desc(std::string("Number of ")+fname+"(...) calls simplified")
73     , occurrences(stat_name.c_str(),stat_desc.c_str())
74 #endif
75   {
76     // Register this call optimizer in the optlist (a hash_map)
77     optlist[func_name] = this;
78   }
79
80   /// @brief Deregister from the optlist
81   virtual ~LibCallOptimization() { optlist.erase(func_name); }
82
83   /// The implementation of this function in subclasses should determine if
84   /// \p F is suitable for the optimization. This method is called by 
85   /// SimplifyLibCalls::runOnModule to short circuit visiting all the call 
86   /// sites of such a function if that function is not suitable in the first 
87   /// place.  If the called function is suitabe, this method should return true;
88   /// false, otherwise. This function should also perform any lazy 
89   /// initialization that the LibCallOptimization needs to do, if its to return 
90   /// true. This avoids doing initialization until the optimizer is actually
91   /// going to be called upon to do some optimization.
92   /// @brief Determine if the function is suitable for optimization
93   virtual bool ValidateCalledFunction(
94     const Function* F,    ///< The function that is the target of call sites
95     SimplifyLibCalls& SLC ///< The pass object invoking us
96   ) = 0;
97
98   /// The implementations of this function in subclasses is the heart of the 
99   /// SimplifyLibCalls algorithm. Sublcasses of this class implement 
100   /// OptimizeCall to determine if (a) the conditions are right for optimizing
101   /// the call and (b) to perform the optimization. If an action is taken 
102   /// against ci, the subclass is responsible for returning true and ensuring
103   /// that ci is erased from its parent.
104   /// @brief Optimize a call, if possible.
105   virtual bool OptimizeCall(
106     CallInst* ci,          ///< The call instruction that should be optimized.
107     SimplifyLibCalls& SLC  ///< The pass object invoking us
108   ) = 0;
109
110   /// @brief Get the name of the library call being optimized
111   const char * getFunctionName() const { return func_name; }
112
113 #ifndef NDEBUG
114   /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
115   void succeeded() { ++occurrences; }
116 #endif
117
118 private:
119   const char* func_name; ///< Name of the library call we optimize
120 #ifndef NDEBUG
121   std::string stat_name; ///< Holder for debug statistic name
122   std::string stat_desc; ///< Holder for debug statistic description
123   Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
124 #endif
125 };
126
127 /// This class is an LLVM Pass that applies each of the LibCallOptimization 
128 /// instances to all the call sites in a module, relatively efficiently. The
129 /// purpose of this pass is to provide optimizations for calls to well-known 
130 /// functions with well-known semantics, such as those in the c library. The
131 /// class provides the basic infrastructure for handling runOnModule.  Whenever /// this pass finds a function call, it asks the appropriate optimizer to 
132 /// validate the call (ValidateLibraryCall). If it is validated, then
133 /// the OptimizeCall method is also called.
134 /// @brief A ModulePass for optimizing well-known function calls.
135 class SimplifyLibCalls : public ModulePass 
136 {
137 public:
138   /// We need some target data for accurate signature details that are
139   /// target dependent. So we require target data in our AnalysisUsage.
140   /// @brief Require TargetData from AnalysisUsage.
141   virtual void getAnalysisUsage(AnalysisUsage& Info) const
142   {
143     // Ask that the TargetData analysis be performed before us so we can use
144     // the target data.
145     Info.addRequired<TargetData>();
146   }
147
148   /// For this pass, process all of the function calls in the module, calling
149   /// ValidateLibraryCall and OptimizeCall as appropriate.
150   /// @brief Run all the lib call optimizations on a Module.
151   virtual bool runOnModule(Module &M)
152   {
153     reset(M);
154
155     bool result = false;
156
157     // The call optimizations can be recursive. That is, the optimization might
158     // generate a call to another function which can also be optimized. This way
159     // we make the LibCallOptimization instances very specific to the case they 
160     // handle. It also means we need to keep running over the function calls in 
161     // the module until we don't get any more optimizations possible.
162     bool found_optimization = false;
163     do
164     {
165       found_optimization = false;
166       for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
167       {
168         // All the "well-known" functions are external and have external linkage
169         // because they live in a runtime library somewhere and were (probably) 
170         // not compiled by LLVM.  So, we only act on external functions that have 
171         // external linkage and non-empty uses.
172         if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
173           continue;
174
175         // Get the optimization class that pertains to this function
176         LibCallOptimization* CO = optlist[FI->getName().c_str()];
177         if (!CO)
178           continue;
179
180         // Make sure the called function is suitable for the optimization
181         if (!CO->ValidateCalledFunction(FI,*this))
182           continue;
183
184         // Loop over each of the uses of the function
185         for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end(); 
186              UI != UE ; )
187         {
188           // If the use of the function is a call instruction
189           if (CallInst* CI = dyn_cast<CallInst>(*UI++))
190           {
191             // Do the optimization on the LibCallOptimization.
192             if (CO->OptimizeCall(CI,*this))
193             {
194               ++SimplifiedLibCalls;
195               found_optimization = result = true;
196 #ifndef NDEBUG
197               CO->succeeded();
198 #endif
199             }
200           }
201         }
202       }
203     } while (found_optimization);
204     return result;
205   }
206
207   /// @brief Return the *current* module we're working on.
208   Module* getModule() const { return M; }
209
210   /// @brief Return the *current* target data for the module we're working on.
211   TargetData* getTargetData() const { return TD; }
212
213   /// @brief Return the size_t type -- syntactic shortcut
214   const Type* getIntPtrType() const { return TD->getIntPtrType(); }
215
216   /// @brief Return a Function* for the fputc libcall
217   Function* get_fputc(const Type* FILEptr_type)
218   {
219     if (!fputc_func)
220     {
221       std::vector<const Type*> args;
222       args.push_back(Type::IntTy);
223       args.push_back(FILEptr_type);
224       FunctionType* fputc_type = 
225         FunctionType::get(Type::IntTy, args, false);
226       fputc_func = M->getOrInsertFunction("fputc",fputc_type);
227     }
228     return fputc_func;
229   }
230
231   /// @brief Return a Function* for the fwrite libcall
232   Function* get_fwrite(const Type* FILEptr_type)
233   {
234     if (!fwrite_func)
235     {
236       std::vector<const Type*> args;
237       args.push_back(PointerType::get(Type::SByteTy));
238       args.push_back(TD->getIntPtrType());
239       args.push_back(TD->getIntPtrType());
240       args.push_back(FILEptr_type);
241       FunctionType* fwrite_type = 
242         FunctionType::get(TD->getIntPtrType(), args, false);
243       fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
244     }
245     return fwrite_func;
246   }
247
248   /// @brief Return a Function* for the sqrt libcall
249   Function* get_sqrt()
250   {
251     if (!sqrt_func)
252     {
253       std::vector<const Type*> args;
254       args.push_back(Type::DoubleTy);
255       FunctionType* sqrt_type = 
256         FunctionType::get(Type::DoubleTy, args, false);
257       sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
258     }
259     return sqrt_func;
260   }
261
262   /// @brief Return a Function* for the strlen libcall
263   Function* get_strlen()
264   {
265     if (!strlen_func)
266     {
267       std::vector<const Type*> args;
268       args.push_back(PointerType::get(Type::SByteTy));
269       FunctionType* strlen_type = 
270         FunctionType::get(TD->getIntPtrType(), args, false);
271       strlen_func = M->getOrInsertFunction("strlen",strlen_type);
272     }
273     return strlen_func;
274   }
275
276   /// @brief Return a Function* for the memcpy libcall
277   Function* get_memcpy()
278   {
279     if (!memcpy_func)
280     {
281       // Note: this is for llvm.memcpy intrinsic
282       std::vector<const Type*> args;
283       args.push_back(PointerType::get(Type::SByteTy));
284       args.push_back(PointerType::get(Type::SByteTy));
285       args.push_back(Type::IntTy);
286       args.push_back(Type::IntTy);
287       FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
288       memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
289     }
290     return memcpy_func;
291   }
292
293 private:
294   /// @brief Reset our cached data for a new Module
295   void reset(Module& mod)
296   {
297     M = &mod;
298     TD = &getAnalysis<TargetData>();
299     fputc_func = 0;
300     fwrite_func = 0;
301     memcpy_func = 0;
302     sqrt_func   = 0;
303     strlen_func = 0;
304   }
305
306 private:
307   Function* fputc_func;  ///< Cached fputc function
308   Function* fwrite_func; ///< Cached fwrite function
309   Function* memcpy_func; ///< Cached llvm.memcpy function
310   Function* sqrt_func;   ///< Cached sqrt function
311   Function* strlen_func; ///< Cached strlen function
312   Module* M;             ///< Cached Module
313   TargetData* TD;        ///< Cached TargetData
314 };
315
316 // Register the pass
317 RegisterOpt<SimplifyLibCalls> 
318 X("simplify-libcalls","Simplify well-known library calls");
319
320 } // anonymous namespace
321
322 // The only public symbol in this file which just instantiates the pass object
323 ModulePass *llvm::createSimplifyLibCallsPass() 
324
325   return new SimplifyLibCalls(); 
326 }
327
328 // Classes below here, in the anonymous namespace, are all subclasses of the
329 // LibCallOptimization class, each implementing all optimizations possible for a
330 // single well-known library call. Each has a static singleton instance that
331 // auto registers it into the "optlist" global above. 
332 namespace {
333
334 // Forward declare a utility function.
335 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
336
337 /// This LibCallOptimization will find instances of a call to "exit" that occurs
338 /// within the "main" function and change it to a simple "ret" instruction with
339 /// the same value passed to the exit function. When this is done, it splits the
340 /// basic block at the exit(3) call and deletes the call instruction.
341 /// @brief Replace calls to exit in main with a simple return
342 struct ExitInMainOptimization : public LibCallOptimization
343 {
344   ExitInMainOptimization() : LibCallOptimization("exit") {}
345   virtual ~ExitInMainOptimization() {}
346
347   // Make sure the called function looks like exit (int argument, int return
348   // type, external linkage, not varargs). 
349   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
350   {
351     if (f->arg_size() >= 1)
352       if (f->arg_begin()->getType()->isInteger())
353         return true;
354     return false;
355   }
356
357   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
358   {
359     // To be careful, we check that the call to exit is coming from "main", that
360     // main has external linkage, and the return type of main and the argument
361     // to exit have the same type. 
362     Function *from = ci->getParent()->getParent();
363     if (from->hasExternalLinkage())
364       if (from->getReturnType() == ci->getOperand(1)->getType())
365         if (from->getName() == "main")
366         {
367           // Okay, time to actually do the optimization. First, get the basic 
368           // block of the call instruction
369           BasicBlock* bb = ci->getParent();
370
371           // Create a return instruction that we'll replace the call with. 
372           // Note that the argument of the return is the argument of the call 
373           // instruction.
374           ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
375
376           // Split the block at the call instruction which places it in a new
377           // basic block.
378           bb->splitBasicBlock(ci);
379
380           // The block split caused a branch instruction to be inserted into
381           // the end of the original block, right after the return instruction
382           // that we put there. That's not a valid block, so delete the branch
383           // instruction.
384           bb->getInstList().pop_back();
385
386           // Now we can finally get rid of the call instruction which now lives
387           // in the new basic block.
388           ci->eraseFromParent();
389
390           // Optimization succeeded, return true.
391           return true;
392         }
393     // We didn't pass the criteria for this optimization so return false
394     return false;
395   }
396 } ExitInMainOptimizer;
397
398 /// This LibCallOptimization will simplify a call to the strcat library 
399 /// function. The simplification is possible only if the string being 
400 /// concatenated is a constant array or a constant expression that results in 
401 /// a constant string. In this case we can replace it with strlen + llvm.memcpy 
402 /// of the constant string. Both of these calls are further reduced, if possible
403 /// on subsequent passes.
404 /// @brief Simplify the strcat library function.
405 struct StrCatOptimization : public LibCallOptimization
406 {
407 public:
408   /// @brief Default constructor
409   StrCatOptimization() : LibCallOptimization("strcat") {}
410
411 public:
412   /// @breif  Destructor
413   virtual ~StrCatOptimization() {}
414
415   /// @brief Make sure that the "strcat" function has the right prototype
416   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
417   {
418     if (f->getReturnType() == PointerType::get(Type::SByteTy))
419       if (f->arg_size() == 2) 
420       {
421         Function::const_arg_iterator AI = f->arg_begin();
422         if (AI++->getType() == PointerType::get(Type::SByteTy))
423           if (AI->getType() == PointerType::get(Type::SByteTy))
424           {
425             // Indicate this is a suitable call type.
426             return true;
427           }
428       }
429     return false;
430   }
431
432   /// @brief Optimize the strcat library function
433   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
434   {
435     // Extract some information from the instruction
436     Module* M = ci->getParent()->getParent()->getParent();
437     Value* dest = ci->getOperand(1);
438     Value* src  = ci->getOperand(2);
439
440     // Extract the initializer (while making numerous checks) from the 
441     // source operand of the call to strcat. If we get null back, one of
442     // a variety of checks in get_GVInitializer failed
443     uint64_t len = 0;
444     if (!getConstantStringLength(src,len))
445       return false;
446
447     // Handle the simple, do-nothing case
448     if (len == 0)
449     {
450       ci->replaceAllUsesWith(dest);
451       ci->eraseFromParent();
452       return true;
453     }
454
455     // Increment the length because we actually want to memcpy the null
456     // terminator as well.
457     len++;
458
459     // We need to find the end of the destination string.  That's where the 
460     // memory is to be moved to. We just generate a call to strlen (further 
461     // optimized in another pass).  Note that the SLC.get_strlen() call 
462     // caches the Function* for us.
463     CallInst* strlen_inst = 
464       new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
465
466     // Now that we have the destination's length, we must index into the 
467     // destination's pointer to get the actual memcpy destination (end of
468     // the string .. we're concatenating).
469     std::vector<Value*> idx;
470     idx.push_back(strlen_inst);
471     GetElementPtrInst* gep = 
472       new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
473
474     // We have enough information to now generate the memcpy call to
475     // do the concatenation for us.
476     std::vector<Value*> vals;
477     vals.push_back(gep); // destination
478     vals.push_back(ci->getOperand(2)); // source
479     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
480     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
481     new CallInst(SLC.get_memcpy(), vals, "", ci);
482
483     // Finally, substitute the first operand of the strcat call for the 
484     // strcat call itself since strcat returns its first operand; and, 
485     // kill the strcat CallInst.
486     ci->replaceAllUsesWith(dest);
487     ci->eraseFromParent();
488     return true;
489   }
490 } StrCatOptimizer;
491
492 /// This LibCallOptimization will simplify a call to the strcmp library 
493 /// function.  It optimizes out cases where one or both arguments are constant
494 /// and the result can be determined statically.
495 /// @brief Simplify the strcmp library function.
496 struct StrCmpOptimization : public LibCallOptimization
497 {
498 public:
499   StrCmpOptimization() : LibCallOptimization("strcmp") {}
500   virtual ~StrCmpOptimization() {}
501
502   /// @brief Make sure that the "strcpy" function has the right prototype
503   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
504   {
505     if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
506       return true;
507     return false;
508   }
509
510   /// @brief Perform the strcpy optimization
511   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
512   {
513     // First, check to see if src and destination are the same. If they are,
514     // then the optimization is to replace the CallInst with a constant 0
515     // because the call is a no-op. 
516     Value* s1 = ci->getOperand(1);
517     Value* s2 = ci->getOperand(2);
518     if (s1 == s2)
519     {
520       // strcmp(x,x)  -> 0
521       ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
522       ci->eraseFromParent();
523       return true;
524     }
525
526     bool isstr_1 = false;
527     uint64_t len_1 = 0;
528     ConstantArray* A1;
529     if (getConstantStringLength(s1,len_1,&A1))
530     {
531       isstr_1 = true;
532       if (len_1 == 0)
533       {
534         // strcmp("",x) -> *x
535         LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
536         CastInst* cast = 
537           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
538         ci->replaceAllUsesWith(cast);
539         ci->eraseFromParent();
540         return true;
541       }
542     }
543
544     bool isstr_2 = false;
545     uint64_t len_2 = 0;
546     ConstantArray* A2;
547     if (getConstantStringLength(s2,len_2,&A2))
548     {
549       isstr_2 = true;
550       if (len_2 == 0)
551       {
552         // strcmp(x,"") -> *x
553         LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
554         CastInst* cast = 
555           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
556         ci->replaceAllUsesWith(cast);
557         ci->eraseFromParent();
558         return true;
559       }
560     }
561
562     if (isstr_1 && isstr_2)
563     {
564       // strcmp(x,y)  -> cnst  (if both x and y are constant strings)
565       std::string str1 = A1->getAsString();
566       std::string str2 = A2->getAsString();
567       int result = strcmp(str1.c_str(), str2.c_str());
568       ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
569       ci->eraseFromParent();
570       return true;
571     }
572     return false;
573   }
574 } StrCmpOptimizer;
575
576 /// This LibCallOptimization will simplify a call to the strncmp library 
577 /// function.  It optimizes out cases where one or both arguments are constant
578 /// and the result can be determined statically.
579 /// @brief Simplify the strncmp library function.
580 struct StrNCmpOptimization : public LibCallOptimization
581 {
582 public:
583   StrNCmpOptimization() : LibCallOptimization("strncmp") {}
584   virtual ~StrNCmpOptimization() {}
585
586   /// @brief Make sure that the "strcpy" function has the right prototype
587   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
588   {
589     if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
590       return true;
591     return false;
592   }
593
594   /// @brief Perform the strncpy optimization
595   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
596   {
597     // First, check to see if src and destination are the same. If they are,
598     // then the optimization is to replace the CallInst with a constant 0
599     // because the call is a no-op. 
600     Value* s1 = ci->getOperand(1);
601     Value* s2 = ci->getOperand(2);
602     if (s1 == s2)
603     {
604       // strncmp(x,x,l)  -> 0
605       ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
606       ci->eraseFromParent();
607       return true;
608     }
609
610     // Check the length argument, if it is Constant zero then the strings are
611     // considered equal.
612     uint64_t len_arg = 0;
613     bool len_arg_is_const = false;
614     if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
615     {
616       len_arg_is_const = true;
617       len_arg = len_CI->getRawValue();
618       if (len_arg == 0)
619       {
620         // strncmp(x,y,0)   -> 0
621         ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
622         ci->eraseFromParent();
623         return true;
624       } 
625     }
626
627     bool isstr_1 = false;
628     uint64_t len_1 = 0;
629     ConstantArray* A1;
630     if (getConstantStringLength(s1,len_1,&A1))
631     {
632       isstr_1 = true;
633       if (len_1 == 0)
634       {
635         // strncmp("",x) -> *x
636         LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
637         CastInst* cast = 
638           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
639         ci->replaceAllUsesWith(cast);
640         ci->eraseFromParent();
641         return true;
642       }
643     }
644
645     bool isstr_2 = false;
646     uint64_t len_2 = 0;
647     ConstantArray* A2;
648     if (getConstantStringLength(s2,len_2,&A2))
649     {
650       isstr_2 = true;
651       if (len_2 == 0)
652       {
653         // strncmp(x,"") -> *x
654         LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
655         CastInst* cast = 
656           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
657         ci->replaceAllUsesWith(cast);
658         ci->eraseFromParent();
659         return true;
660       }
661     }
662
663     if (isstr_1 && isstr_2 && len_arg_is_const)
664     {
665       // strncmp(x,y,const) -> constant
666       std::string str1 = A1->getAsString();
667       std::string str2 = A2->getAsString();
668       int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
669       ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
670       ci->eraseFromParent();
671       return true;
672     }
673     return false;
674   }
675 } StrNCmpOptimizer;
676
677 /// This LibCallOptimization will simplify a call to the strcpy library 
678 /// function.  Two optimizations are possible: 
679 /// (1) If src and dest are the same and not volatile, just return dest
680 /// (2) If the src is a constant then we can convert to llvm.memmove
681 /// @brief Simplify the strcpy library function.
682 struct StrCpyOptimization : public LibCallOptimization
683 {
684 public:
685   StrCpyOptimization() : LibCallOptimization("strcpy") {}
686   virtual ~StrCpyOptimization() {}
687
688   /// @brief Make sure that the "strcpy" function has the right prototype
689   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
690   {
691     if (f->getReturnType() == PointerType::get(Type::SByteTy))
692       if (f->arg_size() == 2) 
693       {
694         Function::const_arg_iterator AI = f->arg_begin();
695         if (AI++->getType() == PointerType::get(Type::SByteTy))
696           if (AI->getType() == PointerType::get(Type::SByteTy))
697           {
698             // Indicate this is a suitable call type.
699             return true;
700           }
701       }
702     return false;
703   }
704
705   /// @brief Perform the strcpy optimization
706   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
707   {
708     // First, check to see if src and destination are the same. If they are,
709     // then the optimization is to replace the CallInst with the destination
710     // because the call is a no-op. Note that this corresponds to the 
711     // degenerate strcpy(X,X) case which should have "undefined" results
712     // according to the C specification. However, it occurs sometimes and
713     // we optimize it as a no-op.
714     Value* dest = ci->getOperand(1);
715     Value* src = ci->getOperand(2);
716     if (dest == src)
717     {
718       ci->replaceAllUsesWith(dest);
719       ci->eraseFromParent();
720       return true;
721     }
722     
723     // Get the length of the constant string referenced by the second operand,
724     // the "src" parameter. Fail the optimization if we can't get the length
725     // (note that getConstantStringLength does lots of checks to make sure this
726     // is valid).
727     uint64_t len = 0;
728     if (!getConstantStringLength(ci->getOperand(2),len))
729       return false;
730
731     // If the constant string's length is zero we can optimize this by just
732     // doing a store of 0 at the first byte of the destination
733     if (len == 0)
734     {
735       new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
736       ci->replaceAllUsesWith(dest);
737       ci->eraseFromParent();
738       return true;
739     }
740
741     // Increment the length because we actually want to memcpy the null
742     // terminator as well.
743     len++;
744
745     // Extract some information from the instruction
746     Module* M = ci->getParent()->getParent()->getParent();
747
748     // We have enough information to now generate the memcpy call to
749     // do the concatenation for us.
750     std::vector<Value*> vals;
751     vals.push_back(dest); // destination
752     vals.push_back(src); // source
753     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
754     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
755     new CallInst(SLC.get_memcpy(), vals, "", ci);
756
757     // Finally, substitute the first operand of the strcat call for the 
758     // strcat call itself since strcat returns its first operand; and, 
759     // kill the strcat CallInst.
760     ci->replaceAllUsesWith(dest);
761     ci->eraseFromParent();
762     return true;
763   }
764 } StrCpyOptimizer;
765
766 /// This LibCallOptimization will simplify a call to the strlen library 
767 /// function by replacing it with a constant value if the string provided to 
768 /// it is a constant array.
769 /// @brief Simplify the strlen library function.
770 struct StrLenOptimization : public LibCallOptimization
771 {
772   StrLenOptimization() : LibCallOptimization("strlen") {}
773   virtual ~StrLenOptimization() {}
774
775   /// @brief Make sure that the "strlen" function has the right prototype
776   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
777   {
778     if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
779       if (f->arg_size() == 1) 
780         if (Function::const_arg_iterator AI = f->arg_begin())
781           if (AI->getType() == PointerType::get(Type::SByteTy))
782             return true;
783     return false;
784   }
785
786   /// @brief Perform the strlen optimization
787   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
788   {
789     // Get the length of the string
790     uint64_t len = 0;
791     if (!getConstantStringLength(ci->getOperand(1),len))
792       return false;
793
794     ci->replaceAllUsesWith(
795         ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
796     ci->eraseFromParent();
797     return true;
798   }
799 } StrLenOptimizer;
800
801 /// This LibCallOptimization will simplify a call to the memcpy library 
802 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8 
803 /// bytes depending on the length of the string and the alignment. Additional
804 /// optimizations are possible in code generation (sequence of immediate store)
805 /// @brief Simplify the memcpy library function.
806 struct MemCpyOptimization : public LibCallOptimization
807 {
808   /// @brief Default Constructor
809   MemCpyOptimization() : LibCallOptimization("llvm.memcpy") {}
810 protected:
811   /// @brief Subclass Constructor 
812   MemCpyOptimization(const char* fname) : LibCallOptimization(fname) {}
813 public:
814   /// @brief Destructor
815   virtual ~MemCpyOptimization() {}
816
817   /// @brief Make sure that the "memcpy" function has the right prototype
818   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
819   {
820     // Just make sure this has 4 arguments per LLVM spec.
821     return (f->arg_size() == 4);
822   }
823
824   /// Because of alignment and instruction information that we don't have, we
825   /// leave the bulk of this to the code generators. The optimization here just
826   /// deals with a few degenerate cases where the length of the string and the
827   /// alignment match the sizes of our intrinsic types so we can do a load and
828   /// store instead of the memcpy call.
829   /// @brief Perform the memcpy optimization.
830   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
831   {
832     // Make sure we have constant int values to work with
833     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
834     if (!LEN)
835       return false;
836     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
837     if (!ALIGN)
838       return false;
839
840     // If the length is larger than the alignment, we can't optimize
841     uint64_t len = LEN->getRawValue();
842     uint64_t alignment = ALIGN->getRawValue();
843     if (len > alignment)
844       return false;
845
846     // Get the type we will cast to, based on size of the string
847     Value* dest = ci->getOperand(1);
848     Value* src = ci->getOperand(2);
849     Type* castType = 0;
850     switch (len)
851     {
852       case 0:
853         // memcpy(d,s,0,a) -> noop
854         ci->eraseFromParent();
855         return true;
856       case 1: castType = Type::SByteTy; break;
857       case 2: castType = Type::ShortTy; break;
858       case 4: castType = Type::IntTy; break;
859       case 8: castType = Type::LongTy; break;
860       default:
861         return false;
862     }
863
864     // Cast source and dest to the right sized primitive and then load/store
865     CastInst* SrcCast = 
866       new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
867     CastInst* DestCast = 
868       new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
869     LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
870     StoreInst* SI = new StoreInst(LI, DestCast, ci);
871     ci->eraseFromParent();
872     return true;
873   }
874 } MemCpyOptimizer;
875
876 /// This LibCallOptimization will simplify a call to the memmove library 
877 /// function. It is identical to MemCopyOptimization except for the name of 
878 /// the intrinsic.
879 /// @brief Simplify the memmove library function.
880 struct MemMoveOptimization : public MemCpyOptimization
881 {
882   /// @brief Default Constructor
883   MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
884
885 } MemMoveOptimizer;
886
887 /// This LibCallOptimization will simplify calls to the "pow" library 
888 /// function. It looks for cases where the result of pow is well known and 
889 /// substitutes the appropriate value.
890 /// @brief Simplify the pow library function.
891 struct PowOptimization : public LibCallOptimization
892 {
893 public:
894   /// @brief Default Constructor
895   PowOptimization() : LibCallOptimization("pow") {}
896   /// @brief Destructor
897   virtual ~PowOptimization() {}
898
899   /// @brief Make sure that the "pow" function has the right prototype
900   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
901   {
902     // Just make sure this has 2 arguments
903     return (f->arg_size() == 2);
904   }
905
906   /// @brief Perform the pow optimization.
907   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
908   {
909     const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
910     Value* base = ci->getOperand(1);
911     Value* expn = ci->getOperand(2);
912     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
913       double Op1V = Op1->getValue();
914       if (Op1V == 1.0)
915       {
916         // pow(1.0,x) -> 1.0
917         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
918         ci->eraseFromParent();
919         return true;
920       }
921     } 
922     else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) 
923     {
924       double Op2V = Op2->getValue();
925       if (Op2V == 0.0)
926       {
927         // pow(x,0.0) -> 1.0
928         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
929         ci->eraseFromParent();
930         return true;
931       }
932       else if (Op2V == 0.5)
933       {
934         // pow(x,0.5) -> sqrt(x)
935         CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
936             ci->getName()+".pow",ci);
937         ci->replaceAllUsesWith(sqrt_inst);
938         ci->eraseFromParent();
939         return true;
940       }
941       else if (Op2V == 1.0)
942       {
943         // pow(x,1.0) -> x
944         ci->replaceAllUsesWith(base);
945         ci->eraseFromParent();
946         return true;
947       }
948       else if (Op2V == -1.0)
949       {
950         // pow(x,-1.0)    -> 1.0/x
951         BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
952           ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
953         ci->replaceAllUsesWith(div_inst);
954         ci->eraseFromParent();
955         return true;
956       }
957     }
958     return false; // opt failed
959   }
960 } PowOptimizer;
961
962 /// This LibCallOptimization will simplify calls to the "fprintf" library 
963 /// function. It looks for cases where the result of fprintf is not used and the
964 /// operation can be reduced to something simpler.
965 /// @brief Simplify the pow library function.
966 struct FPrintFOptimization : public LibCallOptimization
967 {
968 public:
969   /// @brief Default Constructor
970   FPrintFOptimization() : LibCallOptimization("fprintf") {}
971
972   /// @brief Destructor
973   virtual ~FPrintFOptimization() {}
974
975   /// @brief Make sure that the "fprintf" function has the right prototype
976   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
977   {
978     // Just make sure this has at least 2 arguments
979     return (f->arg_size() >= 2);
980   }
981
982   /// @brief Perform the fprintf optimization.
983   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
984   {
985     // If the call has more than 3 operands, we can't optimize it
986     if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
987       return false;
988
989     // If the result of the fprintf call is used, none of these optimizations 
990     // can be made.
991     if (!ci->hasNUses(0)) 
992       return false;
993
994     // All the optimizations depend on the length of the second argument and the
995     // fact that it is a constant string array. Check that now
996     uint64_t len = 0; 
997     ConstantArray* CA = 0;
998     if (!getConstantStringLength(ci->getOperand(2), len, &CA))
999       return false;
1000
1001     if (ci->getNumOperands() == 3)
1002     {
1003       // Make sure there's no % in the constant array
1004       for (unsigned i = 0; i < len; ++i)
1005       {
1006         if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1007         {
1008           // Check for the null terminator
1009           if (CI->getRawValue() == '%')
1010             return false; // we found end of string
1011         }
1012         else 
1013           return false;
1014       }
1015
1016       // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1file) 
1017       const Type* FILEptr_type = ci->getOperand(1)->getType();
1018       Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1019       if (!fwrite_func)
1020         return false;
1021       std::vector<Value*> args;
1022       args.push_back(ci->getOperand(2));
1023       args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1024       args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1025       args.push_back(ci->getOperand(1));
1026       new CallInst(fwrite_func,args,"",ci);
1027       ci->eraseFromParent();
1028       return true;
1029     }
1030
1031     // The remaining optimizations require the format string to be length 2
1032     // "%s" or "%c".
1033     if (len != 2)
1034       return false;
1035
1036     // The first character has to be a %
1037     if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1038       if (CI->getRawValue() != '%')
1039         return false;
1040
1041     // Get the second character and switch on its value
1042     ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1043     switch (CI->getRawValue())
1044     {
1045       case 's':
1046       {
1047         uint64_t len = 0; 
1048         ConstantArray* CA = 0;
1049         if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1050           return false;
1051
1052         // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1,file) 
1053         const Type* FILEptr_type = ci->getOperand(1)->getType();
1054         Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1055         if (!fwrite_func)
1056           return false;
1057         std::vector<Value*> args;
1058         args.push_back(ci->getOperand(3));
1059         args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1060         args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1061         args.push_back(ci->getOperand(1));
1062         new CallInst(fwrite_func,args,"",ci);
1063         break;
1064       }
1065       case 'c':
1066       {
1067         ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1068         if (!CI)
1069           return false;
1070
1071         const Type* FILEptr_type = ci->getOperand(1)->getType();
1072         Function* fputc_func = SLC.get_fputc(FILEptr_type);
1073         if (!fputc_func)
1074           return false;
1075         CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1076         new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1077         break;
1078       }
1079       default:
1080         return false;
1081     }
1082     ci->eraseFromParent();
1083     return true;
1084   }
1085 } FPrintFOptimizer;
1086
1087
1088 /// This LibCallOptimization will simplify calls to the "fputs" library 
1089 /// function. It looks for cases where the result of fputs is not used and the
1090 /// operation can be reduced to something simpler.
1091 /// @brief Simplify the pow library function.
1092 struct PutsOptimization : public LibCallOptimization
1093 {
1094 public:
1095   /// @brief Default Constructor
1096   PutsOptimization() : LibCallOptimization("fputs") {}
1097
1098   /// @brief Destructor
1099   virtual ~PutsOptimization() {}
1100
1101   /// @brief Make sure that the "fputs" function has the right prototype
1102   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1103   {
1104     // Just make sure this has 2 arguments
1105     return (f->arg_size() == 2);
1106   }
1107
1108   /// @brief Perform the fputs optimization.
1109   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1110   {
1111     // If the result is used, none of these optimizations work
1112     if (!ci->hasNUses(0)) 
1113       return false;
1114
1115     // All the optimizations depend on the length of the first argument and the
1116     // fact that it is a constant string array. Check that now
1117     uint64_t len = 0; 
1118     if (!getConstantStringLength(ci->getOperand(1), len))
1119       return false;
1120
1121     switch (len)
1122     {
1123       case 0:
1124         // fputs("",F) -> noop
1125         break;
1126       case 1:
1127       {
1128         // fputs(s,F)  -> fputc(s[0],F)  (if s is constant and strlen(s) == 1)
1129         const Type* FILEptr_type = ci->getOperand(2)->getType();
1130         Function* fputc_func = SLC.get_fputc(FILEptr_type);
1131         if (!fputc_func)
1132           return false;
1133         LoadInst* loadi = new LoadInst(ci->getOperand(1),
1134           ci->getOperand(1)->getName()+".byte",ci);
1135         CastInst* casti = new CastInst(loadi,Type::IntTy,
1136           loadi->getName()+".int",ci);
1137         new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1138         break;
1139       }
1140       default:
1141       {  
1142         // fputs(s,F)  -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1143         const Type* FILEptr_type = ci->getOperand(2)->getType();
1144         Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1145         if (!fwrite_func)
1146           return false;
1147         std::vector<Value*> parms;
1148         parms.push_back(ci->getOperand(1));
1149         parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1150         parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1151         parms.push_back(ci->getOperand(2));
1152         new CallInst(fwrite_func,parms,"",ci);
1153         break;
1154       }
1155     }
1156     ci->eraseFromParent();
1157     return true; // success
1158   }
1159 } PutsOptimizer;
1160
1161 /// This LibCallOptimization will simplify calls to the "toascii" library 
1162 /// function. It simply does the corresponding and operation to restrict the
1163 /// range of values to the ASCII character set (0-127).
1164 /// @brief Simplify the toascii library function.
1165 struct ToAsciiOptimization : public LibCallOptimization
1166 {
1167 public:
1168   /// @brief Default Constructor
1169   ToAsciiOptimization() : LibCallOptimization("toascii") {}
1170
1171   /// @brief Destructor
1172   virtual ~ToAsciiOptimization() {}
1173
1174   /// @brief Make sure that the "fputs" function has the right prototype
1175   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1176   {
1177     // Just make sure this has 2 arguments
1178     return (f->arg_size() == 1);
1179   }
1180
1181   /// @brief Perform the toascii optimization.
1182   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1183   {
1184     // toascii(c)   -> (c & 0x7f)
1185     Value* chr = ci->getOperand(1);
1186     BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1187         ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1188     ci->replaceAllUsesWith(and_inst);
1189     ci->eraseFromParent();
1190     return true;
1191   }
1192 } ToAsciiOptimizer;
1193
1194 /// A function to compute the length of a null-terminated constant array of
1195 /// integers.  This function can't rely on the size of the constant array 
1196 /// because there could be a null terminator in the middle of the array. 
1197 /// We also have to bail out if we find a non-integer constant initializer 
1198 /// of one of the elements or if there is no null-terminator. The logic 
1199 /// below checks each of these conditions and will return true only if all
1200 /// conditions are met. In that case, the \p len parameter is set to the length
1201 /// of the null-terminated string. If false is returned, the conditions were
1202 /// not met and len is set to 0.
1203 /// @brief Get the length of a constant string (null-terminated array).
1204 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1205 {
1206   assert(V != 0 && "Invalid args to getConstantStringLength");
1207   len = 0; // make sure we initialize this 
1208   User* GEP = 0;
1209   // If the value is not a GEP instruction nor a constant expression with a 
1210   // GEP instruction, then return false because ConstantArray can't occur 
1211   // any other way
1212   if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1213     GEP = GEPI;
1214   else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1215     if (CE->getOpcode() == Instruction::GetElementPtr)
1216       GEP = CE;
1217     else
1218       return false;
1219   else
1220     return false;
1221
1222   // Make sure the GEP has exactly three arguments.
1223   if (GEP->getNumOperands() != 3)
1224     return false;
1225
1226   // Check to make sure that the first operand of the GEP is an integer and
1227   // has value 0 so that we are sure we're indexing into the initializer. 
1228   if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1229   {
1230     if (!op1->isNullValue())
1231       return false;
1232   }
1233   else
1234     return false;
1235
1236   // Ensure that the second operand is a ConstantInt. If it isn't then this
1237   // GEP is wonky and we're not really sure what were referencing into and 
1238   // better of not optimizing it. While we're at it, get the second index
1239   // value. We'll need this later for indexing the ConstantArray.
1240   uint64_t start_idx = 0;
1241   if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1242     start_idx = CI->getRawValue();
1243   else
1244     return false;
1245
1246   // The GEP instruction, constant or instruction, must reference a global
1247   // variable that is a constant and is initialized. The referenced constant
1248   // initializer is the array that we'll use for optimization.
1249   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1250   if (!GV || !GV->isConstant() || !GV->hasInitializer())
1251     return false;
1252
1253   // Get the initializer.
1254   Constant* INTLZR = GV->getInitializer();
1255
1256   // Handle the ConstantAggregateZero case
1257   if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1258   {
1259     // This is a degenerate case. The initializer is constant zero so the
1260     // length of the string must be zero.
1261     len = 0;
1262     return true;
1263   }
1264
1265   // Must be a Constant Array
1266   ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1267   if (!A)
1268     return false;
1269
1270   // Get the number of elements in the array
1271   uint64_t max_elems = A->getType()->getNumElements();
1272
1273   // Traverse the constant array from start_idx (derived above) which is
1274   // the place the GEP refers to in the array. 
1275   for ( len = start_idx; len < max_elems; len++)
1276   {
1277     if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1278     {
1279       // Check for the null terminator
1280       if (CI->isNullValue())
1281         break; // we found end of string
1282     }
1283     else
1284       return false; // This array isn't suitable, non-int initializer
1285   }
1286   if (len >= max_elems)
1287     return false; // This array isn't null terminated
1288
1289   // Subtract out the initial value from the length
1290   len -= start_idx;
1291   if (CA)
1292     *CA = A;
1293   return true; // success!
1294 }
1295
1296 // TODO: 
1297 //   Additional cases that we need to add to this file:
1298 //
1299 // cbrt:
1300 //   * cbrt(expN(X))  -> expN(x/3)
1301 //   * cbrt(sqrt(x))  -> pow(x,1/6)
1302 //   * cbrt(sqrt(x))  -> pow(x,1/9)
1303 //
1304 // cos, cosf, cosl:
1305 //   * cos(-x)  -> cos(x)
1306 //
1307 // exp, expf, expl:
1308 //   * exp(log(x))  -> x
1309 //
1310 // ffs, ffsl, ffsll:
1311 //   * ffs(cnst)     -> cnst'
1312 //
1313 // isascii:
1314 //   * isascii(c)    -> ((c & ~0x7f) == 0)
1315 //   
1316 // isdigit:
1317 //   * isdigit(c)    -> (unsigned)(c) - '0' <= 9
1318 //
1319 // log, logf, logl:
1320 //   * log(exp(x))   -> x
1321 //   * log(x**y)     -> y*log(x)
1322 //   * log(exp(y))   -> y*log(e)
1323 //   * log(exp2(y))  -> y*log(2)
1324 //   * log(exp10(y)) -> y*log(10)
1325 //   * log(sqrt(x))  -> 0.5*log(x)
1326 //   * log(pow(x,y)) -> y*log(x)
1327 //
1328 // lround, lroundf, lroundl:
1329 //   * lround(cnst) -> cnst'
1330 //
1331 // memcmp:
1332 //   * memcmp(s1,s2,0) -> 0
1333 //   * memcmp(x,x,l)   -> 0
1334 //   * memcmp(x,y,l)   -> cnst
1335 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1336 //   * memcpy(x,y,1)   -> *x - *y
1337 //
1338 // memmove:
1339 //   * memmove(d,s,l,a) -> memcpy(d,s,l,a) 
1340 //       (if s is a global constant array)
1341 //
1342 // memset:
1343 //   * memset(s,c,0) -> noop
1344 //   * memset(s,c,n) -> store s, c
1345 //      (for n=1,2,4,8)
1346 //
1347 // pow, powf, powl:
1348 //   * pow(exp(x),y)  -> exp(x*y)
1349 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1350 //   * pow(pow(x,y),z)-> pow(x,y*z)
1351 //
1352 // puts:
1353 //   * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1354 //
1355 // round, roundf, roundl:
1356 //   * round(cnst) -> cnst'
1357 //
1358 // signbit:
1359 //   * signbit(cnst) -> cnst'
1360 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1361 //
1362 // sprintf:
1363 //   * sprintf(dest,fmt) -> strcpy(dest,fmt) 
1364 //       (if fmt is constant and constains no % characters)
1365 //   * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1366 //       (only if the sprintf result is not used)
1367 //
1368 // sqrt, sqrtf, sqrtl:
1369 //   * sqrt(expN(x))  -> expN(x*0.5)
1370 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1371 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1372 //
1373 // strchr, strrchr:
1374 //   * strchr(s,c)  -> offset_of_in(c,s)
1375 //      (if c is a constant integer and s is a constant string)
1376 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
1377 //      (if c is a constant integer and s is a constant string)
1378 //   * strrchr(s1,0) -> strchr(s1,0)
1379 //
1380 // strncat:
1381 //   * strncat(x,y,0) -> x
1382 //   * strncat(x,y,0) -> x (if strlen(y) = 0)
1383 //   * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1384 //
1385 // strncpy:
1386 //   * strncpy(d,s,0) -> d
1387 //   * strncpy(d,s,l) -> memcpy(d,s,l,1)
1388 //      (if s and l are constants)
1389 //
1390 // strpbrk:
1391 //   * strpbrk(s,a) -> offset_in_for(s,a)
1392 //      (if s and a are both constant strings)
1393 //   * strpbrk(s,"") -> 0
1394 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1395 //
1396 // strspn, strcspn:
1397 //   * strspn(s,a)   -> const_int (if both args are constant)
1398 //   * strspn("",a)  -> 0
1399 //   * strspn(s,"")  -> 0
1400 //   * strcspn(s,a)  -> const_int (if both args are constant)
1401 //   * strcspn("",a) -> 0
1402 //   * strcspn(s,"") -> strlen(a)
1403 //
1404 // strstr:
1405 //   * strstr(x,x)  -> x
1406 //   * strstr(s1,s2) -> offset_of_s2_in(s1)  
1407 //       (if s1 and s2 are constant strings)
1408 //    
1409 // tan, tanf, tanl:
1410 //   * tan(atan(x)) -> x
1411 // 
1412 // trunc, truncf, truncl:
1413 //   * trunc(cnst) -> cnst'
1414 //
1415 // 
1416 }