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