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