Convert calls to __sinpi and __cospi into __sincospi_stret
[oota-llvm.git] / lib / Transforms / Utils / SimplifyLibCalls.cpp
1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
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 is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification.  If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Target/TargetLibraryInfo.h"
31 #include "llvm/Transforms/Utils/BuildLibCalls.h"
32
33 using namespace llvm;
34
35 /// This class is the abstract base class for the set of optimizations that
36 /// corresponds to one library call.
37 namespace {
38 class LibCallOptimization {
39 protected:
40   Function *Caller;
41   const DataLayout *TD;
42   const TargetLibraryInfo *TLI;
43   const LibCallSimplifier *LCS;
44   LLVMContext* Context;
45 public:
46   LibCallOptimization() { }
47   virtual ~LibCallOptimization() {}
48
49   /// callOptimizer - This pure virtual method is implemented by base classes to
50   /// do various optimizations.  If this returns null then no transformation was
51   /// performed.  If it returns CI, then it transformed the call and CI is to be
52   /// deleted.  If it returns something else, replace CI with the new value and
53   /// delete CI.
54   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
55     =0;
56
57   /// ignoreCallingConv - Returns false if this transformation could possibly
58   /// change the calling convention.
59   virtual bool ignoreCallingConv() { return false; }
60
61   Value *optimizeCall(CallInst *CI, const DataLayout *TD,
62                       const TargetLibraryInfo *TLI,
63                       const LibCallSimplifier *LCS, IRBuilder<> &B) {
64     Caller = CI->getParent()->getParent();
65     this->TD = TD;
66     this->TLI = TLI;
67     this->LCS = LCS;
68     if (CI->getCalledFunction())
69       Context = &CI->getCalledFunction()->getContext();
70
71     // We never change the calling convention.
72     if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C)
73       return NULL;
74
75     return callOptimizer(CI->getCalledFunction(), CI, B);
76   }
77 };
78
79 //===----------------------------------------------------------------------===//
80 // Helper Functions
81 //===----------------------------------------------------------------------===//
82
83 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
84 /// value is equal or not-equal to zero.
85 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
86   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
87        UI != E; ++UI) {
88     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
89       if (IC->isEquality())
90         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
91           if (C->isNullValue())
92             continue;
93     // Unknown instruction.
94     return false;
95   }
96   return true;
97 }
98
99 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
100 /// comparisons with With.
101 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
102   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
103        UI != E; ++UI) {
104     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
105       if (IC->isEquality() && IC->getOperand(1) == With)
106         continue;
107     // Unknown instruction.
108     return false;
109   }
110   return true;
111 }
112
113 static bool callHasFloatingPointArgument(const CallInst *CI) {
114   for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
115        it != e; ++it) {
116     if ((*it)->getType()->isFloatingPointTy())
117       return true;
118   }
119   return false;
120 }
121
122 /// \brief Check whether the overloaded unary floating point function
123 /// corresponing to \a Ty is available.
124 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
125                             LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
126                             LibFunc::Func LongDoubleFn) {
127   switch (Ty->getTypeID()) {
128   case Type::FloatTyID:
129     return TLI->has(FloatFn);
130   case Type::DoubleTyID:
131     return TLI->has(DoubleFn);
132   default:
133     return TLI->has(LongDoubleFn);
134   }
135 }
136
137 //===----------------------------------------------------------------------===//
138 // Fortified Library Call Optimizations
139 //===----------------------------------------------------------------------===//
140
141 struct FortifiedLibCallOptimization : public LibCallOptimization {
142 protected:
143   virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
144                           bool isString) const = 0;
145 };
146
147 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
148   CallInst *CI;
149
150   bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
151     if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
152       return true;
153     if (ConstantInt *SizeCI =
154                            dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
155       if (SizeCI->isAllOnesValue())
156         return true;
157       if (isString) {
158         uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
159         // If the length is 0 we don't know how long it is and so we can't
160         // remove the check.
161         if (Len == 0) return false;
162         return SizeCI->getZExtValue() >= Len;
163       }
164       if (ConstantInt *Arg = dyn_cast<ConstantInt>(
165                                                   CI->getArgOperand(SizeArgOp)))
166         return SizeCI->getZExtValue() >= Arg->getZExtValue();
167     }
168     return false;
169   }
170 };
171
172 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
173   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
174     this->CI = CI;
175     FunctionType *FT = Callee->getFunctionType();
176     LLVMContext &Context = CI->getParent()->getContext();
177
178     // Check if this has the right signature.
179     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
180         !FT->getParamType(0)->isPointerTy() ||
181         !FT->getParamType(1)->isPointerTy() ||
182         FT->getParamType(2) != TD->getIntPtrType(Context) ||
183         FT->getParamType(3) != TD->getIntPtrType(Context))
184       return 0;
185
186     if (isFoldable(3, 2, false)) {
187       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
188                      CI->getArgOperand(2), 1);
189       return CI->getArgOperand(0);
190     }
191     return 0;
192   }
193 };
194
195 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
196   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
197     this->CI = CI;
198     FunctionType *FT = Callee->getFunctionType();
199     LLVMContext &Context = CI->getParent()->getContext();
200
201     // Check if this has the right signature.
202     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
203         !FT->getParamType(0)->isPointerTy() ||
204         !FT->getParamType(1)->isPointerTy() ||
205         FT->getParamType(2) != TD->getIntPtrType(Context) ||
206         FT->getParamType(3) != TD->getIntPtrType(Context))
207       return 0;
208
209     if (isFoldable(3, 2, false)) {
210       B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
211                       CI->getArgOperand(2), 1);
212       return CI->getArgOperand(0);
213     }
214     return 0;
215   }
216 };
217
218 struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
219   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
220     this->CI = CI;
221     FunctionType *FT = Callee->getFunctionType();
222     LLVMContext &Context = CI->getParent()->getContext();
223
224     // Check if this has the right signature.
225     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
226         !FT->getParamType(0)->isPointerTy() ||
227         !FT->getParamType(1)->isIntegerTy() ||
228         FT->getParamType(2) != TD->getIntPtrType(Context) ||
229         FT->getParamType(3) != TD->getIntPtrType(Context))
230       return 0;
231
232     if (isFoldable(3, 2, false)) {
233       Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
234                                    false);
235       B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
236       return CI->getArgOperand(0);
237     }
238     return 0;
239   }
240 };
241
242 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
243   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
244     this->CI = CI;
245     StringRef Name = Callee->getName();
246     FunctionType *FT = Callee->getFunctionType();
247     LLVMContext &Context = CI->getParent()->getContext();
248
249     // Check if this has the right signature.
250     if (FT->getNumParams() != 3 ||
251         FT->getReturnType() != FT->getParamType(0) ||
252         FT->getParamType(0) != FT->getParamType(1) ||
253         FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
254         FT->getParamType(2) != TD->getIntPtrType(Context))
255       return 0;
256
257     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
258     if (Dst == Src)      // __strcpy_chk(x,x)  -> x
259       return Src;
260
261     // If a) we don't have any length information, or b) we know this will
262     // fit then just lower to a plain strcpy. Otherwise we'll keep our
263     // strcpy_chk call which may fail at runtime if the size is too long.
264     // TODO: It might be nice to get a maximum length out of the possible
265     // string lengths for varying.
266     if (isFoldable(2, 1, true)) {
267       Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
268       return Ret;
269     } else {
270       // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
271       uint64_t Len = GetStringLength(Src);
272       if (Len == 0) return 0;
273
274       // This optimization require DataLayout.
275       if (!TD) return 0;
276
277       Value *Ret =
278         EmitMemCpyChk(Dst, Src,
279                       ConstantInt::get(TD->getIntPtrType(Context), Len),
280                       CI->getArgOperand(2), B, TD, TLI);
281       return Ret;
282     }
283     return 0;
284   }
285 };
286
287 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
288   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
289     this->CI = CI;
290     StringRef Name = Callee->getName();
291     FunctionType *FT = Callee->getFunctionType();
292     LLVMContext &Context = CI->getParent()->getContext();
293
294     // Check if this has the right signature.
295     if (FT->getNumParams() != 3 ||
296         FT->getReturnType() != FT->getParamType(0) ||
297         FT->getParamType(0) != FT->getParamType(1) ||
298         FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
299         FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
300       return 0;
301
302     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
303     if (Dst == Src) {  // stpcpy(x,x)  -> x+strlen(x)
304       Value *StrLen = EmitStrLen(Src, B, TD, TLI);
305       return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
306     }
307
308     // If a) we don't have any length information, or b) we know this will
309     // fit then just lower to a plain stpcpy. Otherwise we'll keep our
310     // stpcpy_chk call which may fail at runtime if the size is too long.
311     // TODO: It might be nice to get a maximum length out of the possible
312     // string lengths for varying.
313     if (isFoldable(2, 1, true)) {
314       Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
315       return Ret;
316     } else {
317       // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
318       uint64_t Len = GetStringLength(Src);
319       if (Len == 0) return 0;
320
321       // This optimization require DataLayout.
322       if (!TD) return 0;
323
324       Type *PT = FT->getParamType(0);
325       Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
326       Value *DstEnd = B.CreateGEP(Dst,
327                                   ConstantInt::get(TD->getIntPtrType(PT),
328                                                    Len - 1));
329       if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI))
330         return 0;
331       return DstEnd;
332     }
333     return 0;
334   }
335 };
336
337 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
338   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
339     this->CI = CI;
340     StringRef Name = Callee->getName();
341     FunctionType *FT = Callee->getFunctionType();
342     LLVMContext &Context = CI->getParent()->getContext();
343
344     // Check if this has the right signature.
345     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
346         FT->getParamType(0) != FT->getParamType(1) ||
347         FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
348         !FT->getParamType(2)->isIntegerTy() ||
349         FT->getParamType(3) != TD->getIntPtrType(Context))
350       return 0;
351
352     if (isFoldable(3, 2, false)) {
353       Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
354                                CI->getArgOperand(2), B, TD, TLI,
355                                Name.substr(2, 7));
356       return Ret;
357     }
358     return 0;
359   }
360 };
361
362 //===----------------------------------------------------------------------===//
363 // String and Memory Library Call Optimizations
364 //===----------------------------------------------------------------------===//
365
366 struct StrCatOpt : public LibCallOptimization {
367   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
368     // Verify the "strcat" function prototype.
369     FunctionType *FT = Callee->getFunctionType();
370     if (FT->getNumParams() != 2 ||
371         FT->getReturnType() != B.getInt8PtrTy() ||
372         FT->getParamType(0) != FT->getReturnType() ||
373         FT->getParamType(1) != FT->getReturnType())
374       return 0;
375
376     // Extract some information from the instruction
377     Value *Dst = CI->getArgOperand(0);
378     Value *Src = CI->getArgOperand(1);
379
380     // See if we can get the length of the input string.
381     uint64_t Len = GetStringLength(Src);
382     if (Len == 0) return 0;
383     --Len;  // Unbias length.
384
385     // Handle the simple, do-nothing case: strcat(x, "") -> x
386     if (Len == 0)
387       return Dst;
388
389     // These optimizations require DataLayout.
390     if (!TD) return 0;
391
392     return emitStrLenMemCpy(Src, Dst, Len, B);
393   }
394
395   Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
396                           IRBuilder<> &B) {
397     // We need to find the end of the destination string.  That's where the
398     // memory is to be moved to. We just generate a call to strlen.
399     Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
400     if (!DstLen)
401       return 0;
402
403     // Now that we have the destination's length, we must index into the
404     // destination's pointer to get the actual memcpy destination (end of
405     // the string .. we're concatenating).
406     Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
407
408     // We have enough information to now generate the memcpy call to do the
409     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
410     B.CreateMemCpy(CpyDst, Src,
411                    ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
412     return Dst;
413   }
414 };
415
416 struct StrNCatOpt : public StrCatOpt {
417   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
418     // Verify the "strncat" function prototype.
419     FunctionType *FT = Callee->getFunctionType();
420     if (FT->getNumParams() != 3 ||
421         FT->getReturnType() != B.getInt8PtrTy() ||
422         FT->getParamType(0) != FT->getReturnType() ||
423         FT->getParamType(1) != FT->getReturnType() ||
424         !FT->getParamType(2)->isIntegerTy())
425       return 0;
426
427     // Extract some information from the instruction
428     Value *Dst = CI->getArgOperand(0);
429     Value *Src = CI->getArgOperand(1);
430     uint64_t Len;
431
432     // We don't do anything if length is not constant
433     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
434       Len = LengthArg->getZExtValue();
435     else
436       return 0;
437
438     // See if we can get the length of the input string.
439     uint64_t SrcLen = GetStringLength(Src);
440     if (SrcLen == 0) return 0;
441     --SrcLen;  // Unbias length.
442
443     // Handle the simple, do-nothing cases:
444     // strncat(x, "", c) -> x
445     // strncat(x,  c, 0) -> x
446     if (SrcLen == 0 || Len == 0) return Dst;
447
448     // These optimizations require DataLayout.
449     if (!TD) return 0;
450
451     // We don't optimize this case
452     if (Len < SrcLen) return 0;
453
454     // strncat(x, s, c) -> strcat(x, s)
455     // s is constant so the strcat can be optimized further
456     return emitStrLenMemCpy(Src, Dst, SrcLen, B);
457   }
458 };
459
460 struct StrChrOpt : public LibCallOptimization {
461   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
462     // Verify the "strchr" function prototype.
463     FunctionType *FT = Callee->getFunctionType();
464     if (FT->getNumParams() != 2 ||
465         FT->getReturnType() != B.getInt8PtrTy() ||
466         FT->getParamType(0) != FT->getReturnType() ||
467         !FT->getParamType(1)->isIntegerTy(32))
468       return 0;
469
470     Value *SrcStr = CI->getArgOperand(0);
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->getArgOperand(1));
475     if (CharC == 0) {
476       // These optimizations require DataLayout.
477       if (!TD) return 0;
478
479       uint64_t Len = GetStringLength(SrcStr);
480       if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
481         return 0;
482
483       return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
484                         ConstantInt::get(TD->getIntPtrType(*Context), Len),
485                         B, TD, TLI);
486     }
487
488     // Otherwise, the character is a constant, see if the first argument is
489     // a string literal.  If so, we can constant fold.
490     StringRef Str;
491     if (!getConstantStringInfo(SrcStr, Str))
492       return 0;
493
494     // Compute the offset, make sure to handle the case when we're searching for
495     // zero (a weird way to spell strlen).
496     size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
497         Str.size() : Str.find(CharC->getSExtValue());
498     if (I == StringRef::npos) // Didn't find the char.  strchr returns null.
499       return Constant::getNullValue(CI->getType());
500
501     // strchr(s+n,c)  -> gep(s+n+i,c)
502     return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
503   }
504 };
505
506 struct StrRChrOpt : public LibCallOptimization {
507   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
508     // Verify the "strrchr" function prototype.
509     FunctionType *FT = Callee->getFunctionType();
510     if (FT->getNumParams() != 2 ||
511         FT->getReturnType() != B.getInt8PtrTy() ||
512         FT->getParamType(0) != FT->getReturnType() ||
513         !FT->getParamType(1)->isIntegerTy(32))
514       return 0;
515
516     Value *SrcStr = CI->getArgOperand(0);
517     ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
518
519     // Cannot fold anything if we're not looking for a constant.
520     if (!CharC)
521       return 0;
522
523     StringRef Str;
524     if (!getConstantStringInfo(SrcStr, Str)) {
525       // strrchr(s, 0) -> strchr(s, 0)
526       if (TD && CharC->isZero())
527         return EmitStrChr(SrcStr, '\0', B, TD, TLI);
528       return 0;
529     }
530
531     // Compute the offset.
532     size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
533         Str.size() : Str.rfind(CharC->getSExtValue());
534     if (I == StringRef::npos) // Didn't find the char. Return null.
535       return Constant::getNullValue(CI->getType());
536
537     // strrchr(s+n,c) -> gep(s+n+i,c)
538     return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
539   }
540 };
541
542 struct StrCmpOpt : public LibCallOptimization {
543   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
544     // Verify the "strcmp" function prototype.
545     FunctionType *FT = Callee->getFunctionType();
546     if (FT->getNumParams() != 2 ||
547         !FT->getReturnType()->isIntegerTy(32) ||
548         FT->getParamType(0) != FT->getParamType(1) ||
549         FT->getParamType(0) != B.getInt8PtrTy())
550       return 0;
551
552     Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
553     if (Str1P == Str2P)      // strcmp(x,x)  -> 0
554       return ConstantInt::get(CI->getType(), 0);
555
556     StringRef Str1, Str2;
557     bool HasStr1 = getConstantStringInfo(Str1P, Str1);
558     bool HasStr2 = getConstantStringInfo(Str2P, Str2);
559
560     // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
561     if (HasStr1 && HasStr2)
562       return ConstantInt::get(CI->getType(), Str1.compare(Str2));
563
564     if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
565       return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
566                                       CI->getType()));
567
568     if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
569       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
570
571     // strcmp(P, "x") -> memcmp(P, "x", 2)
572     uint64_t Len1 = GetStringLength(Str1P);
573     uint64_t Len2 = GetStringLength(Str2P);
574     if (Len1 && Len2) {
575       // These optimizations require DataLayout.
576       if (!TD) return 0;
577
578       return EmitMemCmp(Str1P, Str2P,
579                         ConstantInt::get(TD->getIntPtrType(*Context),
580                         std::min(Len1, Len2)), B, TD, TLI);
581     }
582
583     return 0;
584   }
585 };
586
587 struct StrNCmpOpt : public LibCallOptimization {
588   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
589     // Verify the "strncmp" function prototype.
590     FunctionType *FT = Callee->getFunctionType();
591     if (FT->getNumParams() != 3 ||
592         !FT->getReturnType()->isIntegerTy(32) ||
593         FT->getParamType(0) != FT->getParamType(1) ||
594         FT->getParamType(0) != B.getInt8PtrTy() ||
595         !FT->getParamType(2)->isIntegerTy())
596       return 0;
597
598     Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
599     if (Str1P == Str2P)      // strncmp(x,x,n)  -> 0
600       return ConstantInt::get(CI->getType(), 0);
601
602     // Get the length argument if it is constant.
603     uint64_t Length;
604     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
605       Length = LengthArg->getZExtValue();
606     else
607       return 0;
608
609     if (Length == 0) // strncmp(x,y,0)   -> 0
610       return ConstantInt::get(CI->getType(), 0);
611
612     if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
613       return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
614
615     StringRef Str1, Str2;
616     bool HasStr1 = getConstantStringInfo(Str1P, Str1);
617     bool HasStr2 = getConstantStringInfo(Str2P, Str2);
618
619     // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
620     if (HasStr1 && HasStr2) {
621       StringRef SubStr1 = Str1.substr(0, Length);
622       StringRef SubStr2 = Str2.substr(0, Length);
623       return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
624     }
625
626     if (HasStr1 && Str1.empty())  // strncmp("", x, n) -> -*x
627       return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
628                                       CI->getType()));
629
630     if (HasStr2 && Str2.empty())  // strncmp(x, "", n) -> *x
631       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
632
633     return 0;
634   }
635 };
636
637 struct StrCpyOpt : public LibCallOptimization {
638   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
639     // Verify the "strcpy" function prototype.
640     FunctionType *FT = Callee->getFunctionType();
641     if (FT->getNumParams() != 2 ||
642         FT->getReturnType() != FT->getParamType(0) ||
643         FT->getParamType(0) != FT->getParamType(1) ||
644         FT->getParamType(0) != B.getInt8PtrTy())
645       return 0;
646
647     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
648     if (Dst == Src)      // strcpy(x,x)  -> x
649       return Src;
650
651     // These optimizations require DataLayout.
652     if (!TD) return 0;
653
654     // See if we can get the length of the input string.
655     uint64_t Len = GetStringLength(Src);
656     if (Len == 0) return 0;
657
658     // We have enough information to now generate the memcpy call to do the
659     // copy for us.  Make a memcpy to copy the nul byte with align = 1.
660     B.CreateMemCpy(Dst, Src,
661                    ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
662     return Dst;
663   }
664 };
665
666 struct StpCpyOpt: public LibCallOptimization {
667   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
668     // Verify the "stpcpy" function prototype.
669     FunctionType *FT = Callee->getFunctionType();
670     if (FT->getNumParams() != 2 ||
671         FT->getReturnType() != FT->getParamType(0) ||
672         FT->getParamType(0) != FT->getParamType(1) ||
673         FT->getParamType(0) != B.getInt8PtrTy())
674       return 0;
675
676     // These optimizations require DataLayout.
677     if (!TD) return 0;
678
679     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
680     if (Dst == Src) {  // stpcpy(x,x)  -> x+strlen(x)
681       Value *StrLen = EmitStrLen(Src, B, TD, TLI);
682       return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
683     }
684
685     // See if we can get the length of the input string.
686     uint64_t Len = GetStringLength(Src);
687     if (Len == 0) return 0;
688
689     Type *PT = FT->getParamType(0);
690     Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
691     Value *DstEnd = B.CreateGEP(Dst,
692                                 ConstantInt::get(TD->getIntPtrType(PT),
693                                                  Len - 1));
694
695     // We have enough information to now generate the memcpy call to do the
696     // copy for us.  Make a memcpy to copy the nul byte with align = 1.
697     B.CreateMemCpy(Dst, Src, LenV, 1);
698     return DstEnd;
699   }
700 };
701
702 struct StrNCpyOpt : public LibCallOptimization {
703   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
704     FunctionType *FT = Callee->getFunctionType();
705     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
706         FT->getParamType(0) != FT->getParamType(1) ||
707         FT->getParamType(0) != B.getInt8PtrTy() ||
708         !FT->getParamType(2)->isIntegerTy())
709       return 0;
710
711     Value *Dst = CI->getArgOperand(0);
712     Value *Src = CI->getArgOperand(1);
713     Value *LenOp = CI->getArgOperand(2);
714
715     // See if we can get the length of the input string.
716     uint64_t SrcLen = GetStringLength(Src);
717     if (SrcLen == 0) return 0;
718     --SrcLen;
719
720     if (SrcLen == 0) {
721       // strncpy(x, "", y) -> memset(x, '\0', y, 1)
722       B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
723       return Dst;
724     }
725
726     uint64_t Len;
727     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
728       Len = LengthArg->getZExtValue();
729     else
730       return 0;
731
732     if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
733
734     // These optimizations require DataLayout.
735     if (!TD) return 0;
736
737     // Let strncpy handle the zero padding
738     if (Len > SrcLen+1) return 0;
739
740     Type *PT = FT->getParamType(0);
741     // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
742     B.CreateMemCpy(Dst, Src,
743                    ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
744
745     return Dst;
746   }
747 };
748
749 struct StrLenOpt : public LibCallOptimization {
750   virtual bool ignoreCallingConv() { return true; }
751   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
752     FunctionType *FT = Callee->getFunctionType();
753     if (FT->getNumParams() != 1 ||
754         FT->getParamType(0) != B.getInt8PtrTy() ||
755         !FT->getReturnType()->isIntegerTy())
756       return 0;
757
758     Value *Src = CI->getArgOperand(0);
759
760     // Constant folding: strlen("xyz") -> 3
761     if (uint64_t Len = GetStringLength(Src))
762       return ConstantInt::get(CI->getType(), Len-1);
763
764     // strlen(x) != 0 --> *x != 0
765     // strlen(x) == 0 --> *x == 0
766     if (isOnlyUsedInZeroEqualityComparison(CI))
767       return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
768     return 0;
769   }
770 };
771
772 struct StrPBrkOpt : public LibCallOptimization {
773   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
774     FunctionType *FT = Callee->getFunctionType();
775     if (FT->getNumParams() != 2 ||
776         FT->getParamType(0) != B.getInt8PtrTy() ||
777         FT->getParamType(1) != FT->getParamType(0) ||
778         FT->getReturnType() != FT->getParamType(0))
779       return 0;
780
781     StringRef S1, S2;
782     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
783     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
784
785     // strpbrk(s, "") -> NULL
786     // strpbrk("", s) -> NULL
787     if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
788       return Constant::getNullValue(CI->getType());
789
790     // Constant folding.
791     if (HasS1 && HasS2) {
792       size_t I = S1.find_first_of(S2);
793       if (I == StringRef::npos) // No match.
794         return Constant::getNullValue(CI->getType());
795
796       return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
797     }
798
799     // strpbrk(s, "a") -> strchr(s, 'a')
800     if (TD && HasS2 && S2.size() == 1)
801       return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
802
803     return 0;
804   }
805 };
806
807 struct StrToOpt : public LibCallOptimization {
808   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
809     FunctionType *FT = Callee->getFunctionType();
810     if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
811         !FT->getParamType(0)->isPointerTy() ||
812         !FT->getParamType(1)->isPointerTy())
813       return 0;
814
815     Value *EndPtr = CI->getArgOperand(1);
816     if (isa<ConstantPointerNull>(EndPtr)) {
817       // With a null EndPtr, this function won't capture the main argument.
818       // It would be readonly too, except that it still may write to errno.
819       CI->addAttribute(1, Attribute::NoCapture);
820     }
821
822     return 0;
823   }
824 };
825
826 struct StrSpnOpt : public LibCallOptimization {
827   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
828     FunctionType *FT = Callee->getFunctionType();
829     if (FT->getNumParams() != 2 ||
830         FT->getParamType(0) != B.getInt8PtrTy() ||
831         FT->getParamType(1) != FT->getParamType(0) ||
832         !FT->getReturnType()->isIntegerTy())
833       return 0;
834
835     StringRef S1, S2;
836     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
837     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
838
839     // strspn(s, "") -> 0
840     // strspn("", s) -> 0
841     if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
842       return Constant::getNullValue(CI->getType());
843
844     // Constant folding.
845     if (HasS1 && HasS2) {
846       size_t Pos = S1.find_first_not_of(S2);
847       if (Pos == StringRef::npos) Pos = S1.size();
848       return ConstantInt::get(CI->getType(), Pos);
849     }
850
851     return 0;
852   }
853 };
854
855 struct StrCSpnOpt : public LibCallOptimization {
856   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
857     FunctionType *FT = Callee->getFunctionType();
858     if (FT->getNumParams() != 2 ||
859         FT->getParamType(0) != B.getInt8PtrTy() ||
860         FT->getParamType(1) != FT->getParamType(0) ||
861         !FT->getReturnType()->isIntegerTy())
862       return 0;
863
864     StringRef S1, S2;
865     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
866     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
867
868     // strcspn("", s) -> 0
869     if (HasS1 && S1.empty())
870       return Constant::getNullValue(CI->getType());
871
872     // Constant folding.
873     if (HasS1 && HasS2) {
874       size_t Pos = S1.find_first_of(S2);
875       if (Pos == StringRef::npos) Pos = S1.size();
876       return ConstantInt::get(CI->getType(), Pos);
877     }
878
879     // strcspn(s, "") -> strlen(s)
880     if (TD && HasS2 && S2.empty())
881       return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
882
883     return 0;
884   }
885 };
886
887 struct StrStrOpt : public LibCallOptimization {
888   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
889     FunctionType *FT = Callee->getFunctionType();
890     if (FT->getNumParams() != 2 ||
891         !FT->getParamType(0)->isPointerTy() ||
892         !FT->getParamType(1)->isPointerTy() ||
893         !FT->getReturnType()->isPointerTy())
894       return 0;
895
896     // fold strstr(x, x) -> x.
897     if (CI->getArgOperand(0) == CI->getArgOperand(1))
898       return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
899
900     // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
901     if (TD && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
902       Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
903       if (!StrLen)
904         return 0;
905       Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
906                                    StrLen, B, TD, TLI);
907       if (!StrNCmp)
908         return 0;
909       for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
910            UI != UE; ) {
911         ICmpInst *Old = cast<ICmpInst>(*UI++);
912         Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
913                                   ConstantInt::getNullValue(StrNCmp->getType()),
914                                   "cmp");
915         LCS->replaceAllUsesWith(Old, Cmp);
916       }
917       return CI;
918     }
919
920     // See if either input string is a constant string.
921     StringRef SearchStr, ToFindStr;
922     bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
923     bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
924
925     // fold strstr(x, "") -> x.
926     if (HasStr2 && ToFindStr.empty())
927       return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
928
929     // If both strings are known, constant fold it.
930     if (HasStr1 && HasStr2) {
931       size_t Offset = SearchStr.find(ToFindStr);
932
933       if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
934         return Constant::getNullValue(CI->getType());
935
936       // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
937       Value *Result = CastToCStr(CI->getArgOperand(0), B);
938       Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
939       return B.CreateBitCast(Result, CI->getType());
940     }
941
942     // fold strstr(x, "y") -> strchr(x, 'y').
943     if (HasStr2 && ToFindStr.size() == 1) {
944       Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
945       return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
946     }
947     return 0;
948   }
949 };
950
951 struct MemCmpOpt : public LibCallOptimization {
952   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
953     FunctionType *FT = Callee->getFunctionType();
954     if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
955         !FT->getParamType(1)->isPointerTy() ||
956         !FT->getReturnType()->isIntegerTy(32))
957       return 0;
958
959     Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
960
961     if (LHS == RHS)  // memcmp(s,s,x) -> 0
962       return Constant::getNullValue(CI->getType());
963
964     // Make sure we have a constant length.
965     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
966     if (!LenC) return 0;
967     uint64_t Len = LenC->getZExtValue();
968
969     if (Len == 0) // memcmp(s1,s2,0) -> 0
970       return Constant::getNullValue(CI->getType());
971
972     // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
973     if (Len == 1) {
974       Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
975                                  CI->getType(), "lhsv");
976       Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
977                                  CI->getType(), "rhsv");
978       return B.CreateSub(LHSV, RHSV, "chardiff");
979     }
980
981     // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
982     StringRef LHSStr, RHSStr;
983     if (getConstantStringInfo(LHS, LHSStr) &&
984         getConstantStringInfo(RHS, RHSStr)) {
985       // Make sure we're not reading out-of-bounds memory.
986       if (Len > LHSStr.size() || Len > RHSStr.size())
987         return 0;
988       // Fold the memcmp and normalize the result.  This way we get consistent
989       // results across multiple platforms.
990       uint64_t Ret = 0;
991       int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
992       if (Cmp < 0)
993         Ret = -1;
994       else if (Cmp > 0)
995         Ret = 1;
996       return ConstantInt::get(CI->getType(), Ret);
997     }
998
999     return 0;
1000   }
1001 };
1002
1003 struct MemCpyOpt : public LibCallOptimization {
1004   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1005     // These optimizations require DataLayout.
1006     if (!TD) return 0;
1007
1008     FunctionType *FT = Callee->getFunctionType();
1009     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1010         !FT->getParamType(0)->isPointerTy() ||
1011         !FT->getParamType(1)->isPointerTy() ||
1012         FT->getParamType(2) != TD->getIntPtrType(*Context))
1013       return 0;
1014
1015     // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1016     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1017                    CI->getArgOperand(2), 1);
1018     return CI->getArgOperand(0);
1019   }
1020 };
1021
1022 struct MemMoveOpt : public LibCallOptimization {
1023   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1024     // These optimizations require DataLayout.
1025     if (!TD) return 0;
1026
1027     FunctionType *FT = Callee->getFunctionType();
1028     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1029         !FT->getParamType(0)->isPointerTy() ||
1030         !FT->getParamType(1)->isPointerTy() ||
1031         FT->getParamType(2) != TD->getIntPtrType(*Context))
1032       return 0;
1033
1034     // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1035     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1036                     CI->getArgOperand(2), 1);
1037     return CI->getArgOperand(0);
1038   }
1039 };
1040
1041 struct MemSetOpt : public LibCallOptimization {
1042   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1043     // These optimizations require DataLayout.
1044     if (!TD) return 0;
1045
1046     FunctionType *FT = Callee->getFunctionType();
1047     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1048         !FT->getParamType(0)->isPointerTy() ||
1049         !FT->getParamType(1)->isIntegerTy() ||
1050         FT->getParamType(2) != TD->getIntPtrType(*Context))
1051       return 0;
1052
1053     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1054     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1055     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1056     return CI->getArgOperand(0);
1057   }
1058 };
1059
1060 //===----------------------------------------------------------------------===//
1061 // Math Library Optimizations
1062 //===----------------------------------------------------------------------===//
1063
1064 //===----------------------------------------------------------------------===//
1065 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1066
1067 struct UnaryDoubleFPOpt : public LibCallOptimization {
1068   bool CheckRetType;
1069   UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1070   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1071     FunctionType *FT = Callee->getFunctionType();
1072     if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1073         !FT->getParamType(0)->isDoubleTy())
1074       return 0;
1075
1076     if (CheckRetType) {
1077       // Check if all the uses for function like 'sin' are converted to float.
1078       for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1079           ++UseI) {
1080         FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1081         if (Cast == 0 || !Cast->getType()->isFloatTy())
1082           return 0;
1083       }
1084     }
1085
1086     // If this is something like 'floor((double)floatval)', convert to floorf.
1087     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1088     if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1089       return 0;
1090
1091     // floor((double)floatval) -> (double)floorf(floatval)
1092     Value *V = Cast->getOperand(0);
1093     V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1094     return B.CreateFPExt(V, B.getDoubleTy());
1095   }
1096 };
1097
1098 struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1099   bool UnsafeFPShrink;
1100   UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1101     this->UnsafeFPShrink = UnsafeFPShrink;
1102   }
1103 };
1104
1105 struct CosOpt : public UnsafeFPLibCallOptimization {
1106   CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1107   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1108     Value *Ret = NULL;
1109     if (UnsafeFPShrink && Callee->getName() == "cos" &&
1110         TLI->has(LibFunc::cosf)) {
1111       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1112       Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1113     }
1114
1115     FunctionType *FT = Callee->getFunctionType();
1116     // Just make sure this has 1 argument of FP type, which matches the
1117     // result type.
1118     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1119         !FT->getParamType(0)->isFloatingPointTy())
1120       return Ret;
1121
1122     // cos(-x) -> cos(x)
1123     Value *Op1 = CI->getArgOperand(0);
1124     if (BinaryOperator::isFNeg(Op1)) {
1125       BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1126       return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1127     }
1128     return Ret;
1129   }
1130 };
1131
1132 struct PowOpt : public UnsafeFPLibCallOptimization {
1133   PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1134   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1135     Value *Ret = NULL;
1136     if (UnsafeFPShrink && Callee->getName() == "pow" &&
1137         TLI->has(LibFunc::powf)) {
1138       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1139       Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1140     }
1141
1142     FunctionType *FT = Callee->getFunctionType();
1143     // Just make sure this has 2 arguments of the same FP type, which match the
1144     // result type.
1145     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1146         FT->getParamType(0) != FT->getParamType(1) ||
1147         !FT->getParamType(0)->isFloatingPointTy())
1148       return Ret;
1149
1150     Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1151     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1152       // pow(1.0, x) -> 1.0
1153       if (Op1C->isExactlyValue(1.0))
1154         return Op1C;
1155       // pow(2.0, x) -> exp2(x)
1156       if (Op1C->isExactlyValue(2.0) &&
1157           hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1158                           LibFunc::exp2l))
1159         return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1160     }
1161
1162     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1163     if (Op2C == 0) return Ret;
1164
1165     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
1166       return ConstantFP::get(CI->getType(), 1.0);
1167
1168     if (Op2C->isExactlyValue(0.5) &&
1169         hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1170                         LibFunc::sqrtl) &&
1171         hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1172                         LibFunc::fabsl)) {
1173       // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1174       // This is faster than calling pow, and still handles negative zero
1175       // and negative infinity correctly.
1176       // TODO: In fast-math mode, this could be just sqrt(x).
1177       // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1178       Value *Inf = ConstantFP::getInfinity(CI->getType());
1179       Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1180       Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1181                                          Callee->getAttributes());
1182       Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1183                                          Callee->getAttributes());
1184       Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1185       Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1186       return Sel;
1187     }
1188
1189     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
1190       return Op1;
1191     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
1192       return B.CreateFMul(Op1, Op1, "pow2");
1193     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1194       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1195                           Op1, "powrecip");
1196     return 0;
1197   }
1198 };
1199
1200 struct Exp2Opt : public UnsafeFPLibCallOptimization {
1201   Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1202   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1203     Value *Ret = NULL;
1204     if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1205         TLI->has(LibFunc::exp2f)) {
1206       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1207       Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1208     }
1209
1210     FunctionType *FT = Callee->getFunctionType();
1211     // Just make sure this has 1 argument of FP type, which matches the
1212     // result type.
1213     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1214         !FT->getParamType(0)->isFloatingPointTy())
1215       return Ret;
1216
1217     Value *Op = CI->getArgOperand(0);
1218     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1219     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1220     Value *LdExpArg = 0;
1221     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1222       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1223         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1224     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1225       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1226         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1227     }
1228
1229     if (LdExpArg) {
1230       const char *Name;
1231       if (Op->getType()->isFloatTy())
1232         Name = "ldexpf";
1233       else if (Op->getType()->isDoubleTy())
1234         Name = "ldexp";
1235       else
1236         Name = "ldexpl";
1237
1238       Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1239       if (!Op->getType()->isFloatTy())
1240         One = ConstantExpr::getFPExtend(One, Op->getType());
1241
1242       Module *M = Caller->getParent();
1243       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1244                                              Op->getType(),
1245                                              B.getInt32Ty(), NULL);
1246       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1247       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1248         CI->setCallingConv(F->getCallingConv());
1249
1250       return CI;
1251     }
1252     return Ret;
1253   }
1254 };
1255
1256 struct SinCosPiOpt : public LibCallOptimization {
1257   SinCosPiOpt() {}
1258
1259   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1260     // Make sure the prototype is as expected, otherwise the rest of the
1261     // function is probably invalid and likely to abort.
1262     if (!isTrigLibCall(CI))
1263       return 0;
1264
1265     Value *Arg = CI->getArgOperand(0);
1266     SmallVector<CallInst *, 1> SinCalls;
1267     SmallVector<CallInst *, 1> CosCalls;
1268     SmallVector<CallInst *, 1> SinCosCalls;
1269
1270     bool IsFloat = Arg->getType()->isFloatTy();
1271
1272     // Look for all compatible sinpi, cospi and sincospi calls with the same
1273     // argument. If there are enough (in some sense) we can make the
1274     // substitution.
1275     for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
1276          UI != UE; ++UI)
1277       classifyArgUse(*UI, CI->getParent(), IsFloat, SinCalls, CosCalls,
1278                      SinCosCalls);
1279
1280     // It's only worthwhile if both sinpi and cospi are actually used.
1281     if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1282       return 0;
1283
1284     Value *Sin, *Cos, *SinCos;
1285     insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1286                      SinCos);
1287
1288     replaceTrigInsts(SinCalls, Sin);
1289     replaceTrigInsts(CosCalls, Cos);
1290     replaceTrigInsts(SinCosCalls, SinCos);
1291
1292     return 0;
1293   }
1294
1295   bool isTrigLibCall(CallInst *CI) {
1296     Function *Callee = CI->getCalledFunction();
1297     FunctionType *FT = Callee->getFunctionType();
1298
1299     // We can only hope to do anything useful if we can ignore things like errno
1300     // and floating-point exceptions.
1301     bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1302                           CI->hasFnAttr(Attribute::ReadNone);
1303
1304     // Other than that we need float(float) or double(double)
1305     return AttributesSafe && FT->getNumParams() == 1 &&
1306            FT->getReturnType() == FT->getParamType(0) &&
1307            (FT->getParamType(0)->isFloatTy() ||
1308             FT->getParamType(0)->isDoubleTy());
1309   }
1310
1311   void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1312                       SmallVectorImpl<CallInst *> &SinCalls,
1313                       SmallVectorImpl<CallInst *> &CosCalls,
1314                       SmallVectorImpl<CallInst *> &SinCosCalls) {
1315     CallInst *CI = dyn_cast<CallInst>(Val);
1316
1317     if (!CI)
1318       return;
1319
1320     Function *Callee = CI->getCalledFunction();
1321     StringRef FuncName = Callee->getName();
1322     LibFunc::Func Func;
1323     if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1324         !isTrigLibCall(CI))
1325       return;
1326
1327     if (IsFloat) {
1328       if (Func == LibFunc::sinpif)
1329         SinCalls.push_back(CI);
1330       else if (Func == LibFunc::cospif)
1331         CosCalls.push_back(CI);
1332       else if (Func == LibFunc::sincospi_stretf)
1333         SinCosCalls.push_back(CI);
1334     } else {
1335       if (Func == LibFunc::sinpi)
1336         SinCalls.push_back(CI);
1337       else if (Func == LibFunc::cospi)
1338         CosCalls.push_back(CI);
1339       else if (Func == LibFunc::sincospi_stret)
1340         SinCosCalls.push_back(CI);
1341     }
1342   }
1343
1344   void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1345     for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1346            E = Calls.end();
1347          I != E; ++I) {
1348       LCS->replaceAllUsesWith(*I, Res);
1349     }
1350   }
1351
1352   void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1353                         bool UseFloat, Value *&Sin, Value *&Cos,
1354                         Value *&SinCos) {
1355     Type *ArgTy = Arg->getType();
1356     Type *ResTy;
1357     StringRef Name;
1358
1359     Triple T(OrigCallee->getParent()->getTargetTriple());
1360     if (UseFloat) {
1361       Name = "__sincospi_stretf";
1362
1363       assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1364       // x86_64 can't use {float, float} since that would be returned in both
1365       // xmm0 and xmm1, which isn't what a real struct would do.
1366       ResTy = T.getArch() == Triple::x86_64
1367                   ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1368                   : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1369     } else {
1370       Name = "__sincospi_stret";
1371       ResTy = StructType::get(ArgTy, ArgTy, NULL);
1372     }
1373
1374     Module *M = OrigCallee->getParent();
1375     Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1376                                            ResTy, ArgTy, NULL);
1377
1378     if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1379       // If the argument is an instruction, it must dominate all uses so put our
1380       // sincos call there.
1381       BasicBlock::iterator Loc = ArgInst;
1382       B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1383     } else {
1384       // Otherwise (e.g. for a constant) the beginning of the function is as
1385       // good a place as any.
1386       BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1387       B.SetInsertPoint(&EntryBB, EntryBB.begin());
1388     }
1389
1390     SinCos = B.CreateCall(Callee, Arg, "sincospi");
1391
1392     if (SinCos->getType()->isStructTy()) {
1393       Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1394       Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1395     } else {
1396       Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1397                                    "sinpi");
1398       Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1399                                    "cospi");
1400     }
1401   }
1402
1403 };
1404
1405 //===----------------------------------------------------------------------===//
1406 // Integer Library Call Optimizations
1407 //===----------------------------------------------------------------------===//
1408
1409 struct FFSOpt : public LibCallOptimization {
1410   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1411     FunctionType *FT = Callee->getFunctionType();
1412     // Just make sure this has 2 arguments of the same FP type, which match the
1413     // result type.
1414     if (FT->getNumParams() != 1 ||
1415         !FT->getReturnType()->isIntegerTy(32) ||
1416         !FT->getParamType(0)->isIntegerTy())
1417       return 0;
1418
1419     Value *Op = CI->getArgOperand(0);
1420
1421     // Constant fold.
1422     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1423       if (CI->isZero()) // ffs(0) -> 0.
1424         return B.getInt32(0);
1425       // ffs(c) -> cttz(c)+1
1426       return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1427     }
1428
1429     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1430     Type *ArgType = Op->getType();
1431     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1432                                          Intrinsic::cttz, ArgType);
1433     Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1434     V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1435     V = B.CreateIntCast(V, B.getInt32Ty(), false);
1436
1437     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1438     return B.CreateSelect(Cond, V, B.getInt32(0));
1439   }
1440 };
1441
1442 struct AbsOpt : public LibCallOptimization {
1443   virtual bool ignoreCallingConv() { return true; }
1444   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1445     FunctionType *FT = Callee->getFunctionType();
1446     // We require integer(integer) where the types agree.
1447     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1448         FT->getParamType(0) != FT->getReturnType())
1449       return 0;
1450
1451     // abs(x) -> x >s -1 ? x : -x
1452     Value *Op = CI->getArgOperand(0);
1453     Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1454                                  "ispos");
1455     Value *Neg = B.CreateNeg(Op, "neg");
1456     return B.CreateSelect(Pos, Op, Neg);
1457   }
1458 };
1459
1460 struct IsDigitOpt : public LibCallOptimization {
1461   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1462     FunctionType *FT = Callee->getFunctionType();
1463     // We require integer(i32)
1464     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1465         !FT->getParamType(0)->isIntegerTy(32))
1466       return 0;
1467
1468     // isdigit(c) -> (c-'0') <u 10
1469     Value *Op = CI->getArgOperand(0);
1470     Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1471     Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1472     return B.CreateZExt(Op, CI->getType());
1473   }
1474 };
1475
1476 struct IsAsciiOpt : public LibCallOptimization {
1477   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1478     FunctionType *FT = Callee->getFunctionType();
1479     // We require integer(i32)
1480     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1481         !FT->getParamType(0)->isIntegerTy(32))
1482       return 0;
1483
1484     // isascii(c) -> c <u 128
1485     Value *Op = CI->getArgOperand(0);
1486     Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1487     return B.CreateZExt(Op, CI->getType());
1488   }
1489 };
1490
1491 struct ToAsciiOpt : public LibCallOptimization {
1492   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1493     FunctionType *FT = Callee->getFunctionType();
1494     // We require i32(i32)
1495     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1496         !FT->getParamType(0)->isIntegerTy(32))
1497       return 0;
1498
1499     // toascii(c) -> c & 0x7f
1500     return B.CreateAnd(CI->getArgOperand(0),
1501                        ConstantInt::get(CI->getType(),0x7F));
1502   }
1503 };
1504
1505 //===----------------------------------------------------------------------===//
1506 // Formatting and IO Library Call Optimizations
1507 //===----------------------------------------------------------------------===//
1508
1509 struct PrintFOpt : public LibCallOptimization {
1510   Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1511                                    IRBuilder<> &B) {
1512     // Check for a fixed format string.
1513     StringRef FormatStr;
1514     if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1515       return 0;
1516
1517     // Empty format string -> noop.
1518     if (FormatStr.empty())  // Tolerate printf's declared void.
1519       return CI->use_empty() ? (Value*)CI :
1520                                ConstantInt::get(CI->getType(), 0);
1521
1522     // Do not do any of the following transformations if the printf return value
1523     // is used, in general the printf return value is not compatible with either
1524     // putchar() or puts().
1525     if (!CI->use_empty())
1526       return 0;
1527
1528     // printf("x") -> putchar('x'), even for '%'.
1529     if (FormatStr.size() == 1) {
1530       Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
1531       if (CI->use_empty() || !Res) return Res;
1532       return B.CreateIntCast(Res, CI->getType(), true);
1533     }
1534
1535     // printf("foo\n") --> puts("foo")
1536     if (FormatStr[FormatStr.size()-1] == '\n' &&
1537         FormatStr.find('%') == StringRef::npos) { // No format characters.
1538       // Create a string literal with no \n on it.  We expect the constant merge
1539       // pass to be run after this pass, to merge duplicate strings.
1540       FormatStr = FormatStr.drop_back();
1541       Value *GV = B.CreateGlobalString(FormatStr, "str");
1542       Value *NewCI = EmitPutS(GV, B, TD, TLI);
1543       return (CI->use_empty() || !NewCI) ?
1544               NewCI :
1545               ConstantInt::get(CI->getType(), FormatStr.size()+1);
1546     }
1547
1548     // Optimize specific format strings.
1549     // printf("%c", chr) --> putchar(chr)
1550     if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1551         CI->getArgOperand(1)->getType()->isIntegerTy()) {
1552       Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
1553
1554       if (CI->use_empty() || !Res) return Res;
1555       return B.CreateIntCast(Res, CI->getType(), true);
1556     }
1557
1558     // printf("%s\n", str) --> puts(str)
1559     if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1560         CI->getArgOperand(1)->getType()->isPointerTy()) {
1561       return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
1562     }
1563     return 0;
1564   }
1565
1566   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1567     // Require one fixed pointer argument and an integer/void result.
1568     FunctionType *FT = Callee->getFunctionType();
1569     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1570         !(FT->getReturnType()->isIntegerTy() ||
1571           FT->getReturnType()->isVoidTy()))
1572       return 0;
1573
1574     if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1575       return V;
1576     }
1577
1578     // printf(format, ...) -> iprintf(format, ...) if no floating point
1579     // arguments.
1580     if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1581       Module *M = B.GetInsertBlock()->getParent()->getParent();
1582       Constant *IPrintFFn =
1583         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1584       CallInst *New = cast<CallInst>(CI->clone());
1585       New->setCalledFunction(IPrintFFn);
1586       B.Insert(New);
1587       return New;
1588     }
1589     return 0;
1590   }
1591 };
1592
1593 struct SPrintFOpt : public LibCallOptimization {
1594   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1595                                    IRBuilder<> &B) {
1596     // Check for a fixed format string.
1597     StringRef FormatStr;
1598     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1599       return 0;
1600
1601     // If we just have a format string (nothing else crazy) transform it.
1602     if (CI->getNumArgOperands() == 2) {
1603       // Make sure there's no % in the constant array.  We could try to handle
1604       // %% -> % in the future if we cared.
1605       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1606         if (FormatStr[i] == '%')
1607           return 0; // we found a format specifier, bail out.
1608
1609       // These optimizations require DataLayout.
1610       if (!TD) return 0;
1611
1612       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1613       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1614                      ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1615                                       FormatStr.size() + 1), 1);   // nul byte.
1616       return ConstantInt::get(CI->getType(), FormatStr.size());
1617     }
1618
1619     // The remaining optimizations require the format string to be "%s" or "%c"
1620     // and have an extra operand.
1621     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1622         CI->getNumArgOperands() < 3)
1623       return 0;
1624
1625     // Decode the second character of the format string.
1626     if (FormatStr[1] == 'c') {
1627       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1628       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1629       Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1630       Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1631       B.CreateStore(V, Ptr);
1632       Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1633       B.CreateStore(B.getInt8(0), Ptr);
1634
1635       return ConstantInt::get(CI->getType(), 1);
1636     }
1637
1638     if (FormatStr[1] == 's') {
1639       // These optimizations require DataLayout.
1640       if (!TD) return 0;
1641
1642       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1643       if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1644
1645       Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1646       if (!Len)
1647         return 0;
1648       Value *IncLen = B.CreateAdd(Len,
1649                                   ConstantInt::get(Len->getType(), 1),
1650                                   "leninc");
1651       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1652
1653       // The sprintf result is the unincremented number of bytes in the string.
1654       return B.CreateIntCast(Len, CI->getType(), false);
1655     }
1656     return 0;
1657   }
1658
1659   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1660     // Require two fixed pointer arguments and an integer result.
1661     FunctionType *FT = Callee->getFunctionType();
1662     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1663         !FT->getParamType(1)->isPointerTy() ||
1664         !FT->getReturnType()->isIntegerTy())
1665       return 0;
1666
1667     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1668       return V;
1669     }
1670
1671     // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1672     // point arguments.
1673     if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1674       Module *M = B.GetInsertBlock()->getParent()->getParent();
1675       Constant *SIPrintFFn =
1676         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1677       CallInst *New = cast<CallInst>(CI->clone());
1678       New->setCalledFunction(SIPrintFFn);
1679       B.Insert(New);
1680       return New;
1681     }
1682     return 0;
1683   }
1684 };
1685
1686 struct FPrintFOpt : public LibCallOptimization {
1687   Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1688                                    IRBuilder<> &B) {
1689     // All the optimizations depend on the format string.
1690     StringRef FormatStr;
1691     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1692       return 0;
1693
1694     // Do not do any of the following transformations if the fprintf return
1695     // value is used, in general the fprintf return value is not compatible
1696     // with fwrite(), fputc() or fputs().
1697     if (!CI->use_empty())
1698       return 0;
1699
1700     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1701     if (CI->getNumArgOperands() == 2) {
1702       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1703         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
1704           return 0; // We found a format specifier.
1705
1706       // These optimizations require DataLayout.
1707       if (!TD) return 0;
1708
1709       return EmitFWrite(CI->getArgOperand(1),
1710                         ConstantInt::get(TD->getIntPtrType(*Context),
1711                                          FormatStr.size()),
1712                         CI->getArgOperand(0), B, TD, TLI);
1713     }
1714
1715     // The remaining optimizations require the format string to be "%s" or "%c"
1716     // and have an extra operand.
1717     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1718         CI->getNumArgOperands() < 3)
1719       return 0;
1720
1721     // Decode the second character of the format string.
1722     if (FormatStr[1] == 'c') {
1723       // fprintf(F, "%c", chr) --> fputc(chr, F)
1724       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1725       return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1726     }
1727
1728     if (FormatStr[1] == 's') {
1729       // fprintf(F, "%s", str) --> fputs(str, F)
1730       if (!CI->getArgOperand(2)->getType()->isPointerTy())
1731         return 0;
1732       return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1733     }
1734     return 0;
1735   }
1736
1737   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1738     // Require two fixed paramters as pointers and integer result.
1739     FunctionType *FT = Callee->getFunctionType();
1740     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1741         !FT->getParamType(1)->isPointerTy() ||
1742         !FT->getReturnType()->isIntegerTy())
1743       return 0;
1744
1745     if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1746       return V;
1747     }
1748
1749     // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1750     // floating point arguments.
1751     if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1752       Module *M = B.GetInsertBlock()->getParent()->getParent();
1753       Constant *FIPrintFFn =
1754         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1755       CallInst *New = cast<CallInst>(CI->clone());
1756       New->setCalledFunction(FIPrintFFn);
1757       B.Insert(New);
1758       return New;
1759     }
1760     return 0;
1761   }
1762 };
1763
1764 struct FWriteOpt : public LibCallOptimization {
1765   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1766     // Require a pointer, an integer, an integer, a pointer, returning integer.
1767     FunctionType *FT = Callee->getFunctionType();
1768     if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1769         !FT->getParamType(1)->isIntegerTy() ||
1770         !FT->getParamType(2)->isIntegerTy() ||
1771         !FT->getParamType(3)->isPointerTy() ||
1772         !FT->getReturnType()->isIntegerTy())
1773       return 0;
1774
1775     // Get the element size and count.
1776     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1777     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1778     if (!SizeC || !CountC) return 0;
1779     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1780
1781     // If this is writing zero records, remove the call (it's a noop).
1782     if (Bytes == 0)
1783       return ConstantInt::get(CI->getType(), 0);
1784
1785     // If this is writing one byte, turn it into fputc.
1786     // This optimisation is only valid, if the return value is unused.
1787     if (Bytes == 1 && CI->use_empty()) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
1788       Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1789       Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1790       return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1791     }
1792
1793     return 0;
1794   }
1795 };
1796
1797 struct FPutsOpt : public LibCallOptimization {
1798   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1799     // These optimizations require DataLayout.
1800     if (!TD) return 0;
1801
1802     // Require two pointers.  Also, we can't optimize if return value is used.
1803     FunctionType *FT = Callee->getFunctionType();
1804     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1805         !FT->getParamType(1)->isPointerTy() ||
1806         !CI->use_empty())
1807       return 0;
1808
1809     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1810     uint64_t Len = GetStringLength(CI->getArgOperand(0));
1811     if (!Len) return 0;
1812     // Known to have no uses (see above).
1813     return EmitFWrite(CI->getArgOperand(0),
1814                       ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1815                       CI->getArgOperand(1), B, TD, TLI);
1816   }
1817 };
1818
1819 struct PutsOpt : public LibCallOptimization {
1820   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1821     // Require one fixed pointer argument and an integer/void result.
1822     FunctionType *FT = Callee->getFunctionType();
1823     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1824         !(FT->getReturnType()->isIntegerTy() ||
1825           FT->getReturnType()->isVoidTy()))
1826       return 0;
1827
1828     // Check for a constant string.
1829     StringRef Str;
1830     if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1831       return 0;
1832
1833     if (Str.empty() && CI->use_empty()) {
1834       // puts("") -> putchar('\n')
1835       Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1836       if (CI->use_empty() || !Res) return Res;
1837       return B.CreateIntCast(Res, CI->getType(), true);
1838     }
1839
1840     return 0;
1841   }
1842 };
1843
1844 } // End anonymous namespace.
1845
1846 namespace llvm {
1847
1848 class LibCallSimplifierImpl {
1849   const DataLayout *TD;
1850   const TargetLibraryInfo *TLI;
1851   const LibCallSimplifier *LCS;
1852   bool UnsafeFPShrink;
1853
1854   // Math library call optimizations.
1855   CosOpt Cos;
1856   PowOpt Pow;
1857   Exp2Opt Exp2;
1858 public:
1859   LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI,
1860                         const LibCallSimplifier *LCS,
1861                         bool UnsafeFPShrink = false)
1862     : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
1863     this->TD = TD;
1864     this->TLI = TLI;
1865     this->LCS = LCS;
1866     this->UnsafeFPShrink = UnsafeFPShrink;
1867   }
1868
1869   Value *optimizeCall(CallInst *CI);
1870   LibCallOptimization *lookupOptimization(CallInst *CI);
1871   bool hasFloatVersion(StringRef FuncName);
1872 };
1873
1874 bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
1875   LibFunc::Func Func;
1876   SmallString<20> FloatFuncName = FuncName;
1877   FloatFuncName += 'f';
1878   if (TLI->getLibFunc(FloatFuncName, Func))
1879     return TLI->has(Func);
1880   return false;
1881 }
1882
1883 // Fortified library call optimizations.
1884 static MemCpyChkOpt MemCpyChk;
1885 static MemMoveChkOpt MemMoveChk;
1886 static MemSetChkOpt MemSetChk;
1887 static StrCpyChkOpt StrCpyChk;
1888 static StpCpyChkOpt StpCpyChk;
1889 static StrNCpyChkOpt StrNCpyChk;
1890
1891 // String library call optimizations.
1892 static StrCatOpt StrCat;
1893 static StrNCatOpt StrNCat;
1894 static StrChrOpt StrChr;
1895 static StrRChrOpt StrRChr;
1896 static StrCmpOpt StrCmp;
1897 static StrNCmpOpt StrNCmp;
1898 static StrCpyOpt StrCpy;
1899 static StpCpyOpt StpCpy;
1900 static StrNCpyOpt StrNCpy;
1901 static StrLenOpt StrLen;
1902 static StrPBrkOpt StrPBrk;
1903 static StrToOpt StrTo;
1904 static StrSpnOpt StrSpn;
1905 static StrCSpnOpt StrCSpn;
1906 static StrStrOpt StrStr;
1907
1908 // Memory library call optimizations.
1909 static MemCmpOpt MemCmp;
1910 static MemCpyOpt MemCpy;
1911 static MemMoveOpt MemMove;
1912 static MemSetOpt MemSet;
1913
1914 // Math library call optimizations.
1915 static UnaryDoubleFPOpt UnaryDoubleFP(false);
1916 static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1917 static SinCosPiOpt SinCosPi;
1918
1919   // Integer library call optimizations.
1920 static FFSOpt FFS;
1921 static AbsOpt Abs;
1922 static IsDigitOpt IsDigit;
1923 static IsAsciiOpt IsAscii;
1924 static ToAsciiOpt ToAscii;
1925
1926 // Formatting and IO library call optimizations.
1927 static PrintFOpt PrintF;
1928 static SPrintFOpt SPrintF;
1929 static FPrintFOpt FPrintF;
1930 static FWriteOpt FWrite;
1931 static FPutsOpt FPuts;
1932 static PutsOpt Puts;
1933
1934 LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
1935   LibFunc::Func Func;
1936   Function *Callee = CI->getCalledFunction();
1937   StringRef FuncName = Callee->getName();
1938
1939   // Next check for intrinsics.
1940   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1941     switch (II->getIntrinsicID()) {
1942     case Intrinsic::pow:
1943        return &Pow;
1944     case Intrinsic::exp2:
1945        return &Exp2;
1946     default:
1947        return 0;
1948     }
1949   }
1950
1951   // Then check for known library functions.
1952   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1953     switch (Func) {
1954       case LibFunc::strcat:
1955         return &StrCat;
1956       case LibFunc::strncat:
1957         return &StrNCat;
1958       case LibFunc::strchr:
1959         return &StrChr;
1960       case LibFunc::strrchr:
1961         return &StrRChr;
1962       case LibFunc::strcmp:
1963         return &StrCmp;
1964       case LibFunc::strncmp:
1965         return &StrNCmp;
1966       case LibFunc::strcpy:
1967         return &StrCpy;
1968       case LibFunc::stpcpy:
1969         return &StpCpy;
1970       case LibFunc::strncpy:
1971         return &StrNCpy;
1972       case LibFunc::strlen:
1973         return &StrLen;
1974       case LibFunc::strpbrk:
1975         return &StrPBrk;
1976       case LibFunc::strtol:
1977       case LibFunc::strtod:
1978       case LibFunc::strtof:
1979       case LibFunc::strtoul:
1980       case LibFunc::strtoll:
1981       case LibFunc::strtold:
1982       case LibFunc::strtoull:
1983         return &StrTo;
1984       case LibFunc::strspn:
1985         return &StrSpn;
1986       case LibFunc::strcspn:
1987         return &StrCSpn;
1988       case LibFunc::strstr:
1989         return &StrStr;
1990       case LibFunc::memcmp:
1991         return &MemCmp;
1992       case LibFunc::memcpy:
1993         return &MemCpy;
1994       case LibFunc::memmove:
1995         return &MemMove;
1996       case LibFunc::memset:
1997         return &MemSet;
1998       case LibFunc::cosf:
1999       case LibFunc::cos:
2000       case LibFunc::cosl:
2001         return &Cos;
2002       case LibFunc::sinpif:
2003       case LibFunc::sinpi:
2004       case LibFunc::cospif:
2005       case LibFunc::cospi:
2006         return &SinCosPi;
2007       case LibFunc::powf:
2008       case LibFunc::pow:
2009       case LibFunc::powl:
2010         return &Pow;
2011       case LibFunc::exp2l:
2012       case LibFunc::exp2:
2013       case LibFunc::exp2f:
2014         return &Exp2;
2015       case LibFunc::ffs:
2016       case LibFunc::ffsl:
2017       case LibFunc::ffsll:
2018         return &FFS;
2019       case LibFunc::abs:
2020       case LibFunc::labs:
2021       case LibFunc::llabs:
2022         return &Abs;
2023       case LibFunc::isdigit:
2024         return &IsDigit;
2025       case LibFunc::isascii:
2026         return &IsAscii;
2027       case LibFunc::toascii:
2028         return &ToAscii;
2029       case LibFunc::printf:
2030         return &PrintF;
2031       case LibFunc::sprintf:
2032         return &SPrintF;
2033       case LibFunc::fprintf:
2034         return &FPrintF;
2035       case LibFunc::fwrite:
2036         return &FWrite;
2037       case LibFunc::fputs:
2038         return &FPuts;
2039       case LibFunc::puts:
2040         return &Puts;
2041       case LibFunc::ceil:
2042       case LibFunc::fabs:
2043       case LibFunc::floor:
2044       case LibFunc::rint:
2045       case LibFunc::round:
2046       case LibFunc::nearbyint:
2047       case LibFunc::trunc:
2048         if (hasFloatVersion(FuncName))
2049           return &UnaryDoubleFP;
2050         return 0;
2051       case LibFunc::acos:
2052       case LibFunc::acosh:
2053       case LibFunc::asin:
2054       case LibFunc::asinh:
2055       case LibFunc::atan:
2056       case LibFunc::atanh:
2057       case LibFunc::cbrt:
2058       case LibFunc::cosh:
2059       case LibFunc::exp:
2060       case LibFunc::exp10:
2061       case LibFunc::expm1:
2062       case LibFunc::log:
2063       case LibFunc::log10:
2064       case LibFunc::log1p:
2065       case LibFunc::log2:
2066       case LibFunc::logb:
2067       case LibFunc::sin:
2068       case LibFunc::sinh:
2069       case LibFunc::sqrt:
2070       case LibFunc::tan:
2071       case LibFunc::tanh:
2072         if (UnsafeFPShrink && hasFloatVersion(FuncName))
2073          return &UnsafeUnaryDoubleFP;
2074         return 0;
2075       case LibFunc::memcpy_chk:
2076         return &MemCpyChk;
2077       default:
2078         return 0;
2079       }
2080   }
2081
2082   // Finally check for fortified library calls.
2083   if (FuncName.endswith("_chk")) {
2084     if (FuncName == "__memmove_chk")
2085       return &MemMoveChk;
2086     else if (FuncName == "__memset_chk")
2087       return &MemSetChk;
2088     else if (FuncName == "__strcpy_chk")
2089       return &StrCpyChk;
2090     else if (FuncName == "__stpcpy_chk")
2091       return &StpCpyChk;
2092     else if (FuncName == "__strncpy_chk")
2093       return &StrNCpyChk;
2094     else if (FuncName == "__stpncpy_chk")
2095       return &StrNCpyChk;
2096   }
2097
2098   return 0;
2099
2100 }
2101
2102 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
2103   LibCallOptimization *LCO = lookupOptimization(CI);
2104   if (LCO) {
2105     IRBuilder<> Builder(CI);
2106     return LCO->optimizeCall(CI, TD, TLI, LCS, Builder);
2107   }
2108   return 0;
2109 }
2110
2111 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD,
2112                                      const TargetLibraryInfo *TLI,
2113                                      bool UnsafeFPShrink) {
2114   Impl = new LibCallSimplifierImpl(TD, TLI, this, UnsafeFPShrink);
2115 }
2116
2117 LibCallSimplifier::~LibCallSimplifier() {
2118   delete Impl;
2119 }
2120
2121 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2122   if (CI->isNoBuiltin()) return 0;
2123   return Impl->optimizeCall(CI);
2124 }
2125
2126 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2127   I->replaceAllUsesWith(With);
2128   I->eraseFromParent();
2129 }
2130
2131 }
2132
2133 // TODO:
2134 //   Additional cases that we need to add to this file:
2135 //
2136 // cbrt:
2137 //   * cbrt(expN(X))  -> expN(x/3)
2138 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2139 //   * cbrt(sqrt(x))  -> pow(x,1/9)
2140 //
2141 // exp, expf, expl:
2142 //   * exp(log(x))  -> x
2143 //
2144 // log, logf, logl:
2145 //   * log(exp(x))   -> x
2146 //   * log(x**y)     -> y*log(x)
2147 //   * log(exp(y))   -> y*log(e)
2148 //   * log(exp2(y))  -> y*log(2)
2149 //   * log(exp10(y)) -> y*log(10)
2150 //   * log(sqrt(x))  -> 0.5*log(x)
2151 //   * log(pow(x,y)) -> y*log(x)
2152 //
2153 // lround, lroundf, lroundl:
2154 //   * lround(cnst) -> cnst'
2155 //
2156 // pow, powf, powl:
2157 //   * pow(exp(x),y)  -> exp(x*y)
2158 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2159 //   * pow(pow(x,y),z)-> pow(x,y*z)
2160 //
2161 // round, roundf, roundl:
2162 //   * round(cnst) -> cnst'
2163 //
2164 // signbit:
2165 //   * signbit(cnst) -> cnst'
2166 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2167 //
2168 // sqrt, sqrtf, sqrtl:
2169 //   * sqrt(expN(x))  -> expN(x*0.5)
2170 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2171 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2172 //
2173 // strchr:
2174 //   * strchr(p, 0) -> strlen(p)
2175 // tan, tanf, tanl:
2176 //   * tan(atan(x)) -> x
2177 //
2178 // trunc, truncf, truncl:
2179 //   * trunc(cnst) -> cnst'
2180 //
2181 //