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