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