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