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