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