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