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