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