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