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