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