14212bc5799eb63c4385b7d8a56b8b8bcbdab25e
[oota-llvm.git] / lib / Transforms / Scalar / SimplifyLibCalls.cpp
1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple 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/Transforms/Scalar.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/IRBuilder.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Config/config.h"
36 using namespace llvm;
37
38 STATISTIC(NumSimplified, "Number of library calls simplified");
39 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
40
41 //===----------------------------------------------------------------------===//
42 // Optimizer Base Class
43 //===----------------------------------------------------------------------===//
44
45 /// This class is the abstract base class for the set of optimizations that
46 /// corresponds to one library call.
47 namespace {
48 class VISIBILITY_HIDDEN LibCallOptimization {
49 protected:
50   Function *Caller;
51   const TargetData *TD;
52   LLVMContext* Context;
53 public:
54   LibCallOptimization() { }
55   virtual ~LibCallOptimization() {}
56
57   /// CallOptimizer - This pure virtual method is implemented by base classes to
58   /// do various optimizations.  If this returns null then no transformation was
59   /// performed.  If it returns CI, then it transformed the call and CI is to be
60   /// deleted.  If it returns something else, replace CI with the new value and
61   /// delete CI.
62   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) 
63     =0;
64   
65   Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
66     Caller = CI->getParent()->getParent();
67     this->TD = &TD;
68     if (CI->getCalledFunction())
69       Context = &CI->getCalledFunction()->getContext();
70     return CallOptimizer(CI->getCalledFunction(), CI, B);
71   }
72
73   /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
74   Value *CastToCStr(Value *V, IRBuilder<> &B);
75
76   /// EmitStrLen - Emit a call to the strlen function to the builder, for the
77   /// specified pointer.  Ptr is required to be some pointer type, and the
78   /// return value has 'intptr_t' type.
79   Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
80   
81   /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This
82   /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
83   Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len, 
84                     unsigned Align, IRBuilder<> &B);
85   
86   /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
87   /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
88   Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
89
90   /// EmitMemCmp - Emit a call to the memcmp function.
91   Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
92
93   /// EmitMemSet - Emit a call to the memset function
94   Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
95
96   /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
97   /// 'floor').  This function is known to take a single of type matching 'Op'
98   /// and returns one value with the same type.  If 'Op' is a long double, 'l'
99   /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
100   Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
101   
102   /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
103   /// is an integer.
104   void EmitPutChar(Value *Char, IRBuilder<> &B);
105   
106   /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
107   /// some pointer.
108   void EmitPutS(Value *Str, IRBuilder<> &B);
109     
110   /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
111   /// an i32, and File is a pointer to FILE.
112   void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
113   
114   /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
115   /// pointer and File is a pointer to FILE.
116   void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
117   
118   /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
119   /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
120   void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
121   
122 };
123 } // End anonymous namespace.
124
125 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
126 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
127   return
128         B.CreateBitCast(V, Context->getPointerTypeUnqual(Type::Int8Ty), "cstr");
129 }
130
131 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
132 /// specified pointer.  This always returns an integer value of size intptr_t.
133 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
134   Module *M = Caller->getParent();
135   AttributeWithIndex AWI[2];
136   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
137   AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
138                                    Attribute::NoUnwind);
139
140   Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
141                                            TD->getIntPtrType(),
142                                     Context->getPointerTypeUnqual(Type::Int8Ty),
143                                            NULL);
144   CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
145   if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
146     CI->setCallingConv(F->getCallingConv());
147
148   return CI;
149 }
150
151 /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This always
152 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
153 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
154                                        unsigned Align, IRBuilder<> &B) {
155   Module *M = Caller->getParent();
156   Intrinsic::ID IID = Intrinsic::memcpy;
157   const Type *Tys[1];
158   Tys[0] = Len->getType();
159   Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
160   return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
161                        ConstantInt::get(Type::Int32Ty, Align));
162 }
163
164 /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
165 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
166 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
167                                        Value *Len, IRBuilder<> &B) {
168   Module *M = Caller->getParent();
169   AttributeWithIndex AWI;
170   AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
171
172   Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
173                                     Context->getPointerTypeUnqual(Type::Int8Ty),
174                                     Context->getPointerTypeUnqual(Type::Int8Ty),
175                                          Type::Int32Ty, TD->getIntPtrType(),
176                                          NULL);
177   CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
178
179   if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
180     CI->setCallingConv(F->getCallingConv());
181
182   return CI;
183 }
184
185 /// EmitMemCmp - Emit a call to the memcmp function.
186 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
187                                        Value *Len, IRBuilder<> &B) {
188   Module *M = Caller->getParent();
189   AttributeWithIndex AWI[3];
190   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
191   AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
192   AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
193                                    Attribute::NoUnwind);
194
195   Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
196                                          Type::Int32Ty,
197                                     Context->getPointerTypeUnqual(Type::Int8Ty),
198                                     Context->getPointerTypeUnqual(Type::Int8Ty),
199                                          TD->getIntPtrType(), NULL);
200   CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
201                                Len, "memcmp");
202
203   if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
204     CI->setCallingConv(F->getCallingConv());
205
206   return CI;
207 }
208
209 /// EmitMemSet - Emit a call to the memset function
210 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
211                                        Value *Len, IRBuilder<> &B) {
212  Module *M = Caller->getParent();
213  Intrinsic::ID IID = Intrinsic::memset;
214  const Type *Tys[1];
215  Tys[0] = Len->getType();
216  Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
217  Value *Align = ConstantInt::get(Type::Int32Ty, 1);
218  return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
219 }
220
221 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
222 /// 'floor').  This function is known to take a single of type matching 'Op' and
223 /// returns one value with the same type.  If 'Op' is a long double, 'l' is
224 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
225 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
226                                                  IRBuilder<> &B) {
227   char NameBuffer[20];
228   if (Op->getType() != Type::DoubleTy) {
229     // If we need to add a suffix, copy into NameBuffer.
230     unsigned NameLen = strlen(Name);
231     assert(NameLen < sizeof(NameBuffer)-2);
232     memcpy(NameBuffer, Name, NameLen);
233     if (Op->getType() == Type::FloatTy)
234       NameBuffer[NameLen] = 'f';  // floorf
235     else
236       NameBuffer[NameLen] = 'l';  // floorl
237     NameBuffer[NameLen+1] = 0;
238     Name = NameBuffer;
239   }
240
241   Module *M = Caller->getParent();
242   Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
243                                          Op->getType(), NULL);
244   CallInst *CI = B.CreateCall(Callee, Op, Name);
245
246   if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
247     CI->setCallingConv(F->getCallingConv());
248
249   return CI;
250 }
251
252 /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
253 /// is an integer.
254 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
255   Module *M = Caller->getParent();
256   Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
257                                           Type::Int32Ty, NULL);
258   CallInst *CI = B.CreateCall(PutChar,
259                               B.CreateIntCast(Char, Type::Int32Ty, "chari"),
260                               "putchar");
261
262   if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
263     CI->setCallingConv(F->getCallingConv());
264 }
265
266 /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
267 /// some pointer.
268 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
269   Module *M = Caller->getParent();
270   AttributeWithIndex AWI[2];
271   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
272   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
273
274   Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
275                                        Type::Int32Ty,
276                                     Context->getPointerTypeUnqual(Type::Int8Ty),
277                                        NULL);
278   CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
279   if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
280     CI->setCallingConv(F->getCallingConv());
281
282 }
283
284 /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
285 /// an integer and File is a pointer to FILE.
286 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
287   Module *M = Caller->getParent();
288   AttributeWithIndex AWI[2];
289   AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
290   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
291   Constant *F;
292   if (isa<PointerType>(File->getType()))
293     F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
294                                Type::Int32Ty, File->getType(), NULL);
295   else
296     F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
297                                File->getType(), NULL);
298   Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
299   CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
300
301   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
302     CI->setCallingConv(Fn->getCallingConv());
303 }
304
305 /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
306 /// pointer and File is a pointer to FILE.
307 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
308   Module *M = Caller->getParent();
309   AttributeWithIndex AWI[3];
310   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
311   AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
312   AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
313   Constant *F;
314   if (isa<PointerType>(File->getType()))
315     F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
316                                Context->getPointerTypeUnqual(Type::Int8Ty),
317                                File->getType(), NULL);
318   else
319     F = M->getOrInsertFunction("fputs", Type::Int32Ty,
320                                Context->getPointerTypeUnqual(Type::Int8Ty),
321                                File->getType(), NULL);
322   CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
323
324   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
325     CI->setCallingConv(Fn->getCallingConv());
326 }
327
328 /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
329 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
330 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
331                                      IRBuilder<> &B) {
332   Module *M = Caller->getParent();
333   AttributeWithIndex AWI[3];
334   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
335   AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
336   AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
337   Constant *F;
338   if (isa<PointerType>(File->getType()))
339     F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
340                                TD->getIntPtrType(),
341                                Context->getPointerTypeUnqual(Type::Int8Ty),
342                                TD->getIntPtrType(), TD->getIntPtrType(),
343                                File->getType(), NULL);
344   else
345     F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
346                                Context->getPointerTypeUnqual(Type::Int8Ty),
347                                TD->getIntPtrType(), TD->getIntPtrType(),
348                                File->getType(), NULL);
349   CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
350                         ConstantInt::get(TD->getIntPtrType(), 1), File);
351
352   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
353     CI->setCallingConv(Fn->getCallingConv());
354 }
355
356 //===----------------------------------------------------------------------===//
357 // Helper Functions
358 //===----------------------------------------------------------------------===//
359
360 /// GetStringLengthH - If we can compute the length of the string pointed to by
361 /// the specified pointer, return 'len+1'.  If we can't, return 0.
362 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
363   // Look through noop bitcast instructions.
364   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
365     return GetStringLengthH(BCI->getOperand(0), PHIs);
366   
367   // If this is a PHI node, there are two cases: either we have already seen it
368   // or we haven't.
369   if (PHINode *PN = dyn_cast<PHINode>(V)) {
370     if (!PHIs.insert(PN))
371       return ~0ULL;  // already in the set.
372     
373     // If it was new, see if all the input strings are the same length.
374     uint64_t LenSoFar = ~0ULL;
375     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
376       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
377       if (Len == 0) return 0; // Unknown length -> unknown.
378       
379       if (Len == ~0ULL) continue;
380       
381       if (Len != LenSoFar && LenSoFar != ~0ULL)
382         return 0;    // Disagree -> unknown.
383       LenSoFar = Len;
384     }
385     
386     // Success, all agree.
387     return LenSoFar;
388   }
389   
390   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
391   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
392     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
393     if (Len1 == 0) return 0;
394     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
395     if (Len2 == 0) return 0;
396     if (Len1 == ~0ULL) return Len2;
397     if (Len2 == ~0ULL) return Len1;
398     if (Len1 != Len2) return 0;
399     return Len1;
400   }
401   
402   // If the value is not a GEP instruction nor a constant expression with a
403   // GEP instruction, then return unknown.
404   User *GEP = 0;
405   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
406     GEP = GEPI;
407   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
408     if (CE->getOpcode() != Instruction::GetElementPtr)
409       return 0;
410     GEP = CE;
411   } else {
412     return 0;
413   }
414   
415   // Make sure the GEP has exactly three arguments.
416   if (GEP->getNumOperands() != 3)
417     return 0;
418   
419   // Check to make sure that the first operand of the GEP is an integer and
420   // has value 0 so that we are sure we're indexing into the initializer.
421   if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
422     if (!Idx->isZero())
423       return 0;
424   } else
425     return 0;
426   
427   // If the second index isn't a ConstantInt, then this is a variable index
428   // into the array.  If this occurs, we can't say anything meaningful about
429   // the string.
430   uint64_t StartIdx = 0;
431   if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
432     StartIdx = CI->getZExtValue();
433   else
434     return 0;
435   
436   // The GEP instruction, constant or instruction, must reference a global
437   // variable that is a constant and is initialized. The referenced constant
438   // initializer is the array that we'll use for optimization.
439   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
440   if (!GV || !GV->isConstant() || !GV->hasInitializer())
441     return 0;
442   Constant *GlobalInit = GV->getInitializer();
443   
444   // Handle the ConstantAggregateZero case, which is a degenerate case. The
445   // initializer is constant zero so the length of the string must be zero.
446   if (isa<ConstantAggregateZero>(GlobalInit))
447     return 1;  // Len = 0 offset by 1.
448   
449   // Must be a Constant Array
450   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
451   if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
452     return false;
453   
454   // Get the number of elements in the array
455   uint64_t NumElts = Array->getType()->getNumElements();
456   
457   // Traverse the constant array from StartIdx (derived above) which is
458   // the place the GEP refers to in the array.
459   for (unsigned i = StartIdx; i != NumElts; ++i) {
460     Constant *Elt = Array->getOperand(i);
461     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
462     if (!CI) // This array isn't suitable, non-int initializer.
463       return 0;
464     if (CI->isZero())
465       return i-StartIdx+1; // We found end of string, success!
466   }
467   
468   return 0; // The array isn't null terminated, conservatively return 'unknown'.
469 }
470
471 /// GetStringLength - If we can compute the length of the string pointed to by
472 /// the specified pointer, return 'len+1'.  If we can't, return 0.
473 static uint64_t GetStringLength(Value *V) {
474   if (!isa<PointerType>(V->getType())) return 0;
475   
476   SmallPtrSet<PHINode*, 32> PHIs;
477   uint64_t Len = GetStringLengthH(V, PHIs);
478   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
479   // an empty string as a length.
480   return Len == ~0ULL ? 1 : Len;
481 }
482
483 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
484 /// value is equal or not-equal to zero. 
485 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
486   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
487        UI != E; ++UI) {
488     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
489       if (IC->isEquality())
490         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
491           if (C->isNullValue())
492             continue;
493     // Unknown instruction.
494     return false;
495   }
496   return true;
497 }
498
499 //===----------------------------------------------------------------------===//
500 // Miscellaneous LibCall Optimizations
501 //===----------------------------------------------------------------------===//
502
503 namespace {
504 //===---------------------------------------===//
505 // 'exit' Optimizations
506
507 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
508 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
509   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
510     // Verify we have a reasonable prototype for exit.
511     if (Callee->arg_size() == 0 || !CI->use_empty())
512       return 0;
513
514     // Verify the caller is main, and that the result type of main matches the
515     // argument type of exit.
516     if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
517         Caller->getReturnType() != CI->getOperand(1)->getType())
518       return 0;
519
520     TerminatorInst *OldTI = CI->getParent()->getTerminator();
521     
522     // Drop all successor phi node entries.
523     for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
524       OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
525     
526     // Split the basic block after the call to exit.
527     BasicBlock::iterator FirstDead = CI; ++FirstDead;
528     CI->getParent()->splitBasicBlock(FirstDead);
529     B.SetInsertPoint(B.GetInsertBlock());
530
531     // Remove the branch that splitBB created and insert a return instead.
532     CI->getParent()->getTerminator()->eraseFromParent();
533     B.CreateRet(CI->getOperand(1));
534
535     return CI;
536   }
537 };
538
539 //===----------------------------------------------------------------------===//
540 // String and Memory LibCall Optimizations
541 //===----------------------------------------------------------------------===//
542
543 //===---------------------------------------===//
544 // 'strcat' Optimizations
545
546 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
547   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
548     // Verify the "strcat" function prototype.
549     const FunctionType *FT = Callee->getFunctionType();
550     if (FT->getNumParams() != 2 ||
551         FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
552         FT->getParamType(0) != FT->getReturnType() ||
553         FT->getParamType(1) != FT->getReturnType())
554       return 0;
555     
556     // Extract some information from the instruction
557     Value *Dst = CI->getOperand(1);
558     Value *Src = CI->getOperand(2);
559     
560     // See if we can get the length of the input string.
561     uint64_t Len = GetStringLength(Src);
562     if (Len == 0) return 0;
563     --Len;  // Unbias length.
564     
565     // Handle the simple, do-nothing case: strcat(x, "") -> x
566     if (Len == 0)
567       return Dst;
568     
569     EmitStrLenMemCpy(Src, Dst, Len, B);
570     return Dst;
571   }
572
573   void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
574     // We need to find the end of the destination string.  That's where the
575     // memory is to be moved to. We just generate a call to strlen.
576     Value *DstLen = EmitStrLen(Dst, B);
577     
578     // Now that we have the destination's length, we must index into the
579     // destination's pointer to get the actual memcpy destination (end of
580     // the string .. we're concatenating).
581     Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
582     
583     // We have enough information to now generate the memcpy call to do the
584     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
585     EmitMemCpy(CpyDst, Src,
586                ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
587   }
588 };
589
590 //===---------------------------------------===//
591 // 'strncat' Optimizations
592
593 struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
594   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
595     // Verify the "strncat" function prototype.
596     const FunctionType *FT = Callee->getFunctionType();
597     if (FT->getNumParams() != 3 ||
598         FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
599         FT->getParamType(0) != FT->getReturnType() ||
600         FT->getParamType(1) != FT->getReturnType() ||
601         !isa<IntegerType>(FT->getParamType(2)))
602       return 0;
603
604     // Extract some information from the instruction
605     Value *Dst = CI->getOperand(1);
606     Value *Src = CI->getOperand(2);
607     uint64_t Len;
608
609     // We don't do anything if length is not constant
610     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
611       Len = LengthArg->getZExtValue();
612     else
613       return 0;
614
615     // See if we can get the length of the input string.
616     uint64_t SrcLen = GetStringLength(Src);
617     if (SrcLen == 0) return 0;
618     --SrcLen;  // Unbias length.
619
620     // Handle the simple, do-nothing cases:
621     // strncat(x, "", c) -> x
622     // strncat(x,  c, 0) -> x
623     if (SrcLen == 0 || Len == 0) return Dst;
624
625     // We don't optimize this case
626     if (Len < SrcLen) return 0;
627
628     // strncat(x, s, c) -> strcat(x, s)
629     // s is constant so the strcat can be optimized further
630     EmitStrLenMemCpy(Src, Dst, SrcLen, B);
631     return Dst;
632   }
633 };
634
635 //===---------------------------------------===//
636 // 'strchr' Optimizations
637
638 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
639   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
640     // Verify the "strchr" function prototype.
641     const FunctionType *FT = Callee->getFunctionType();
642     if (FT->getNumParams() != 2 ||
643         FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
644         FT->getParamType(0) != FT->getReturnType())
645       return 0;
646     
647     Value *SrcStr = CI->getOperand(1);
648     
649     // If the second operand is non-constant, see if we can compute the length
650     // of the input string and turn this into memchr.
651     ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
652     if (CharC == 0) {
653       uint64_t Len = GetStringLength(SrcStr);
654       if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
655         return 0;
656       
657       return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
658                         ConstantInt::get(TD->getIntPtrType(), Len), B);
659     }
660
661     // Otherwise, the character is a constant, see if the first argument is
662     // a string literal.  If so, we can constant fold.
663     std::string Str;
664     if (!GetConstantStringInfo(SrcStr, Str))
665       return 0;
666     
667     // strchr can find the nul character.
668     Str += '\0';
669     char CharValue = CharC->getSExtValue();
670     
671     // Compute the offset.
672     uint64_t i = 0;
673     while (1) {
674       if (i == Str.size())    // Didn't find the char.  strchr returns null.
675         return Context->getNullValue(CI->getType());
676       // Did we find our match?
677       if (Str[i] == CharValue)
678         break;
679       ++i;
680     }
681     
682     // strchr(s+n,c)  -> gep(s+n+i,c)
683     Value *Idx = ConstantInt::get(Type::Int64Ty, i);
684     return B.CreateGEP(SrcStr, Idx, "strchr");
685   }
686 };
687
688 //===---------------------------------------===//
689 // 'strcmp' Optimizations
690
691 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
692   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
693     // Verify the "strcmp" function prototype.
694     const FunctionType *FT = Callee->getFunctionType();
695     if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
696         FT->getParamType(0) != FT->getParamType(1) ||
697         FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
698       return 0;
699     
700     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
701     if (Str1P == Str2P)      // strcmp(x,x)  -> 0
702       return ConstantInt::get(CI->getType(), 0);
703     
704     std::string Str1, Str2;
705     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
706     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
707     
708     if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
709       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
710     
711     if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
712       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
713     
714     // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
715     if (HasStr1 && HasStr2)
716       return ConstantInt::get(CI->getType(), 
717                                      strcmp(Str1.c_str(),Str2.c_str()));
718
719     // strcmp(P, "x") -> memcmp(P, "x", 2)
720     uint64_t Len1 = GetStringLength(Str1P);
721     uint64_t Len2 = GetStringLength(Str2P);
722     if (Len1 && Len2) {
723       return EmitMemCmp(Str1P, Str2P,
724                         ConstantInt::get(TD->getIntPtrType(),
725                         std::min(Len1, Len2)), B);
726     }
727
728     return 0;
729   }
730 };
731
732 //===---------------------------------------===//
733 // 'strncmp' Optimizations
734
735 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
736   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
737     // Verify the "strncmp" function prototype.
738     const FunctionType *FT = Callee->getFunctionType();
739     if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
740         FT->getParamType(0) != FT->getParamType(1) ||
741         FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
742         !isa<IntegerType>(FT->getParamType(2)))
743       return 0;
744     
745     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
746     if (Str1P == Str2P)      // strncmp(x,x,n)  -> 0
747       return ConstantInt::get(CI->getType(), 0);
748     
749     // Get the length argument if it is constant.
750     uint64_t Length;
751     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
752       Length = LengthArg->getZExtValue();
753     else
754       return 0;
755     
756     if (Length == 0) // strncmp(x,y,0)   -> 0
757       return ConstantInt::get(CI->getType(), 0);
758     
759     std::string Str1, Str2;
760     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
761     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
762     
763     if (HasStr1 && Str1.empty())  // strncmp("", x, n) -> *x
764       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
765     
766     if (HasStr2 && Str2.empty())  // strncmp(x, "", n) -> *x
767       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
768     
769     // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
770     if (HasStr1 && HasStr2)
771       return ConstantInt::get(CI->getType(),
772                               strncmp(Str1.c_str(), Str2.c_str(), Length));
773     return 0;
774   }
775 };
776
777
778 //===---------------------------------------===//
779 // 'strcpy' Optimizations
780
781 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
782   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
783     // Verify the "strcpy" function prototype.
784     const FunctionType *FT = Callee->getFunctionType();
785     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
786         FT->getParamType(0) != FT->getParamType(1) ||
787         FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
788       return 0;
789     
790     Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
791     if (Dst == Src)      // strcpy(x,x)  -> x
792       return Src;
793     
794     // See if we can get the length of the input string.
795     uint64_t Len = GetStringLength(Src);
796     if (Len == 0) return 0;
797     
798     // We have enough information to now generate the memcpy call to do the
799     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
800     EmitMemCpy(Dst, Src,
801                ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
802     return Dst;
803   }
804 };
805
806 //===---------------------------------------===//
807 // 'strncpy' Optimizations
808
809 struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
810   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
811     const FunctionType *FT = Callee->getFunctionType();
812     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
813         FT->getParamType(0) != FT->getParamType(1) ||
814         FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
815         !isa<IntegerType>(FT->getParamType(2)))
816       return 0;
817
818     Value *Dst = CI->getOperand(1);
819     Value *Src = CI->getOperand(2);
820     Value *LenOp = CI->getOperand(3);
821
822     // See if we can get the length of the input string.
823     uint64_t SrcLen = GetStringLength(Src);
824     if (SrcLen == 0) return 0;
825     --SrcLen;
826
827     if (SrcLen == 0) {
828       // strncpy(x, "", y) -> memset(x, '\0', y, 1)
829       EmitMemSet(Dst, ConstantInt::get(Type::Int8Ty, '\0'), LenOp, B);
830       return Dst;
831     }
832
833     uint64_t Len;
834     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
835       Len = LengthArg->getZExtValue();
836     else
837       return 0;
838
839     if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
840
841     // Let strncpy handle the zero padding
842     if (Len > SrcLen+1) return 0;
843
844     // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
845     EmitMemCpy(Dst, Src,
846                ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
847
848     return Dst;
849   }
850 };
851
852 //===---------------------------------------===//
853 // 'strlen' Optimizations
854
855 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
856   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
857     const FunctionType *FT = Callee->getFunctionType();
858     if (FT->getNumParams() != 1 ||
859         FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
860         !isa<IntegerType>(FT->getReturnType()))
861       return 0;
862     
863     Value *Src = CI->getOperand(1);
864
865     // Constant folding: strlen("xyz") -> 3
866     if (uint64_t Len = GetStringLength(Src))
867       return ConstantInt::get(CI->getType(), Len-1);
868
869     // Handle strlen(p) != 0.
870     if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
871
872     // strlen(x) != 0 --> *x != 0
873     // strlen(x) == 0 --> *x == 0
874     return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
875   }
876 };
877
878 //===---------------------------------------===//
879 // 'strto*' Optimizations
880
881 struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
882   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
883     const FunctionType *FT = Callee->getFunctionType();
884     if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
885         !isa<PointerType>(FT->getParamType(0)) ||
886         !isa<PointerType>(FT->getParamType(1)))
887       return 0;
888
889     Value *EndPtr = CI->getOperand(2);
890     if (isa<ConstantPointerNull>(EndPtr)) {
891       CI->setOnlyReadsMemory();
892       CI->addAttribute(1, Attribute::NoCapture);
893     }
894
895     return 0;
896   }
897 };
898
899
900 //===---------------------------------------===//
901 // 'memcmp' Optimizations
902
903 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
904   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
905     const FunctionType *FT = Callee->getFunctionType();
906     if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
907         !isa<PointerType>(FT->getParamType(1)) ||
908         FT->getReturnType() != Type::Int32Ty)
909       return 0;
910
911     Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
912
913     if (LHS == RHS)  // memcmp(s,s,x) -> 0
914       return Context->getNullValue(CI->getType());
915
916     // Make sure we have a constant length.
917     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
918     if (!LenC) return 0;
919     uint64_t Len = LenC->getZExtValue();
920
921     if (Len == 0) // memcmp(s1,s2,0) -> 0
922       return Context->getNullValue(CI->getType());
923
924     if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
925       Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
926       Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
927       return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
928     }
929
930     // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS)  != 0
931     // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS)  != 0
932     if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
933       const Type *PTy = Context->getPointerTypeUnqual(Len == 2 ?
934                                                Type::Int16Ty : Type::Int32Ty);
935       LHS = B.CreateBitCast(LHS, PTy, "tmp");
936       RHS = B.CreateBitCast(RHS, PTy, "tmp");
937       LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
938       LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
939       LHSV->setAlignment(1); RHSV->setAlignment(1);  // Unaligned loads.
940       return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
941     }
942
943     return 0;
944   }
945 };
946
947 //===---------------------------------------===//
948 // 'memcpy' Optimizations
949
950 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
951   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
952     const FunctionType *FT = Callee->getFunctionType();
953     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
954         !isa<PointerType>(FT->getParamType(0)) ||
955         !isa<PointerType>(FT->getParamType(1)) ||
956         FT->getParamType(2) != TD->getIntPtrType())
957       return 0;
958
959     // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
960     EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
961     return CI->getOperand(1);
962   }
963 };
964
965 //===---------------------------------------===//
966 // 'memmove' Optimizations
967
968 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
969   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
970     const FunctionType *FT = Callee->getFunctionType();
971     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
972         !isa<PointerType>(FT->getParamType(0)) ||
973         !isa<PointerType>(FT->getParamType(1)) ||
974         FT->getParamType(2) != TD->getIntPtrType())
975       return 0;
976
977     // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
978     Module *M = Caller->getParent();
979     Intrinsic::ID IID = Intrinsic::memmove;
980     const Type *Tys[1];
981     Tys[0] = TD->getIntPtrType();
982     Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
983     Value *Dst = CastToCStr(CI->getOperand(1), B);
984     Value *Src = CastToCStr(CI->getOperand(2), B);
985     Value *Size = CI->getOperand(3);
986     Value *Align = ConstantInt::get(Type::Int32Ty, 1);
987     B.CreateCall4(MemMove, Dst, Src, Size, Align);
988     return CI->getOperand(1);
989   }
990 };
991
992 //===---------------------------------------===//
993 // 'memset' Optimizations
994
995 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
996   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
997     const FunctionType *FT = Callee->getFunctionType();
998     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
999         !isa<PointerType>(FT->getParamType(0)) ||
1000         !isa<IntegerType>(FT->getParamType(1)) ||
1001         FT->getParamType(2) != TD->getIntPtrType())
1002       return 0;
1003
1004     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1005     Value *Val = B.CreateIntCast(CI->getOperand(2), Type::Int8Ty, false);
1006     EmitMemSet(CI->getOperand(1), Val,  CI->getOperand(3), B);
1007     return CI->getOperand(1);
1008   }
1009 };
1010
1011 //===----------------------------------------------------------------------===//
1012 // Math Library Optimizations
1013 //===----------------------------------------------------------------------===//
1014
1015 //===---------------------------------------===//
1016 // 'pow*' Optimizations
1017
1018 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
1019   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1020     const FunctionType *FT = Callee->getFunctionType();
1021     // Just make sure this has 2 arguments of the same FP type, which match the
1022     // result type.
1023     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1024         FT->getParamType(0) != FT->getParamType(1) ||
1025         !FT->getParamType(0)->isFloatingPoint())
1026       return 0;
1027     
1028     Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1029     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1030       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
1031         return Op1C;
1032       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
1033         return EmitUnaryFloatFnCall(Op2, "exp2", B);
1034     }
1035     
1036     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1037     if (Op2C == 0) return 0;
1038     
1039     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
1040       return ConstantFP::get(CI->getType(), 1.0);
1041     
1042     if (Op2C->isExactlyValue(0.5)) {
1043       // FIXME: This is not safe for -0.0 and -inf.  This can only be done when
1044       // 'unsafe' math optimizations are allowed.
1045       // x    pow(x, 0.5)  sqrt(x)
1046       // ---------------------------------------------
1047       // -0.0    +0.0       -0.0
1048       // -inf    +inf       NaN
1049 #if 0
1050       // pow(x, 0.5) -> sqrt(x)
1051       return B.CreateCall(get_sqrt(), Op1, "sqrt");
1052 #endif
1053     }
1054     
1055     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
1056       return Op1;
1057     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
1058       return B.CreateFMul(Op1, Op1, "pow2");
1059     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1060       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1061                           Op1, "powrecip");
1062     return 0;
1063   }
1064 };
1065
1066 //===---------------------------------------===//
1067 // 'exp2' Optimizations
1068
1069 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
1070   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1071     const FunctionType *FT = Callee->getFunctionType();
1072     // Just make sure this has 1 argument of FP type, which matches the
1073     // result type.
1074     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1075         !FT->getParamType(0)->isFloatingPoint())
1076       return 0;
1077     
1078     Value *Op = CI->getOperand(1);
1079     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1080     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1081     Value *LdExpArg = 0;
1082     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1083       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1084         LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1085     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1086       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1087         LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1088     }
1089
1090     if (LdExpArg) {
1091       const char *Name;
1092       if (Op->getType() == Type::FloatTy)
1093         Name = "ldexpf";
1094       else if (Op->getType() == Type::DoubleTy)
1095         Name = "ldexp";
1096       else
1097         Name = "ldexpl";
1098
1099       Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1100       if (Op->getType() != Type::FloatTy)
1101         One = Context->getConstantExprFPExtend(One, Op->getType());
1102
1103       Module *M = Caller->getParent();
1104       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1105                                              Op->getType(), Type::Int32Ty,NULL);
1106       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1107       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1108         CI->setCallingConv(F->getCallingConv());
1109
1110       return CI;
1111     }
1112     return 0;
1113   }
1114 };
1115
1116 //===---------------------------------------===//
1117 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1118
1119 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
1120   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1121     const FunctionType *FT = Callee->getFunctionType();
1122     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1123         FT->getParamType(0) != Type::DoubleTy)
1124       return 0;
1125
1126     // If this is something like 'floor((double)floatval)', convert to floorf.
1127     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1128     if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1129       return 0;
1130
1131     // floor((double)floatval) -> (double)floorf(floatval)
1132     Value *V = Cast->getOperand(0);
1133     V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
1134     return B.CreateFPExt(V, Type::DoubleTy);
1135   }
1136 };
1137
1138 //===----------------------------------------------------------------------===//
1139 // Integer Optimizations
1140 //===----------------------------------------------------------------------===//
1141
1142 //===---------------------------------------===//
1143 // 'ffs*' Optimizations
1144
1145 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
1146   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1147     const FunctionType *FT = Callee->getFunctionType();
1148     // Just make sure this has 2 arguments of the same FP type, which match the
1149     // result type.
1150     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1151         !isa<IntegerType>(FT->getParamType(0)))
1152       return 0;
1153     
1154     Value *Op = CI->getOperand(1);
1155     
1156     // Constant fold.
1157     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1158       if (CI->getValue() == 0)  // ffs(0) -> 0.
1159         return Context->getNullValue(CI->getType());
1160       return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
1161                               CI->getValue().countTrailingZeros()+1);
1162     }
1163     
1164     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1165     const Type *ArgType = Op->getType();
1166     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1167                                          Intrinsic::cttz, &ArgType, 1);
1168     Value *V = B.CreateCall(F, Op, "cttz");
1169     V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1170     V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1171     
1172     Value *Cond = B.CreateICmpNE(Op, Context->getNullValue(ArgType), "tmp");
1173     return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
1174   }
1175 };
1176
1177 //===---------------------------------------===//
1178 // 'isdigit' Optimizations
1179
1180 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
1181   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1182     const FunctionType *FT = Callee->getFunctionType();
1183     // We require integer(i32)
1184     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1185         FT->getParamType(0) != Type::Int32Ty)
1186       return 0;
1187     
1188     // isdigit(c) -> (c-'0') <u 10
1189     Value *Op = CI->getOperand(1);
1190     Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), 
1191                      "isdigittmp");
1192     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), 
1193                          "isdigit");
1194     return B.CreateZExt(Op, CI->getType());
1195   }
1196 };
1197
1198 //===---------------------------------------===//
1199 // 'isascii' Optimizations
1200
1201 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
1202   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1203     const FunctionType *FT = Callee->getFunctionType();
1204     // We require integer(i32)
1205     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1206         FT->getParamType(0) != Type::Int32Ty)
1207       return 0;
1208     
1209     // isascii(c) -> c <u 128
1210     Value *Op = CI->getOperand(1);
1211     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128),
1212                          "isascii");
1213     return B.CreateZExt(Op, CI->getType());
1214   }
1215 };
1216   
1217 //===---------------------------------------===//
1218 // 'abs', 'labs', 'llabs' Optimizations
1219
1220 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
1221   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1222     const FunctionType *FT = Callee->getFunctionType();
1223     // We require integer(integer) where the types agree.
1224     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1225         FT->getParamType(0) != FT->getReturnType())
1226       return 0;
1227     
1228     // abs(x) -> x >s -1 ? x : -x
1229     Value *Op = CI->getOperand(1);
1230     Value *Pos = B.CreateICmpSGT(Op, 
1231                              Context->getAllOnesValue(Op->getType()),
1232                                  "ispos");
1233     Value *Neg = B.CreateNeg(Op, "neg");
1234     return B.CreateSelect(Pos, Op, Neg);
1235   }
1236 };
1237   
1238
1239 //===---------------------------------------===//
1240 // 'toascii' Optimizations
1241
1242 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
1243   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1244     const FunctionType *FT = Callee->getFunctionType();
1245     // We require i32(i32)
1246     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1247         FT->getParamType(0) != Type::Int32Ty)
1248       return 0;
1249     
1250     // isascii(c) -> c & 0x7f
1251     return B.CreateAnd(CI->getOperand(1),
1252                        ConstantInt::get(CI->getType(),0x7F));
1253   }
1254 };
1255
1256 //===----------------------------------------------------------------------===//
1257 // Formatting and IO Optimizations
1258 //===----------------------------------------------------------------------===//
1259
1260 //===---------------------------------------===//
1261 // 'printf' Optimizations
1262
1263 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1264   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1265     // Require one fixed pointer argument and an integer/void result.
1266     const FunctionType *FT = Callee->getFunctionType();
1267     if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1268         !(isa<IntegerType>(FT->getReturnType()) ||
1269           FT->getReturnType() == Type::VoidTy))
1270       return 0;
1271     
1272     // Check for a fixed format string.
1273     std::string FormatStr;
1274     if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1275       return 0;
1276
1277     // Empty format string -> noop.
1278     if (FormatStr.empty())  // Tolerate printf's declared void.
1279       return CI->use_empty() ? (Value*)CI : 
1280                                ConstantInt::get(CI->getType(), 0);
1281     
1282     // printf("x") -> putchar('x'), even for '%'.
1283     if (FormatStr.size() == 1) {
1284       EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1285       return CI->use_empty() ? (Value*)CI : 
1286                                ConstantInt::get(CI->getType(), 1);
1287     }
1288     
1289     // printf("foo\n") --> puts("foo")
1290     if (FormatStr[FormatStr.size()-1] == '\n' &&
1291         FormatStr.find('%') == std::string::npos) {  // no format characters.
1292       // Create a string literal with no \n on it.  We expect the constant merge
1293       // pass to be run after this pass, to merge duplicate strings.
1294       FormatStr.erase(FormatStr.end()-1);
1295       Constant *C = ConstantArray::get(FormatStr, true);
1296       C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1297                              GlobalVariable::InternalLinkage, C, "str");
1298       EmitPutS(C, B);
1299       return CI->use_empty() ? (Value*)CI : 
1300                     ConstantInt::get(CI->getType(), FormatStr.size()+1);
1301     }
1302     
1303     // Optimize specific format strings.
1304     // printf("%c", chr) --> putchar(*(i8*)dst)
1305     if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1306         isa<IntegerType>(CI->getOperand(2)->getType())) {
1307       EmitPutChar(CI->getOperand(2), B);
1308       return CI->use_empty() ? (Value*)CI : 
1309                                ConstantInt::get(CI->getType(), 1);
1310     }
1311     
1312     // printf("%s\n", str) --> puts(str)
1313     if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1314         isa<PointerType>(CI->getOperand(2)->getType()) &&
1315         CI->use_empty()) {
1316       EmitPutS(CI->getOperand(2), B);
1317       return CI;
1318     }
1319     return 0;
1320   }
1321 };
1322
1323 //===---------------------------------------===//
1324 // 'sprintf' Optimizations
1325
1326 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1327   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1328     // Require two fixed pointer arguments and an integer result.
1329     const FunctionType *FT = Callee->getFunctionType();
1330     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1331         !isa<PointerType>(FT->getParamType(1)) ||
1332         !isa<IntegerType>(FT->getReturnType()))
1333       return 0;
1334
1335     // Check for a fixed format string.
1336     std::string FormatStr;
1337     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1338       return 0;
1339     
1340     // If we just have a format string (nothing else crazy) transform it.
1341     if (CI->getNumOperands() == 3) {
1342       // Make sure there's no % in the constant array.  We could try to handle
1343       // %% -> % in the future if we cared.
1344       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1345         if (FormatStr[i] == '%')
1346           return 0; // we found a format specifier, bail out.
1347       
1348       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1349       EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1350           ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1351       return ConstantInt::get(CI->getType(), FormatStr.size());
1352     }
1353     
1354     // The remaining optimizations require the format string to be "%s" or "%c"
1355     // and have an extra operand.
1356     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1357       return 0;
1358     
1359     // Decode the second character of the format string.
1360     if (FormatStr[1] == 'c') {
1361       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1362       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1363       Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1364       Value *Ptr = CastToCStr(CI->getOperand(1), B);
1365       B.CreateStore(V, Ptr);
1366       Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1367       B.CreateStore(Context->getNullValue(Type::Int8Ty), Ptr);
1368       
1369       return ConstantInt::get(CI->getType(), 1);
1370     }
1371     
1372     if (FormatStr[1] == 's') {
1373       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1374       if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1375
1376       Value *Len = EmitStrLen(CI->getOperand(3), B);
1377       Value *IncLen = B.CreateAdd(Len,
1378                                   ConstantInt::get(Len->getType(), 1),
1379                                   "leninc");
1380       EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1381       
1382       // The sprintf result is the unincremented number of bytes in the string.
1383       return B.CreateIntCast(Len, CI->getType(), false);
1384     }
1385     return 0;
1386   }
1387 };
1388
1389 //===---------------------------------------===//
1390 // 'fwrite' Optimizations
1391
1392 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1393   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1394     // Require a pointer, an integer, an integer, a pointer, returning integer.
1395     const FunctionType *FT = Callee->getFunctionType();
1396     if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1397         !isa<IntegerType>(FT->getParamType(1)) ||
1398         !isa<IntegerType>(FT->getParamType(2)) ||
1399         !isa<PointerType>(FT->getParamType(3)) ||
1400         !isa<IntegerType>(FT->getReturnType()))
1401       return 0;
1402     
1403     // Get the element size and count.
1404     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1405     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1406     if (!SizeC || !CountC) return 0;
1407     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1408     
1409     // If this is writing zero records, remove the call (it's a noop).
1410     if (Bytes == 0)
1411       return ConstantInt::get(CI->getType(), 0);
1412     
1413     // If this is writing one byte, turn it into fputc.
1414     if (Bytes == 1) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
1415       Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1416       EmitFPutC(Char, CI->getOperand(4), B);
1417       return ConstantInt::get(CI->getType(), 1);
1418     }
1419
1420     return 0;
1421   }
1422 };
1423
1424 //===---------------------------------------===//
1425 // 'fputs' Optimizations
1426
1427 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1428   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1429     // Require two pointers.  Also, we can't optimize if return value is used.
1430     const FunctionType *FT = Callee->getFunctionType();
1431     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1432         !isa<PointerType>(FT->getParamType(1)) ||
1433         !CI->use_empty())
1434       return 0;
1435     
1436     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1437     uint64_t Len = GetStringLength(CI->getOperand(1));
1438     if (!Len) return 0;
1439     EmitFWrite(CI->getOperand(1),
1440                ConstantInt::get(TD->getIntPtrType(), Len-1),
1441                CI->getOperand(2), B);
1442     return CI;  // Known to have no uses (see above).
1443   }
1444 };
1445
1446 //===---------------------------------------===//
1447 // 'fprintf' Optimizations
1448
1449 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1450   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1451     // Require two fixed paramters as pointers and integer result.
1452     const FunctionType *FT = Callee->getFunctionType();
1453     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1454         !isa<PointerType>(FT->getParamType(1)) ||
1455         !isa<IntegerType>(FT->getReturnType()))
1456       return 0;
1457     
1458     // All the optimizations depend on the format string.
1459     std::string FormatStr;
1460     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1461       return 0;
1462
1463     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1464     if (CI->getNumOperands() == 3) {
1465       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1466         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
1467           return 0; // We found a format specifier.
1468       
1469       EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1470                                                      FormatStr.size()),
1471                  CI->getOperand(1), B);
1472       return ConstantInt::get(CI->getType(), FormatStr.size());
1473     }
1474     
1475     // The remaining optimizations require the format string to be "%s" or "%c"
1476     // and have an extra operand.
1477     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1478       return 0;
1479     
1480     // Decode the second character of the format string.
1481     if (FormatStr[1] == 'c') {
1482       // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1483       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1484       EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1485       return ConstantInt::get(CI->getType(), 1);
1486     }
1487     
1488     if (FormatStr[1] == 's') {
1489       // fprintf(F, "%s", str) -> fputs(str, F)
1490       if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1491         return 0;
1492       EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1493       return CI;
1494     }
1495     return 0;
1496   }
1497 };
1498
1499 } // end anonymous namespace.
1500
1501 //===----------------------------------------------------------------------===//
1502 // SimplifyLibCalls Pass Implementation
1503 //===----------------------------------------------------------------------===//
1504
1505 namespace {
1506   /// This pass optimizes well known library functions from libc and libm.
1507   ///
1508   class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1509     StringMap<LibCallOptimization*> Optimizations;
1510     // Miscellaneous LibCall Optimizations
1511     ExitOpt Exit; 
1512     // String and Memory LibCall Optimizations
1513     StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1514     StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1515     StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1516     MemSetOpt MemSet;
1517     // Math Library Optimizations
1518     PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1519     // Integer Optimizations
1520     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1521     ToAsciiOpt ToAscii;
1522     // Formatting and IO Optimizations
1523     SPrintFOpt SPrintF; PrintFOpt PrintF;
1524     FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1525
1526     bool Modified;  // This is only used by doInitialization.
1527   public:
1528     static char ID; // Pass identification
1529     SimplifyLibCalls() : FunctionPass(&ID) {}
1530
1531     void InitOptimizations();
1532     bool runOnFunction(Function &F);
1533
1534     void setDoesNotAccessMemory(Function &F);
1535     void setOnlyReadsMemory(Function &F);
1536     void setDoesNotThrow(Function &F);
1537     void setDoesNotCapture(Function &F, unsigned n);
1538     void setDoesNotAlias(Function &F, unsigned n);
1539     bool doInitialization(Module &M);
1540
1541     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1542       AU.addRequired<TargetData>();
1543     }
1544   };
1545   char SimplifyLibCalls::ID = 0;
1546 } // end anonymous namespace.
1547
1548 static RegisterPass<SimplifyLibCalls>
1549 X("simplify-libcalls", "Simplify well-known library calls");
1550
1551 // Public interface to the Simplify LibCalls pass.
1552 FunctionPass *llvm::createSimplifyLibCallsPass() {
1553   return new SimplifyLibCalls(); 
1554 }
1555
1556 /// Optimizations - Populate the Optimizations map with all the optimizations
1557 /// we know.
1558 void SimplifyLibCalls::InitOptimizations() {
1559   // Miscellaneous LibCall Optimizations
1560   Optimizations["exit"] = &Exit;
1561   
1562   // String and Memory LibCall Optimizations
1563   Optimizations["strcat"] = &StrCat;
1564   Optimizations["strncat"] = &StrNCat;
1565   Optimizations["strchr"] = &StrChr;
1566   Optimizations["strcmp"] = &StrCmp;
1567   Optimizations["strncmp"] = &StrNCmp;
1568   Optimizations["strcpy"] = &StrCpy;
1569   Optimizations["strncpy"] = &StrNCpy;
1570   Optimizations["strlen"] = &StrLen;
1571   Optimizations["strtol"] = &StrTo;
1572   Optimizations["strtod"] = &StrTo;
1573   Optimizations["strtof"] = &StrTo;
1574   Optimizations["strtoul"] = &StrTo;
1575   Optimizations["strtoll"] = &StrTo;
1576   Optimizations["strtold"] = &StrTo;
1577   Optimizations["strtoull"] = &StrTo;
1578   Optimizations["memcmp"] = &MemCmp;
1579   Optimizations["memcpy"] = &MemCpy;
1580   Optimizations["memmove"] = &MemMove;
1581   Optimizations["memset"] = &MemSet;
1582   
1583   // Math Library Optimizations
1584   Optimizations["powf"] = &Pow;
1585   Optimizations["pow"] = &Pow;
1586   Optimizations["powl"] = &Pow;
1587   Optimizations["llvm.pow.f32"] = &Pow;
1588   Optimizations["llvm.pow.f64"] = &Pow;
1589   Optimizations["llvm.pow.f80"] = &Pow;
1590   Optimizations["llvm.pow.f128"] = &Pow;
1591   Optimizations["llvm.pow.ppcf128"] = &Pow;
1592   Optimizations["exp2l"] = &Exp2;
1593   Optimizations["exp2"] = &Exp2;
1594   Optimizations["exp2f"] = &Exp2;
1595   Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1596   Optimizations["llvm.exp2.f128"] = &Exp2;
1597   Optimizations["llvm.exp2.f80"] = &Exp2;
1598   Optimizations["llvm.exp2.f64"] = &Exp2;
1599   Optimizations["llvm.exp2.f32"] = &Exp2;
1600   
1601 #ifdef HAVE_FLOORF
1602   Optimizations["floor"] = &UnaryDoubleFP;
1603 #endif
1604 #ifdef HAVE_CEILF
1605   Optimizations["ceil"] = &UnaryDoubleFP;
1606 #endif
1607 #ifdef HAVE_ROUNDF
1608   Optimizations["round"] = &UnaryDoubleFP;
1609 #endif
1610 #ifdef HAVE_RINTF
1611   Optimizations["rint"] = &UnaryDoubleFP;
1612 #endif
1613 #ifdef HAVE_NEARBYINTF
1614   Optimizations["nearbyint"] = &UnaryDoubleFP;
1615 #endif
1616   
1617   // Integer Optimizations
1618   Optimizations["ffs"] = &FFS;
1619   Optimizations["ffsl"] = &FFS;
1620   Optimizations["ffsll"] = &FFS;
1621   Optimizations["abs"] = &Abs;
1622   Optimizations["labs"] = &Abs;
1623   Optimizations["llabs"] = &Abs;
1624   Optimizations["isdigit"] = &IsDigit;
1625   Optimizations["isascii"] = &IsAscii;
1626   Optimizations["toascii"] = &ToAscii;
1627   
1628   // Formatting and IO Optimizations
1629   Optimizations["sprintf"] = &SPrintF;
1630   Optimizations["printf"] = &PrintF;
1631   Optimizations["fwrite"] = &FWrite;
1632   Optimizations["fputs"] = &FPuts;
1633   Optimizations["fprintf"] = &FPrintF;
1634 }
1635
1636
1637 /// runOnFunction - Top level algorithm.
1638 ///
1639 bool SimplifyLibCalls::runOnFunction(Function &F) {
1640   if (Optimizations.empty())
1641     InitOptimizations();
1642   
1643   const TargetData &TD = getAnalysis<TargetData>();
1644   
1645   IRBuilder<> Builder(F.getContext());
1646
1647   bool Changed = false;
1648   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1649     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1650       // Ignore non-calls.
1651       CallInst *CI = dyn_cast<CallInst>(I++);
1652       if (!CI) continue;
1653       
1654       // Ignore indirect calls and calls to non-external functions.
1655       Function *Callee = CI->getCalledFunction();
1656       if (Callee == 0 || !Callee->isDeclaration() ||
1657           !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1658         continue;
1659       
1660       // Ignore unknown calls.
1661       LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1662       if (!LCO) continue;
1663       
1664       // Set the builder to the instruction after the call.
1665       Builder.SetInsertPoint(BB, I);
1666       
1667       // Try to optimize this call.
1668       Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1669       if (Result == 0) continue;
1670
1671       DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1672             errs() << "  into: " << *Result << "\n");
1673       
1674       // Something changed!
1675       Changed = true;
1676       ++NumSimplified;
1677       
1678       // Inspect the instruction after the call (which was potentially just
1679       // added) next.
1680       I = CI; ++I;
1681       
1682       if (CI != Result && !CI->use_empty()) {
1683         CI->replaceAllUsesWith(Result);
1684         if (!Result->hasName())
1685           Result->takeName(CI);
1686       }
1687       CI->eraseFromParent();
1688     }
1689   }
1690   return Changed;
1691 }
1692
1693 // Utility methods for doInitialization.
1694
1695 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1696   if (!F.doesNotAccessMemory()) {
1697     F.setDoesNotAccessMemory();
1698     ++NumAnnotated;
1699     Modified = true;
1700   }
1701 }
1702 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1703   if (!F.onlyReadsMemory()) {
1704     F.setOnlyReadsMemory();
1705     ++NumAnnotated;
1706     Modified = true;
1707   }
1708 }
1709 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1710   if (!F.doesNotThrow()) {
1711     F.setDoesNotThrow();
1712     ++NumAnnotated;
1713     Modified = true;
1714   }
1715 }
1716 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1717   if (!F.doesNotCapture(n)) {
1718     F.setDoesNotCapture(n);
1719     ++NumAnnotated;
1720     Modified = true;
1721   }
1722 }
1723 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1724   if (!F.doesNotAlias(n)) {
1725     F.setDoesNotAlias(n);
1726     ++NumAnnotated;
1727     Modified = true;
1728   }
1729 }
1730
1731 /// doInitialization - Add attributes to well-known functions.
1732 ///
1733 bool SimplifyLibCalls::doInitialization(Module &M) {
1734   Modified = false;
1735   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1736     Function &F = *I;
1737     if (!F.isDeclaration())
1738       continue;
1739
1740     if (!F.hasName())
1741       continue;
1742
1743     const FunctionType *FTy = F.getFunctionType();
1744
1745     StringRef Name = F.getName();
1746     switch (Name[0]) {
1747       case 's':
1748         if (Name == "strlen") {
1749           if (FTy->getNumParams() != 1 ||
1750               !isa<PointerType>(FTy->getParamType(0)))
1751             continue;
1752           setOnlyReadsMemory(F);
1753           setDoesNotThrow(F);
1754           setDoesNotCapture(F, 1);
1755         } else if (Name == "strcpy" ||
1756                    Name == "stpcpy" ||
1757                    Name == "strcat" ||
1758                    Name == "strtol" ||
1759                    Name == "strtod" ||
1760                    Name == "strtof" ||
1761                    Name == "strtoul" ||
1762                    Name == "strtoll" ||
1763                    Name == "strtold" ||
1764                    Name == "strncat" ||
1765                    Name == "strncpy" ||
1766                    Name == "strtoull") {
1767           if (FTy->getNumParams() < 2 ||
1768               !isa<PointerType>(FTy->getParamType(1)))
1769             continue;
1770           setDoesNotThrow(F);
1771           setDoesNotCapture(F, 2);
1772         } else if (Name == "strxfrm") {
1773           if (FTy->getNumParams() != 3 ||
1774               !isa<PointerType>(FTy->getParamType(0)) ||
1775               !isa<PointerType>(FTy->getParamType(1)))
1776             continue;
1777           setDoesNotThrow(F);
1778           setDoesNotCapture(F, 1);
1779           setDoesNotCapture(F, 2);
1780         } else if (Name == "strcmp" ||
1781                    Name == "strspn" ||
1782                    Name == "strncmp" ||
1783                    Name ==" strcspn" ||
1784                    Name == "strcoll" ||
1785                    Name == "strcasecmp" ||
1786                    Name == "strncasecmp") {
1787           if (FTy->getNumParams() < 2 ||
1788               !isa<PointerType>(FTy->getParamType(0)) ||
1789               !isa<PointerType>(FTy->getParamType(1)))
1790             continue;
1791           setOnlyReadsMemory(F);
1792           setDoesNotThrow(F);
1793           setDoesNotCapture(F, 1);
1794           setDoesNotCapture(F, 2);
1795         } else if (Name == "strstr" ||
1796                    Name == "strpbrk") {
1797           if (FTy->getNumParams() != 2 ||
1798               !isa<PointerType>(FTy->getParamType(1)))
1799             continue;
1800           setOnlyReadsMemory(F);
1801           setDoesNotThrow(F);
1802           setDoesNotCapture(F, 2);
1803         } else if (Name == "strtok" ||
1804                    Name == "strtok_r") {
1805           if (FTy->getNumParams() < 2 ||
1806               !isa<PointerType>(FTy->getParamType(1)))
1807             continue;
1808           setDoesNotThrow(F);
1809           setDoesNotCapture(F, 2);
1810         } else if (Name == "scanf" ||
1811                    Name == "setbuf" ||
1812                    Name == "setvbuf") {
1813           if (FTy->getNumParams() < 1 ||
1814               !isa<PointerType>(FTy->getParamType(0)))
1815             continue;
1816           setDoesNotThrow(F);
1817           setDoesNotCapture(F, 1);
1818         } else if (Name == "strdup" ||
1819                    Name == "strndup") {
1820           if (FTy->getNumParams() < 1 ||
1821               !isa<PointerType>(FTy->getReturnType()) ||
1822               !isa<PointerType>(FTy->getParamType(0)))
1823             continue;
1824           setDoesNotThrow(F);
1825           setDoesNotAlias(F, 0);
1826           setDoesNotCapture(F, 1);
1827         } else if (Name == "stat" ||
1828                    Name == "sscanf" ||
1829                    Name == "sprintf" ||
1830                    Name == "statvfs") {
1831           if (FTy->getNumParams() < 2 ||
1832               !isa<PointerType>(FTy->getParamType(0)) ||
1833               !isa<PointerType>(FTy->getParamType(1)))
1834             continue;
1835           setDoesNotThrow(F);
1836           setDoesNotCapture(F, 1);
1837           setDoesNotCapture(F, 2);
1838         } else if (Name == "snprintf") {
1839           if (FTy->getNumParams() != 3 ||
1840               !isa<PointerType>(FTy->getParamType(0)) ||
1841               !isa<PointerType>(FTy->getParamType(2)))
1842             continue;
1843           setDoesNotThrow(F);
1844           setDoesNotCapture(F, 1);
1845           setDoesNotCapture(F, 3);
1846         } else if (Name == "setitimer") {
1847           if (FTy->getNumParams() != 3 ||
1848               !isa<PointerType>(FTy->getParamType(1)) ||
1849               !isa<PointerType>(FTy->getParamType(2)))
1850             continue;
1851           setDoesNotThrow(F);
1852           setDoesNotCapture(F, 2);
1853           setDoesNotCapture(F, 3);
1854         } else if (Name == "system") {
1855           if (FTy->getNumParams() != 1 ||
1856               !isa<PointerType>(FTy->getParamType(0)))
1857             continue;
1858           // May throw; "system" is a valid pthread cancellation point.
1859           setDoesNotCapture(F, 1);
1860         }
1861         break;
1862       case 'm':
1863         if (Name == "memcmp") {
1864           if (FTy->getNumParams() != 3 ||
1865               !isa<PointerType>(FTy->getParamType(0)) ||
1866               !isa<PointerType>(FTy->getParamType(1)))
1867             continue;
1868           setOnlyReadsMemory(F);
1869           setDoesNotThrow(F);
1870           setDoesNotCapture(F, 1);
1871           setDoesNotCapture(F, 2);
1872         } else if (Name == "memchr" ||
1873                    Name == "memrchr") {
1874           if (FTy->getNumParams() != 3)
1875             continue;
1876           setOnlyReadsMemory(F);
1877           setDoesNotThrow(F);
1878         } else if (Name == "modf" ||
1879                    Name == "modff" ||
1880                    Name == "modfl" ||
1881                    Name == "memcpy" ||
1882                    Name == "memccpy" ||
1883                    Name == "memmove") {
1884           if (FTy->getNumParams() < 2 ||
1885               !isa<PointerType>(FTy->getParamType(1)))
1886             continue;
1887           setDoesNotThrow(F);
1888           setDoesNotCapture(F, 2);
1889         } else if (Name == "memalign") {
1890           if (!isa<PointerType>(FTy->getReturnType()))
1891             continue;
1892           setDoesNotAlias(F, 0);
1893         } else if (Name == "mkdir" ||
1894                    Name == "mktime") {
1895           if (FTy->getNumParams() == 0 ||
1896               !isa<PointerType>(FTy->getParamType(0)))
1897             continue;
1898           setDoesNotThrow(F);
1899           setDoesNotCapture(F, 1);
1900         }
1901         break;
1902       case 'r':
1903         if (Name == "realloc") {
1904           if (FTy->getNumParams() != 2 ||
1905               !isa<PointerType>(FTy->getParamType(0)) ||
1906               !isa<PointerType>(FTy->getReturnType()))
1907             continue;
1908           setDoesNotThrow(F);
1909           setDoesNotAlias(F, 0);
1910           setDoesNotCapture(F, 1);
1911         } else if (Name == "read") {
1912           if (FTy->getNumParams() != 3 ||
1913               !isa<PointerType>(FTy->getParamType(1)))
1914             continue;
1915           // May throw; "read" is a valid pthread cancellation point.
1916           setDoesNotCapture(F, 2);
1917         } else if (Name == "rmdir" ||
1918                    Name == "rewind" ||
1919                    Name == "remove" ||
1920                    Name == "realpath") {
1921           if (FTy->getNumParams() < 1 ||
1922               !isa<PointerType>(FTy->getParamType(0)))
1923             continue;
1924           setDoesNotThrow(F);
1925           setDoesNotCapture(F, 1);
1926         } else if (Name == "rename" ||
1927                    Name == "readlink") {
1928           if (FTy->getNumParams() < 2 ||
1929               !isa<PointerType>(FTy->getParamType(0)) ||
1930               !isa<PointerType>(FTy->getParamType(1)))
1931             continue;
1932           setDoesNotThrow(F);
1933           setDoesNotCapture(F, 1);
1934           setDoesNotCapture(F, 2);
1935         }
1936         break;
1937       case 'w':
1938         if (Name == "write") {
1939           if (FTy->getNumParams() != 3 ||
1940               !isa<PointerType>(FTy->getParamType(1)))
1941             continue;
1942           // May throw; "write" is a valid pthread cancellation point.
1943           setDoesNotCapture(F, 2);
1944         }
1945         break;
1946       case 'b':
1947         if (Name == "bcopy") {
1948           if (FTy->getNumParams() != 3 ||
1949               !isa<PointerType>(FTy->getParamType(0)) ||
1950               !isa<PointerType>(FTy->getParamType(1)))
1951             continue;
1952           setDoesNotThrow(F);
1953           setDoesNotCapture(F, 1);
1954           setDoesNotCapture(F, 2);
1955         } else if (Name == "bcmp") {
1956           if (FTy->getNumParams() != 3 ||
1957               !isa<PointerType>(FTy->getParamType(0)) ||
1958               !isa<PointerType>(FTy->getParamType(1)))
1959             continue;
1960           setDoesNotThrow(F);
1961           setOnlyReadsMemory(F);
1962           setDoesNotCapture(F, 1);
1963           setDoesNotCapture(F, 2);
1964         } else if (Name == "bzero") {
1965           if (FTy->getNumParams() != 2 ||
1966               !isa<PointerType>(FTy->getParamType(0)))
1967             continue;
1968           setDoesNotThrow(F);
1969           setDoesNotCapture(F, 1);
1970         }
1971         break;
1972       case 'c':
1973         if (Name == "calloc") {
1974           if (FTy->getNumParams() != 2 ||
1975               !isa<PointerType>(FTy->getReturnType()))
1976             continue;
1977           setDoesNotThrow(F);
1978           setDoesNotAlias(F, 0);
1979         } else if (Name == "chmod" ||
1980                    Name == "chown" ||
1981                    Name == "ctermid" ||
1982                    Name == "clearerr" ||
1983                    Name == "closedir") {
1984           if (FTy->getNumParams() == 0 ||
1985               !isa<PointerType>(FTy->getParamType(0)))
1986             continue;
1987           setDoesNotThrow(F);
1988           setDoesNotCapture(F, 1);
1989         }
1990         break;
1991       case 'a':
1992         if (Name == "atoi" ||
1993             Name == "atol" ||
1994             Name == "atof" ||
1995             Name == "atoll") {
1996           if (FTy->getNumParams() != 1 ||
1997               !isa<PointerType>(FTy->getParamType(0)))
1998             continue;
1999           setDoesNotThrow(F);
2000           setOnlyReadsMemory(F);
2001           setDoesNotCapture(F, 1);
2002         } else if (Name == "access") {
2003           if (FTy->getNumParams() != 2 ||
2004               !isa<PointerType>(FTy->getParamType(0)))
2005             continue;
2006           setDoesNotThrow(F);
2007           setDoesNotCapture(F, 1);
2008         }
2009         break;
2010       case 'f':
2011         if (Name == "fopen") {
2012           if (FTy->getNumParams() != 2 ||
2013               !isa<PointerType>(FTy->getReturnType()) ||
2014               !isa<PointerType>(FTy->getParamType(0)) ||
2015               !isa<PointerType>(FTy->getParamType(1)))
2016             continue;
2017           setDoesNotThrow(F);
2018           setDoesNotAlias(F, 0);
2019           setDoesNotCapture(F, 1);
2020           setDoesNotCapture(F, 2);
2021         } else if (Name == "fdopen") {
2022           if (FTy->getNumParams() != 2 ||
2023               !isa<PointerType>(FTy->getReturnType()) ||
2024               !isa<PointerType>(FTy->getParamType(1)))
2025             continue;
2026           setDoesNotThrow(F);
2027           setDoesNotAlias(F, 0);
2028           setDoesNotCapture(F, 2);
2029         } else if (Name == "feof" ||
2030                    Name == "free" ||
2031                    Name == "fseek" ||
2032                    Name == "ftell" ||
2033                    Name == "fgetc" ||
2034                    Name == "fseeko" ||
2035                    Name == "ftello" ||
2036                    Name == "fileno" ||
2037                    Name == "fflush" ||
2038                    Name == "fclose" ||
2039                    Name == "fsetpos" ||
2040                    Name == "flockfile" ||
2041                    Name == "funlockfile" ||
2042                    Name == "ftrylockfile") {
2043           if (FTy->getNumParams() == 0 ||
2044               !isa<PointerType>(FTy->getParamType(0)))
2045             continue;
2046           setDoesNotThrow(F);
2047           setDoesNotCapture(F, 1);
2048         } else if (Name == "ferror") {
2049           if (FTy->getNumParams() != 1 ||
2050               !isa<PointerType>(FTy->getParamType(0)))
2051             continue;
2052           setDoesNotThrow(F);
2053           setDoesNotCapture(F, 1);
2054           setOnlyReadsMemory(F);
2055         } else if (Name == "fputc" ||
2056                    Name == "fstat" ||
2057                    Name == "frexp" ||
2058                    Name == "frexpf" ||
2059                    Name == "frexpl" ||
2060                    Name == "fstatvfs") {
2061           if (FTy->getNumParams() != 2 ||
2062               !isa<PointerType>(FTy->getParamType(1)))
2063             continue;
2064           setDoesNotThrow(F);
2065           setDoesNotCapture(F, 2);
2066         } else if (Name == "fgets") {
2067           if (FTy->getNumParams() != 3 ||
2068               !isa<PointerType>(FTy->getParamType(0)) ||
2069               !isa<PointerType>(FTy->getParamType(2)))
2070             continue;
2071           setDoesNotThrow(F);
2072           setDoesNotCapture(F, 3);
2073         } else if (Name == "fread" ||
2074                    Name == "fwrite") {
2075           if (FTy->getNumParams() != 4 ||
2076               !isa<PointerType>(FTy->getParamType(0)) ||
2077               !isa<PointerType>(FTy->getParamType(3)))
2078             continue;
2079           setDoesNotThrow(F);
2080           setDoesNotCapture(F, 1);
2081           setDoesNotCapture(F, 4);
2082         } else if (Name == "fputs" ||
2083                    Name == "fscanf" ||
2084                    Name == "fprintf" ||
2085                    Name == "fgetpos") {
2086           if (FTy->getNumParams() < 2 ||
2087               !isa<PointerType>(FTy->getParamType(0)) ||
2088               !isa<PointerType>(FTy->getParamType(1)))
2089             continue;
2090           setDoesNotThrow(F);
2091           setDoesNotCapture(F, 1);
2092           setDoesNotCapture(F, 2);
2093         }
2094         break;
2095       case 'g':
2096         if (Name == "getc" ||
2097             Name == "getlogin_r" ||
2098             Name == "getc_unlocked") {
2099           if (FTy->getNumParams() == 0 ||
2100               !isa<PointerType>(FTy->getParamType(0)))
2101             continue;
2102           setDoesNotThrow(F);
2103           setDoesNotCapture(F, 1);
2104         } else if (Name == "getenv") {
2105           if (FTy->getNumParams() != 1 ||
2106               !isa<PointerType>(FTy->getParamType(0)))
2107             continue;
2108           setDoesNotThrow(F);
2109           setOnlyReadsMemory(F);
2110           setDoesNotCapture(F, 1);
2111         } else if (Name == "gets" ||
2112                    Name == "getchar") {
2113           setDoesNotThrow(F);
2114         } else if (Name == "getitimer") {
2115           if (FTy->getNumParams() != 2 ||
2116               !isa<PointerType>(FTy->getParamType(1)))
2117             continue;
2118           setDoesNotThrow(F);
2119           setDoesNotCapture(F, 2);
2120         } else if (Name == "getpwnam") {
2121           if (FTy->getNumParams() != 1 ||
2122               !isa<PointerType>(FTy->getParamType(0)))
2123             continue;
2124           setDoesNotThrow(F);
2125           setDoesNotCapture(F, 1);
2126         }
2127         break;
2128       case 'u':
2129         if (Name == "ungetc") {
2130           if (FTy->getNumParams() != 2 ||
2131               !isa<PointerType>(FTy->getParamType(1)))
2132             continue;
2133           setDoesNotThrow(F);
2134           setDoesNotCapture(F, 2);
2135         } else if (Name == "uname" ||
2136                    Name == "unlink" ||
2137                    Name == "unsetenv") {
2138           if (FTy->getNumParams() != 1 ||
2139               !isa<PointerType>(FTy->getParamType(0)))
2140             continue;
2141           setDoesNotThrow(F);
2142           setDoesNotCapture(F, 1);
2143         } else if (Name == "utime" ||
2144                    Name == "utimes") {
2145           if (FTy->getNumParams() != 2 ||
2146               !isa<PointerType>(FTy->getParamType(0)) ||
2147               !isa<PointerType>(FTy->getParamType(1)))
2148             continue;
2149           setDoesNotThrow(F);
2150           setDoesNotCapture(F, 1);
2151           setDoesNotCapture(F, 2);
2152         }
2153         break;
2154       case 'p':
2155         if (Name == "putc") {
2156           if (FTy->getNumParams() != 2 ||
2157               !isa<PointerType>(FTy->getParamType(1)))
2158             continue;
2159           setDoesNotThrow(F);
2160           setDoesNotCapture(F, 2);
2161         } else if (Name == "puts" ||
2162                    Name == "printf" ||
2163                    Name == "perror") {
2164           if (FTy->getNumParams() != 1 ||
2165               !isa<PointerType>(FTy->getParamType(0)))
2166             continue;
2167           setDoesNotThrow(F);
2168           setDoesNotCapture(F, 1);
2169         } else if (Name == "pread" ||
2170                    Name == "pwrite") {
2171           if (FTy->getNumParams() != 4 ||
2172               !isa<PointerType>(FTy->getParamType(1)))
2173             continue;
2174           // May throw; these are valid pthread cancellation points.
2175           setDoesNotCapture(F, 2);
2176         } else if (Name == "putchar") {
2177           setDoesNotThrow(F);
2178         } else if (Name == "popen") {
2179           if (FTy->getNumParams() != 2 ||
2180               !isa<PointerType>(FTy->getReturnType()) ||
2181               !isa<PointerType>(FTy->getParamType(0)) ||
2182               !isa<PointerType>(FTy->getParamType(1)))
2183             continue;
2184           setDoesNotThrow(F);
2185           setDoesNotAlias(F, 0);
2186           setDoesNotCapture(F, 1);
2187           setDoesNotCapture(F, 2);
2188         } else if (Name == "pclose") {
2189           if (FTy->getNumParams() != 1 ||
2190               !isa<PointerType>(FTy->getParamType(0)))
2191             continue;
2192           setDoesNotThrow(F);
2193           setDoesNotCapture(F, 1);
2194         }
2195         break;
2196       case 'v':
2197         if (Name == "vscanf") {
2198           if (FTy->getNumParams() != 2 ||
2199               !isa<PointerType>(FTy->getParamType(1)))
2200             continue;
2201           setDoesNotThrow(F);
2202           setDoesNotCapture(F, 1);
2203         } else if (Name == "vsscanf" ||
2204                    Name == "vfscanf") {
2205           if (FTy->getNumParams() != 3 ||
2206               !isa<PointerType>(FTy->getParamType(1)) ||
2207               !isa<PointerType>(FTy->getParamType(2)))
2208             continue;
2209           setDoesNotThrow(F);
2210           setDoesNotCapture(F, 1);
2211           setDoesNotCapture(F, 2);
2212         } else if (Name == "valloc") {
2213           if (!isa<PointerType>(FTy->getReturnType()))
2214             continue;
2215           setDoesNotThrow(F);
2216           setDoesNotAlias(F, 0);
2217         } else if (Name == "vprintf") {
2218           if (FTy->getNumParams() != 2 ||
2219               !isa<PointerType>(FTy->getParamType(0)))
2220             continue;
2221           setDoesNotThrow(F);
2222           setDoesNotCapture(F, 1);
2223         } else if (Name == "vfprintf" ||
2224                    Name == "vsprintf") {
2225           if (FTy->getNumParams() != 3 ||
2226               !isa<PointerType>(FTy->getParamType(0)) ||
2227               !isa<PointerType>(FTy->getParamType(1)))
2228             continue;
2229           setDoesNotThrow(F);
2230           setDoesNotCapture(F, 1);
2231           setDoesNotCapture(F, 2);
2232         } else if (Name == "vsnprintf") {
2233           if (FTy->getNumParams() != 4 ||
2234               !isa<PointerType>(FTy->getParamType(0)) ||
2235               !isa<PointerType>(FTy->getParamType(2)))
2236             continue;
2237           setDoesNotThrow(F);
2238           setDoesNotCapture(F, 1);
2239           setDoesNotCapture(F, 3);
2240         }
2241         break;
2242       case 'o':
2243         if (Name == "open") {
2244           if (FTy->getNumParams() < 2 ||
2245               !isa<PointerType>(FTy->getParamType(0)))
2246             continue;
2247           // May throw; "open" is a valid pthread cancellation point.
2248           setDoesNotCapture(F, 1);
2249         } else if (Name == "opendir") {
2250           if (FTy->getNumParams() != 1 ||
2251               !isa<PointerType>(FTy->getReturnType()) ||
2252               !isa<PointerType>(FTy->getParamType(0)))
2253             continue;
2254           setDoesNotThrow(F);
2255           setDoesNotAlias(F, 0);
2256           setDoesNotCapture(F, 1);
2257         }
2258         break;
2259       case 't':
2260         if (Name == "tmpfile") {
2261           if (!isa<PointerType>(FTy->getReturnType()))
2262             continue;
2263           setDoesNotThrow(F);
2264           setDoesNotAlias(F, 0);
2265         } else if (Name == "times") {
2266           if (FTy->getNumParams() != 1 ||
2267               !isa<PointerType>(FTy->getParamType(0)))
2268             continue;
2269           setDoesNotThrow(F);
2270           setDoesNotCapture(F, 1);
2271         }
2272         break;
2273       case 'h':
2274         if (Name == "htonl" ||
2275             Name == "htons") {
2276           setDoesNotThrow(F);
2277           setDoesNotAccessMemory(F);
2278         }
2279         break;
2280       case 'n':
2281         if (Name == "ntohl" ||
2282             Name == "ntohs") {
2283           setDoesNotThrow(F);
2284           setDoesNotAccessMemory(F);
2285         }
2286         break;
2287       case 'l':
2288         if (Name == "lstat") {
2289           if (FTy->getNumParams() != 2 ||
2290               !isa<PointerType>(FTy->getParamType(0)) ||
2291               !isa<PointerType>(FTy->getParamType(1)))
2292             continue;
2293           setDoesNotThrow(F);
2294           setDoesNotCapture(F, 1);
2295           setDoesNotCapture(F, 2);
2296         } else if (Name == "lchown") {
2297           if (FTy->getNumParams() != 3 ||
2298               !isa<PointerType>(FTy->getParamType(0)))
2299             continue;
2300           setDoesNotThrow(F);
2301           setDoesNotCapture(F, 1);
2302         }
2303         break;
2304       case 'q':
2305         if (Name == "qsort") {
2306           if (FTy->getNumParams() != 4 ||
2307               !isa<PointerType>(FTy->getParamType(3)))
2308             continue;
2309           // May throw; places call through function pointer.
2310           setDoesNotCapture(F, 4);
2311         }
2312         break;
2313       case '_':
2314         if (Name == "__strdup" ||
2315             Name == "__strndup") {
2316           if (FTy->getNumParams() < 1 ||
2317               !isa<PointerType>(FTy->getReturnType()) ||
2318               !isa<PointerType>(FTy->getParamType(0)))
2319             continue;
2320           setDoesNotThrow(F);
2321           setDoesNotAlias(F, 0);
2322           setDoesNotCapture(F, 1);
2323         } else if (Name == "__strtok_r") {
2324           if (FTy->getNumParams() != 3 ||
2325               !isa<PointerType>(FTy->getParamType(1)))
2326             continue;
2327           setDoesNotThrow(F);
2328           setDoesNotCapture(F, 2);
2329         } else if (Name == "_IO_getc") {
2330           if (FTy->getNumParams() != 1 ||
2331               !isa<PointerType>(FTy->getParamType(0)))
2332             continue;
2333           setDoesNotThrow(F);
2334           setDoesNotCapture(F, 1);
2335         } else if (Name == "_IO_putc") {
2336           if (FTy->getNumParams() != 2 ||
2337               !isa<PointerType>(FTy->getParamType(1)))
2338             continue;
2339           setDoesNotThrow(F);
2340           setDoesNotCapture(F, 2);
2341         }
2342         break;
2343       case 1:
2344         if (Name == "\1__isoc99_scanf") {
2345           if (FTy->getNumParams() < 1 ||
2346               !isa<PointerType>(FTy->getParamType(0)))
2347             continue;
2348           setDoesNotThrow(F);
2349           setDoesNotCapture(F, 1);
2350         } else if (Name == "\1stat64" ||
2351                    Name == "\1lstat64" ||
2352                    Name == "\1statvfs64" ||
2353                    Name == "\1__isoc99_sscanf") {
2354           if (FTy->getNumParams() < 1 ||
2355               !isa<PointerType>(FTy->getParamType(0)) ||
2356               !isa<PointerType>(FTy->getParamType(1)))
2357             continue;
2358           setDoesNotThrow(F);
2359           setDoesNotCapture(F, 1);
2360           setDoesNotCapture(F, 2);
2361         } else if (Name == "\1fopen64") {
2362           if (FTy->getNumParams() != 2 ||
2363               !isa<PointerType>(FTy->getReturnType()) ||
2364               !isa<PointerType>(FTy->getParamType(0)) ||
2365               !isa<PointerType>(FTy->getParamType(1)))
2366             continue;
2367           setDoesNotThrow(F);
2368           setDoesNotAlias(F, 0);
2369           setDoesNotCapture(F, 1);
2370           setDoesNotCapture(F, 2);
2371         } else if (Name == "\1fseeko64" ||
2372                    Name == "\1ftello64") {
2373           if (FTy->getNumParams() == 0 ||
2374               !isa<PointerType>(FTy->getParamType(0)))
2375             continue;
2376           setDoesNotThrow(F);
2377           setDoesNotCapture(F, 1);
2378         } else if (Name == "\1tmpfile64") {
2379           if (!isa<PointerType>(FTy->getReturnType()))
2380             continue;
2381           setDoesNotThrow(F);
2382           setDoesNotAlias(F, 0);
2383         } else if (Name == "\1fstat64" ||
2384                    Name == "\1fstatvfs64") {
2385           if (FTy->getNumParams() != 2 ||
2386               !isa<PointerType>(FTy->getParamType(1)))
2387             continue;
2388           setDoesNotThrow(F);
2389           setDoesNotCapture(F, 2);
2390         } else if (Name == "\1open64") {
2391           if (FTy->getNumParams() < 2 ||
2392               !isa<PointerType>(FTy->getParamType(0)))
2393             continue;
2394           // May throw; "open" is a valid pthread cancellation point.
2395           setDoesNotCapture(F, 1);
2396         }
2397         break;
2398     }
2399   }
2400   return Modified;
2401 }
2402
2403 // TODO:
2404 //   Additional cases that we need to add to this file:
2405 //
2406 // cbrt:
2407 //   * cbrt(expN(X))  -> expN(x/3)
2408 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2409 //   * cbrt(sqrt(x))  -> pow(x,1/9)
2410 //
2411 // cos, cosf, cosl:
2412 //   * cos(-x)  -> cos(x)
2413 //
2414 // exp, expf, expl:
2415 //   * exp(log(x))  -> x
2416 //
2417 // log, logf, logl:
2418 //   * log(exp(x))   -> x
2419 //   * log(x**y)     -> y*log(x)
2420 //   * log(exp(y))   -> y*log(e)
2421 //   * log(exp2(y))  -> y*log(2)
2422 //   * log(exp10(y)) -> y*log(10)
2423 //   * log(sqrt(x))  -> 0.5*log(x)
2424 //   * log(pow(x,y)) -> y*log(x)
2425 //
2426 // lround, lroundf, lroundl:
2427 //   * lround(cnst) -> cnst'
2428 //
2429 // memcmp:
2430 //   * memcmp(x,y,l)   -> cnst
2431 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2432 //
2433 // pow, powf, powl:
2434 //   * pow(exp(x),y)  -> exp(x*y)
2435 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2436 //   * pow(pow(x,y),z)-> pow(x,y*z)
2437 //
2438 // puts:
2439 //   * puts("") -> putchar("\n")
2440 //
2441 // round, roundf, roundl:
2442 //   * round(cnst) -> cnst'
2443 //
2444 // signbit:
2445 //   * signbit(cnst) -> cnst'
2446 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2447 //
2448 // sqrt, sqrtf, sqrtl:
2449 //   * sqrt(expN(x))  -> expN(x*0.5)
2450 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2451 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2452 //
2453 // stpcpy:
2454 //   * stpcpy(str, "literal") ->
2455 //           llvm.memcpy(str,"literal",strlen("literal")+1,1)
2456 // strrchr:
2457 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
2458 //      (if c is a constant integer and s is a constant string)
2459 //   * strrchr(s1,0) -> strchr(s1,0)
2460 //
2461 // strpbrk:
2462 //   * strpbrk(s,a) -> offset_in_for(s,a)
2463 //      (if s and a are both constant strings)
2464 //   * strpbrk(s,"") -> 0
2465 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2466 //
2467 // strspn, strcspn:
2468 //   * strspn(s,a)   -> const_int (if both args are constant)
2469 //   * strspn("",a)  -> 0
2470 //   * strspn(s,"")  -> 0
2471 //   * strcspn(s,a)  -> const_int (if both args are constant)
2472 //   * strcspn("",a) -> 0
2473 //   * strcspn(s,"") -> strlen(a)
2474 //
2475 // strstr:
2476 //   * strstr(x,x)  -> x
2477 //   * strstr(s1,s2) -> offset_of_s2_in(s1)
2478 //       (if s1 and s2 are constant strings)
2479 //
2480 // tan, tanf, tanl:
2481 //   * tan(atan(x)) -> x
2482 //
2483 // trunc, truncf, truncl:
2484 //   * trunc(cnst) -> cnst'
2485 //
2486 //