Optimize memmove and memset into the LLVM builtins. Note that these
[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
38 //===----------------------------------------------------------------------===//
39 // Optimizer Base Class
40 //===----------------------------------------------------------------------===//
41
42 /// This class is the abstract base class for the set of optimizations that
43 /// corresponds to one library call.
44 namespace {
45 class VISIBILITY_HIDDEN LibCallOptimization {
46 protected:
47   Function *Caller;
48   const TargetData *TD;
49 public:
50   LibCallOptimization() { }
51   virtual ~LibCallOptimization() {}
52
53   /// CallOptimizer - This pure virtual method is implemented by base classes to
54   /// do various optimizations.  If this returns null then no transformation was
55   /// performed.  If it returns CI, then it transformed the call and CI is to be
56   /// deleted.  If it returns something else, replace CI with the new value and
57   /// delete CI.
58   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) 
59     =0;
60   
61   Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
62     Caller = CI->getParent()->getParent();
63     this->TD = &TD;
64     return CallOptimizer(CI->getCalledFunction(), CI, B);
65   }
66
67   /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
68   Value *CastToCStr(Value *V, IRBuilder<> &B);
69
70   /// EmitStrLen - Emit a call to the strlen function to the builder, for the
71   /// specified pointer.  Ptr is required to be some pointer type, and the
72   /// return value has 'intptr_t' type.
73   Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
74   
75   /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This
76   /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
77   Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len, 
78                     unsigned Align, IRBuilder<> &B);
79   
80   /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
81   /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
82   Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
83     
84   /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
85   /// 'floor').  This function is known to take a single of type matching 'Op'
86   /// and returns one value with the same type.  If 'Op' is a long double, 'l'
87   /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
88   Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
89   
90   /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
91   /// is an integer.
92   void EmitPutChar(Value *Char, IRBuilder<> &B);
93   
94   /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
95   /// some pointer.
96   void EmitPutS(Value *Str, IRBuilder<> &B);
97     
98   /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
99   /// an i32, and File is a pointer to FILE.
100   void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
101   
102   /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
103   /// pointer and File is a pointer to FILE.
104   void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
105   
106   /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
107   /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
108   void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
109     
110 };
111 } // End anonymous namespace.
112
113 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
114 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
115   return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
116 }
117
118 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
119 /// specified pointer.  This always returns an integer value of size intptr_t.
120 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
121   Module *M = Caller->getParent();
122   Constant *StrLen =M->getOrInsertFunction("strlen", TD->getIntPtrType(),
123                                            PointerType::getUnqual(Type::Int8Ty),
124                                            NULL);
125   return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
126 }
127
128 /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This always
129 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
130 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
131                                        unsigned Align, IRBuilder<> &B) {
132   Module *M = Caller->getParent();
133   Intrinsic::ID IID = Intrinsic::memcpy;
134   const Type *Tys[1];
135   Tys[0] = Len->getType();
136   Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
137   return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
138                        ConstantInt::get(Type::Int32Ty, Align));
139 }
140
141 /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
142 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
143 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
144                                        Value *Len, IRBuilder<> &B) {
145   Module *M = Caller->getParent();
146   Value *MemChr = M->getOrInsertFunction("memchr",
147                                          PointerType::getUnqual(Type::Int8Ty),
148                                          PointerType::getUnqual(Type::Int8Ty),
149                                          Type::Int32Ty, TD->getIntPtrType(),
150                                          NULL);
151   return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
152 }
153
154 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
155 /// 'floor').  This function is known to take a single of type matching 'Op' and
156 /// returns one value with the same type.  If 'Op' is a long double, 'l' is
157 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
158 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
159                                                  IRBuilder<> &B) {
160   char NameBuffer[20];
161   if (Op->getType() != Type::DoubleTy) {
162     // If we need to add a suffix, copy into NameBuffer.
163     unsigned NameLen = strlen(Name);
164     assert(NameLen < sizeof(NameBuffer)-2);
165     memcpy(NameBuffer, Name, NameLen);
166     if (Op->getType() == Type::FloatTy)
167       NameBuffer[NameLen] = 'f';  // floorf
168     else
169       NameBuffer[NameLen] = 'l';  // floorl
170     NameBuffer[NameLen+1] = 0;
171     Name = NameBuffer;
172   }
173   
174   Module *M = Caller->getParent();
175   Value *Callee = M->getOrInsertFunction(Name, Op->getType(), 
176                                          Op->getType(), NULL);
177   return B.CreateCall(Callee, Op, Name);
178 }
179
180 /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
181 /// is an integer.
182 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
183   Module *M = Caller->getParent();
184   Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
185                                     Type::Int32Ty, NULL);
186   B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
187 }
188
189 /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
190 /// some pointer.
191 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
192   Module *M = Caller->getParent();
193   Value *F = M->getOrInsertFunction("puts", Type::Int32Ty,
194                                     PointerType::getUnqual(Type::Int8Ty), NULL);
195   B.CreateCall(F, CastToCStr(Str, B), "puts");
196 }
197
198 /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
199 /// an integer and File is a pointer to FILE.
200 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
201   Module *M = Caller->getParent();
202   Constant *F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
203                                        File->getType(), NULL);
204   Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
205   B.CreateCall2(F, Char, File, "fputc");
206 }
207
208 /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
209 /// pointer and File is a pointer to FILE.
210 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
211   Module *M = Caller->getParent();
212   Constant *F = M->getOrInsertFunction("fputs", Type::Int32Ty,
213                                        PointerType::getUnqual(Type::Int8Ty),
214                                        File->getType(), NULL);
215   B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
216 }
217
218 /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
219 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
220 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
221                                      IRBuilder<> &B) {
222   Module *M = Caller->getParent();
223   Constant *F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
224                                        PointerType::getUnqual(Type::Int8Ty),
225                                        TD->getIntPtrType(), TD->getIntPtrType(),
226                                        File->getType(), NULL);
227   B.CreateCall4(F, CastToCStr(Ptr, B), Size, 
228                 ConstantInt::get(TD->getIntPtrType(), 1), File);
229 }
230
231 //===----------------------------------------------------------------------===//
232 // Helper Functions
233 //===----------------------------------------------------------------------===//
234
235 /// GetStringLengthH - If we can compute the length of the string pointed to by
236 /// the specified pointer, return 'len+1'.  If we can't, return 0.
237 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
238   // Look through noop bitcast instructions.
239   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
240     return GetStringLengthH(BCI->getOperand(0), PHIs);
241   
242   // If this is a PHI node, there are two cases: either we have already seen it
243   // or we haven't.
244   if (PHINode *PN = dyn_cast<PHINode>(V)) {
245     if (!PHIs.insert(PN))
246       return ~0ULL;  // already in the set.
247     
248     // If it was new, see if all the input strings are the same length.
249     uint64_t LenSoFar = ~0ULL;
250     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
251       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
252       if (Len == 0) return 0; // Unknown length -> unknown.
253       
254       if (Len == ~0ULL) continue;
255       
256       if (Len != LenSoFar && LenSoFar != ~0ULL)
257         return 0;    // Disagree -> unknown.
258       LenSoFar = Len;
259     }
260     
261     // Success, all agree.
262     return LenSoFar;
263   }
264   
265   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
266   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
267     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
268     if (Len1 == 0) return 0;
269     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
270     if (Len2 == 0) return 0;
271     if (Len1 == ~0ULL) return Len2;
272     if (Len2 == ~0ULL) return Len1;
273     if (Len1 != Len2) return 0;
274     return Len1;
275   }
276   
277   // If the value is not a GEP instruction nor a constant expression with a
278   // GEP instruction, then return unknown.
279   User *GEP = 0;
280   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
281     GEP = GEPI;
282   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
283     if (CE->getOpcode() != Instruction::GetElementPtr)
284       return 0;
285     GEP = CE;
286   } else {
287     return 0;
288   }
289   
290   // Make sure the GEP has exactly three arguments.
291   if (GEP->getNumOperands() != 3)
292     return 0;
293   
294   // Check to make sure that the first operand of the GEP is an integer and
295   // has value 0 so that we are sure we're indexing into the initializer.
296   if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
297     if (!Idx->isZero())
298       return 0;
299   } else
300     return 0;
301   
302   // If the second index isn't a ConstantInt, then this is a variable index
303   // into the array.  If this occurs, we can't say anything meaningful about
304   // the string.
305   uint64_t StartIdx = 0;
306   if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
307     StartIdx = CI->getZExtValue();
308   else
309     return 0;
310   
311   // The GEP instruction, constant or instruction, must reference a global
312   // variable that is a constant and is initialized. The referenced constant
313   // initializer is the array that we'll use for optimization.
314   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
315   if (!GV || !GV->isConstant() || !GV->hasInitializer())
316     return 0;
317   Constant *GlobalInit = GV->getInitializer();
318   
319   // Handle the ConstantAggregateZero case, which is a degenerate case. The
320   // initializer is constant zero so the length of the string must be zero.
321   if (isa<ConstantAggregateZero>(GlobalInit))
322     return 1;  // Len = 0 offset by 1.
323   
324   // Must be a Constant Array
325   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
326   if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
327     return false;
328   
329   // Get the number of elements in the array
330   uint64_t NumElts = Array->getType()->getNumElements();
331   
332   // Traverse the constant array from StartIdx (derived above) which is
333   // the place the GEP refers to in the array.
334   for (unsigned i = StartIdx; i != NumElts; ++i) {
335     Constant *Elt = Array->getOperand(i);
336     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
337     if (!CI) // This array isn't suitable, non-int initializer.
338       return 0;
339     if (CI->isZero())
340       return i-StartIdx+1; // We found end of string, success!
341   }
342   
343   return 0; // The array isn't null terminated, conservatively return 'unknown'.
344 }
345
346 /// GetStringLength - If we can compute the length of the string pointed to by
347 /// the specified pointer, return 'len+1'.  If we can't, return 0.
348 static uint64_t GetStringLength(Value *V) {
349   if (!isa<PointerType>(V->getType())) return 0;
350   
351   SmallPtrSet<PHINode*, 32> PHIs;
352   uint64_t Len = GetStringLengthH(V, PHIs);
353   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
354   // an empty string as a length.
355   return Len == ~0ULL ? 1 : Len;
356 }
357
358 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
359 /// value is equal or not-equal to zero. 
360 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
361   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
362        UI != E; ++UI) {
363     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
364       if (IC->isEquality())
365         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
366           if (C->isNullValue())
367             continue;
368     // Unknown instruction.
369     return false;
370   }
371   return true;
372 }
373
374 //===----------------------------------------------------------------------===//
375 // Miscellaneous LibCall Optimizations
376 //===----------------------------------------------------------------------===//
377
378 namespace {
379 //===---------------------------------------===//
380 // 'exit' Optimizations
381
382 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
383 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
384   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
385     // Verify we have a reasonable prototype for exit.
386     if (Callee->arg_size() == 0 || !CI->use_empty())
387       return 0;
388
389     // Verify the caller is main, and that the result type of main matches the
390     // argument type of exit.
391     if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
392         Caller->getReturnType() != CI->getOperand(1)->getType())
393       return 0;
394
395     TerminatorInst *OldTI = CI->getParent()->getTerminator();
396     
397     // Create the return after the call.
398     ReturnInst *RI = B.CreateRet(CI->getOperand(1));
399
400     // Drop all successor phi node entries.
401     for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
402       OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
403     
404     // Erase all instructions from after our return instruction until the end of
405     // the block.
406     BasicBlock::iterator FirstDead = RI; ++FirstDead;
407     CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
408     return CI;
409   }
410 };
411
412 //===----------------------------------------------------------------------===//
413 // String and Memory LibCall Optimizations
414 //===----------------------------------------------------------------------===//
415
416 //===---------------------------------------===//
417 // 'strcat' Optimizations
418
419 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
420   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
421     // Verify the "strcat" function prototype.
422     const FunctionType *FT = Callee->getFunctionType();
423     if (FT->getNumParams() != 2 ||
424         FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
425         FT->getParamType(0) != FT->getReturnType() ||
426         FT->getParamType(1) != FT->getReturnType())
427       return 0;
428     
429     // Extract some information from the instruction
430     Value *Dst = CI->getOperand(1);
431     Value *Src = CI->getOperand(2);
432     
433     // See if we can get the length of the input string.
434     uint64_t Len = GetStringLength(Src);
435     if (Len == 0) return 0;
436     --Len;  // Unbias length.
437     
438     // Handle the simple, do-nothing case: strcat(x, "") -> x
439     if (Len == 0)
440       return Dst;
441     
442     // We need to find the end of the destination string.  That's where the
443     // memory is to be moved to. We just generate a call to strlen.
444     Value *DstLen = EmitStrLen(Dst, B);
445     
446     // Now that we have the destination's length, we must index into the
447     // destination's pointer to get the actual memcpy destination (end of
448     // the string .. we're concatenating).
449     Dst = B.CreateGEP(Dst, DstLen, "endptr");
450     
451     // We have enough information to now generate the memcpy call to do the
452     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
453     EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
454     return Dst;
455   }
456 };
457
458 //===---------------------------------------===//
459 // 'strchr' Optimizations
460
461 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
462   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
463     // Verify the "strchr" function prototype.
464     const FunctionType *FT = Callee->getFunctionType();
465     if (FT->getNumParams() != 2 ||
466         FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
467         FT->getParamType(0) != FT->getReturnType())
468       return 0;
469     
470     Value *SrcStr = CI->getOperand(1);
471     
472     // If the second operand is non-constant, see if we can compute the length
473     // of the input string and turn this into memchr.
474     ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
475     if (CharC == 0) {
476       uint64_t Len = GetStringLength(SrcStr);
477       if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
478         return 0;
479       
480       return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
481                         ConstantInt::get(TD->getIntPtrType(), Len), B);
482     }
483
484     // Otherwise, the character is a constant, see if the first argument is
485     // a string literal.  If so, we can constant fold.
486     std::string Str;
487     if (!GetConstantStringInfo(SrcStr, Str))
488       return 0;
489     
490     // strchr can find the nul character.
491     Str += '\0';
492     char CharValue = CharC->getSExtValue();
493     
494     // Compute the offset.
495     uint64_t i = 0;
496     while (1) {
497       if (i == Str.size())    // Didn't find the char.  strchr returns null.
498         return Constant::getNullValue(CI->getType());
499       // Did we find our match?
500       if (Str[i] == CharValue)
501         break;
502       ++i;
503     }
504     
505     // strchr(s+n,c)  -> gep(s+n+i,c)
506     Value *Idx = ConstantInt::get(Type::Int64Ty, i);
507     return B.CreateGEP(SrcStr, Idx, "strchr");
508   }
509 };
510
511 //===---------------------------------------===//
512 // 'strcmp' Optimizations
513
514 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
515   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
516     // Verify the "strcmp" function prototype.
517     const FunctionType *FT = Callee->getFunctionType();
518     if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
519         FT->getParamType(0) != FT->getParamType(1) ||
520         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
521       return 0;
522     
523     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
524     if (Str1P == Str2P)      // strcmp(x,x)  -> 0
525       return ConstantInt::get(CI->getType(), 0);
526     
527     std::string Str1, Str2;
528     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
529     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
530     
531     if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
532       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
533     
534     if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
535       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
536     
537     // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
538     if (HasStr1 && HasStr2)
539       return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
540     return 0;
541   }
542 };
543
544 //===---------------------------------------===//
545 // 'strncmp' Optimizations
546
547 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
548   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
549     // Verify the "strncmp" function prototype.
550     const FunctionType *FT = Callee->getFunctionType();
551     if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
552         FT->getParamType(0) != FT->getParamType(1) ||
553         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
554         !isa<IntegerType>(FT->getParamType(2)))
555       return 0;
556     
557     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
558     if (Str1P == Str2P)      // strncmp(x,x,n)  -> 0
559       return ConstantInt::get(CI->getType(), 0);
560     
561     // Get the length argument if it is constant.
562     uint64_t Length;
563     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
564       Length = LengthArg->getZExtValue();
565     else
566       return 0;
567     
568     if (Length == 0) // strncmp(x,y,0)   -> 0
569       return ConstantInt::get(CI->getType(), 0);
570     
571     std::string Str1, Str2;
572     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
573     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
574     
575     if (HasStr1 && Str1.empty())  // strncmp("", x, n) -> *x
576       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
577     
578     if (HasStr2 && Str2.empty())  // strncmp(x, "", n) -> *x
579       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
580     
581     // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
582     if (HasStr1 && HasStr2)
583       return ConstantInt::get(CI->getType(),
584                               strncmp(Str1.c_str(), Str2.c_str(), Length));
585     return 0;
586   }
587 };
588
589
590 //===---------------------------------------===//
591 // 'strcpy' Optimizations
592
593 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
594   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
595     // Verify the "strcpy" function prototype.
596     const FunctionType *FT = Callee->getFunctionType();
597     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
598         FT->getParamType(0) != FT->getParamType(1) ||
599         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
600       return 0;
601     
602     Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
603     if (Dst == Src)      // strcpy(x,x)  -> x
604       return Src;
605     
606     // See if we can get the length of the input string.
607     uint64_t Len = GetStringLength(Src);
608     if (Len == 0) return 0;
609     
610     // We have enough information to now generate the memcpy call to do the
611     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
612     EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
613     return Dst;
614   }
615 };
616
617
618
619 //===---------------------------------------===//
620 // 'strlen' Optimizations
621
622 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
623   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
624     const FunctionType *FT = Callee->getFunctionType();
625     if (FT->getNumParams() != 1 ||
626         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
627         !isa<IntegerType>(FT->getReturnType()))
628       return 0;
629     
630     Value *Src = CI->getOperand(1);
631
632     // Constant folding: strlen("xyz") -> 3
633     if (uint64_t Len = GetStringLength(Src))
634       return ConstantInt::get(CI->getType(), Len-1);
635
636     // Handle strlen(p) != 0.
637     if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
638
639     // strlen(x) != 0 --> *x != 0
640     // strlen(x) == 0 --> *x == 0
641     return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
642   }
643 };
644
645 //===---------------------------------------===//
646 // 'memcmp' Optimizations
647
648 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
649   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
650     const FunctionType *FT = Callee->getFunctionType();
651     if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
652         !isa<PointerType>(FT->getParamType(1)) ||
653         FT->getReturnType() != Type::Int32Ty)
654       return 0;
655
656     Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
657
658     if (LHS == RHS)  // memcmp(s,s,x) -> 0
659       return Constant::getNullValue(CI->getType());
660
661     // Make sure we have a constant length.
662     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
663     if (!LenC) return 0;
664     uint64_t Len = LenC->getZExtValue();
665
666     if (Len == 0) // memcmp(s1,s2,0) -> 0
667       return Constant::getNullValue(CI->getType());
668
669     if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
670       Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
671       Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
672       return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
673     }
674
675     // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS)  != 0
676     // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS)  != 0
677     if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
678       const Type *PTy = PointerType::getUnqual(Len == 2 ?
679                                                Type::Int16Ty : Type::Int32Ty);
680       LHS = B.CreateBitCast(LHS, PTy, "tmp");
681       RHS = B.CreateBitCast(RHS, PTy, "tmp");
682       LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
683       LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
684       LHSV->setAlignment(1); RHSV->setAlignment(1);  // Unaligned loads.
685       return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
686     }
687
688     return 0;
689   }
690 };
691
692 //===---------------------------------------===//
693 // 'memcpy' Optimizations
694
695 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
696   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
697     const FunctionType *FT = Callee->getFunctionType();
698     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
699         !isa<PointerType>(FT->getParamType(0)) ||
700         !isa<PointerType>(FT->getParamType(1)) ||
701         FT->getParamType(2) != TD->getIntPtrType())
702       return 0;
703
704     // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
705     EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
706     return CI->getOperand(1);
707   }
708 };
709
710 //===---------------------------------------===//
711 // 'memmove' Optimizations
712
713 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
714   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
715     const FunctionType *FT = Callee->getFunctionType();
716     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
717         !isa<PointerType>(FT->getParamType(0)) ||
718         !isa<PointerType>(FT->getParamType(1)) ||
719         FT->getParamType(2) != TD->getIntPtrType())
720       return 0;
721
722     // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
723     Module *M = Caller->getParent();
724     Intrinsic::ID IID = Intrinsic::memmove;
725     const Type *Tys[1];
726     Tys[0] = TD->getIntPtrType();
727     Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
728     Value *Dst = CastToCStr(CI->getOperand(1), B);
729     Value *Src = CastToCStr(CI->getOperand(2), B);
730     Value *Size = CI->getOperand(3);
731     Value *Align = ConstantInt::get(Type::Int32Ty, 1);
732     B.CreateCall4(MemMove, Dst, Src, Size, Align);
733     return CI->getOperand(1);
734   }
735 };
736
737 //===---------------------------------------===//
738 // 'memset' Optimizations
739
740 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
741   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
742     const FunctionType *FT = Callee->getFunctionType();
743     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
744         !isa<PointerType>(FT->getParamType(0)) ||
745         FT->getParamType(1) != TD->getIntPtrType() ||
746         FT->getParamType(2) != TD->getIntPtrType())
747       return 0;
748
749     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
750     Module *M = Caller->getParent();
751     Intrinsic::ID IID = Intrinsic::memset;
752     const Type *Tys[1];
753     Tys[0] = TD->getIntPtrType();
754     Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
755     Value *Dst = CastToCStr(CI->getOperand(1), B);
756     Value *Val = B.CreateTrunc(CI->getOperand(2), Type::Int8Ty);
757     Value *Size = CI->getOperand(3);
758     Value *Align = ConstantInt::get(Type::Int32Ty, 1);
759     B.CreateCall4(MemSet, Dst, Val, Size, Align);
760     return CI->getOperand(1);
761   }
762 };
763
764 //===----------------------------------------------------------------------===//
765 // Math Library Optimizations
766 //===----------------------------------------------------------------------===//
767
768 //===---------------------------------------===//
769 // 'pow*' Optimizations
770
771 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
772   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
773     const FunctionType *FT = Callee->getFunctionType();
774     // Just make sure this has 2 arguments of the same FP type, which match the
775     // result type.
776     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
777         FT->getParamType(0) != FT->getParamType(1) ||
778         !FT->getParamType(0)->isFloatingPoint())
779       return 0;
780     
781     Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
782     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
783       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
784         return Op1C;
785       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
786         return EmitUnaryFloatFnCall(Op2, "exp2", B);
787     }
788     
789     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
790     if (Op2C == 0) return 0;
791     
792     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
793       return ConstantFP::get(CI->getType(), 1.0);
794     
795     if (Op2C->isExactlyValue(0.5)) {
796       // FIXME: This is not safe for -0.0 and -inf.  This can only be done when
797       // 'unsafe' math optimizations are allowed.
798       // x    pow(x, 0.5)  sqrt(x)
799       // ---------------------------------------------
800       // -0.0    +0.0       -0.0
801       // -inf    +inf       NaN
802 #if 0
803       // pow(x, 0.5) -> sqrt(x)
804       return B.CreateCall(get_sqrt(), Op1, "sqrt");
805 #endif
806     }
807     
808     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
809       return Op1;
810     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
811       return B.CreateMul(Op1, Op1, "pow2");
812     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
813       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
814     return 0;
815   }
816 };
817
818 //===---------------------------------------===//
819 // 'exp2' Optimizations
820
821 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
822   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
823     const FunctionType *FT = Callee->getFunctionType();
824     // Just make sure this has 1 argument of FP type, which matches the
825     // result type.
826     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
827         !FT->getParamType(0)->isFloatingPoint())
828       return 0;
829     
830     Value *Op = CI->getOperand(1);
831     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
832     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
833     Value *LdExpArg = 0;
834     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
835       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
836         LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
837     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
838       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
839         LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
840     }
841     
842     if (LdExpArg) {
843       const char *Name;
844       if (Op->getType() == Type::FloatTy)
845         Name = "ldexpf";
846       else if (Op->getType() == Type::DoubleTy)
847         Name = "ldexp";
848       else
849         Name = "ldexpl";
850
851       Constant *One = ConstantFP::get(APFloat(1.0f));
852       if (Op->getType() != Type::FloatTy)
853         One = ConstantExpr::getFPExtend(One, Op->getType());
854
855       Module *M = Caller->getParent();
856       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
857                                              Op->getType(), Type::Int32Ty,NULL);
858       return B.CreateCall2(Callee, One, LdExpArg);
859     }
860     return 0;
861   }
862 };
863     
864
865 //===---------------------------------------===//
866 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
867
868 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
869   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
870     const FunctionType *FT = Callee->getFunctionType();
871     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
872         FT->getParamType(0) != Type::DoubleTy)
873       return 0;
874     
875     // If this is something like 'floor((double)floatval)', convert to floorf.
876     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
877     if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
878       return 0;
879
880     // floor((double)floatval) -> (double)floorf(floatval)
881     Value *V = Cast->getOperand(0);
882     V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
883     return B.CreateFPExt(V, Type::DoubleTy);
884   }
885 };
886
887 //===----------------------------------------------------------------------===//
888 // Integer Optimizations
889 //===----------------------------------------------------------------------===//
890
891 //===---------------------------------------===//
892 // 'ffs*' Optimizations
893
894 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
895   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
896     const FunctionType *FT = Callee->getFunctionType();
897     // Just make sure this has 2 arguments of the same FP type, which match the
898     // result type.
899     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
900         !isa<IntegerType>(FT->getParamType(0)))
901       return 0;
902     
903     Value *Op = CI->getOperand(1);
904     
905     // Constant fold.
906     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
907       if (CI->getValue() == 0)  // ffs(0) -> 0.
908         return Constant::getNullValue(CI->getType());
909       return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
910                               CI->getValue().countTrailingZeros()+1);
911     }
912     
913     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
914     const Type *ArgType = Op->getType();
915     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
916                                          Intrinsic::cttz, &ArgType, 1);
917     Value *V = B.CreateCall(F, Op, "cttz");
918     V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
919     V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
920     
921     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
922     return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
923   }
924 };
925
926 //===---------------------------------------===//
927 // 'isdigit' Optimizations
928
929 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
930   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
931     const FunctionType *FT = Callee->getFunctionType();
932     // We require integer(i32)
933     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
934         FT->getParamType(0) != Type::Int32Ty)
935       return 0;
936     
937     // isdigit(c) -> (c-'0') <u 10
938     Value *Op = CI->getOperand(1);
939     Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
940     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
941     return B.CreateZExt(Op, CI->getType());
942   }
943 };
944
945 //===---------------------------------------===//
946 // 'isascii' Optimizations
947
948 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
949   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
950     const FunctionType *FT = Callee->getFunctionType();
951     // We require integer(i32)
952     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
953         FT->getParamType(0) != Type::Int32Ty)
954       return 0;
955     
956     // isascii(c) -> c <u 128
957     Value *Op = CI->getOperand(1);
958     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
959     return B.CreateZExt(Op, CI->getType());
960   }
961 };
962   
963 //===---------------------------------------===//
964 // 'abs', 'labs', 'llabs' Optimizations
965
966 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
967   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
968     const FunctionType *FT = Callee->getFunctionType();
969     // We require integer(integer) where the types agree.
970     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
971         FT->getParamType(0) != FT->getReturnType())
972       return 0;
973     
974     // abs(x) -> x >s -1 ? x : -x
975     Value *Op = CI->getOperand(1);
976     Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
977                                  "ispos");
978     Value *Neg = B.CreateNeg(Op, "neg");
979     return B.CreateSelect(Pos, Op, Neg);
980   }
981 };
982   
983
984 //===---------------------------------------===//
985 // 'toascii' Optimizations
986
987 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
988   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
989     const FunctionType *FT = Callee->getFunctionType();
990     // We require i32(i32)
991     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
992         FT->getParamType(0) != Type::Int32Ty)
993       return 0;
994     
995     // isascii(c) -> c & 0x7f
996     return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
997   }
998 };
999
1000 //===----------------------------------------------------------------------===//
1001 // Formatting and IO Optimizations
1002 //===----------------------------------------------------------------------===//
1003
1004 //===---------------------------------------===//
1005 // 'printf' Optimizations
1006
1007 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1008   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1009     // Require one fixed pointer argument and an integer/void result.
1010     const FunctionType *FT = Callee->getFunctionType();
1011     if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1012         !(isa<IntegerType>(FT->getReturnType()) ||
1013           FT->getReturnType() == Type::VoidTy))
1014       return 0;
1015     
1016     // Check for a fixed format string.
1017     std::string FormatStr;
1018     if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1019       return 0;
1020
1021     // Empty format string -> noop.
1022     if (FormatStr.empty())  // Tolerate printf's declared void.
1023       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
1024     
1025     // printf("x") -> putchar('x'), even for '%'.
1026     if (FormatStr.size() == 1) {
1027       EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1028       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1029     }
1030     
1031     // printf("foo\n") --> puts("foo")
1032     if (FormatStr[FormatStr.size()-1] == '\n' &&
1033         FormatStr.find('%') == std::string::npos) {  // no format characters.
1034       // Create a string literal with no \n on it.  We expect the constant merge
1035       // pass to be run after this pass, to merge duplicate strings.
1036       FormatStr.erase(FormatStr.end()-1);
1037       Constant *C = ConstantArray::get(FormatStr, true);
1038       C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
1039                              C, "str", Callee->getParent());
1040       EmitPutS(C, B);
1041       return CI->use_empty() ? (Value*)CI : 
1042                           ConstantInt::get(CI->getType(), FormatStr.size()+1);
1043     }
1044     
1045     // Optimize specific format strings.
1046     // printf("%c", chr) --> putchar(*(i8*)dst)
1047     if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1048         isa<IntegerType>(CI->getOperand(2)->getType())) {
1049       EmitPutChar(CI->getOperand(2), B);
1050       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1051     }
1052     
1053     // printf("%s\n", str) --> puts(str)
1054     if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1055         isa<PointerType>(CI->getOperand(2)->getType()) &&
1056         CI->use_empty()) {
1057       EmitPutS(CI->getOperand(2), B);
1058       return CI;
1059     }
1060     return 0;
1061   }
1062 };
1063
1064 //===---------------------------------------===//
1065 // 'sprintf' Optimizations
1066
1067 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1068   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1069     // Require two fixed pointer arguments and an integer result.
1070     const FunctionType *FT = Callee->getFunctionType();
1071     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1072         !isa<PointerType>(FT->getParamType(1)) ||
1073         !isa<IntegerType>(FT->getReturnType()))
1074       return 0;
1075
1076     // Check for a fixed format string.
1077     std::string FormatStr;
1078     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1079       return 0;
1080     
1081     // If we just have a format string (nothing else crazy) transform it.
1082     if (CI->getNumOperands() == 3) {
1083       // Make sure there's no % in the constant array.  We could try to handle
1084       // %% -> % in the future if we cared.
1085       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1086         if (FormatStr[i] == '%')
1087           return 0; // we found a format specifier, bail out.
1088       
1089       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1090       EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1091                  ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1092       return ConstantInt::get(CI->getType(), FormatStr.size());
1093     }
1094     
1095     // The remaining optimizations require the format string to be "%s" or "%c"
1096     // and have an extra operand.
1097     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1098       return 0;
1099     
1100     // Decode the second character of the format string.
1101     if (FormatStr[1] == 'c') {
1102       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1103       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1104       Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1105       Value *Ptr = CastToCStr(CI->getOperand(1), B);
1106       B.CreateStore(V, Ptr);
1107       Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1108       B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1109       
1110       return ConstantInt::get(CI->getType(), 1);
1111     }
1112     
1113     if (FormatStr[1] == 's') {
1114       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1115       if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1116
1117       Value *Len = EmitStrLen(CI->getOperand(3), B);
1118       Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1119                                   "leninc");
1120       EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1121       
1122       // The sprintf result is the unincremented number of bytes in the string.
1123       return B.CreateIntCast(Len, CI->getType(), false);
1124     }
1125     return 0;
1126   }
1127 };
1128
1129 //===---------------------------------------===//
1130 // 'fwrite' Optimizations
1131
1132 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1133   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1134     // Require a pointer, an integer, an integer, a pointer, returning integer.
1135     const FunctionType *FT = Callee->getFunctionType();
1136     if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1137         !isa<IntegerType>(FT->getParamType(1)) ||
1138         !isa<IntegerType>(FT->getParamType(2)) ||
1139         !isa<PointerType>(FT->getParamType(3)) ||
1140         !isa<IntegerType>(FT->getReturnType()))
1141       return 0;
1142     
1143     // Get the element size and count.
1144     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1145     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1146     if (!SizeC || !CountC) return 0;
1147     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1148     
1149     // If this is writing zero records, remove the call (it's a noop).
1150     if (Bytes == 0)
1151       return ConstantInt::get(CI->getType(), 0);
1152     
1153     // If this is writing one byte, turn it into fputc.
1154     if (Bytes == 1) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
1155       Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1156       EmitFPutC(Char, CI->getOperand(4), B);
1157       return ConstantInt::get(CI->getType(), 1);
1158     }
1159
1160     return 0;
1161   }
1162 };
1163
1164 //===---------------------------------------===//
1165 // 'fputs' Optimizations
1166
1167 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1168   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1169     // Require two pointers.  Also, we can't optimize if return value is used.
1170     const FunctionType *FT = Callee->getFunctionType();
1171     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1172         !isa<PointerType>(FT->getParamType(1)) ||
1173         !CI->use_empty())
1174       return 0;
1175     
1176     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1177     uint64_t Len = GetStringLength(CI->getOperand(1));
1178     if (!Len) return 0;
1179     EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1180                CI->getOperand(2), B);
1181     return CI;  // Known to have no uses (see above).
1182   }
1183 };
1184
1185 //===---------------------------------------===//
1186 // 'fprintf' Optimizations
1187
1188 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1189   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1190     // Require two fixed paramters as pointers and integer result.
1191     const FunctionType *FT = Callee->getFunctionType();
1192     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1193         !isa<PointerType>(FT->getParamType(1)) ||
1194         !isa<IntegerType>(FT->getReturnType()))
1195       return 0;
1196     
1197     // All the optimizations depend on the format string.
1198     std::string FormatStr;
1199     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1200       return 0;
1201
1202     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1203     if (CI->getNumOperands() == 3) {
1204       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1205         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
1206           return 0; // We found a format specifier.
1207       
1208       EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1209                                                      FormatStr.size()),
1210                  CI->getOperand(1), B);
1211       return ConstantInt::get(CI->getType(), FormatStr.size());
1212     }
1213     
1214     // The remaining optimizations require the format string to be "%s" or "%c"
1215     // and have an extra operand.
1216     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1217       return 0;
1218     
1219     // Decode the second character of the format string.
1220     if (FormatStr[1] == 'c') {
1221       // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1222       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1223       EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1224       return ConstantInt::get(CI->getType(), 1);
1225     }
1226     
1227     if (FormatStr[1] == 's') {
1228       // fprintf(F, "%s", str) -> fputs(str, F)
1229       if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1230         return 0;
1231       EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1232       return CI;
1233     }
1234     return 0;
1235   }
1236 };
1237
1238 } // end anonymous namespace.
1239
1240 //===----------------------------------------------------------------------===//
1241 // SimplifyLibCalls Pass Implementation
1242 //===----------------------------------------------------------------------===//
1243
1244 namespace {
1245   /// This pass optimizes well known library functions from libc and libm.
1246   ///
1247   class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1248     StringMap<LibCallOptimization*> Optimizations;
1249     // Miscellaneous LibCall Optimizations
1250     ExitOpt Exit; 
1251     // String and Memory LibCall Optimizations
1252     StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1253     StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt  MemCpy;
1254     MemMoveOpt MemMove; MemSetOpt MemSet;
1255     // Math Library Optimizations
1256     PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1257     // Integer Optimizations
1258     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1259     ToAsciiOpt ToAscii;
1260     // Formatting and IO Optimizations
1261     SPrintFOpt SPrintF; PrintFOpt PrintF;
1262     FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1263   public:
1264     static char ID; // Pass identification
1265     SimplifyLibCalls() : FunctionPass(&ID) {}
1266
1267     void InitOptimizations();
1268     bool runOnFunction(Function &F);
1269
1270     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1271       AU.addRequired<TargetData>();
1272     }
1273   };
1274   char SimplifyLibCalls::ID = 0;
1275 } // end anonymous namespace.
1276
1277 static RegisterPass<SimplifyLibCalls>
1278 X("simplify-libcalls", "Simplify well-known library calls");
1279
1280 // Public interface to the Simplify LibCalls pass.
1281 FunctionPass *llvm::createSimplifyLibCallsPass() {
1282   return new SimplifyLibCalls(); 
1283 }
1284
1285 /// Optimizations - Populate the Optimizations map with all the optimizations
1286 /// we know.
1287 void SimplifyLibCalls::InitOptimizations() {
1288   // Miscellaneous LibCall Optimizations
1289   Optimizations["exit"] = &Exit;
1290   
1291   // String and Memory LibCall Optimizations
1292   Optimizations["strcat"] = &StrCat;
1293   Optimizations["strchr"] = &StrChr;
1294   Optimizations["strcmp"] = &StrCmp;
1295   Optimizations["strncmp"] = &StrNCmp;
1296   Optimizations["strcpy"] = &StrCpy;
1297   Optimizations["strlen"] = &StrLen;
1298   Optimizations["memcmp"] = &MemCmp;
1299   Optimizations["memcpy"] = &MemCpy;
1300   Optimizations["memmove"] = &MemMove;
1301   Optimizations["memset"] = &MemSet;
1302   
1303   // Math Library Optimizations
1304   Optimizations["powf"] = &Pow;
1305   Optimizations["pow"] = &Pow;
1306   Optimizations["powl"] = &Pow;
1307   Optimizations["llvm.pow.f32"] = &Pow;
1308   Optimizations["llvm.pow.f64"] = &Pow;
1309   Optimizations["llvm.pow.f80"] = &Pow;
1310   Optimizations["llvm.pow.f128"] = &Pow;
1311   Optimizations["llvm.pow.ppcf128"] = &Pow;
1312   Optimizations["exp2l"] = &Exp2;
1313   Optimizations["exp2"] = &Exp2;
1314   Optimizations["exp2f"] = &Exp2;
1315   Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1316   Optimizations["llvm.exp2.f128"] = &Exp2;
1317   Optimizations["llvm.exp2.f80"] = &Exp2;
1318   Optimizations["llvm.exp2.f64"] = &Exp2;
1319   Optimizations["llvm.exp2.f32"] = &Exp2;
1320   
1321 #ifdef HAVE_FLOORF
1322   Optimizations["floor"] = &UnaryDoubleFP;
1323 #endif
1324 #ifdef HAVE_CEILF
1325   Optimizations["ceil"] = &UnaryDoubleFP;
1326 #endif
1327 #ifdef HAVE_ROUNDF
1328   Optimizations["round"] = &UnaryDoubleFP;
1329 #endif
1330 #ifdef HAVE_RINTF
1331   Optimizations["rint"] = &UnaryDoubleFP;
1332 #endif
1333 #ifdef HAVE_NEARBYINTF
1334   Optimizations["nearbyint"] = &UnaryDoubleFP;
1335 #endif
1336   
1337   // Integer Optimizations
1338   Optimizations["ffs"] = &FFS;
1339   Optimizations["ffsl"] = &FFS;
1340   Optimizations["ffsll"] = &FFS;
1341   Optimizations["abs"] = &Abs;
1342   Optimizations["labs"] = &Abs;
1343   Optimizations["llabs"] = &Abs;
1344   Optimizations["isdigit"] = &IsDigit;
1345   Optimizations["isascii"] = &IsAscii;
1346   Optimizations["toascii"] = &ToAscii;
1347   
1348   // Formatting and IO Optimizations
1349   Optimizations["sprintf"] = &SPrintF;
1350   Optimizations["printf"] = &PrintF;
1351   Optimizations["fwrite"] = &FWrite;
1352   Optimizations["fputs"] = &FPuts;
1353   Optimizations["fprintf"] = &FPrintF;
1354 }
1355
1356
1357 /// runOnFunction - Top level algorithm.
1358 ///
1359 bool SimplifyLibCalls::runOnFunction(Function &F) {
1360   if (Optimizations.empty())
1361     InitOptimizations();
1362   
1363   const TargetData &TD = getAnalysis<TargetData>();
1364   
1365   IRBuilder<> Builder;
1366
1367   bool Changed = false;
1368   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1369     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1370       // Ignore non-calls.
1371       CallInst *CI = dyn_cast<CallInst>(I++);
1372       if (!CI) continue;
1373       
1374       // Ignore indirect calls and calls to non-external functions.
1375       Function *Callee = CI->getCalledFunction();
1376       if (Callee == 0 || !Callee->isDeclaration() ||
1377           !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1378         continue;
1379       
1380       // Ignore unknown calls.
1381       const char *CalleeName = Callee->getNameStart();
1382       StringMap<LibCallOptimization*>::iterator OMI =
1383         Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1384       if (OMI == Optimizations.end()) continue;
1385       
1386       // Set the builder to the instruction after the call.
1387       Builder.SetInsertPoint(BB, I);
1388       
1389       // Try to optimize this call.
1390       Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1391       if (Result == 0) continue;
1392
1393       DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1394             DOUT << "  into: " << *Result << "\n");
1395       
1396       // Something changed!
1397       Changed = true;
1398       ++NumSimplified;
1399       
1400       // Inspect the instruction after the call (which was potentially just
1401       // added) next.
1402       I = CI; ++I;
1403       
1404       if (CI != Result && !CI->use_empty()) {
1405         CI->replaceAllUsesWith(Result);
1406         if (!Result->hasName())
1407           Result->takeName(CI);
1408       }
1409       CI->eraseFromParent();
1410     }
1411   }
1412   return Changed;
1413 }
1414
1415
1416 // TODO:
1417 //   Additional cases that we need to add to this file:
1418 //
1419 // cbrt:
1420 //   * cbrt(expN(X))  -> expN(x/3)
1421 //   * cbrt(sqrt(x))  -> pow(x,1/6)
1422 //   * cbrt(sqrt(x))  -> pow(x,1/9)
1423 //
1424 // cos, cosf, cosl:
1425 //   * cos(-x)  -> cos(x)
1426 //
1427 // exp, expf, expl:
1428 //   * exp(log(x))  -> x
1429 //
1430 // log, logf, logl:
1431 //   * log(exp(x))   -> x
1432 //   * log(x**y)     -> y*log(x)
1433 //   * log(exp(y))   -> y*log(e)
1434 //   * log(exp2(y))  -> y*log(2)
1435 //   * log(exp10(y)) -> y*log(10)
1436 //   * log(sqrt(x))  -> 0.5*log(x)
1437 //   * log(pow(x,y)) -> y*log(x)
1438 //
1439 // lround, lroundf, lroundl:
1440 //   * lround(cnst) -> cnst'
1441 //
1442 // memcmp:
1443 //   * memcmp(x,y,l)   -> cnst
1444 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1445 //
1446 // pow, powf, powl:
1447 //   * pow(exp(x),y)  -> exp(x*y)
1448 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1449 //   * pow(pow(x,y),z)-> pow(x,y*z)
1450 //
1451 // puts:
1452 //   * puts("") -> putchar("\n")
1453 //
1454 // round, roundf, roundl:
1455 //   * round(cnst) -> cnst'
1456 //
1457 // signbit:
1458 //   * signbit(cnst) -> cnst'
1459 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1460 //
1461 // sqrt, sqrtf, sqrtl:
1462 //   * sqrt(expN(x))  -> expN(x*0.5)
1463 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1464 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1465 //
1466 // stpcpy:
1467 //   * stpcpy(str, "literal") ->
1468 //           llvm.memcpy(str,"literal",strlen("literal")+1,1)
1469 // strrchr:
1470 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
1471 //      (if c is a constant integer and s is a constant string)
1472 //   * strrchr(s1,0) -> strchr(s1,0)
1473 //
1474 // strncat:
1475 //   * strncat(x,y,0) -> x
1476 //   * strncat(x,y,0) -> x (if strlen(y) = 0)
1477 //   * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1478 //
1479 // strncpy:
1480 //   * strncpy(d,s,0) -> d
1481 //   * strncpy(d,s,l) -> memcpy(d,s,l,1)
1482 //      (if s and l are constants)
1483 //
1484 // strpbrk:
1485 //   * strpbrk(s,a) -> offset_in_for(s,a)
1486 //      (if s and a are both constant strings)
1487 //   * strpbrk(s,"") -> 0
1488 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1489 //
1490 // strspn, strcspn:
1491 //   * strspn(s,a)   -> const_int (if both args are constant)
1492 //   * strspn("",a)  -> 0
1493 //   * strspn(s,"")  -> 0
1494 //   * strcspn(s,a)  -> const_int (if both args are constant)
1495 //   * strcspn("",a) -> 0
1496 //   * strcspn(s,"") -> strlen(a)
1497 //
1498 // strstr:
1499 //   * strstr(x,x)  -> x
1500 //   * strstr(s1,s2) -> offset_of_s2_in(s1)
1501 //       (if s1 and s2 are constant strings)
1502 //
1503 // tan, tanf, tanl:
1504 //   * tan(atan(x)) -> x
1505 //
1506 // trunc, truncf, truncl:
1507 //   * trunc(cnst) -> cnst'
1508 //
1509 //