32fcdbfe9054d24b1f216641e4af6d0d8e7e2c4c
[oota-llvm.git] / lib / Transforms / Scalar / SimplifyLibCalls.cpp
1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions).   Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/BuildLibCalls.h"
21 #include "llvm/IRBuilder.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/DataLayout.h"
35 #include "llvm/Target/TargetLibraryInfo.h"
36 #include "llvm/Config/config.h"            // FIXME: Shouldn't depend on host!
37 using namespace llvm;
38
39 STATISTIC(NumSimplified, "Number of library calls simplified");
40 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
41
42 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43                                    cl::init(false),
44                                    cl::desc("Enable unsafe double to float "
45                                             "shrinking for math lib calls"));
46 //===----------------------------------------------------------------------===//
47 // Optimizer Base Class
48 //===----------------------------------------------------------------------===//
49
50 /// This class is the abstract base class for the set of optimizations that
51 /// corresponds to one library call.
52 namespace {
53 class LibCallOptimization {
54 protected:
55   Function *Caller;
56   const DataLayout *TD;
57   const TargetLibraryInfo *TLI;
58   LLVMContext* Context;
59 public:
60   LibCallOptimization() { }
61   virtual ~LibCallOptimization() {}
62
63   /// CallOptimizer - This pure virtual method is implemented by base classes to
64   /// do various optimizations.  If this returns null then no transformation was
65   /// performed.  If it returns CI, then it transformed the call and CI is to be
66   /// deleted.  If it returns something else, replace CI with the new value and
67   /// delete CI.
68   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
69     =0;
70
71   Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
72                       const TargetLibraryInfo *TLI, IRBuilder<> &B) {
73     Caller = CI->getParent()->getParent();
74     this->TD = TD;
75     this->TLI = TLI;
76     if (CI->getCalledFunction())
77       Context = &CI->getCalledFunction()->getContext();
78
79     // We never change the calling convention.
80     if (CI->getCallingConv() != llvm::CallingConv::C)
81       return NULL;
82
83     return CallOptimizer(CI->getCalledFunction(), CI, B);
84   }
85 };
86 } // End anonymous namespace.
87
88
89 //===----------------------------------------------------------------------===//
90 // Helper Functions
91 //===----------------------------------------------------------------------===//
92
93 static bool CallHasFloatingPointArgument(const CallInst *CI) {
94   for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
95        it != e; ++it) {
96     if ((*it)->getType()->isFloatingPointTy())
97       return true;
98   }
99   return false;
100 }
101
102 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
103 /// comparisons with With.
104 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
105   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
106        UI != E; ++UI) {
107     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
108       if (IC->isEquality() && IC->getOperand(1) == With)
109         continue;
110     // Unknown instruction.
111     return false;
112   }
113   return true;
114 }
115
116 //===----------------------------------------------------------------------===//
117 // String and Memory LibCall Optimizations
118 //===----------------------------------------------------------------------===//
119
120 namespace {
121 //===---------------------------------------===//
122 // 'strspn' Optimizations
123
124 struct StrSpnOpt : public LibCallOptimization {
125   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
126     FunctionType *FT = Callee->getFunctionType();
127     if (FT->getNumParams() != 2 ||
128         FT->getParamType(0) != B.getInt8PtrTy() ||
129         FT->getParamType(1) != FT->getParamType(0) ||
130         !FT->getReturnType()->isIntegerTy())
131       return 0;
132
133     StringRef S1, S2;
134     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
135     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
136
137     // strspn(s, "") -> 0
138     // strspn("", s) -> 0
139     if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
140       return Constant::getNullValue(CI->getType());
141
142     // Constant folding.
143     if (HasS1 && HasS2) {
144       size_t Pos = S1.find_first_not_of(S2);
145       if (Pos == StringRef::npos) Pos = S1.size();
146       return ConstantInt::get(CI->getType(), Pos);
147     }
148
149     return 0;
150   }
151 };
152
153 //===---------------------------------------===//
154 // 'strcspn' Optimizations
155
156 struct StrCSpnOpt : public LibCallOptimization {
157   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
158     FunctionType *FT = Callee->getFunctionType();
159     if (FT->getNumParams() != 2 ||
160         FT->getParamType(0) != B.getInt8PtrTy() ||
161         FT->getParamType(1) != FT->getParamType(0) ||
162         !FT->getReturnType()->isIntegerTy())
163       return 0;
164
165     StringRef S1, S2;
166     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
167     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
168
169     // strcspn("", s) -> 0
170     if (HasS1 && S1.empty())
171       return Constant::getNullValue(CI->getType());
172
173     // Constant folding.
174     if (HasS1 && HasS2) {
175       size_t Pos = S1.find_first_of(S2);
176       if (Pos == StringRef::npos) Pos = S1.size();
177       return ConstantInt::get(CI->getType(), Pos);
178     }
179
180     // strcspn(s, "") -> strlen(s)
181     if (TD && HasS2 && S2.empty())
182       return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
183
184     return 0;
185   }
186 };
187
188 //===---------------------------------------===//
189 // 'strstr' Optimizations
190
191 struct StrStrOpt : public LibCallOptimization {
192   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
193     FunctionType *FT = Callee->getFunctionType();
194     if (FT->getNumParams() != 2 ||
195         !FT->getParamType(0)->isPointerTy() ||
196         !FT->getParamType(1)->isPointerTy() ||
197         !FT->getReturnType()->isPointerTy())
198       return 0;
199
200     // fold strstr(x, x) -> x.
201     if (CI->getArgOperand(0) == CI->getArgOperand(1))
202       return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
203
204     // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
205     if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
206       Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
207       if (!StrLen)
208         return 0;
209       Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
210                                    StrLen, B, TD, TLI);
211       if (!StrNCmp)
212         return 0;
213       for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
214            UI != UE; ) {
215         ICmpInst *Old = cast<ICmpInst>(*UI++);
216         Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
217                                   ConstantInt::getNullValue(StrNCmp->getType()),
218                                   "cmp");
219         Old->replaceAllUsesWith(Cmp);
220         Old->eraseFromParent();
221       }
222       return CI;
223     }
224
225     // See if either input string is a constant string.
226     StringRef SearchStr, ToFindStr;
227     bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
228     bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
229
230     // fold strstr(x, "") -> x.
231     if (HasStr2 && ToFindStr.empty())
232       return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
233
234     // If both strings are known, constant fold it.
235     if (HasStr1 && HasStr2) {
236       std::string::size_type Offset = SearchStr.find(ToFindStr);
237
238       if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
239         return Constant::getNullValue(CI->getType());
240
241       // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
242       Value *Result = CastToCStr(CI->getArgOperand(0), B);
243       Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
244       return B.CreateBitCast(Result, CI->getType());
245     }
246
247     // fold strstr(x, "y") -> strchr(x, 'y').
248     if (HasStr2 && ToFindStr.size() == 1) {
249       Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
250       return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
251     }
252     return 0;
253   }
254 };
255
256
257 //===---------------------------------------===//
258 // 'memcmp' Optimizations
259
260 struct MemCmpOpt : public LibCallOptimization {
261   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
262     FunctionType *FT = Callee->getFunctionType();
263     if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
264         !FT->getParamType(1)->isPointerTy() ||
265         !FT->getReturnType()->isIntegerTy(32))
266       return 0;
267
268     Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
269
270     if (LHS == RHS)  // memcmp(s,s,x) -> 0
271       return Constant::getNullValue(CI->getType());
272
273     // Make sure we have a constant length.
274     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
275     if (!LenC) return 0;
276     uint64_t Len = LenC->getZExtValue();
277
278     if (Len == 0) // memcmp(s1,s2,0) -> 0
279       return Constant::getNullValue(CI->getType());
280
281     // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
282     if (Len == 1) {
283       Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
284                                  CI->getType(), "lhsv");
285       Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
286                                  CI->getType(), "rhsv");
287       return B.CreateSub(LHSV, RHSV, "chardiff");
288     }
289
290     // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
291     StringRef LHSStr, RHSStr;
292     if (getConstantStringInfo(LHS, LHSStr) &&
293         getConstantStringInfo(RHS, RHSStr)) {
294       // Make sure we're not reading out-of-bounds memory.
295       if (Len > LHSStr.size() || Len > RHSStr.size())
296         return 0;
297       uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
298       return ConstantInt::get(CI->getType(), Ret);
299     }
300
301     return 0;
302   }
303 };
304
305 //===---------------------------------------===//
306 // 'memcpy' Optimizations
307
308 struct MemCpyOpt : public LibCallOptimization {
309   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
310     // These optimizations require DataLayout.
311     if (!TD) return 0;
312
313     FunctionType *FT = Callee->getFunctionType();
314     Type *PT = FT->getParamType(0);
315     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
316         !FT->getParamType(0)->isPointerTy() ||
317         !FT->getParamType(1)->isPointerTy() ||
318         FT->getParamType(2) != TD->getIntPtrType(PT))
319       return 0;
320
321     // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
322     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
323                    CI->getArgOperand(2), 1);
324     return CI->getArgOperand(0);
325   }
326 };
327
328 //===---------------------------------------===//
329 // 'memmove' Optimizations
330
331 struct MemMoveOpt : public LibCallOptimization {
332   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
333     // These optimizations require DataLayout.
334     if (!TD) return 0;
335
336     FunctionType *FT = Callee->getFunctionType();
337     Type *PT = FT->getParamType(0);
338     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
339         !FT->getParamType(0)->isPointerTy() ||
340         !FT->getParamType(1)->isPointerTy() ||
341         FT->getParamType(2) != TD->getIntPtrType(PT))
342       return 0;
343
344     // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
345     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
346                     CI->getArgOperand(2), 1);
347     return CI->getArgOperand(0);
348   }
349 };
350
351 //===---------------------------------------===//
352 // 'memset' Optimizations
353
354 struct MemSetOpt : public LibCallOptimization {
355   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
356     // These optimizations require DataLayout.
357     if (!TD) return 0;
358
359     FunctionType *FT = Callee->getFunctionType();
360     Type *PT = FT->getParamType(0);
361     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
362         !FT->getParamType(0)->isPointerTy() ||
363         !FT->getParamType(1)->isIntegerTy() ||
364         FT->getParamType(2) != TD->getIntPtrType(PT))
365       return 0;
366
367     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
368     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
369     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
370     return CI->getArgOperand(0);
371   }
372 };
373
374 //===----------------------------------------------------------------------===//
375 // Math Library Optimizations
376 //===----------------------------------------------------------------------===//
377
378 //===---------------------------------------===//
379 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
380
381 struct UnaryDoubleFPOpt : public LibCallOptimization {
382   bool CheckRetType;
383   UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
384   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
385     FunctionType *FT = Callee->getFunctionType();
386     if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
387         !FT->getParamType(0)->isDoubleTy())
388       return 0;
389
390     if (CheckRetType) {
391       // Check if all the uses for function like 'sin' are converted to float.
392       for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
393           ++UseI) {
394         FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
395         if (Cast == 0 || !Cast->getType()->isFloatTy())
396           return 0;
397       }
398     }
399
400     // If this is something like 'floor((double)floatval)', convert to floorf.
401     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
402     if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
403       return 0;
404
405     // floor((double)floatval) -> (double)floorf(floatval)
406     Value *V = Cast->getOperand(0);
407     V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
408     return B.CreateFPExt(V, B.getDoubleTy());
409   }
410 };
411
412 //===---------------------------------------===//
413 // 'cos*' Optimizations
414 struct CosOpt : public LibCallOptimization {
415   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
416     Value *Ret = NULL;
417     if (UnsafeFPShrink && Callee->getName() == "cos" &&
418         TLI->has(LibFunc::cosf)) {
419       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
420       Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
421     }
422
423     FunctionType *FT = Callee->getFunctionType();
424     // Just make sure this has 1 argument of FP type, which matches the
425     // result type.
426     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
427         !FT->getParamType(0)->isFloatingPointTy())
428       return Ret;
429
430     // cos(-x) -> cos(x)
431     Value *Op1 = CI->getArgOperand(0);
432     if (BinaryOperator::isFNeg(Op1)) {
433       BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
434       return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
435     }
436     return Ret;
437   }
438 };
439
440 //===---------------------------------------===//
441 // 'pow*' Optimizations
442
443 struct PowOpt : public LibCallOptimization {
444   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
445     Value *Ret = NULL;
446     if (UnsafeFPShrink && Callee->getName() == "pow" &&
447         TLI->has(LibFunc::powf)) {
448       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
449       Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
450     }
451
452     FunctionType *FT = Callee->getFunctionType();
453     // Just make sure this has 2 arguments of the same FP type, which match the
454     // result type.
455     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
456         FT->getParamType(0) != FT->getParamType(1) ||
457         !FT->getParamType(0)->isFloatingPointTy())
458       return Ret;
459
460     Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
461     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
462       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
463         return Op1C;
464       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
465         return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
466     }
467
468     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
469     if (Op2C == 0) return Ret;
470
471     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
472       return ConstantFP::get(CI->getType(), 1.0);
473
474     if (Op2C->isExactlyValue(0.5)) {
475       // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
476       // This is faster than calling pow, and still handles negative zero
477       // and negative infinity correctly.
478       // TODO: In fast-math mode, this could be just sqrt(x).
479       // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
480       Value *Inf = ConstantFP::getInfinity(CI->getType());
481       Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
482       Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
483                                          Callee->getAttributes());
484       Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
485                                          Callee->getAttributes());
486       Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
487       Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
488       return Sel;
489     }
490
491     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
492       return Op1;
493     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
494       return B.CreateFMul(Op1, Op1, "pow2");
495     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
496       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
497                           Op1, "powrecip");
498     return 0;
499   }
500 };
501
502 //===---------------------------------------===//
503 // 'exp2' Optimizations
504
505 struct Exp2Opt : public LibCallOptimization {
506   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
507     Value *Ret = NULL;
508     if (UnsafeFPShrink && Callee->getName() == "exp2" &&
509         TLI->has(LibFunc::exp2)) {
510       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
511       Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
512     }
513
514     FunctionType *FT = Callee->getFunctionType();
515     // Just make sure this has 1 argument of FP type, which matches the
516     // result type.
517     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
518         !FT->getParamType(0)->isFloatingPointTy())
519       return Ret;
520
521     Value *Op = CI->getArgOperand(0);
522     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
523     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
524     Value *LdExpArg = 0;
525     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
526       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
527         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
528     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
529       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
530         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
531     }
532
533     if (LdExpArg) {
534       const char *Name;
535       if (Op->getType()->isFloatTy())
536         Name = "ldexpf";
537       else if (Op->getType()->isDoubleTy())
538         Name = "ldexp";
539       else
540         Name = "ldexpl";
541
542       Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
543       if (!Op->getType()->isFloatTy())
544         One = ConstantExpr::getFPExtend(One, Op->getType());
545
546       Module *M = Caller->getParent();
547       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
548                                              Op->getType(),
549                                              B.getInt32Ty(), NULL);
550       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
551       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
552         CI->setCallingConv(F->getCallingConv());
553
554       return CI;
555     }
556     return Ret;
557   }
558 };
559
560 //===----------------------------------------------------------------------===//
561 // Integer Optimizations
562 //===----------------------------------------------------------------------===//
563
564 //===---------------------------------------===//
565 // 'ffs*' Optimizations
566
567 struct FFSOpt : public LibCallOptimization {
568   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
569     FunctionType *FT = Callee->getFunctionType();
570     // Just make sure this has 2 arguments of the same FP type, which match the
571     // result type.
572     if (FT->getNumParams() != 1 ||
573         !FT->getReturnType()->isIntegerTy(32) ||
574         !FT->getParamType(0)->isIntegerTy())
575       return 0;
576
577     Value *Op = CI->getArgOperand(0);
578
579     // Constant fold.
580     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
581       if (CI->isZero()) // ffs(0) -> 0.
582         return B.getInt32(0);
583       // ffs(c) -> cttz(c)+1
584       return B.getInt32(CI->getValue().countTrailingZeros() + 1);
585     }
586
587     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
588     Type *ArgType = Op->getType();
589     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
590                                          Intrinsic::cttz, ArgType);
591     Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
592     V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
593     V = B.CreateIntCast(V, B.getInt32Ty(), false);
594
595     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
596     return B.CreateSelect(Cond, V, B.getInt32(0));
597   }
598 };
599
600 //===---------------------------------------===//
601 // 'isdigit' Optimizations
602
603 struct IsDigitOpt : public LibCallOptimization {
604   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
605     FunctionType *FT = Callee->getFunctionType();
606     // We require integer(i32)
607     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
608         !FT->getParamType(0)->isIntegerTy(32))
609       return 0;
610
611     // isdigit(c) -> (c-'0') <u 10
612     Value *Op = CI->getArgOperand(0);
613     Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
614     Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
615     return B.CreateZExt(Op, CI->getType());
616   }
617 };
618
619 //===---------------------------------------===//
620 // 'isascii' Optimizations
621
622 struct IsAsciiOpt : public LibCallOptimization {
623   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
624     FunctionType *FT = Callee->getFunctionType();
625     // We require integer(i32)
626     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
627         !FT->getParamType(0)->isIntegerTy(32))
628       return 0;
629
630     // isascii(c) -> c <u 128
631     Value *Op = CI->getArgOperand(0);
632     Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
633     return B.CreateZExt(Op, CI->getType());
634   }
635 };
636
637 //===---------------------------------------===//
638 // 'abs', 'labs', 'llabs' Optimizations
639
640 struct AbsOpt : public LibCallOptimization {
641   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
642     FunctionType *FT = Callee->getFunctionType();
643     // We require integer(integer) where the types agree.
644     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
645         FT->getParamType(0) != FT->getReturnType())
646       return 0;
647
648     // abs(x) -> x >s -1 ? x : -x
649     Value *Op = CI->getArgOperand(0);
650     Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
651                                  "ispos");
652     Value *Neg = B.CreateNeg(Op, "neg");
653     return B.CreateSelect(Pos, Op, Neg);
654   }
655 };
656
657
658 //===---------------------------------------===//
659 // 'toascii' Optimizations
660
661 struct ToAsciiOpt : public LibCallOptimization {
662   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
663     FunctionType *FT = Callee->getFunctionType();
664     // We require i32(i32)
665     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
666         !FT->getParamType(0)->isIntegerTy(32))
667       return 0;
668
669     // isascii(c) -> c & 0x7f
670     return B.CreateAnd(CI->getArgOperand(0),
671                        ConstantInt::get(CI->getType(),0x7F));
672   }
673 };
674
675 //===----------------------------------------------------------------------===//
676 // Formatting and IO Optimizations
677 //===----------------------------------------------------------------------===//
678
679 //===---------------------------------------===//
680 // 'printf' Optimizations
681
682 struct PrintFOpt : public LibCallOptimization {
683   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
684                                    IRBuilder<> &B) {
685     // Check for a fixed format string.
686     StringRef FormatStr;
687     if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
688       return 0;
689
690     // Empty format string -> noop.
691     if (FormatStr.empty())  // Tolerate printf's declared void.
692       return CI->use_empty() ? (Value*)CI :
693                                ConstantInt::get(CI->getType(), 0);
694
695     // Do not do any of the following transformations if the printf return value
696     // is used, in general the printf return value is not compatible with either
697     // putchar() or puts().
698     if (!CI->use_empty())
699       return 0;
700
701     // printf("x") -> putchar('x'), even for '%'.
702     if (FormatStr.size() == 1) {
703       Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
704       if (CI->use_empty() || !Res) return Res;
705       return B.CreateIntCast(Res, CI->getType(), true);
706     }
707
708     // printf("foo\n") --> puts("foo")
709     if (FormatStr[FormatStr.size()-1] == '\n' &&
710         FormatStr.find('%') == std::string::npos) {  // no format characters.
711       // Create a string literal with no \n on it.  We expect the constant merge
712       // pass to be run after this pass, to merge duplicate strings.
713       FormatStr = FormatStr.drop_back();
714       Value *GV = B.CreateGlobalString(FormatStr, "str");
715       Value *NewCI = EmitPutS(GV, B, TD, TLI);
716       return (CI->use_empty() || !NewCI) ?
717               NewCI :
718               ConstantInt::get(CI->getType(), FormatStr.size()+1);
719     }
720
721     // Optimize specific format strings.
722     // printf("%c", chr) --> putchar(chr)
723     if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
724         CI->getArgOperand(1)->getType()->isIntegerTy()) {
725       Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
726
727       if (CI->use_empty() || !Res) return Res;
728       return B.CreateIntCast(Res, CI->getType(), true);
729     }
730
731     // printf("%s\n", str) --> puts(str)
732     if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
733         CI->getArgOperand(1)->getType()->isPointerTy()) {
734       return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
735     }
736     return 0;
737   }
738
739   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
740     // Require one fixed pointer argument and an integer/void result.
741     FunctionType *FT = Callee->getFunctionType();
742     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
743         !(FT->getReturnType()->isIntegerTy() ||
744           FT->getReturnType()->isVoidTy()))
745       return 0;
746
747     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
748       return V;
749     }
750
751     // printf(format, ...) -> iprintf(format, ...) if no floating point
752     // arguments.
753     if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
754       Module *M = B.GetInsertBlock()->getParent()->getParent();
755       Constant *IPrintFFn =
756         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
757       CallInst *New = cast<CallInst>(CI->clone());
758       New->setCalledFunction(IPrintFFn);
759       B.Insert(New);
760       return New;
761     }
762     return 0;
763   }
764 };
765
766 //===---------------------------------------===//
767 // 'sprintf' Optimizations
768
769 struct SPrintFOpt : public LibCallOptimization {
770   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
771                                    IRBuilder<> &B) {
772     // Check for a fixed format string.
773     StringRef FormatStr;
774     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
775       return 0;
776
777     // If we just have a format string (nothing else crazy) transform it.
778     if (CI->getNumArgOperands() == 2) {
779       // Make sure there's no % in the constant array.  We could try to handle
780       // %% -> % in the future if we cared.
781       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
782         if (FormatStr[i] == '%')
783           return 0; // we found a format specifier, bail out.
784
785       // These optimizations require DataLayout.
786       if (!TD) return 0;
787
788       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
789       Type *AT = CI->getArgOperand(0)->getType();
790       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
791                      ConstantInt::get(TD->getIntPtrType(AT), // Copy the
792                                       FormatStr.size() + 1), 1);   // nul byte.
793       return ConstantInt::get(CI->getType(), FormatStr.size());
794     }
795
796     // The remaining optimizations require the format string to be "%s" or "%c"
797     // and have an extra operand.
798     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
799         CI->getNumArgOperands() < 3)
800       return 0;
801
802     // Decode the second character of the format string.
803     if (FormatStr[1] == 'c') {
804       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
805       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
806       Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
807       Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
808       B.CreateStore(V, Ptr);
809       Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
810       B.CreateStore(B.getInt8(0), Ptr);
811
812       return ConstantInt::get(CI->getType(), 1);
813     }
814
815     if (FormatStr[1] == 's') {
816       // These optimizations require DataLayout.
817       if (!TD) return 0;
818
819       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
820       if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
821
822       Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
823       if (!Len)
824         return 0;
825       Value *IncLen = B.CreateAdd(Len,
826                                   ConstantInt::get(Len->getType(), 1),
827                                   "leninc");
828       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
829
830       // The sprintf result is the unincremented number of bytes in the string.
831       return B.CreateIntCast(Len, CI->getType(), false);
832     }
833     return 0;
834   }
835
836   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
837     // Require two fixed pointer arguments and an integer result.
838     FunctionType *FT = Callee->getFunctionType();
839     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
840         !FT->getParamType(1)->isPointerTy() ||
841         !FT->getReturnType()->isIntegerTy())
842       return 0;
843
844     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
845       return V;
846     }
847
848     // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
849     // point arguments.
850     if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
851       Module *M = B.GetInsertBlock()->getParent()->getParent();
852       Constant *SIPrintFFn =
853         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
854       CallInst *New = cast<CallInst>(CI->clone());
855       New->setCalledFunction(SIPrintFFn);
856       B.Insert(New);
857       return New;
858     }
859     return 0;
860   }
861 };
862
863 //===---------------------------------------===//
864 // 'fwrite' Optimizations
865
866 struct FWriteOpt : public LibCallOptimization {
867   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
868     // Require a pointer, an integer, an integer, a pointer, returning integer.
869     FunctionType *FT = Callee->getFunctionType();
870     if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
871         !FT->getParamType(1)->isIntegerTy() ||
872         !FT->getParamType(2)->isIntegerTy() ||
873         !FT->getParamType(3)->isPointerTy() ||
874         !FT->getReturnType()->isIntegerTy())
875       return 0;
876
877     // Get the element size and count.
878     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
879     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
880     if (!SizeC || !CountC) return 0;
881     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
882
883     // If this is writing zero records, remove the call (it's a noop).
884     if (Bytes == 0)
885       return ConstantInt::get(CI->getType(), 0);
886
887     // If this is writing one byte, turn it into fputc.
888     // This optimisation is only valid, if the return value is unused.
889     if (Bytes == 1 && CI->use_empty()) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
890       Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
891       Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
892       return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
893     }
894
895     return 0;
896   }
897 };
898
899 //===---------------------------------------===//
900 // 'fputs' Optimizations
901
902 struct FPutsOpt : public LibCallOptimization {
903   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
904     // These optimizations require DataLayout.
905     if (!TD) return 0;
906
907     // Require two pointers.  Also, we can't optimize if return value is used.
908     FunctionType *FT = Callee->getFunctionType();
909     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
910         !FT->getParamType(1)->isPointerTy() ||
911         !CI->use_empty())
912       return 0;
913
914     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
915     uint64_t Len = GetStringLength(CI->getArgOperand(0));
916     if (!Len) return 0;
917     // Known to have no uses (see above).
918     Type *PT = FT->getParamType(0);
919     return EmitFWrite(CI->getArgOperand(0),
920                       ConstantInt::get(TD->getIntPtrType(PT), Len-1),
921                       CI->getArgOperand(1), B, TD, TLI);
922   }
923 };
924
925 //===---------------------------------------===//
926 // 'fprintf' Optimizations
927
928 struct FPrintFOpt : public LibCallOptimization {
929   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
930                                    IRBuilder<> &B) {
931     // All the optimizations depend on the format string.
932     StringRef FormatStr;
933     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
934       return 0;
935
936     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
937     if (CI->getNumArgOperands() == 2) {
938       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
939         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
940           return 0; // We found a format specifier.
941
942       // These optimizations require DataLayout.
943       if (!TD) return 0;
944
945       Type *AT = CI->getArgOperand(1)->getType();
946       Value *NewCI = EmitFWrite(CI->getArgOperand(1),
947                                 ConstantInt::get(TD->getIntPtrType(AT),
948                                                  FormatStr.size()),
949                                 CI->getArgOperand(0), B, TD, TLI);
950       return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
951     }
952
953     // The remaining optimizations require the format string to be "%s" or "%c"
954     // and have an extra operand.
955     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
956         CI->getNumArgOperands() < 3)
957       return 0;
958
959     // Decode the second character of the format string.
960     if (FormatStr[1] == 'c') {
961       // fprintf(F, "%c", chr) --> fputc(chr, F)
962       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
963       Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
964                                TD, TLI);
965       return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
966     }
967
968     if (FormatStr[1] == 's') {
969       // fprintf(F, "%s", str) --> fputs(str, F)
970       if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
971         return 0;
972       return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
973     }
974     return 0;
975   }
976
977   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
978     // Require two fixed paramters as pointers and integer result.
979     FunctionType *FT = Callee->getFunctionType();
980     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
981         !FT->getParamType(1)->isPointerTy() ||
982         !FT->getReturnType()->isIntegerTy())
983       return 0;
984
985     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
986       return V;
987     }
988
989     // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
990     // floating point arguments.
991     if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
992       Module *M = B.GetInsertBlock()->getParent()->getParent();
993       Constant *FIPrintFFn =
994         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
995       CallInst *New = cast<CallInst>(CI->clone());
996       New->setCalledFunction(FIPrintFFn);
997       B.Insert(New);
998       return New;
999     }
1000     return 0;
1001   }
1002 };
1003
1004 //===---------------------------------------===//
1005 // 'puts' Optimizations
1006
1007 struct PutsOpt : public LibCallOptimization {
1008   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1009     // Require one fixed pointer argument and an integer/void result.
1010     FunctionType *FT = Callee->getFunctionType();
1011     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1012         !(FT->getReturnType()->isIntegerTy() ||
1013           FT->getReturnType()->isVoidTy()))
1014       return 0;
1015
1016     // Check for a constant string.
1017     StringRef Str;
1018     if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1019       return 0;
1020
1021     if (Str.empty() && CI->use_empty()) {
1022       // puts("") -> putchar('\n')
1023       Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1024       if (CI->use_empty() || !Res) return Res;
1025       return B.CreateIntCast(Res, CI->getType(), true);
1026     }
1027
1028     return 0;
1029   }
1030 };
1031
1032 } // end anonymous namespace.
1033
1034 //===----------------------------------------------------------------------===//
1035 // SimplifyLibCalls Pass Implementation
1036 //===----------------------------------------------------------------------===//
1037
1038 namespace {
1039   /// This pass optimizes well known library functions from libc and libm.
1040   ///
1041   class SimplifyLibCalls : public FunctionPass {
1042     TargetLibraryInfo *TLI;
1043
1044     StringMap<LibCallOptimization*> Optimizations;
1045     // String and Memory LibCall Optimizations
1046     StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1047     MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1048     // Math Library Optimizations
1049     CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
1050     UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
1051     // Integer Optimizations
1052     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1053     ToAsciiOpt ToAscii;
1054     // Formatting and IO Optimizations
1055     SPrintFOpt SPrintF; PrintFOpt PrintF;
1056     FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1057     PutsOpt Puts;
1058
1059     bool Modified;  // This is only used by doInitialization.
1060   public:
1061     static char ID; // Pass identification
1062     SimplifyLibCalls() : FunctionPass(ID), UnaryDoubleFP(false),
1063                          UnsafeUnaryDoubleFP(true) {
1064       initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1065     }
1066     void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1067     void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1068
1069     void InitOptimizations();
1070     bool runOnFunction(Function &F);
1071
1072     void setDoesNotAccessMemory(Function &F);
1073     void setOnlyReadsMemory(Function &F);
1074     void setDoesNotThrow(Function &F);
1075     void setDoesNotCapture(Function &F, unsigned n);
1076     void setDoesNotAlias(Function &F, unsigned n);
1077     bool doInitialization(Module &M);
1078
1079     void inferPrototypeAttributes(Function &F);
1080     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1081       AU.addRequired<TargetLibraryInfo>();
1082     }
1083   };
1084 } // end anonymous namespace.
1085
1086 char SimplifyLibCalls::ID = 0;
1087
1088 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1089                       "Simplify well-known library calls", false, false)
1090 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1091 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1092                     "Simplify well-known library calls", false, false)
1093
1094 // Public interface to the Simplify LibCalls pass.
1095 FunctionPass *llvm::createSimplifyLibCallsPass() {
1096   return new SimplifyLibCalls();
1097 }
1098
1099 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1100   if (TLI->has(F))
1101     Optimizations[TLI->getName(F)] = Opt;
1102 }
1103
1104 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
1105                               LibCallOptimization* Opt) {
1106   if (TLI->has(F1) && TLI->has(F2))
1107     Optimizations[TLI->getName(F1)] = Opt;
1108 }
1109
1110 /// Optimizations - Populate the Optimizations map with all the optimizations
1111 /// we know.
1112 void SimplifyLibCalls::InitOptimizations() {
1113   // String and Memory LibCall Optimizations
1114   Optimizations["strspn"] = &StrSpn;
1115   Optimizations["strcspn"] = &StrCSpn;
1116   Optimizations["strstr"] = &StrStr;
1117   Optimizations["memcmp"] = &MemCmp;
1118   AddOpt(LibFunc::memcpy, &MemCpy);
1119   Optimizations["memmove"] = &MemMove;
1120   AddOpt(LibFunc::memset, &MemSet);
1121
1122   // Math Library Optimizations
1123   Optimizations["cosf"] = &Cos;
1124   Optimizations["cos"] = &Cos;
1125   Optimizations["cosl"] = &Cos;
1126   Optimizations["powf"] = &Pow;
1127   Optimizations["pow"] = &Pow;
1128   Optimizations["powl"] = &Pow;
1129   Optimizations["llvm.pow.f32"] = &Pow;
1130   Optimizations["llvm.pow.f64"] = &Pow;
1131   Optimizations["llvm.pow.f80"] = &Pow;
1132   Optimizations["llvm.pow.f128"] = &Pow;
1133   Optimizations["llvm.pow.ppcf128"] = &Pow;
1134   Optimizations["exp2l"] = &Exp2;
1135   Optimizations["exp2"] = &Exp2;
1136   Optimizations["exp2f"] = &Exp2;
1137   Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1138   Optimizations["llvm.exp2.f128"] = &Exp2;
1139   Optimizations["llvm.exp2.f80"] = &Exp2;
1140   Optimizations["llvm.exp2.f64"] = &Exp2;
1141   Optimizations["llvm.exp2.f32"] = &Exp2;
1142
1143   AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1144   AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
1145   AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
1146   AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
1147   AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
1148   AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
1149   AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
1150
1151   if(UnsafeFPShrink) {
1152     AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
1153     AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
1154     AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
1155     AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
1156     AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
1157     AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
1158     AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
1159     AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
1160     AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
1161     AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
1162     AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
1163     AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
1164     AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
1165     AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
1166     AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
1167     AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
1168     AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
1169     AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
1170     AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
1171     AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
1172     AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
1173   }
1174
1175   // Integer Optimizations
1176   Optimizations["ffs"] = &FFS;
1177   Optimizations["ffsl"] = &FFS;
1178   Optimizations["ffsll"] = &FFS;
1179   Optimizations["abs"] = &Abs;
1180   Optimizations["labs"] = &Abs;
1181   Optimizations["llabs"] = &Abs;
1182   Optimizations["isdigit"] = &IsDigit;
1183   Optimizations["isascii"] = &IsAscii;
1184   Optimizations["toascii"] = &ToAscii;
1185
1186   // Formatting and IO Optimizations
1187   Optimizations["sprintf"] = &SPrintF;
1188   Optimizations["printf"] = &PrintF;
1189   AddOpt(LibFunc::fwrite, &FWrite);
1190   AddOpt(LibFunc::fputs, &FPuts);
1191   Optimizations["fprintf"] = &FPrintF;
1192   Optimizations["puts"] = &Puts;
1193 }
1194
1195
1196 /// runOnFunction - Top level algorithm.
1197 ///
1198 bool SimplifyLibCalls::runOnFunction(Function &F) {
1199   TLI = &getAnalysis<TargetLibraryInfo>();
1200
1201   if (Optimizations.empty())
1202     InitOptimizations();
1203
1204   const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
1205
1206   IRBuilder<> Builder(F.getContext());
1207
1208   bool Changed = false;
1209   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1210     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1211       // Ignore non-calls.
1212       CallInst *CI = dyn_cast<CallInst>(I++);
1213       if (!CI) continue;
1214
1215       // Ignore indirect calls and calls to non-external functions.
1216       Function *Callee = CI->getCalledFunction();
1217       if (Callee == 0 || !Callee->isDeclaration() ||
1218           !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1219         continue;
1220
1221       // Ignore unknown calls.
1222       LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1223       if (!LCO) continue;
1224
1225       // Set the builder to the instruction after the call.
1226       Builder.SetInsertPoint(BB, I);
1227
1228       // Use debug location of CI for all new instructions.
1229       Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1230
1231       // Try to optimize this call.
1232       Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1233       if (Result == 0) continue;
1234
1235       DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1236             dbgs() << "  into: " << *Result << "\n");
1237
1238       // Something changed!
1239       Changed = true;
1240       ++NumSimplified;
1241
1242       // Inspect the instruction after the call (which was potentially just
1243       // added) next.
1244       I = CI; ++I;
1245
1246       if (CI != Result && !CI->use_empty()) {
1247         CI->replaceAllUsesWith(Result);
1248         if (!Result->hasName())
1249           Result->takeName(CI);
1250       }
1251       CI->eraseFromParent();
1252     }
1253   }
1254   return Changed;
1255 }
1256
1257 // Utility methods for doInitialization.
1258
1259 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1260   if (!F.doesNotAccessMemory()) {
1261     F.setDoesNotAccessMemory();
1262     ++NumAnnotated;
1263     Modified = true;
1264   }
1265 }
1266 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1267   if (!F.onlyReadsMemory()) {
1268     F.setOnlyReadsMemory();
1269     ++NumAnnotated;
1270     Modified = true;
1271   }
1272 }
1273 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1274   if (!F.doesNotThrow()) {
1275     F.setDoesNotThrow();
1276     ++NumAnnotated;
1277     Modified = true;
1278   }
1279 }
1280 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1281   if (!F.doesNotCapture(n)) {
1282     F.setDoesNotCapture(n);
1283     ++NumAnnotated;
1284     Modified = true;
1285   }
1286 }
1287 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1288   if (!F.doesNotAlias(n)) {
1289     F.setDoesNotAlias(n);
1290     ++NumAnnotated;
1291     Modified = true;
1292   }
1293 }
1294
1295
1296 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1297   FunctionType *FTy = F.getFunctionType();
1298
1299   StringRef Name = F.getName();
1300   switch (Name[0]) {
1301   case 's':
1302     if (Name == "strlen") {
1303       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1304         return;
1305       setOnlyReadsMemory(F);
1306       setDoesNotThrow(F);
1307       setDoesNotCapture(F, 1);
1308     } else if (Name == "strchr" ||
1309                Name == "strrchr") {
1310       if (FTy->getNumParams() != 2 ||
1311           !FTy->getParamType(0)->isPointerTy() ||
1312           !FTy->getParamType(1)->isIntegerTy())
1313         return;
1314       setOnlyReadsMemory(F);
1315       setDoesNotThrow(F);
1316     } else if (Name == "strcpy" ||
1317                Name == "stpcpy" ||
1318                Name == "strcat" ||
1319                Name == "strtol" ||
1320                Name == "strtod" ||
1321                Name == "strtof" ||
1322                Name == "strtoul" ||
1323                Name == "strtoll" ||
1324                Name == "strtold" ||
1325                Name == "strncat" ||
1326                Name == "strncpy" ||
1327                Name == "stpncpy" ||
1328                Name == "strtoull") {
1329       if (FTy->getNumParams() < 2 ||
1330           !FTy->getParamType(1)->isPointerTy())
1331         return;
1332       setDoesNotThrow(F);
1333       setDoesNotCapture(F, 2);
1334     } else if (Name == "strxfrm") {
1335       if (FTy->getNumParams() != 3 ||
1336           !FTy->getParamType(0)->isPointerTy() ||
1337           !FTy->getParamType(1)->isPointerTy())
1338         return;
1339       setDoesNotThrow(F);
1340       setDoesNotCapture(F, 1);
1341       setDoesNotCapture(F, 2);
1342     } else if (Name == "strcmp" ||
1343                Name == "strspn" ||
1344                Name == "strncmp" ||
1345                Name == "strcspn" ||
1346                Name == "strcoll" ||
1347                Name == "strcasecmp" ||
1348                Name == "strncasecmp") {
1349       if (FTy->getNumParams() < 2 ||
1350           !FTy->getParamType(0)->isPointerTy() ||
1351           !FTy->getParamType(1)->isPointerTy())
1352         return;
1353       setOnlyReadsMemory(F);
1354       setDoesNotThrow(F);
1355       setDoesNotCapture(F, 1);
1356       setDoesNotCapture(F, 2);
1357     } else if (Name == "strstr" ||
1358                Name == "strpbrk") {
1359       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1360         return;
1361       setOnlyReadsMemory(F);
1362       setDoesNotThrow(F);
1363       setDoesNotCapture(F, 2);
1364     } else if (Name == "strtok" ||
1365                Name == "strtok_r") {
1366       if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1367         return;
1368       setDoesNotThrow(F);
1369       setDoesNotCapture(F, 2);
1370     } else if (Name == "scanf" ||
1371                Name == "setbuf" ||
1372                Name == "setvbuf") {
1373       if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1374         return;
1375       setDoesNotThrow(F);
1376       setDoesNotCapture(F, 1);
1377     } else if (Name == "strdup" ||
1378                Name == "strndup") {
1379       if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1380           !FTy->getParamType(0)->isPointerTy())
1381         return;
1382       setDoesNotThrow(F);
1383       setDoesNotAlias(F, 0);
1384       setDoesNotCapture(F, 1);
1385     } else if (Name == "stat" ||
1386                Name == "sscanf" ||
1387                Name == "sprintf" ||
1388                Name == "statvfs") {
1389       if (FTy->getNumParams() < 2 ||
1390           !FTy->getParamType(0)->isPointerTy() ||
1391           !FTy->getParamType(1)->isPointerTy())
1392         return;
1393       setDoesNotThrow(F);
1394       setDoesNotCapture(F, 1);
1395       setDoesNotCapture(F, 2);
1396     } else if (Name == "snprintf") {
1397       if (FTy->getNumParams() != 3 ||
1398           !FTy->getParamType(0)->isPointerTy() ||
1399           !FTy->getParamType(2)->isPointerTy())
1400         return;
1401       setDoesNotThrow(F);
1402       setDoesNotCapture(F, 1);
1403       setDoesNotCapture(F, 3);
1404     } else if (Name == "setitimer") {
1405       if (FTy->getNumParams() != 3 ||
1406           !FTy->getParamType(1)->isPointerTy() ||
1407           !FTy->getParamType(2)->isPointerTy())
1408         return;
1409       setDoesNotThrow(F);
1410       setDoesNotCapture(F, 2);
1411       setDoesNotCapture(F, 3);
1412     } else if (Name == "system") {
1413       if (FTy->getNumParams() != 1 ||
1414           !FTy->getParamType(0)->isPointerTy())
1415         return;
1416       // May throw; "system" is a valid pthread cancellation point.
1417       setDoesNotCapture(F, 1);
1418     }
1419     break;
1420   case 'm':
1421     if (Name == "malloc") {
1422       if (FTy->getNumParams() != 1 ||
1423           !FTy->getReturnType()->isPointerTy())
1424         return;
1425       setDoesNotThrow(F);
1426       setDoesNotAlias(F, 0);
1427     } else if (Name == "memcmp") {
1428       if (FTy->getNumParams() != 3 ||
1429           !FTy->getParamType(0)->isPointerTy() ||
1430           !FTy->getParamType(1)->isPointerTy())
1431         return;
1432       setOnlyReadsMemory(F);
1433       setDoesNotThrow(F);
1434       setDoesNotCapture(F, 1);
1435       setDoesNotCapture(F, 2);
1436     } else if (Name == "memchr" ||
1437                Name == "memrchr") {
1438       if (FTy->getNumParams() != 3)
1439         return;
1440       setOnlyReadsMemory(F);
1441       setDoesNotThrow(F);
1442     } else if (Name == "modf" ||
1443                Name == "modff" ||
1444                Name == "modfl" ||
1445                Name == "memcpy" ||
1446                Name == "memccpy" ||
1447                Name == "memmove") {
1448       if (FTy->getNumParams() < 2 ||
1449           !FTy->getParamType(1)->isPointerTy())
1450         return;
1451       setDoesNotThrow(F);
1452       setDoesNotCapture(F, 2);
1453     } else if (Name == "memalign") {
1454       if (!FTy->getReturnType()->isPointerTy())
1455         return;
1456       setDoesNotAlias(F, 0);
1457     } else if (Name == "mkdir" ||
1458                Name == "mktime") {
1459       if (FTy->getNumParams() == 0 ||
1460           !FTy->getParamType(0)->isPointerTy())
1461         return;
1462       setDoesNotThrow(F);
1463       setDoesNotCapture(F, 1);
1464     }
1465     break;
1466   case 'r':
1467     if (Name == "realloc") {
1468       if (FTy->getNumParams() != 2 ||
1469           !FTy->getParamType(0)->isPointerTy() ||
1470           !FTy->getReturnType()->isPointerTy())
1471         return;
1472       setDoesNotThrow(F);
1473       setDoesNotAlias(F, 0);
1474       setDoesNotCapture(F, 1);
1475     } else if (Name == "read") {
1476       if (FTy->getNumParams() != 3 ||
1477           !FTy->getParamType(1)->isPointerTy())
1478         return;
1479       // May throw; "read" is a valid pthread cancellation point.
1480       setDoesNotCapture(F, 2);
1481     } else if (Name == "rmdir" ||
1482                Name == "rewind" ||
1483                Name == "remove" ||
1484                Name == "realpath") {
1485       if (FTy->getNumParams() < 1 ||
1486           !FTy->getParamType(0)->isPointerTy())
1487         return;
1488       setDoesNotThrow(F);
1489       setDoesNotCapture(F, 1);
1490     } else if (Name == "rename" ||
1491                Name == "readlink") {
1492       if (FTy->getNumParams() < 2 ||
1493           !FTy->getParamType(0)->isPointerTy() ||
1494           !FTy->getParamType(1)->isPointerTy())
1495         return;
1496       setDoesNotThrow(F);
1497       setDoesNotCapture(F, 1);
1498       setDoesNotCapture(F, 2);
1499     }
1500     break;
1501   case 'w':
1502     if (Name == "write") {
1503       if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1504         return;
1505       // May throw; "write" is a valid pthread cancellation point.
1506       setDoesNotCapture(F, 2);
1507     }
1508     break;
1509   case 'b':
1510     if (Name == "bcopy") {
1511       if (FTy->getNumParams() != 3 ||
1512           !FTy->getParamType(0)->isPointerTy() ||
1513           !FTy->getParamType(1)->isPointerTy())
1514         return;
1515       setDoesNotThrow(F);
1516       setDoesNotCapture(F, 1);
1517       setDoesNotCapture(F, 2);
1518     } else if (Name == "bcmp") {
1519       if (FTy->getNumParams() != 3 ||
1520           !FTy->getParamType(0)->isPointerTy() ||
1521           !FTy->getParamType(1)->isPointerTy())
1522         return;
1523       setDoesNotThrow(F);
1524       setOnlyReadsMemory(F);
1525       setDoesNotCapture(F, 1);
1526       setDoesNotCapture(F, 2);
1527     } else if (Name == "bzero") {
1528       if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1529         return;
1530       setDoesNotThrow(F);
1531       setDoesNotCapture(F, 1);
1532     }
1533     break;
1534   case 'c':
1535     if (Name == "calloc") {
1536       if (FTy->getNumParams() != 2 ||
1537           !FTy->getReturnType()->isPointerTy())
1538         return;
1539       setDoesNotThrow(F);
1540       setDoesNotAlias(F, 0);
1541     } else if (Name == "chmod" ||
1542                Name == "chown" ||
1543                Name == "ctermid" ||
1544                Name == "clearerr" ||
1545                Name == "closedir") {
1546       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1547         return;
1548       setDoesNotThrow(F);
1549       setDoesNotCapture(F, 1);
1550     }
1551     break;
1552   case 'a':
1553     if (Name == "atoi" ||
1554         Name == "atol" ||
1555         Name == "atof" ||
1556         Name == "atoll") {
1557       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1558         return;
1559       setDoesNotThrow(F);
1560       setOnlyReadsMemory(F);
1561       setDoesNotCapture(F, 1);
1562     } else if (Name == "access") {
1563       if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1564         return;
1565       setDoesNotThrow(F);
1566       setDoesNotCapture(F, 1);
1567     }
1568     break;
1569   case 'f':
1570     if (Name == "fopen") {
1571       if (FTy->getNumParams() != 2 ||
1572           !FTy->getReturnType()->isPointerTy() ||
1573           !FTy->getParamType(0)->isPointerTy() ||
1574           !FTy->getParamType(1)->isPointerTy())
1575         return;
1576       setDoesNotThrow(F);
1577       setDoesNotAlias(F, 0);
1578       setDoesNotCapture(F, 1);
1579       setDoesNotCapture(F, 2);
1580     } else if (Name == "fdopen") {
1581       if (FTy->getNumParams() != 2 ||
1582           !FTy->getReturnType()->isPointerTy() ||
1583           !FTy->getParamType(1)->isPointerTy())
1584         return;
1585       setDoesNotThrow(F);
1586       setDoesNotAlias(F, 0);
1587       setDoesNotCapture(F, 2);
1588     } else if (Name == "feof" ||
1589                Name == "free" ||
1590                Name == "fseek" ||
1591                Name == "ftell" ||
1592                Name == "fgetc" ||
1593                Name == "fseeko" ||
1594                Name == "ftello" ||
1595                Name == "fileno" ||
1596                Name == "fflush" ||
1597                Name == "fclose" ||
1598                Name == "fsetpos" ||
1599                Name == "flockfile" ||
1600                Name == "funlockfile" ||
1601                Name == "ftrylockfile") {
1602       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1603         return;
1604       setDoesNotThrow(F);
1605       setDoesNotCapture(F, 1);
1606     } else if (Name == "ferror") {
1607       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1608         return;
1609       setDoesNotThrow(F);
1610       setDoesNotCapture(F, 1);
1611       setOnlyReadsMemory(F);
1612     } else if (Name == "fputc" ||
1613                Name == "fstat" ||
1614                Name == "frexp" ||
1615                Name == "frexpf" ||
1616                Name == "frexpl" ||
1617                Name == "fstatvfs") {
1618       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1619         return;
1620       setDoesNotThrow(F);
1621       setDoesNotCapture(F, 2);
1622     } else if (Name == "fgets") {
1623       if (FTy->getNumParams() != 3 ||
1624           !FTy->getParamType(0)->isPointerTy() ||
1625           !FTy->getParamType(2)->isPointerTy())
1626         return;
1627       setDoesNotThrow(F);
1628       setDoesNotCapture(F, 3);
1629     } else if (Name == "fread" ||
1630                Name == "fwrite") {
1631       if (FTy->getNumParams() != 4 ||
1632           !FTy->getParamType(0)->isPointerTy() ||
1633           !FTy->getParamType(3)->isPointerTy())
1634         return;
1635       setDoesNotThrow(F);
1636       setDoesNotCapture(F, 1);
1637       setDoesNotCapture(F, 4);
1638     } else if (Name == "fputs" ||
1639                Name == "fscanf" ||
1640                Name == "fprintf" ||
1641                Name == "fgetpos") {
1642       if (FTy->getNumParams() < 2 ||
1643           !FTy->getParamType(0)->isPointerTy() ||
1644           !FTy->getParamType(1)->isPointerTy())
1645         return;
1646       setDoesNotThrow(F);
1647       setDoesNotCapture(F, 1);
1648       setDoesNotCapture(F, 2);
1649     }
1650     break;
1651   case 'g':
1652     if (Name == "getc" ||
1653         Name == "getlogin_r" ||
1654         Name == "getc_unlocked") {
1655       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1656         return;
1657       setDoesNotThrow(F);
1658       setDoesNotCapture(F, 1);
1659     } else if (Name == "getenv") {
1660       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1661         return;
1662       setDoesNotThrow(F);
1663       setOnlyReadsMemory(F);
1664       setDoesNotCapture(F, 1);
1665     } else if (Name == "gets" ||
1666                Name == "getchar") {
1667       setDoesNotThrow(F);
1668     } else if (Name == "getitimer") {
1669       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1670         return;
1671       setDoesNotThrow(F);
1672       setDoesNotCapture(F, 2);
1673     } else if (Name == "getpwnam") {
1674       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1675         return;
1676       setDoesNotThrow(F);
1677       setDoesNotCapture(F, 1);
1678     }
1679     break;
1680   case 'u':
1681     if (Name == "ungetc") {
1682       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1683         return;
1684       setDoesNotThrow(F);
1685       setDoesNotCapture(F, 2);
1686     } else if (Name == "uname" ||
1687                Name == "unlink" ||
1688                Name == "unsetenv") {
1689       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1690         return;
1691       setDoesNotThrow(F);
1692       setDoesNotCapture(F, 1);
1693     } else if (Name == "utime" ||
1694                Name == "utimes") {
1695       if (FTy->getNumParams() != 2 ||
1696           !FTy->getParamType(0)->isPointerTy() ||
1697           !FTy->getParamType(1)->isPointerTy())
1698         return;
1699       setDoesNotThrow(F);
1700       setDoesNotCapture(F, 1);
1701       setDoesNotCapture(F, 2);
1702     }
1703     break;
1704   case 'p':
1705     if (Name == "putc") {
1706       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1707         return;
1708       setDoesNotThrow(F);
1709       setDoesNotCapture(F, 2);
1710     } else if (Name == "puts" ||
1711                Name == "printf" ||
1712                Name == "perror") {
1713       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1714         return;
1715       setDoesNotThrow(F);
1716       setDoesNotCapture(F, 1);
1717     } else if (Name == "pread" ||
1718                Name == "pwrite") {
1719       if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1720         return;
1721       // May throw; these are valid pthread cancellation points.
1722       setDoesNotCapture(F, 2);
1723     } else if (Name == "putchar") {
1724       setDoesNotThrow(F);
1725     } else if (Name == "popen") {
1726       if (FTy->getNumParams() != 2 ||
1727           !FTy->getReturnType()->isPointerTy() ||
1728           !FTy->getParamType(0)->isPointerTy() ||
1729           !FTy->getParamType(1)->isPointerTy())
1730         return;
1731       setDoesNotThrow(F);
1732       setDoesNotAlias(F, 0);
1733       setDoesNotCapture(F, 1);
1734       setDoesNotCapture(F, 2);
1735     } else if (Name == "pclose") {
1736       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1737         return;
1738       setDoesNotThrow(F);
1739       setDoesNotCapture(F, 1);
1740     }
1741     break;
1742   case 'v':
1743     if (Name == "vscanf") {
1744       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1745         return;
1746       setDoesNotThrow(F);
1747       setDoesNotCapture(F, 1);
1748     } else if (Name == "vsscanf" ||
1749                Name == "vfscanf") {
1750       if (FTy->getNumParams() != 3 ||
1751           !FTy->getParamType(1)->isPointerTy() ||
1752           !FTy->getParamType(2)->isPointerTy())
1753         return;
1754       setDoesNotThrow(F);
1755       setDoesNotCapture(F, 1);
1756       setDoesNotCapture(F, 2);
1757     } else if (Name == "valloc") {
1758       if (!FTy->getReturnType()->isPointerTy())
1759         return;
1760       setDoesNotThrow(F);
1761       setDoesNotAlias(F, 0);
1762     } else if (Name == "vprintf") {
1763       if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1764         return;
1765       setDoesNotThrow(F);
1766       setDoesNotCapture(F, 1);
1767     } else if (Name == "vfprintf" ||
1768                Name == "vsprintf") {
1769       if (FTy->getNumParams() != 3 ||
1770           !FTy->getParamType(0)->isPointerTy() ||
1771           !FTy->getParamType(1)->isPointerTy())
1772         return;
1773       setDoesNotThrow(F);
1774       setDoesNotCapture(F, 1);
1775       setDoesNotCapture(F, 2);
1776     } else if (Name == "vsnprintf") {
1777       if (FTy->getNumParams() != 4 ||
1778           !FTy->getParamType(0)->isPointerTy() ||
1779           !FTy->getParamType(2)->isPointerTy())
1780         return;
1781       setDoesNotThrow(F);
1782       setDoesNotCapture(F, 1);
1783       setDoesNotCapture(F, 3);
1784     }
1785     break;
1786   case 'o':
1787     if (Name == "open") {
1788       if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1789         return;
1790       // May throw; "open" is a valid pthread cancellation point.
1791       setDoesNotCapture(F, 1);
1792     } else if (Name == "opendir") {
1793       if (FTy->getNumParams() != 1 ||
1794           !FTy->getReturnType()->isPointerTy() ||
1795           !FTy->getParamType(0)->isPointerTy())
1796         return;
1797       setDoesNotThrow(F);
1798       setDoesNotAlias(F, 0);
1799       setDoesNotCapture(F, 1);
1800     }
1801     break;
1802   case 't':
1803     if (Name == "tmpfile") {
1804       if (!FTy->getReturnType()->isPointerTy())
1805         return;
1806       setDoesNotThrow(F);
1807       setDoesNotAlias(F, 0);
1808     } else if (Name == "times") {
1809       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1810         return;
1811       setDoesNotThrow(F);
1812       setDoesNotCapture(F, 1);
1813     }
1814     break;
1815   case 'h':
1816     if (Name == "htonl" ||
1817         Name == "htons") {
1818       setDoesNotThrow(F);
1819       setDoesNotAccessMemory(F);
1820     }
1821     break;
1822   case 'n':
1823     if (Name == "ntohl" ||
1824         Name == "ntohs") {
1825       setDoesNotThrow(F);
1826       setDoesNotAccessMemory(F);
1827     }
1828     break;
1829   case 'l':
1830     if (Name == "lstat") {
1831       if (FTy->getNumParams() != 2 ||
1832           !FTy->getParamType(0)->isPointerTy() ||
1833           !FTy->getParamType(1)->isPointerTy())
1834         return;
1835       setDoesNotThrow(F);
1836       setDoesNotCapture(F, 1);
1837       setDoesNotCapture(F, 2);
1838     } else if (Name == "lchown") {
1839       if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1840         return;
1841       setDoesNotThrow(F);
1842       setDoesNotCapture(F, 1);
1843     }
1844     break;
1845   case 'q':
1846     if (Name == "qsort") {
1847       if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1848         return;
1849       // May throw; places call through function pointer.
1850       setDoesNotCapture(F, 4);
1851     }
1852     break;
1853   case '_':
1854     if (Name == "__strdup" ||
1855         Name == "__strndup") {
1856       if (FTy->getNumParams() < 1 ||
1857           !FTy->getReturnType()->isPointerTy() ||
1858           !FTy->getParamType(0)->isPointerTy())
1859         return;
1860       setDoesNotThrow(F);
1861       setDoesNotAlias(F, 0);
1862       setDoesNotCapture(F, 1);
1863     } else if (Name == "__strtok_r") {
1864       if (FTy->getNumParams() != 3 ||
1865           !FTy->getParamType(1)->isPointerTy())
1866         return;
1867       setDoesNotThrow(F);
1868       setDoesNotCapture(F, 2);
1869     } else if (Name == "_IO_getc") {
1870       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1871         return;
1872       setDoesNotThrow(F);
1873       setDoesNotCapture(F, 1);
1874     } else if (Name == "_IO_putc") {
1875       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1876         return;
1877       setDoesNotThrow(F);
1878       setDoesNotCapture(F, 2);
1879     }
1880     break;
1881   case 1:
1882     if (Name == "\1__isoc99_scanf") {
1883       if (FTy->getNumParams() < 1 ||
1884           !FTy->getParamType(0)->isPointerTy())
1885         return;
1886       setDoesNotThrow(F);
1887       setDoesNotCapture(F, 1);
1888     } else if (Name == "\1stat64" ||
1889                Name == "\1lstat64" ||
1890                Name == "\1statvfs64" ||
1891                Name == "\1__isoc99_sscanf") {
1892       if (FTy->getNumParams() < 1 ||
1893           !FTy->getParamType(0)->isPointerTy() ||
1894           !FTy->getParamType(1)->isPointerTy())
1895         return;
1896       setDoesNotThrow(F);
1897       setDoesNotCapture(F, 1);
1898       setDoesNotCapture(F, 2);
1899     } else if (Name == "\1fopen64") {
1900       if (FTy->getNumParams() != 2 ||
1901           !FTy->getReturnType()->isPointerTy() ||
1902           !FTy->getParamType(0)->isPointerTy() ||
1903           !FTy->getParamType(1)->isPointerTy())
1904         return;
1905       setDoesNotThrow(F);
1906       setDoesNotAlias(F, 0);
1907       setDoesNotCapture(F, 1);
1908       setDoesNotCapture(F, 2);
1909     } else if (Name == "\1fseeko64" ||
1910                Name == "\1ftello64") {
1911       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1912         return;
1913       setDoesNotThrow(F);
1914       setDoesNotCapture(F, 1);
1915     } else if (Name == "\1tmpfile64") {
1916       if (!FTy->getReturnType()->isPointerTy())
1917         return;
1918       setDoesNotThrow(F);
1919       setDoesNotAlias(F, 0);
1920     } else if (Name == "\1fstat64" ||
1921                Name == "\1fstatvfs64") {
1922       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1923         return;
1924       setDoesNotThrow(F);
1925       setDoesNotCapture(F, 2);
1926     } else if (Name == "\1open64") {
1927       if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1928         return;
1929       // May throw; "open" is a valid pthread cancellation point.
1930       setDoesNotCapture(F, 1);
1931     }
1932     break;
1933   }
1934 }
1935
1936 /// doInitialization - Add attributes to well-known functions.
1937 ///
1938 bool SimplifyLibCalls::doInitialization(Module &M) {
1939   Modified = false;
1940   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1941     Function &F = *I;
1942     if (F.isDeclaration() && F.hasName())
1943       inferPrototypeAttributes(F);
1944   }
1945   return Modified;
1946 }
1947
1948 // TODO:
1949 //   Additional cases that we need to add to this file:
1950 //
1951 // cbrt:
1952 //   * cbrt(expN(X))  -> expN(x/3)
1953 //   * cbrt(sqrt(x))  -> pow(x,1/6)
1954 //   * cbrt(sqrt(x))  -> pow(x,1/9)
1955 //
1956 // exp, expf, expl:
1957 //   * exp(log(x))  -> x
1958 //
1959 // log, logf, logl:
1960 //   * log(exp(x))   -> x
1961 //   * log(x**y)     -> y*log(x)
1962 //   * log(exp(y))   -> y*log(e)
1963 //   * log(exp2(y))  -> y*log(2)
1964 //   * log(exp10(y)) -> y*log(10)
1965 //   * log(sqrt(x))  -> 0.5*log(x)
1966 //   * log(pow(x,y)) -> y*log(x)
1967 //
1968 // lround, lroundf, lroundl:
1969 //   * lround(cnst) -> cnst'
1970 //
1971 // pow, powf, powl:
1972 //   * pow(exp(x),y)  -> exp(x*y)
1973 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1974 //   * pow(pow(x,y),z)-> pow(x,y*z)
1975 //
1976 // round, roundf, roundl:
1977 //   * round(cnst) -> cnst'
1978 //
1979 // signbit:
1980 //   * signbit(cnst) -> cnst'
1981 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1982 //
1983 // sqrt, sqrtf, sqrtl:
1984 //   * sqrt(expN(x))  -> expN(x*0.5)
1985 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1986 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1987 //
1988 // strchr:
1989 //   * strchr(p, 0) -> strlen(p)
1990 // tan, tanf, tanl:
1991 //   * tan(atan(x)) -> x
1992 //
1993 // trunc, truncf, truncl:
1994 //   * trunc(cnst) -> cnst'
1995 //
1996 //