89527477a8046983a25471d306769d6d75a5288b
[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 // Math Library Optimizations
712 //===----------------------------------------------------------------------===//
713
714 //===---------------------------------------===//
715 // 'pow*' Optimizations
716
717 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
718   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
719     const FunctionType *FT = Callee->getFunctionType();
720     // Just make sure this has 2 arguments of the same FP type, which match the
721     // result type.
722     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
723         FT->getParamType(0) != FT->getParamType(1) ||
724         !FT->getParamType(0)->isFloatingPoint())
725       return 0;
726     
727     Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
728     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
729       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
730         return Op1C;
731       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
732         return EmitUnaryFloatFnCall(Op2, "exp2", B);
733     }
734     
735     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
736     if (Op2C == 0) return 0;
737     
738     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
739       return ConstantFP::get(CI->getType(), 1.0);
740     
741     if (Op2C->isExactlyValue(0.5)) {
742       // FIXME: This is not safe for -0.0 and -inf.  This can only be done when
743       // 'unsafe' math optimizations are allowed.
744       // x    pow(x, 0.5)  sqrt(x)
745       // ---------------------------------------------
746       // -0.0    +0.0       -0.0
747       // -inf    +inf       NaN
748 #if 0
749       // pow(x, 0.5) -> sqrt(x)
750       return B.CreateCall(get_sqrt(), Op1, "sqrt");
751 #endif
752     }
753     
754     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
755       return Op1;
756     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
757       return B.CreateMul(Op1, Op1, "pow2");
758     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
759       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
760     return 0;
761   }
762 };
763
764 //===---------------------------------------===//
765 // 'exp2' Optimizations
766
767 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
768   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
769     const FunctionType *FT = Callee->getFunctionType();
770     // Just make sure this has 1 argument of FP type, which matches the
771     // result type.
772     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
773         !FT->getParamType(0)->isFloatingPoint())
774       return 0;
775     
776     Value *Op = CI->getOperand(1);
777     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
778     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
779     Value *LdExpArg = 0;
780     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
781       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
782         LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
783     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
784       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
785         LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
786     }
787     
788     if (LdExpArg) {
789       const char *Name;
790       if (Op->getType() == Type::FloatTy)
791         Name = "ldexpf";
792       else if (Op->getType() == Type::DoubleTy)
793         Name = "ldexp";
794       else
795         Name = "ldexpl";
796
797       Constant *One = ConstantFP::get(APFloat(1.0f));
798       if (Op->getType() != Type::FloatTy)
799         One = ConstantExpr::getFPExtend(One, Op->getType());
800
801       Module *M = Caller->getParent();
802       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
803                                              Op->getType(), Type::Int32Ty,NULL);
804       return B.CreateCall2(Callee, One, LdExpArg);
805     }
806     return 0;
807   }
808 };
809     
810
811 //===---------------------------------------===//
812 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
813
814 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
815   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
816     const FunctionType *FT = Callee->getFunctionType();
817     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
818         FT->getParamType(0) != Type::DoubleTy)
819       return 0;
820     
821     // If this is something like 'floor((double)floatval)', convert to floorf.
822     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
823     if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
824       return 0;
825
826     // floor((double)floatval) -> (double)floorf(floatval)
827     Value *V = Cast->getOperand(0);
828     V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
829     return B.CreateFPExt(V, Type::DoubleTy);
830   }
831 };
832
833 //===----------------------------------------------------------------------===//
834 // Integer Optimizations
835 //===----------------------------------------------------------------------===//
836
837 //===---------------------------------------===//
838 // 'ffs*' Optimizations
839
840 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
841   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
842     const FunctionType *FT = Callee->getFunctionType();
843     // Just make sure this has 2 arguments of the same FP type, which match the
844     // result type.
845     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
846         !isa<IntegerType>(FT->getParamType(0)))
847       return 0;
848     
849     Value *Op = CI->getOperand(1);
850     
851     // Constant fold.
852     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
853       if (CI->getValue() == 0)  // ffs(0) -> 0.
854         return Constant::getNullValue(CI->getType());
855       return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
856                               CI->getValue().countTrailingZeros()+1);
857     }
858     
859     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
860     const Type *ArgType = Op->getType();
861     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
862                                          Intrinsic::cttz, &ArgType, 1);
863     Value *V = B.CreateCall(F, Op, "cttz");
864     V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
865     V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
866     
867     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
868     return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
869   }
870 };
871
872 //===---------------------------------------===//
873 // 'isdigit' Optimizations
874
875 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
876   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
877     const FunctionType *FT = Callee->getFunctionType();
878     // We require integer(i32)
879     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
880         FT->getParamType(0) != Type::Int32Ty)
881       return 0;
882     
883     // isdigit(c) -> (c-'0') <u 10
884     Value *Op = CI->getOperand(1);
885     Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
886     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
887     return B.CreateZExt(Op, CI->getType());
888   }
889 };
890
891 //===---------------------------------------===//
892 // 'isascii' Optimizations
893
894 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
895   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
896     const FunctionType *FT = Callee->getFunctionType();
897     // We require integer(i32)
898     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
899         FT->getParamType(0) != Type::Int32Ty)
900       return 0;
901     
902     // isascii(c) -> c <u 128
903     Value *Op = CI->getOperand(1);
904     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
905     return B.CreateZExt(Op, CI->getType());
906   }
907 };
908   
909 //===---------------------------------------===//
910 // 'abs', 'labs', 'llabs' Optimizations
911
912 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
913   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
914     const FunctionType *FT = Callee->getFunctionType();
915     // We require integer(integer) where the types agree.
916     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
917         FT->getParamType(0) != FT->getReturnType())
918       return 0;
919     
920     // abs(x) -> x >s -1 ? x : -x
921     Value *Op = CI->getOperand(1);
922     Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
923                                  "ispos");
924     Value *Neg = B.CreateNeg(Op, "neg");
925     return B.CreateSelect(Pos, Op, Neg);
926   }
927 };
928   
929
930 //===---------------------------------------===//
931 // 'toascii' Optimizations
932
933 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
934   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
935     const FunctionType *FT = Callee->getFunctionType();
936     // We require i32(i32)
937     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
938         FT->getParamType(0) != Type::Int32Ty)
939       return 0;
940     
941     // isascii(c) -> c & 0x7f
942     return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
943   }
944 };
945
946 //===----------------------------------------------------------------------===//
947 // Formatting and IO Optimizations
948 //===----------------------------------------------------------------------===//
949
950 //===---------------------------------------===//
951 // 'printf' Optimizations
952
953 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
954   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
955     // Require one fixed pointer argument and an integer/void result.
956     const FunctionType *FT = Callee->getFunctionType();
957     if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
958         !(isa<IntegerType>(FT->getReturnType()) ||
959           FT->getReturnType() == Type::VoidTy))
960       return 0;
961     
962     // Check for a fixed format string.
963     std::string FormatStr;
964     if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
965       return 0;
966
967     // Empty format string -> noop.
968     if (FormatStr.empty())  // Tolerate printf's declared void.
969       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
970     
971     // printf("x") -> putchar('x'), even for '%'.
972     if (FormatStr.size() == 1) {
973       EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
974       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
975     }
976     
977     // printf("foo\n") --> puts("foo")
978     if (FormatStr[FormatStr.size()-1] == '\n' &&
979         FormatStr.find('%') == std::string::npos) {  // no format characters.
980       // Create a string literal with no \n on it.  We expect the constant merge
981       // pass to be run after this pass, to merge duplicate strings.
982       FormatStr.erase(FormatStr.end()-1);
983       Constant *C = ConstantArray::get(FormatStr, true);
984       C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
985                              C, "str", Callee->getParent());
986       EmitPutS(C, B);
987       return CI->use_empty() ? (Value*)CI : 
988                           ConstantInt::get(CI->getType(), FormatStr.size()+1);
989     }
990     
991     // Optimize specific format strings.
992     // printf("%c", chr) --> putchar(*(i8*)dst)
993     if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
994         isa<IntegerType>(CI->getOperand(2)->getType())) {
995       EmitPutChar(CI->getOperand(2), B);
996       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
997     }
998     
999     // printf("%s\n", str) --> puts(str)
1000     if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1001         isa<PointerType>(CI->getOperand(2)->getType()) &&
1002         CI->use_empty()) {
1003       EmitPutS(CI->getOperand(2), B);
1004       return CI;
1005     }
1006     return 0;
1007   }
1008 };
1009
1010 //===---------------------------------------===//
1011 // 'sprintf' Optimizations
1012
1013 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1014   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1015     // Require two fixed pointer arguments and an integer result.
1016     const FunctionType *FT = Callee->getFunctionType();
1017     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1018         !isa<PointerType>(FT->getParamType(1)) ||
1019         !isa<IntegerType>(FT->getReturnType()))
1020       return 0;
1021
1022     // Check for a fixed format string.
1023     std::string FormatStr;
1024     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1025       return 0;
1026     
1027     // If we just have a format string (nothing else crazy) transform it.
1028     if (CI->getNumOperands() == 3) {
1029       // Make sure there's no % in the constant array.  We could try to handle
1030       // %% -> % in the future if we cared.
1031       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1032         if (FormatStr[i] == '%')
1033           return 0; // we found a format specifier, bail out.
1034       
1035       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1036       EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1037                  ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1038       return ConstantInt::get(CI->getType(), FormatStr.size());
1039     }
1040     
1041     // The remaining optimizations require the format string to be "%s" or "%c"
1042     // and have an extra operand.
1043     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1044       return 0;
1045     
1046     // Decode the second character of the format string.
1047     if (FormatStr[1] == 'c') {
1048       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1049       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1050       Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1051       Value *Ptr = CastToCStr(CI->getOperand(1), B);
1052       B.CreateStore(V, Ptr);
1053       Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1054       B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1055       
1056       return ConstantInt::get(CI->getType(), 1);
1057     }
1058     
1059     if (FormatStr[1] == 's') {
1060       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1061       if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1062
1063       Value *Len = EmitStrLen(CI->getOperand(3), B);
1064       Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1065                                   "leninc");
1066       EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1067       
1068       // The sprintf result is the unincremented number of bytes in the string.
1069       return B.CreateIntCast(Len, CI->getType(), false);
1070     }
1071     return 0;
1072   }
1073 };
1074
1075 //===---------------------------------------===//
1076 // 'fwrite' Optimizations
1077
1078 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1079   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1080     // Require a pointer, an integer, an integer, a pointer, returning integer.
1081     const FunctionType *FT = Callee->getFunctionType();
1082     if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1083         !isa<IntegerType>(FT->getParamType(1)) ||
1084         !isa<IntegerType>(FT->getParamType(2)) ||
1085         !isa<PointerType>(FT->getParamType(3)) ||
1086         !isa<IntegerType>(FT->getReturnType()))
1087       return 0;
1088     
1089     // Get the element size and count.
1090     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1091     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1092     if (!SizeC || !CountC) return 0;
1093     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1094     
1095     // If this is writing zero records, remove the call (it's a noop).
1096     if (Bytes == 0)
1097       return ConstantInt::get(CI->getType(), 0);
1098     
1099     // If this is writing one byte, turn it into fputc.
1100     if (Bytes == 1) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
1101       Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1102       EmitFPutC(Char, CI->getOperand(4), B);
1103       return ConstantInt::get(CI->getType(), 1);
1104     }
1105
1106     return 0;
1107   }
1108 };
1109
1110 //===---------------------------------------===//
1111 // 'fputs' Optimizations
1112
1113 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1114   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1115     // Require two pointers.  Also, we can't optimize if return value is used.
1116     const FunctionType *FT = Callee->getFunctionType();
1117     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1118         !isa<PointerType>(FT->getParamType(1)) ||
1119         !CI->use_empty())
1120       return 0;
1121     
1122     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1123     uint64_t Len = GetStringLength(CI->getOperand(1));
1124     if (!Len) return 0;
1125     EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1126                CI->getOperand(2), B);
1127     return CI;  // Known to have no uses (see above).
1128   }
1129 };
1130
1131 //===---------------------------------------===//
1132 // 'fprintf' Optimizations
1133
1134 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1135   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1136     // Require two fixed paramters as pointers and integer result.
1137     const FunctionType *FT = Callee->getFunctionType();
1138     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1139         !isa<PointerType>(FT->getParamType(1)) ||
1140         !isa<IntegerType>(FT->getReturnType()))
1141       return 0;
1142     
1143     // All the optimizations depend on the format string.
1144     std::string FormatStr;
1145     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1146       return 0;
1147
1148     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1149     if (CI->getNumOperands() == 3) {
1150       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1151         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
1152           return 0; // We found a format specifier.
1153       
1154       EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1155                                                      FormatStr.size()),
1156                  CI->getOperand(1), B);
1157       return ConstantInt::get(CI->getType(), FormatStr.size());
1158     }
1159     
1160     // The remaining optimizations require the format string to be "%s" or "%c"
1161     // and have an extra operand.
1162     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1163       return 0;
1164     
1165     // Decode the second character of the format string.
1166     if (FormatStr[1] == 'c') {
1167       // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1168       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1169       EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1170       return ConstantInt::get(CI->getType(), 1);
1171     }
1172     
1173     if (FormatStr[1] == 's') {
1174       // fprintf(F, "%s", str) -> fputs(str, F)
1175       if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1176         return 0;
1177       EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1178       return CI;
1179     }
1180     return 0;
1181   }
1182 };
1183
1184 } // end anonymous namespace.
1185
1186 //===----------------------------------------------------------------------===//
1187 // SimplifyLibCalls Pass Implementation
1188 //===----------------------------------------------------------------------===//
1189
1190 namespace {
1191   /// This pass optimizes well known library functions from libc and libm.
1192   ///
1193   class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1194     StringMap<LibCallOptimization*> Optimizations;
1195     // Miscellaneous LibCall Optimizations
1196     ExitOpt Exit; 
1197     // String and Memory LibCall Optimizations
1198     StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1199     StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt  MemCpy;
1200     // Math Library Optimizations
1201     PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1202     // Integer Optimizations
1203     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1204     ToAsciiOpt ToAscii;
1205     // Formatting and IO Optimizations
1206     SPrintFOpt SPrintF; PrintFOpt PrintF;
1207     FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1208   public:
1209     static char ID; // Pass identification
1210     SimplifyLibCalls() : FunctionPass(&ID) {}
1211
1212     void InitOptimizations();
1213     bool runOnFunction(Function &F);
1214
1215     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1216       AU.addRequired<TargetData>();
1217     }
1218   };
1219   char SimplifyLibCalls::ID = 0;
1220 } // end anonymous namespace.
1221
1222 static RegisterPass<SimplifyLibCalls>
1223 X("simplify-libcalls", "Simplify well-known library calls");
1224
1225 // Public interface to the Simplify LibCalls pass.
1226 FunctionPass *llvm::createSimplifyLibCallsPass() {
1227   return new SimplifyLibCalls(); 
1228 }
1229
1230 /// Optimizations - Populate the Optimizations map with all the optimizations
1231 /// we know.
1232 void SimplifyLibCalls::InitOptimizations() {
1233   // Miscellaneous LibCall Optimizations
1234   Optimizations["exit"] = &Exit;
1235   
1236   // String and Memory LibCall Optimizations
1237   Optimizations["strcat"] = &StrCat;
1238   Optimizations["strchr"] = &StrChr;
1239   Optimizations["strcmp"] = &StrCmp;
1240   Optimizations["strncmp"] = &StrNCmp;
1241   Optimizations["strcpy"] = &StrCpy;
1242   Optimizations["strlen"] = &StrLen;
1243   Optimizations["memcmp"] = &MemCmp;
1244   Optimizations["memcpy"] = &MemCpy;
1245   
1246   // Math Library Optimizations
1247   Optimizations["powf"] = &Pow;
1248   Optimizations["pow"] = &Pow;
1249   Optimizations["powl"] = &Pow;
1250   Optimizations["llvm.pow.f32"] = &Pow;
1251   Optimizations["llvm.pow.f64"] = &Pow;
1252   Optimizations["llvm.pow.f80"] = &Pow;
1253   Optimizations["llvm.pow.f128"] = &Pow;
1254   Optimizations["llvm.pow.ppcf128"] = &Pow;
1255   Optimizations["exp2l"] = &Exp2;
1256   Optimizations["exp2"] = &Exp2;
1257   Optimizations["exp2f"] = &Exp2;
1258   Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1259   Optimizations["llvm.exp2.f128"] = &Exp2;
1260   Optimizations["llvm.exp2.f80"] = &Exp2;
1261   Optimizations["llvm.exp2.f64"] = &Exp2;
1262   Optimizations["llvm.exp2.f32"] = &Exp2;
1263   
1264 #ifdef HAVE_FLOORF
1265   Optimizations["floor"] = &UnaryDoubleFP;
1266 #endif
1267 #ifdef HAVE_CEILF
1268   Optimizations["ceil"] = &UnaryDoubleFP;
1269 #endif
1270 #ifdef HAVE_ROUNDF
1271   Optimizations["round"] = &UnaryDoubleFP;
1272 #endif
1273 #ifdef HAVE_RINTF
1274   Optimizations["rint"] = &UnaryDoubleFP;
1275 #endif
1276 #ifdef HAVE_NEARBYINTF
1277   Optimizations["nearbyint"] = &UnaryDoubleFP;
1278 #endif
1279   
1280   // Integer Optimizations
1281   Optimizations["ffs"] = &FFS;
1282   Optimizations["ffsl"] = &FFS;
1283   Optimizations["ffsll"] = &FFS;
1284   Optimizations["abs"] = &Abs;
1285   Optimizations["labs"] = &Abs;
1286   Optimizations["llabs"] = &Abs;
1287   Optimizations["isdigit"] = &IsDigit;
1288   Optimizations["isascii"] = &IsAscii;
1289   Optimizations["toascii"] = &ToAscii;
1290   
1291   // Formatting and IO Optimizations
1292   Optimizations["sprintf"] = &SPrintF;
1293   Optimizations["printf"] = &PrintF;
1294   Optimizations["fwrite"] = &FWrite;
1295   Optimizations["fputs"] = &FPuts;
1296   Optimizations["fprintf"] = &FPrintF;
1297 }
1298
1299
1300 /// runOnFunction - Top level algorithm.
1301 ///
1302 bool SimplifyLibCalls::runOnFunction(Function &F) {
1303   if (Optimizations.empty())
1304     InitOptimizations();
1305   
1306   const TargetData &TD = getAnalysis<TargetData>();
1307   
1308   IRBuilder<> Builder;
1309
1310   bool Changed = false;
1311   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1312     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1313       // Ignore non-calls.
1314       CallInst *CI = dyn_cast<CallInst>(I++);
1315       if (!CI) continue;
1316       
1317       // Ignore indirect calls and calls to non-external functions.
1318       Function *Callee = CI->getCalledFunction();
1319       if (Callee == 0 || !Callee->isDeclaration() ||
1320           !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1321         continue;
1322       
1323       // Ignore unknown calls.
1324       const char *CalleeName = Callee->getNameStart();
1325       StringMap<LibCallOptimization*>::iterator OMI =
1326         Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1327       if (OMI == Optimizations.end()) continue;
1328       
1329       // Set the builder to the instruction after the call.
1330       Builder.SetInsertPoint(BB, I);
1331       
1332       // Try to optimize this call.
1333       Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1334       if (Result == 0) continue;
1335
1336       DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1337             DOUT << "  into: " << *Result << "\n");
1338       
1339       // Something changed!
1340       Changed = true;
1341       ++NumSimplified;
1342       
1343       // Inspect the instruction after the call (which was potentially just
1344       // added) next.
1345       I = CI; ++I;
1346       
1347       if (CI != Result && !CI->use_empty()) {
1348         CI->replaceAllUsesWith(Result);
1349         if (!Result->hasName())
1350           Result->takeName(CI);
1351       }
1352       CI->eraseFromParent();
1353     }
1354   }
1355   return Changed;
1356 }
1357
1358
1359 // TODO:
1360 //   Additional cases that we need to add to this file:
1361 //
1362 // cbrt:
1363 //   * cbrt(expN(X))  -> expN(x/3)
1364 //   * cbrt(sqrt(x))  -> pow(x,1/6)
1365 //   * cbrt(sqrt(x))  -> pow(x,1/9)
1366 //
1367 // cos, cosf, cosl:
1368 //   * cos(-x)  -> cos(x)
1369 //
1370 // exp, expf, expl:
1371 //   * exp(log(x))  -> x
1372 //
1373 // log, logf, logl:
1374 //   * log(exp(x))   -> x
1375 //   * log(x**y)     -> y*log(x)
1376 //   * log(exp(y))   -> y*log(e)
1377 //   * log(exp2(y))  -> y*log(2)
1378 //   * log(exp10(y)) -> y*log(10)
1379 //   * log(sqrt(x))  -> 0.5*log(x)
1380 //   * log(pow(x,y)) -> y*log(x)
1381 //
1382 // lround, lroundf, lroundl:
1383 //   * lround(cnst) -> cnst'
1384 //
1385 // memcmp:
1386 //   * memcmp(x,y,l)   -> cnst
1387 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1388 //
1389 // memmove:
1390 //   * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1391 //       (if s is a global constant array)
1392 //
1393 // pow, powf, powl:
1394 //   * pow(exp(x),y)  -> exp(x*y)
1395 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1396 //   * pow(pow(x,y),z)-> pow(x,y*z)
1397 //
1398 // puts:
1399 //   * puts("") -> putchar("\n")
1400 //
1401 // round, roundf, roundl:
1402 //   * round(cnst) -> cnst'
1403 //
1404 // signbit:
1405 //   * signbit(cnst) -> cnst'
1406 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1407 //
1408 // sqrt, sqrtf, sqrtl:
1409 //   * sqrt(expN(x))  -> expN(x*0.5)
1410 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1411 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1412 //
1413 // stpcpy:
1414 //   * stpcpy(str, "literal") ->
1415 //           llvm.memcpy(str,"literal",strlen("literal")+1,1)
1416 // strrchr:
1417 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
1418 //      (if c is a constant integer and s is a constant string)
1419 //   * strrchr(s1,0) -> strchr(s1,0)
1420 //
1421 // strncat:
1422 //   * strncat(x,y,0) -> x
1423 //   * strncat(x,y,0) -> x (if strlen(y) = 0)
1424 //   * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1425 //
1426 // strncpy:
1427 //   * strncpy(d,s,0) -> d
1428 //   * strncpy(d,s,l) -> memcpy(d,s,l,1)
1429 //      (if s and l are constants)
1430 //
1431 // strpbrk:
1432 //   * strpbrk(s,a) -> offset_in_for(s,a)
1433 //      (if s and a are both constant strings)
1434 //   * strpbrk(s,"") -> 0
1435 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1436 //
1437 // strspn, strcspn:
1438 //   * strspn(s,a)   -> const_int (if both args are constant)
1439 //   * strspn("",a)  -> 0
1440 //   * strspn(s,"")  -> 0
1441 //   * strcspn(s,a)  -> const_int (if both args are constant)
1442 //   * strcspn("",a) -> 0
1443 //   * strcspn(s,"") -> strlen(a)
1444 //
1445 // strstr:
1446 //   * strstr(x,x)  -> x
1447 //   * strstr(s1,s2) -> offset_of_s2_in(s1)
1448 //       (if s1 and s2 are constant strings)
1449 //
1450 // tan, tanf, tanl:
1451 //   * tan(atan(x)) -> x
1452 //
1453 // trunc, truncf, truncl:
1454 //   * trunc(cnst) -> cnst'
1455 //
1456 //