1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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). Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/IRBuilder.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Config/config.h"
36 STATISTIC(NumSimplified, "Number of library calls simplified");
37 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
39 //===----------------------------------------------------------------------===//
40 // Optimizer Base Class
41 //===----------------------------------------------------------------------===//
43 /// This class is the abstract base class for the set of optimizations that
44 /// corresponds to one library call.
46 class LibCallOptimization {
52 LibCallOptimization() { }
53 virtual ~LibCallOptimization() {}
55 /// CallOptimizer - This pure virtual method is implemented by base classes to
56 /// do various optimizations. If this returns null then no transformation was
57 /// performed. If it returns CI, then it transformed the call and CI is to be
58 /// deleted. If it returns something else, replace CI with the new value and
60 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
63 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
64 Caller = CI->getParent()->getParent();
66 if (CI->getCalledFunction())
67 Context = &CI->getCalledFunction()->getContext();
68 return CallOptimizer(CI->getCalledFunction(), CI, B);
71 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
72 Value *CastToCStr(Value *V, IRBuilder<> &B);
74 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
75 /// specified pointer. Ptr is required to be some pointer type, and the
76 /// return value has 'intptr_t' type.
77 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
79 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
80 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
81 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
82 unsigned Align, IRBuilder<> &B);
84 /// EmitMemMove - Emit a call to the memmove function to the builder. This
85 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
86 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
87 unsigned Align, IRBuilder<> &B);
89 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
90 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
91 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
93 /// EmitMemCmp - Emit a call to the memcmp function.
94 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
96 /// EmitMemSet - Emit a call to the memset function
97 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
99 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
100 /// 'floor'). This function is known to take a single of type matching 'Op'
101 /// and returns one value with the same type. If 'Op' is a long double, 'l'
102 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
103 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
104 const AttrListPtr &Attrs);
106 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
108 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
110 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
112 void EmitPutS(Value *Str, IRBuilder<> &B);
114 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
115 /// an i32, and File is a pointer to FILE.
116 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
118 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
119 /// pointer and File is a pointer to FILE.
120 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
122 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
123 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
124 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
127 } // End anonymous namespace.
129 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
130 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
131 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
134 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
135 /// specified pointer. This always returns an integer value of size intptr_t.
136 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
137 Module *M = Caller->getParent();
138 AttributeWithIndex AWI[2];
139 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
140 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
141 Attribute::NoUnwind);
143 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
144 TD->getIntPtrType(*Context),
145 Type::getInt8PtrTy(*Context),
147 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
148 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
149 CI->setCallingConv(F->getCallingConv());
154 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
155 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
156 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
157 unsigned Align, IRBuilder<> &B) {
158 Module *M = Caller->getParent();
159 const Type *Ty = Len->getType();
160 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
161 Dst = CastToCStr(Dst, B);
162 Src = CastToCStr(Src, B);
163 return B.CreateCall4(MemCpy, Dst, Src, Len,
164 ConstantInt::get(Type::getInt32Ty(*Context), Align));
167 /// EmitMemMove - Emit a call to the memmove function to the builder. This
168 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
169 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
170 unsigned Align, IRBuilder<> &B) {
171 Module *M = Caller->getParent();
172 const Type *Ty = TD->getIntPtrType(*Context);
173 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
174 Dst = CastToCStr(Dst, B);
175 Src = CastToCStr(Src, B);
176 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
177 return B.CreateCall4(MemMove, Dst, Src, Len, A);
180 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
181 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
182 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
183 Value *Len, IRBuilder<> &B) {
184 Module *M = Caller->getParent();
185 AttributeWithIndex AWI;
186 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
188 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
189 Type::getInt8PtrTy(*Context),
190 Type::getInt8PtrTy(*Context),
191 Type::getInt32Ty(*Context),
192 TD->getIntPtrType(*Context),
194 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
196 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
197 CI->setCallingConv(F->getCallingConv());
202 /// EmitMemCmp - Emit a call to the memcmp function.
203 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
204 Value *Len, IRBuilder<> &B) {
205 Module *M = Caller->getParent();
206 AttributeWithIndex AWI[3];
207 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
208 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
209 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
210 Attribute::NoUnwind);
212 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
213 Type::getInt32Ty(*Context),
214 Type::getInt8PtrTy(*Context),
215 Type::getInt8PtrTy(*Context),
216 TD->getIntPtrType(*Context), NULL);
217 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
220 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
221 CI->setCallingConv(F->getCallingConv());
226 /// EmitMemSet - Emit a call to the memset function
227 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
228 Value *Len, IRBuilder<> &B) {
229 Module *M = Caller->getParent();
230 Intrinsic::ID IID = Intrinsic::memset;
232 Tys[0] = Len->getType();
233 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
234 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
235 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
238 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
239 /// 'floor'). This function is known to take a single of type matching 'Op' and
240 /// returns one value with the same type. If 'Op' is a long double, 'l' is
241 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
242 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
244 const AttrListPtr &Attrs) {
246 if (!Op->getType()->isDoubleTy()) {
247 // If we need to add a suffix, copy into NameBuffer.
248 unsigned NameLen = strlen(Name);
249 assert(NameLen < sizeof(NameBuffer)-2);
250 memcpy(NameBuffer, Name, NameLen);
251 if (Op->getType()->isFloatTy())
252 NameBuffer[NameLen] = 'f'; // floorf
254 NameBuffer[NameLen] = 'l'; // floorl
255 NameBuffer[NameLen+1] = 0;
259 Module *M = Caller->getParent();
260 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
261 Op->getType(), NULL);
262 CallInst *CI = B.CreateCall(Callee, Op, Name);
263 CI->setAttributes(Attrs);
264 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
265 CI->setCallingConv(F->getCallingConv());
270 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
272 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
273 Module *M = Caller->getParent();
274 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
275 Type::getInt32Ty(*Context), NULL);
276 CallInst *CI = B.CreateCall(PutChar,
277 B.CreateIntCast(Char,
278 Type::getInt32Ty(*Context),
283 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
284 CI->setCallingConv(F->getCallingConv());
288 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
290 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
291 Module *M = Caller->getParent();
292 AttributeWithIndex AWI[2];
293 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
294 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
296 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
297 Type::getInt32Ty(*Context),
298 Type::getInt8PtrTy(*Context),
300 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
301 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
302 CI->setCallingConv(F->getCallingConv());
306 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
307 /// an integer and File is a pointer to FILE.
308 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
309 Module *M = Caller->getParent();
310 AttributeWithIndex AWI[2];
311 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
312 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
314 if (isa<PointerType>(File->getType()))
315 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
316 Type::getInt32Ty(*Context),
317 Type::getInt32Ty(*Context), File->getType(),
320 F = M->getOrInsertFunction("fputc",
321 Type::getInt32Ty(*Context),
322 Type::getInt32Ty(*Context),
323 File->getType(), NULL);
324 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
326 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
328 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
329 CI->setCallingConv(Fn->getCallingConv());
332 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
333 /// pointer and File is a pointer to FILE.
334 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
335 Module *M = Caller->getParent();
336 AttributeWithIndex AWI[3];
337 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
338 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
339 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
341 if (isa<PointerType>(File->getType()))
342 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
343 Type::getInt32Ty(*Context),
344 Type::getInt8PtrTy(*Context),
345 File->getType(), NULL);
347 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
348 Type::getInt8PtrTy(*Context),
349 File->getType(), NULL);
350 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
352 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
353 CI->setCallingConv(Fn->getCallingConv());
356 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
357 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
358 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
360 Module *M = Caller->getParent();
361 AttributeWithIndex AWI[3];
362 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
363 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
364 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
366 if (isa<PointerType>(File->getType()))
367 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
368 TD->getIntPtrType(*Context),
369 Type::getInt8PtrTy(*Context),
370 TD->getIntPtrType(*Context),
371 TD->getIntPtrType(*Context),
372 File->getType(), NULL);
374 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
375 Type::getInt8PtrTy(*Context),
376 TD->getIntPtrType(*Context),
377 TD->getIntPtrType(*Context),
378 File->getType(), NULL);
379 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
380 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
382 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
383 CI->setCallingConv(Fn->getCallingConv());
386 //===----------------------------------------------------------------------===//
388 //===----------------------------------------------------------------------===//
390 /// GetStringLengthH - If we can compute the length of the string pointed to by
391 /// the specified pointer, return 'len+1'. If we can't, return 0.
392 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
393 // Look through noop bitcast instructions.
394 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
395 return GetStringLengthH(BCI->getOperand(0), PHIs);
397 // If this is a PHI node, there are two cases: either we have already seen it
399 if (PHINode *PN = dyn_cast<PHINode>(V)) {
400 if (!PHIs.insert(PN))
401 return ~0ULL; // already in the set.
403 // If it was new, see if all the input strings are the same length.
404 uint64_t LenSoFar = ~0ULL;
405 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
406 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
407 if (Len == 0) return 0; // Unknown length -> unknown.
409 if (Len == ~0ULL) continue;
411 if (Len != LenSoFar && LenSoFar != ~0ULL)
412 return 0; // Disagree -> unknown.
416 // Success, all agree.
420 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
421 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
422 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
423 if (Len1 == 0) return 0;
424 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
425 if (Len2 == 0) return 0;
426 if (Len1 == ~0ULL) return Len2;
427 if (Len2 == ~0ULL) return Len1;
428 if (Len1 != Len2) return 0;
432 // If the value is not a GEP instruction nor a constant expression with a
433 // GEP instruction, then return unknown.
435 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
437 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
438 if (CE->getOpcode() != Instruction::GetElementPtr)
445 // Make sure the GEP has exactly three arguments.
446 if (GEP->getNumOperands() != 3)
449 // Check to make sure that the first operand of the GEP is an integer and
450 // has value 0 so that we are sure we're indexing into the initializer.
451 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
457 // If the second index isn't a ConstantInt, then this is a variable index
458 // into the array. If this occurs, we can't say anything meaningful about
460 uint64_t StartIdx = 0;
461 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
462 StartIdx = CI->getZExtValue();
466 // The GEP instruction, constant or instruction, must reference a global
467 // variable that is a constant and is initialized. The referenced constant
468 // initializer is the array that we'll use for optimization.
469 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
470 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
471 GV->mayBeOverridden())
473 Constant *GlobalInit = GV->getInitializer();
475 // Handle the ConstantAggregateZero case, which is a degenerate case. The
476 // initializer is constant zero so the length of the string must be zero.
477 if (isa<ConstantAggregateZero>(GlobalInit))
478 return 1; // Len = 0 offset by 1.
480 // Must be a Constant Array
481 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
483 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
486 // Get the number of elements in the array
487 uint64_t NumElts = Array->getType()->getNumElements();
489 // Traverse the constant array from StartIdx (derived above) which is
490 // the place the GEP refers to in the array.
491 for (unsigned i = StartIdx; i != NumElts; ++i) {
492 Constant *Elt = Array->getOperand(i);
493 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
494 if (!CI) // This array isn't suitable, non-int initializer.
497 return i-StartIdx+1; // We found end of string, success!
500 return 0; // The array isn't null terminated, conservatively return 'unknown'.
503 /// GetStringLength - If we can compute the length of the string pointed to by
504 /// the specified pointer, return 'len+1'. If we can't, return 0.
505 static uint64_t GetStringLength(Value *V) {
506 if (!isa<PointerType>(V->getType())) return 0;
508 SmallPtrSet<PHINode*, 32> PHIs;
509 uint64_t Len = GetStringLengthH(V, PHIs);
510 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
511 // an empty string as a length.
512 return Len == ~0ULL ? 1 : Len;
515 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
516 /// value is equal or not-equal to zero.
517 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
518 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
520 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
521 if (IC->isEquality())
522 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
523 if (C->isNullValue())
525 // Unknown instruction.
531 //===----------------------------------------------------------------------===//
532 // String and Memory LibCall Optimizations
533 //===----------------------------------------------------------------------===//
535 //===---------------------------------------===//
536 // 'strcat' Optimizations
538 struct StrCatOpt : public LibCallOptimization {
539 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
540 // Verify the "strcat" function prototype.
541 const FunctionType *FT = Callee->getFunctionType();
542 if (FT->getNumParams() != 2 ||
543 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
544 FT->getParamType(0) != FT->getReturnType() ||
545 FT->getParamType(1) != FT->getReturnType())
548 // Extract some information from the instruction
549 Value *Dst = CI->getOperand(1);
550 Value *Src = CI->getOperand(2);
552 // See if we can get the length of the input string.
553 uint64_t Len = GetStringLength(Src);
554 if (Len == 0) return 0;
555 --Len; // Unbias length.
557 // Handle the simple, do-nothing case: strcat(x, "") -> x
561 // These optimizations require TargetData.
564 EmitStrLenMemCpy(Src, Dst, Len, B);
568 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
569 // We need to find the end of the destination string. That's where the
570 // memory is to be moved to. We just generate a call to strlen.
571 Value *DstLen = EmitStrLen(Dst, B);
573 // Now that we have the destination's length, we must index into the
574 // destination's pointer to get the actual memcpy destination (end of
575 // the string .. we're concatenating).
576 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
578 // We have enough information to now generate the memcpy call to do the
579 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
580 EmitMemCpy(CpyDst, Src,
581 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
585 //===---------------------------------------===//
586 // 'strncat' Optimizations
588 struct StrNCatOpt : public StrCatOpt {
589 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
590 // Verify the "strncat" function prototype.
591 const FunctionType *FT = Callee->getFunctionType();
592 if (FT->getNumParams() != 3 ||
593 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
594 FT->getParamType(0) != FT->getReturnType() ||
595 FT->getParamType(1) != FT->getReturnType() ||
596 !isa<IntegerType>(FT->getParamType(2)))
599 // Extract some information from the instruction
600 Value *Dst = CI->getOperand(1);
601 Value *Src = CI->getOperand(2);
604 // We don't do anything if length is not constant
605 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
606 Len = LengthArg->getZExtValue();
610 // See if we can get the length of the input string.
611 uint64_t SrcLen = GetStringLength(Src);
612 if (SrcLen == 0) return 0;
613 --SrcLen; // Unbias length.
615 // Handle the simple, do-nothing cases:
616 // strncat(x, "", c) -> x
617 // strncat(x, c, 0) -> x
618 if (SrcLen == 0 || Len == 0) return Dst;
620 // These optimizations require TargetData.
623 // We don't optimize this case
624 if (Len < SrcLen) return 0;
626 // strncat(x, s, c) -> strcat(x, s)
627 // s is constant so the strcat can be optimized further
628 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
633 //===---------------------------------------===//
634 // 'strchr' Optimizations
636 struct StrChrOpt : public LibCallOptimization {
637 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
638 // Verify the "strchr" function prototype.
639 const FunctionType *FT = Callee->getFunctionType();
640 if (FT->getNumParams() != 2 ||
641 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
642 FT->getParamType(0) != FT->getReturnType())
645 Value *SrcStr = CI->getOperand(1);
647 // If the second operand is non-constant, see if we can compute the length
648 // of the input string and turn this into memchr.
649 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
651 // These optimizations require TargetData.
654 uint64_t Len = GetStringLength(SrcStr);
656 FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs i32.
659 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
660 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
663 // Otherwise, the character is a constant, see if the first argument is
664 // a string literal. If so, we can constant fold.
666 if (!GetConstantStringInfo(SrcStr, Str))
669 // strchr can find the nul character.
671 char CharValue = CharC->getSExtValue();
673 // Compute the offset.
676 if (i == Str.size()) // Didn't find the char. strchr returns null.
677 return Constant::getNullValue(CI->getType());
678 // Did we find our match?
679 if (Str[i] == CharValue)
684 // strchr(s+n,c) -> gep(s+n+i,c)
685 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
686 return B.CreateGEP(SrcStr, Idx, "strchr");
690 //===---------------------------------------===//
691 // 'strcmp' Optimizations
693 struct StrCmpOpt : public LibCallOptimization {
694 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
695 // Verify the "strcmp" function prototype.
696 const FunctionType *FT = Callee->getFunctionType();
697 if (FT->getNumParams() != 2 ||
698 FT->getReturnType() != Type::getInt32Ty(*Context) ||
699 FT->getParamType(0) != FT->getParamType(1) ||
700 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
703 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
704 if (Str1P == Str2P) // strcmp(x,x) -> 0
705 return ConstantInt::get(CI->getType(), 0);
707 std::string Str1, Str2;
708 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
709 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
711 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
712 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
714 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
715 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
717 // strcmp(x, y) -> cnst (if both x and y are constant strings)
718 if (HasStr1 && HasStr2)
719 return ConstantInt::get(CI->getType(),
720 strcmp(Str1.c_str(),Str2.c_str()));
722 // strcmp(P, "x") -> memcmp(P, "x", 2)
723 uint64_t Len1 = GetStringLength(Str1P);
724 uint64_t Len2 = GetStringLength(Str2P);
726 // These optimizations require TargetData.
729 return EmitMemCmp(Str1P, Str2P,
730 ConstantInt::get(TD->getIntPtrType(*Context),
731 std::min(Len1, Len2)), B);
738 //===---------------------------------------===//
739 // 'strncmp' Optimizations
741 struct StrNCmpOpt : public LibCallOptimization {
742 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
743 // Verify the "strncmp" function prototype.
744 const FunctionType *FT = Callee->getFunctionType();
745 if (FT->getNumParams() != 3 ||
746 FT->getReturnType() != Type::getInt32Ty(*Context) ||
747 FT->getParamType(0) != FT->getParamType(1) ||
748 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
749 !isa<IntegerType>(FT->getParamType(2)))
752 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
753 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
754 return ConstantInt::get(CI->getType(), 0);
756 // Get the length argument if it is constant.
758 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
759 Length = LengthArg->getZExtValue();
763 if (Length == 0) // strncmp(x,y,0) -> 0
764 return ConstantInt::get(CI->getType(), 0);
766 std::string Str1, Str2;
767 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
768 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
770 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
771 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
773 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
774 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
776 // strncmp(x, y) -> cnst (if both x and y are constant strings)
777 if (HasStr1 && HasStr2)
778 return ConstantInt::get(CI->getType(),
779 strncmp(Str1.c_str(), Str2.c_str(), Length));
785 //===---------------------------------------===//
786 // 'strcpy' Optimizations
788 struct StrCpyOpt : public LibCallOptimization {
789 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
790 // Verify the "strcpy" function prototype.
791 const FunctionType *FT = Callee->getFunctionType();
792 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
793 FT->getParamType(0) != FT->getParamType(1) ||
794 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
797 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
798 if (Dst == Src) // strcpy(x,x) -> x
801 // These optimizations require TargetData.
804 // See if we can get the length of the input string.
805 uint64_t Len = GetStringLength(Src);
806 if (Len == 0) return 0;
808 // We have enough information to now generate the memcpy call to do the
809 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
811 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
816 //===---------------------------------------===//
817 // 'strncpy' Optimizations
819 struct StrNCpyOpt : public LibCallOptimization {
820 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
821 const FunctionType *FT = Callee->getFunctionType();
822 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
823 FT->getParamType(0) != FT->getParamType(1) ||
824 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
825 !isa<IntegerType>(FT->getParamType(2)))
828 Value *Dst = CI->getOperand(1);
829 Value *Src = CI->getOperand(2);
830 Value *LenOp = CI->getOperand(3);
832 // See if we can get the length of the input string.
833 uint64_t SrcLen = GetStringLength(Src);
834 if (SrcLen == 0) return 0;
838 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
839 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
845 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
846 Len = LengthArg->getZExtValue();
850 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
852 // These optimizations require TargetData.
855 // Let strncpy handle the zero padding
856 if (Len > SrcLen+1) return 0;
858 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
860 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
866 //===---------------------------------------===//
867 // 'strlen' Optimizations
869 struct StrLenOpt : public LibCallOptimization {
870 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
871 const FunctionType *FT = Callee->getFunctionType();
872 if (FT->getNumParams() != 1 ||
873 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
874 !isa<IntegerType>(FT->getReturnType()))
877 Value *Src = CI->getOperand(1);
879 // Constant folding: strlen("xyz") -> 3
880 if (uint64_t Len = GetStringLength(Src))
881 return ConstantInt::get(CI->getType(), Len-1);
883 // Handle strlen(p) != 0.
884 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
886 // strlen(x) != 0 --> *x != 0
887 // strlen(x) == 0 --> *x == 0
888 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
892 //===---------------------------------------===//
893 // 'strto*' Optimizations
895 struct StrToOpt : public LibCallOptimization {
896 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
897 const FunctionType *FT = Callee->getFunctionType();
898 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
899 !isa<PointerType>(FT->getParamType(0)) ||
900 !isa<PointerType>(FT->getParamType(1)))
903 Value *EndPtr = CI->getOperand(2);
904 if (isa<ConstantPointerNull>(EndPtr)) {
905 CI->setOnlyReadsMemory();
906 CI->addAttribute(1, Attribute::NoCapture);
914 //===---------------------------------------===//
915 // 'memcmp' Optimizations
917 struct MemCmpOpt : public LibCallOptimization {
918 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
919 const FunctionType *FT = Callee->getFunctionType();
920 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
921 !isa<PointerType>(FT->getParamType(1)) ||
922 FT->getReturnType() != Type::getInt32Ty(*Context))
925 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
927 if (LHS == RHS) // memcmp(s,s,x) -> 0
928 return Constant::getNullValue(CI->getType());
930 // Make sure we have a constant length.
931 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
933 uint64_t Len = LenC->getZExtValue();
935 if (Len == 0) // memcmp(s1,s2,0) -> 0
936 return Constant::getNullValue(CI->getType());
938 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
939 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
940 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
941 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
944 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
945 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
946 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
947 const Type *PTy = PointerType::getUnqual(Len == 2 ?
948 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
949 LHS = B.CreateBitCast(LHS, PTy, "tmp");
950 RHS = B.CreateBitCast(RHS, PTy, "tmp");
951 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
952 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
953 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
954 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
957 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
958 std::string LHSStr, RHSStr;
959 if (GetConstantStringInfo(LHS, LHSStr) &&
960 GetConstantStringInfo(RHS, RHSStr)) {
961 // Make sure we're not reading out-of-bounds memory.
962 if (Len > LHSStr.length() || Len > RHSStr.length())
964 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
965 return ConstantInt::get(CI->getType(), Ret);
972 //===---------------------------------------===//
973 // 'memcpy' Optimizations
975 struct MemCpyOpt : public LibCallOptimization {
976 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
977 // These optimizations require TargetData.
980 const FunctionType *FT = Callee->getFunctionType();
981 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
982 !isa<PointerType>(FT->getParamType(0)) ||
983 !isa<PointerType>(FT->getParamType(1)) ||
984 FT->getParamType(2) != TD->getIntPtrType(*Context))
987 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
988 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
989 return CI->getOperand(1);
993 //===---------------------------------------===//
994 // 'memmove' Optimizations
996 struct MemMoveOpt : public LibCallOptimization {
997 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
998 // These optimizations require TargetData.
1001 const FunctionType *FT = Callee->getFunctionType();
1002 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1003 !isa<PointerType>(FT->getParamType(0)) ||
1004 !isa<PointerType>(FT->getParamType(1)) ||
1005 FT->getParamType(2) != TD->getIntPtrType(*Context))
1008 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1009 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1010 return CI->getOperand(1);
1014 //===---------------------------------------===//
1015 // 'memset' Optimizations
1017 struct MemSetOpt : public LibCallOptimization {
1018 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1019 // These optimizations require TargetData.
1022 const FunctionType *FT = Callee->getFunctionType();
1023 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1024 !isa<PointerType>(FT->getParamType(0)) ||
1025 !isa<IntegerType>(FT->getParamType(1)) ||
1026 FT->getParamType(2) != TD->getIntPtrType(*Context))
1029 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1030 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1032 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1033 return CI->getOperand(1);
1037 //===----------------------------------------------------------------------===//
1038 // Object Size Checking Optimizations
1039 //===----------------------------------------------------------------------===//
1041 //===---------------------------------------===//
1044 struct SizeOpt : public LibCallOptimization {
1045 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1046 // TODO: We can do more with this, but delaying to here should be no change
1048 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
1050 if (!Const) return 0;
1052 const Type *Ty = Callee->getFunctionType()->getReturnType();
1054 if (Const->getZExtValue() < 2)
1055 return Constant::getAllOnesValue(Ty);
1057 return ConstantInt::get(Ty, 0);
1062 //===---------------------------------------===//
1063 // 'memcpy_chk' Optimizations
1065 struct MemCpyChkOpt : public LibCallOptimization {
1066 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1067 // These optimizations require TargetData.
1070 const FunctionType *FT = Callee->getFunctionType();
1071 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1072 !isa<PointerType>(FT->getParamType(0)) ||
1073 !isa<PointerType>(FT->getParamType(1)) ||
1074 !isa<IntegerType>(FT->getParamType(3)) ||
1075 FT->getParamType(2) != TD->getIntPtrType(*Context))
1078 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1081 if (SizeCI->isAllOnesValue()) {
1082 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1083 return CI->getOperand(1);
1090 //===---------------------------------------===//
1091 // 'memset_chk' Optimizations
1093 struct MemSetChkOpt : public LibCallOptimization {
1094 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1095 // These optimizations require TargetData.
1098 const FunctionType *FT = Callee->getFunctionType();
1099 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1100 !isa<PointerType>(FT->getParamType(0)) ||
1101 !isa<IntegerType>(FT->getParamType(1)) ||
1102 !isa<IntegerType>(FT->getParamType(3)) ||
1103 FT->getParamType(2) != TD->getIntPtrType(*Context))
1106 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1109 if (SizeCI->isAllOnesValue()) {
1110 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1112 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1113 return CI->getOperand(1);
1120 //===---------------------------------------===//
1121 // 'memmove_chk' Optimizations
1123 struct MemMoveChkOpt : public LibCallOptimization {
1124 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1125 // These optimizations require TargetData.
1128 const FunctionType *FT = Callee->getFunctionType();
1129 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1130 !isa<PointerType>(FT->getParamType(0)) ||
1131 !isa<PointerType>(FT->getParamType(1)) ||
1132 !isa<IntegerType>(FT->getParamType(3)) ||
1133 FT->getParamType(2) != TD->getIntPtrType(*Context))
1136 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1139 if (SizeCI->isAllOnesValue()) {
1140 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1142 return CI->getOperand(1);
1149 //===----------------------------------------------------------------------===//
1150 // Math Library Optimizations
1151 //===----------------------------------------------------------------------===//
1153 //===---------------------------------------===//
1154 // 'pow*' Optimizations
1156 struct PowOpt : public LibCallOptimization {
1157 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1158 const FunctionType *FT = Callee->getFunctionType();
1159 // Just make sure this has 2 arguments of the same FP type, which match the
1161 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1162 FT->getParamType(0) != FT->getParamType(1) ||
1163 !FT->getParamType(0)->isFloatingPoint())
1166 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1167 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1168 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1170 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1171 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1174 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1175 if (Op2C == 0) return 0;
1177 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1178 return ConstantFP::get(CI->getType(), 1.0);
1180 if (Op2C->isExactlyValue(0.5)) {
1181 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1182 // This is faster than calling pow, and still handles negative zero
1183 // and negative infinite correctly.
1184 // TODO: In fast-math mode, this could be just sqrt(x).
1185 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1186 Value *Inf = ConstantFP::getInfinity(CI->getType());
1187 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1188 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1189 Callee->getAttributes());
1190 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1191 Callee->getAttributes());
1192 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1193 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1197 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1199 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1200 return B.CreateFMul(Op1, Op1, "pow2");
1201 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1202 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1208 //===---------------------------------------===//
1209 // 'exp2' Optimizations
1211 struct Exp2Opt : public LibCallOptimization {
1212 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1213 const FunctionType *FT = Callee->getFunctionType();
1214 // Just make sure this has 1 argument of FP type, which matches the
1216 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1217 !FT->getParamType(0)->isFloatingPoint())
1220 Value *Op = CI->getOperand(1);
1221 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1222 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1223 Value *LdExpArg = 0;
1224 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1225 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1226 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1227 Type::getInt32Ty(*Context), "tmp");
1228 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1229 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1230 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1231 Type::getInt32Ty(*Context), "tmp");
1236 if (Op->getType()->isFloatTy())
1238 else if (Op->getType()->isDoubleTy())
1243 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1244 if (!Op->getType()->isFloatTy())
1245 One = ConstantExpr::getFPExtend(One, Op->getType());
1247 Module *M = Caller->getParent();
1248 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1250 Type::getInt32Ty(*Context),NULL);
1251 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1252 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1253 CI->setCallingConv(F->getCallingConv());
1261 //===---------------------------------------===//
1262 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1264 struct UnaryDoubleFPOpt : public LibCallOptimization {
1265 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1266 const FunctionType *FT = Callee->getFunctionType();
1267 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1268 !FT->getParamType(0)->isDoubleTy())
1271 // If this is something like 'floor((double)floatval)', convert to floorf.
1272 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1273 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1276 // floor((double)floatval) -> (double)floorf(floatval)
1277 Value *V = Cast->getOperand(0);
1278 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1279 Callee->getAttributes());
1280 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1284 //===----------------------------------------------------------------------===//
1285 // Integer Optimizations
1286 //===----------------------------------------------------------------------===//
1288 //===---------------------------------------===//
1289 // 'ffs*' Optimizations
1291 struct FFSOpt : public LibCallOptimization {
1292 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1293 const FunctionType *FT = Callee->getFunctionType();
1294 // Just make sure this has 2 arguments of the same FP type, which match the
1296 if (FT->getNumParams() != 1 ||
1297 FT->getReturnType() != Type::getInt32Ty(*Context) ||
1298 !isa<IntegerType>(FT->getParamType(0)))
1301 Value *Op = CI->getOperand(1);
1304 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1305 if (CI->getValue() == 0) // ffs(0) -> 0.
1306 return Constant::getNullValue(CI->getType());
1307 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1308 CI->getValue().countTrailingZeros()+1);
1311 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1312 const Type *ArgType = Op->getType();
1313 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1314 Intrinsic::cttz, &ArgType, 1);
1315 Value *V = B.CreateCall(F, Op, "cttz");
1316 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1317 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1319 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1320 return B.CreateSelect(Cond, V,
1321 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1325 //===---------------------------------------===//
1326 // 'isdigit' Optimizations
1328 struct IsDigitOpt : public LibCallOptimization {
1329 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1330 const FunctionType *FT = Callee->getFunctionType();
1331 // We require integer(i32)
1332 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1333 FT->getParamType(0) != Type::getInt32Ty(*Context))
1336 // isdigit(c) -> (c-'0') <u 10
1337 Value *Op = CI->getOperand(1);
1338 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1340 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1342 return B.CreateZExt(Op, CI->getType());
1346 //===---------------------------------------===//
1347 // 'isascii' Optimizations
1349 struct IsAsciiOpt : public LibCallOptimization {
1350 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1351 const FunctionType *FT = Callee->getFunctionType();
1352 // We require integer(i32)
1353 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1354 FT->getParamType(0) != Type::getInt32Ty(*Context))
1357 // isascii(c) -> c <u 128
1358 Value *Op = CI->getOperand(1);
1359 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1361 return B.CreateZExt(Op, CI->getType());
1365 //===---------------------------------------===//
1366 // 'abs', 'labs', 'llabs' Optimizations
1368 struct AbsOpt : public LibCallOptimization {
1369 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1370 const FunctionType *FT = Callee->getFunctionType();
1371 // We require integer(integer) where the types agree.
1372 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1373 FT->getParamType(0) != FT->getReturnType())
1376 // abs(x) -> x >s -1 ? x : -x
1377 Value *Op = CI->getOperand(1);
1378 Value *Pos = B.CreateICmpSGT(Op,
1379 Constant::getAllOnesValue(Op->getType()),
1381 Value *Neg = B.CreateNeg(Op, "neg");
1382 return B.CreateSelect(Pos, Op, Neg);
1387 //===---------------------------------------===//
1388 // 'toascii' Optimizations
1390 struct ToAsciiOpt : public LibCallOptimization {
1391 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1392 const FunctionType *FT = Callee->getFunctionType();
1393 // We require i32(i32)
1394 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1395 FT->getParamType(0) != Type::getInt32Ty(*Context))
1398 // isascii(c) -> c & 0x7f
1399 return B.CreateAnd(CI->getOperand(1),
1400 ConstantInt::get(CI->getType(),0x7F));
1404 //===----------------------------------------------------------------------===//
1405 // Formatting and IO Optimizations
1406 //===----------------------------------------------------------------------===//
1408 //===---------------------------------------===//
1409 // 'printf' Optimizations
1411 struct PrintFOpt : public LibCallOptimization {
1412 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1413 // Require one fixed pointer argument and an integer/void result.
1414 const FunctionType *FT = Callee->getFunctionType();
1415 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1416 !(isa<IntegerType>(FT->getReturnType()) ||
1417 FT->getReturnType()->isVoidTy()))
1420 // Check for a fixed format string.
1421 std::string FormatStr;
1422 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1425 // Empty format string -> noop.
1426 if (FormatStr.empty()) // Tolerate printf's declared void.
1427 return CI->use_empty() ? (Value*)CI :
1428 ConstantInt::get(CI->getType(), 0);
1430 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1431 // in case there is an error writing to stdout.
1432 if (FormatStr.size() == 1) {
1433 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1435 if (CI->use_empty()) return CI;
1436 return B.CreateIntCast(Res, CI->getType(), true);
1439 // printf("foo\n") --> puts("foo")
1440 if (FormatStr[FormatStr.size()-1] == '\n' &&
1441 FormatStr.find('%') == std::string::npos) { // no format characters.
1442 // Create a string literal with no \n on it. We expect the constant merge
1443 // pass to be run after this pass, to merge duplicate strings.
1444 FormatStr.erase(FormatStr.end()-1);
1445 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1446 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1447 GlobalVariable::InternalLinkage, C, "str");
1449 return CI->use_empty() ? (Value*)CI :
1450 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1453 // Optimize specific format strings.
1454 // printf("%c", chr) --> putchar(*(i8*)dst)
1455 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1456 isa<IntegerType>(CI->getOperand(2)->getType())) {
1457 Value *Res = EmitPutChar(CI->getOperand(2), B);
1459 if (CI->use_empty()) return CI;
1460 return B.CreateIntCast(Res, CI->getType(), true);
1463 // printf("%s\n", str) --> puts(str)
1464 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1465 isa<PointerType>(CI->getOperand(2)->getType()) &&
1467 EmitPutS(CI->getOperand(2), B);
1474 //===---------------------------------------===//
1475 // 'sprintf' Optimizations
1477 struct SPrintFOpt : public LibCallOptimization {
1478 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1479 // Require two fixed pointer arguments and an integer result.
1480 const FunctionType *FT = Callee->getFunctionType();
1481 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1482 !isa<PointerType>(FT->getParamType(1)) ||
1483 !isa<IntegerType>(FT->getReturnType()))
1486 // Check for a fixed format string.
1487 std::string FormatStr;
1488 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1491 // If we just have a format string (nothing else crazy) transform it.
1492 if (CI->getNumOperands() == 3) {
1493 // Make sure there's no % in the constant array. We could try to handle
1494 // %% -> % in the future if we cared.
1495 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1496 if (FormatStr[i] == '%')
1497 return 0; // we found a format specifier, bail out.
1499 // These optimizations require TargetData.
1502 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1503 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1504 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1505 return ConstantInt::get(CI->getType(), FormatStr.size());
1508 // The remaining optimizations require the format string to be "%s" or "%c"
1509 // and have an extra operand.
1510 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1513 // Decode the second character of the format string.
1514 if (FormatStr[1] == 'c') {
1515 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1516 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1517 Value *V = B.CreateTrunc(CI->getOperand(3),
1518 Type::getInt8Ty(*Context), "char");
1519 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1520 B.CreateStore(V, Ptr);
1521 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1523 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1525 return ConstantInt::get(CI->getType(), 1);
1528 if (FormatStr[1] == 's') {
1529 // These optimizations require TargetData.
1532 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1533 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1535 Value *Len = EmitStrLen(CI->getOperand(3), B);
1536 Value *IncLen = B.CreateAdd(Len,
1537 ConstantInt::get(Len->getType(), 1),
1539 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1541 // The sprintf result is the unincremented number of bytes in the string.
1542 return B.CreateIntCast(Len, CI->getType(), false);
1548 //===---------------------------------------===//
1549 // 'fwrite' Optimizations
1551 struct FWriteOpt : public LibCallOptimization {
1552 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1553 // Require a pointer, an integer, an integer, a pointer, returning integer.
1554 const FunctionType *FT = Callee->getFunctionType();
1555 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1556 !isa<IntegerType>(FT->getParamType(1)) ||
1557 !isa<IntegerType>(FT->getParamType(2)) ||
1558 !isa<PointerType>(FT->getParamType(3)) ||
1559 !isa<IntegerType>(FT->getReturnType()))
1562 // Get the element size and count.
1563 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1564 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1565 if (!SizeC || !CountC) return 0;
1566 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1568 // If this is writing zero records, remove the call (it's a noop).
1570 return ConstantInt::get(CI->getType(), 0);
1572 // If this is writing one byte, turn it into fputc.
1573 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1574 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1575 EmitFPutC(Char, CI->getOperand(4), B);
1576 return ConstantInt::get(CI->getType(), 1);
1583 //===---------------------------------------===//
1584 // 'fputs' Optimizations
1586 struct FPutsOpt : public LibCallOptimization {
1587 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1588 // These optimizations require TargetData.
1591 // Require two pointers. Also, we can't optimize if return value is used.
1592 const FunctionType *FT = Callee->getFunctionType();
1593 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1594 !isa<PointerType>(FT->getParamType(1)) ||
1598 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1599 uint64_t Len = GetStringLength(CI->getOperand(1));
1601 EmitFWrite(CI->getOperand(1),
1602 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1603 CI->getOperand(2), B);
1604 return CI; // Known to have no uses (see above).
1608 //===---------------------------------------===//
1609 // 'fprintf' Optimizations
1611 struct FPrintFOpt : public LibCallOptimization {
1612 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1613 // Require two fixed paramters as pointers and integer result.
1614 const FunctionType *FT = Callee->getFunctionType();
1615 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1616 !isa<PointerType>(FT->getParamType(1)) ||
1617 !isa<IntegerType>(FT->getReturnType()))
1620 // All the optimizations depend on the format string.
1621 std::string FormatStr;
1622 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1625 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1626 if (CI->getNumOperands() == 3) {
1627 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1628 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1629 return 0; // We found a format specifier.
1631 // These optimizations require TargetData.
1634 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
1636 CI->getOperand(1), B);
1637 return ConstantInt::get(CI->getType(), FormatStr.size());
1640 // The remaining optimizations require the format string to be "%s" or "%c"
1641 // and have an extra operand.
1642 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1645 // Decode the second character of the format string.
1646 if (FormatStr[1] == 'c') {
1647 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1648 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1649 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1650 return ConstantInt::get(CI->getType(), 1);
1653 if (FormatStr[1] == 's') {
1654 // fprintf(F, "%s", str) -> fputs(str, F)
1655 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1657 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1664 } // end anonymous namespace.
1666 //===----------------------------------------------------------------------===//
1667 // SimplifyLibCalls Pass Implementation
1668 //===----------------------------------------------------------------------===//
1671 /// This pass optimizes well known library functions from libc and libm.
1673 class SimplifyLibCalls : public FunctionPass {
1674 StringMap<LibCallOptimization*> Optimizations;
1675 // String and Memory LibCall Optimizations
1676 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1677 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1678 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1680 // Math Library Optimizations
1681 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1682 // Integer Optimizations
1683 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1685 // Formatting and IO Optimizations
1686 SPrintFOpt SPrintF; PrintFOpt PrintF;
1687 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1689 // Object Size Checking
1691 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1693 bool Modified; // This is only used by doInitialization.
1695 static char ID; // Pass identification
1696 SimplifyLibCalls() : FunctionPass(&ID) {}
1698 void InitOptimizations();
1699 bool runOnFunction(Function &F);
1701 void setDoesNotAccessMemory(Function &F);
1702 void setOnlyReadsMemory(Function &F);
1703 void setDoesNotThrow(Function &F);
1704 void setDoesNotCapture(Function &F, unsigned n);
1705 void setDoesNotAlias(Function &F, unsigned n);
1706 bool doInitialization(Module &M);
1708 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1711 char SimplifyLibCalls::ID = 0;
1712 } // end anonymous namespace.
1714 static RegisterPass<SimplifyLibCalls>
1715 X("simplify-libcalls", "Simplify well-known library calls");
1717 // Public interface to the Simplify LibCalls pass.
1718 FunctionPass *llvm::createSimplifyLibCallsPass() {
1719 return new SimplifyLibCalls();
1722 /// Optimizations - Populate the Optimizations map with all the optimizations
1724 void SimplifyLibCalls::InitOptimizations() {
1725 // String and Memory LibCall Optimizations
1726 Optimizations["strcat"] = &StrCat;
1727 Optimizations["strncat"] = &StrNCat;
1728 Optimizations["strchr"] = &StrChr;
1729 Optimizations["strcmp"] = &StrCmp;
1730 Optimizations["strncmp"] = &StrNCmp;
1731 Optimizations["strcpy"] = &StrCpy;
1732 Optimizations["strncpy"] = &StrNCpy;
1733 Optimizations["strlen"] = &StrLen;
1734 Optimizations["strtol"] = &StrTo;
1735 Optimizations["strtod"] = &StrTo;
1736 Optimizations["strtof"] = &StrTo;
1737 Optimizations["strtoul"] = &StrTo;
1738 Optimizations["strtoll"] = &StrTo;
1739 Optimizations["strtold"] = &StrTo;
1740 Optimizations["strtoull"] = &StrTo;
1741 Optimizations["memcmp"] = &MemCmp;
1742 Optimizations["memcpy"] = &MemCpy;
1743 Optimizations["memmove"] = &MemMove;
1744 Optimizations["memset"] = &MemSet;
1746 // Math Library Optimizations
1747 Optimizations["powf"] = &Pow;
1748 Optimizations["pow"] = &Pow;
1749 Optimizations["powl"] = &Pow;
1750 Optimizations["llvm.pow.f32"] = &Pow;
1751 Optimizations["llvm.pow.f64"] = &Pow;
1752 Optimizations["llvm.pow.f80"] = &Pow;
1753 Optimizations["llvm.pow.f128"] = &Pow;
1754 Optimizations["llvm.pow.ppcf128"] = &Pow;
1755 Optimizations["exp2l"] = &Exp2;
1756 Optimizations["exp2"] = &Exp2;
1757 Optimizations["exp2f"] = &Exp2;
1758 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1759 Optimizations["llvm.exp2.f128"] = &Exp2;
1760 Optimizations["llvm.exp2.f80"] = &Exp2;
1761 Optimizations["llvm.exp2.f64"] = &Exp2;
1762 Optimizations["llvm.exp2.f32"] = &Exp2;
1765 Optimizations["floor"] = &UnaryDoubleFP;
1768 Optimizations["ceil"] = &UnaryDoubleFP;
1771 Optimizations["round"] = &UnaryDoubleFP;
1774 Optimizations["rint"] = &UnaryDoubleFP;
1776 #ifdef HAVE_NEARBYINTF
1777 Optimizations["nearbyint"] = &UnaryDoubleFP;
1780 // Integer Optimizations
1781 Optimizations["ffs"] = &FFS;
1782 Optimizations["ffsl"] = &FFS;
1783 Optimizations["ffsll"] = &FFS;
1784 Optimizations["abs"] = &Abs;
1785 Optimizations["labs"] = &Abs;
1786 Optimizations["llabs"] = &Abs;
1787 Optimizations["isdigit"] = &IsDigit;
1788 Optimizations["isascii"] = &IsAscii;
1789 Optimizations["toascii"] = &ToAscii;
1791 // Formatting and IO Optimizations
1792 Optimizations["sprintf"] = &SPrintF;
1793 Optimizations["printf"] = &PrintF;
1794 Optimizations["fwrite"] = &FWrite;
1795 Optimizations["fputs"] = &FPuts;
1796 Optimizations["fprintf"] = &FPrintF;
1798 // Object Size Checking
1799 Optimizations["llvm.objectsize.i32"] = &ObjectSize;
1800 Optimizations["llvm.objectsize.i64"] = &ObjectSize;
1801 Optimizations["__memcpy_chk"] = &MemCpyChk;
1802 Optimizations["__memset_chk"] = &MemSetChk;
1803 Optimizations["__memmove_chk"] = &MemMoveChk;
1807 /// runOnFunction - Top level algorithm.
1809 bool SimplifyLibCalls::runOnFunction(Function &F) {
1810 if (Optimizations.empty())
1811 InitOptimizations();
1813 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1815 IRBuilder<> Builder(F.getContext());
1817 bool Changed = false;
1818 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1819 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1820 // Ignore non-calls.
1821 CallInst *CI = dyn_cast<CallInst>(I++);
1824 // Ignore indirect calls and calls to non-external functions.
1825 Function *Callee = CI->getCalledFunction();
1826 if (Callee == 0 || !Callee->isDeclaration() ||
1827 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1830 // Ignore unknown calls.
1831 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1834 // Set the builder to the instruction after the call.
1835 Builder.SetInsertPoint(BB, I);
1837 // Try to optimize this call.
1838 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1839 if (Result == 0) continue;
1841 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1842 errs() << " into: " << *Result << "\n");
1844 // Something changed!
1848 // Inspect the instruction after the call (which was potentially just
1852 if (CI != Result && !CI->use_empty()) {
1853 CI->replaceAllUsesWith(Result);
1854 if (!Result->hasName())
1855 Result->takeName(CI);
1857 CI->eraseFromParent();
1863 // Utility methods for doInitialization.
1865 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1866 if (!F.doesNotAccessMemory()) {
1867 F.setDoesNotAccessMemory();
1872 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1873 if (!F.onlyReadsMemory()) {
1874 F.setOnlyReadsMemory();
1879 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1880 if (!F.doesNotThrow()) {
1881 F.setDoesNotThrow();
1886 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1887 if (!F.doesNotCapture(n)) {
1888 F.setDoesNotCapture(n);
1893 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1894 if (!F.doesNotAlias(n)) {
1895 F.setDoesNotAlias(n);
1901 /// doInitialization - Add attributes to well-known functions.
1903 bool SimplifyLibCalls::doInitialization(Module &M) {
1905 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1907 if (!F.isDeclaration())
1913 const FunctionType *FTy = F.getFunctionType();
1915 StringRef Name = F.getName();
1918 if (Name == "strlen") {
1919 if (FTy->getNumParams() != 1 ||
1920 !isa<PointerType>(FTy->getParamType(0)))
1922 setOnlyReadsMemory(F);
1924 setDoesNotCapture(F, 1);
1925 } else if (Name == "strcpy" ||
1931 Name == "strtoul" ||
1932 Name == "strtoll" ||
1933 Name == "strtold" ||
1934 Name == "strncat" ||
1935 Name == "strncpy" ||
1936 Name == "strtoull") {
1937 if (FTy->getNumParams() < 2 ||
1938 !isa<PointerType>(FTy->getParamType(1)))
1941 setDoesNotCapture(F, 2);
1942 } else if (Name == "strxfrm") {
1943 if (FTy->getNumParams() != 3 ||
1944 !isa<PointerType>(FTy->getParamType(0)) ||
1945 !isa<PointerType>(FTy->getParamType(1)))
1948 setDoesNotCapture(F, 1);
1949 setDoesNotCapture(F, 2);
1950 } else if (Name == "strcmp" ||
1952 Name == "strncmp" ||
1953 Name ==" strcspn" ||
1954 Name == "strcoll" ||
1955 Name == "strcasecmp" ||
1956 Name == "strncasecmp") {
1957 if (FTy->getNumParams() < 2 ||
1958 !isa<PointerType>(FTy->getParamType(0)) ||
1959 !isa<PointerType>(FTy->getParamType(1)))
1961 setOnlyReadsMemory(F);
1963 setDoesNotCapture(F, 1);
1964 setDoesNotCapture(F, 2);
1965 } else if (Name == "strstr" ||
1966 Name == "strpbrk") {
1967 if (FTy->getNumParams() != 2 ||
1968 !isa<PointerType>(FTy->getParamType(1)))
1970 setOnlyReadsMemory(F);
1972 setDoesNotCapture(F, 2);
1973 } else if (Name == "strtok" ||
1974 Name == "strtok_r") {
1975 if (FTy->getNumParams() < 2 ||
1976 !isa<PointerType>(FTy->getParamType(1)))
1979 setDoesNotCapture(F, 2);
1980 } else if (Name == "scanf" ||
1982 Name == "setvbuf") {
1983 if (FTy->getNumParams() < 1 ||
1984 !isa<PointerType>(FTy->getParamType(0)))
1987 setDoesNotCapture(F, 1);
1988 } else if (Name == "strdup" ||
1989 Name == "strndup") {
1990 if (FTy->getNumParams() < 1 ||
1991 !isa<PointerType>(FTy->getReturnType()) ||
1992 !isa<PointerType>(FTy->getParamType(0)))
1995 setDoesNotAlias(F, 0);
1996 setDoesNotCapture(F, 1);
1997 } else if (Name == "stat" ||
1999 Name == "sprintf" ||
2000 Name == "statvfs") {
2001 if (FTy->getNumParams() < 2 ||
2002 !isa<PointerType>(FTy->getParamType(0)) ||
2003 !isa<PointerType>(FTy->getParamType(1)))
2006 setDoesNotCapture(F, 1);
2007 setDoesNotCapture(F, 2);
2008 } else if (Name == "snprintf") {
2009 if (FTy->getNumParams() != 3 ||
2010 !isa<PointerType>(FTy->getParamType(0)) ||
2011 !isa<PointerType>(FTy->getParamType(2)))
2014 setDoesNotCapture(F, 1);
2015 setDoesNotCapture(F, 3);
2016 } else if (Name == "setitimer") {
2017 if (FTy->getNumParams() != 3 ||
2018 !isa<PointerType>(FTy->getParamType(1)) ||
2019 !isa<PointerType>(FTy->getParamType(2)))
2022 setDoesNotCapture(F, 2);
2023 setDoesNotCapture(F, 3);
2024 } else if (Name == "system") {
2025 if (FTy->getNumParams() != 1 ||
2026 !isa<PointerType>(FTy->getParamType(0)))
2028 // May throw; "system" is a valid pthread cancellation point.
2029 setDoesNotCapture(F, 1);
2033 if (Name == "malloc") {
2034 if (FTy->getNumParams() != 1 ||
2035 !isa<PointerType>(FTy->getReturnType()))
2038 setDoesNotAlias(F, 0);
2039 } else if (Name == "memcmp") {
2040 if (FTy->getNumParams() != 3 ||
2041 !isa<PointerType>(FTy->getParamType(0)) ||
2042 !isa<PointerType>(FTy->getParamType(1)))
2044 setOnlyReadsMemory(F);
2046 setDoesNotCapture(F, 1);
2047 setDoesNotCapture(F, 2);
2048 } else if (Name == "memchr" ||
2049 Name == "memrchr") {
2050 if (FTy->getNumParams() != 3)
2052 setOnlyReadsMemory(F);
2054 } else if (Name == "modf" ||
2058 Name == "memccpy" ||
2059 Name == "memmove") {
2060 if (FTy->getNumParams() < 2 ||
2061 !isa<PointerType>(FTy->getParamType(1)))
2064 setDoesNotCapture(F, 2);
2065 } else if (Name == "memalign") {
2066 if (!isa<PointerType>(FTy->getReturnType()))
2068 setDoesNotAlias(F, 0);
2069 } else if (Name == "mkdir" ||
2071 if (FTy->getNumParams() == 0 ||
2072 !isa<PointerType>(FTy->getParamType(0)))
2075 setDoesNotCapture(F, 1);
2079 if (Name == "realloc") {
2080 if (FTy->getNumParams() != 2 ||
2081 !isa<PointerType>(FTy->getParamType(0)) ||
2082 !isa<PointerType>(FTy->getReturnType()))
2085 setDoesNotAlias(F, 0);
2086 setDoesNotCapture(F, 1);
2087 } else if (Name == "read") {
2088 if (FTy->getNumParams() != 3 ||
2089 !isa<PointerType>(FTy->getParamType(1)))
2091 // May throw; "read" is a valid pthread cancellation point.
2092 setDoesNotCapture(F, 2);
2093 } else if (Name == "rmdir" ||
2096 Name == "realpath") {
2097 if (FTy->getNumParams() < 1 ||
2098 !isa<PointerType>(FTy->getParamType(0)))
2101 setDoesNotCapture(F, 1);
2102 } else if (Name == "rename" ||
2103 Name == "readlink") {
2104 if (FTy->getNumParams() < 2 ||
2105 !isa<PointerType>(FTy->getParamType(0)) ||
2106 !isa<PointerType>(FTy->getParamType(1)))
2109 setDoesNotCapture(F, 1);
2110 setDoesNotCapture(F, 2);
2114 if (Name == "write") {
2115 if (FTy->getNumParams() != 3 ||
2116 !isa<PointerType>(FTy->getParamType(1)))
2118 // May throw; "write" is a valid pthread cancellation point.
2119 setDoesNotCapture(F, 2);
2123 if (Name == "bcopy") {
2124 if (FTy->getNumParams() != 3 ||
2125 !isa<PointerType>(FTy->getParamType(0)) ||
2126 !isa<PointerType>(FTy->getParamType(1)))
2129 setDoesNotCapture(F, 1);
2130 setDoesNotCapture(F, 2);
2131 } else if (Name == "bcmp") {
2132 if (FTy->getNumParams() != 3 ||
2133 !isa<PointerType>(FTy->getParamType(0)) ||
2134 !isa<PointerType>(FTy->getParamType(1)))
2137 setOnlyReadsMemory(F);
2138 setDoesNotCapture(F, 1);
2139 setDoesNotCapture(F, 2);
2140 } else if (Name == "bzero") {
2141 if (FTy->getNumParams() != 2 ||
2142 !isa<PointerType>(FTy->getParamType(0)))
2145 setDoesNotCapture(F, 1);
2149 if (Name == "calloc") {
2150 if (FTy->getNumParams() != 2 ||
2151 !isa<PointerType>(FTy->getReturnType()))
2154 setDoesNotAlias(F, 0);
2155 } else if (Name == "chmod" ||
2157 Name == "ctermid" ||
2158 Name == "clearerr" ||
2159 Name == "closedir") {
2160 if (FTy->getNumParams() == 0 ||
2161 !isa<PointerType>(FTy->getParamType(0)))
2164 setDoesNotCapture(F, 1);
2168 if (Name == "atoi" ||
2172 if (FTy->getNumParams() != 1 ||
2173 !isa<PointerType>(FTy->getParamType(0)))
2176 setOnlyReadsMemory(F);
2177 setDoesNotCapture(F, 1);
2178 } else if (Name == "access") {
2179 if (FTy->getNumParams() != 2 ||
2180 !isa<PointerType>(FTy->getParamType(0)))
2183 setDoesNotCapture(F, 1);
2187 if (Name == "fopen") {
2188 if (FTy->getNumParams() != 2 ||
2189 !isa<PointerType>(FTy->getReturnType()) ||
2190 !isa<PointerType>(FTy->getParamType(0)) ||
2191 !isa<PointerType>(FTy->getParamType(1)))
2194 setDoesNotAlias(F, 0);
2195 setDoesNotCapture(F, 1);
2196 setDoesNotCapture(F, 2);
2197 } else if (Name == "fdopen") {
2198 if (FTy->getNumParams() != 2 ||
2199 !isa<PointerType>(FTy->getReturnType()) ||
2200 !isa<PointerType>(FTy->getParamType(1)))
2203 setDoesNotAlias(F, 0);
2204 setDoesNotCapture(F, 2);
2205 } else if (Name == "feof" ||
2215 Name == "fsetpos" ||
2216 Name == "flockfile" ||
2217 Name == "funlockfile" ||
2218 Name == "ftrylockfile") {
2219 if (FTy->getNumParams() == 0 ||
2220 !isa<PointerType>(FTy->getParamType(0)))
2223 setDoesNotCapture(F, 1);
2224 } else if (Name == "ferror") {
2225 if (FTy->getNumParams() != 1 ||
2226 !isa<PointerType>(FTy->getParamType(0)))
2229 setDoesNotCapture(F, 1);
2230 setOnlyReadsMemory(F);
2231 } else if (Name == "fputc" ||
2236 Name == "fstatvfs") {
2237 if (FTy->getNumParams() != 2 ||
2238 !isa<PointerType>(FTy->getParamType(1)))
2241 setDoesNotCapture(F, 2);
2242 } else if (Name == "fgets") {
2243 if (FTy->getNumParams() != 3 ||
2244 !isa<PointerType>(FTy->getParamType(0)) ||
2245 !isa<PointerType>(FTy->getParamType(2)))
2248 setDoesNotCapture(F, 3);
2249 } else if (Name == "fread" ||
2251 if (FTy->getNumParams() != 4 ||
2252 !isa<PointerType>(FTy->getParamType(0)) ||
2253 !isa<PointerType>(FTy->getParamType(3)))
2256 setDoesNotCapture(F, 1);
2257 setDoesNotCapture(F, 4);
2258 } else if (Name == "fputs" ||
2260 Name == "fprintf" ||
2261 Name == "fgetpos") {
2262 if (FTy->getNumParams() < 2 ||
2263 !isa<PointerType>(FTy->getParamType(0)) ||
2264 !isa<PointerType>(FTy->getParamType(1)))
2267 setDoesNotCapture(F, 1);
2268 setDoesNotCapture(F, 2);
2272 if (Name == "getc" ||
2273 Name == "getlogin_r" ||
2274 Name == "getc_unlocked") {
2275 if (FTy->getNumParams() == 0 ||
2276 !isa<PointerType>(FTy->getParamType(0)))
2279 setDoesNotCapture(F, 1);
2280 } else if (Name == "getenv") {
2281 if (FTy->getNumParams() != 1 ||
2282 !isa<PointerType>(FTy->getParamType(0)))
2285 setOnlyReadsMemory(F);
2286 setDoesNotCapture(F, 1);
2287 } else if (Name == "gets" ||
2288 Name == "getchar") {
2290 } else if (Name == "getitimer") {
2291 if (FTy->getNumParams() != 2 ||
2292 !isa<PointerType>(FTy->getParamType(1)))
2295 setDoesNotCapture(F, 2);
2296 } else if (Name == "getpwnam") {
2297 if (FTy->getNumParams() != 1 ||
2298 !isa<PointerType>(FTy->getParamType(0)))
2301 setDoesNotCapture(F, 1);
2305 if (Name == "ungetc") {
2306 if (FTy->getNumParams() != 2 ||
2307 !isa<PointerType>(FTy->getParamType(1)))
2310 setDoesNotCapture(F, 2);
2311 } else if (Name == "uname" ||
2313 Name == "unsetenv") {
2314 if (FTy->getNumParams() != 1 ||
2315 !isa<PointerType>(FTy->getParamType(0)))
2318 setDoesNotCapture(F, 1);
2319 } else if (Name == "utime" ||
2321 if (FTy->getNumParams() != 2 ||
2322 !isa<PointerType>(FTy->getParamType(0)) ||
2323 !isa<PointerType>(FTy->getParamType(1)))
2326 setDoesNotCapture(F, 1);
2327 setDoesNotCapture(F, 2);
2331 if (Name == "putc") {
2332 if (FTy->getNumParams() != 2 ||
2333 !isa<PointerType>(FTy->getParamType(1)))
2336 setDoesNotCapture(F, 2);
2337 } else if (Name == "puts" ||
2340 if (FTy->getNumParams() != 1 ||
2341 !isa<PointerType>(FTy->getParamType(0)))
2344 setDoesNotCapture(F, 1);
2345 } else if (Name == "pread" ||
2347 if (FTy->getNumParams() != 4 ||
2348 !isa<PointerType>(FTy->getParamType(1)))
2350 // May throw; these are valid pthread cancellation points.
2351 setDoesNotCapture(F, 2);
2352 } else if (Name == "putchar") {
2354 } else if (Name == "popen") {
2355 if (FTy->getNumParams() != 2 ||
2356 !isa<PointerType>(FTy->getReturnType()) ||
2357 !isa<PointerType>(FTy->getParamType(0)) ||
2358 !isa<PointerType>(FTy->getParamType(1)))
2361 setDoesNotAlias(F, 0);
2362 setDoesNotCapture(F, 1);
2363 setDoesNotCapture(F, 2);
2364 } else if (Name == "pclose") {
2365 if (FTy->getNumParams() != 1 ||
2366 !isa<PointerType>(FTy->getParamType(0)))
2369 setDoesNotCapture(F, 1);
2373 if (Name == "vscanf") {
2374 if (FTy->getNumParams() != 2 ||
2375 !isa<PointerType>(FTy->getParamType(1)))
2378 setDoesNotCapture(F, 1);
2379 } else if (Name == "vsscanf" ||
2380 Name == "vfscanf") {
2381 if (FTy->getNumParams() != 3 ||
2382 !isa<PointerType>(FTy->getParamType(1)) ||
2383 !isa<PointerType>(FTy->getParamType(2)))
2386 setDoesNotCapture(F, 1);
2387 setDoesNotCapture(F, 2);
2388 } else if (Name == "valloc") {
2389 if (!isa<PointerType>(FTy->getReturnType()))
2392 setDoesNotAlias(F, 0);
2393 } else if (Name == "vprintf") {
2394 if (FTy->getNumParams() != 2 ||
2395 !isa<PointerType>(FTy->getParamType(0)))
2398 setDoesNotCapture(F, 1);
2399 } else if (Name == "vfprintf" ||
2400 Name == "vsprintf") {
2401 if (FTy->getNumParams() != 3 ||
2402 !isa<PointerType>(FTy->getParamType(0)) ||
2403 !isa<PointerType>(FTy->getParamType(1)))
2406 setDoesNotCapture(F, 1);
2407 setDoesNotCapture(F, 2);
2408 } else if (Name == "vsnprintf") {
2409 if (FTy->getNumParams() != 4 ||
2410 !isa<PointerType>(FTy->getParamType(0)) ||
2411 !isa<PointerType>(FTy->getParamType(2)))
2414 setDoesNotCapture(F, 1);
2415 setDoesNotCapture(F, 3);
2419 if (Name == "open") {
2420 if (FTy->getNumParams() < 2 ||
2421 !isa<PointerType>(FTy->getParamType(0)))
2423 // May throw; "open" is a valid pthread cancellation point.
2424 setDoesNotCapture(F, 1);
2425 } else if (Name == "opendir") {
2426 if (FTy->getNumParams() != 1 ||
2427 !isa<PointerType>(FTy->getReturnType()) ||
2428 !isa<PointerType>(FTy->getParamType(0)))
2431 setDoesNotAlias(F, 0);
2432 setDoesNotCapture(F, 1);
2436 if (Name == "tmpfile") {
2437 if (!isa<PointerType>(FTy->getReturnType()))
2440 setDoesNotAlias(F, 0);
2441 } else if (Name == "times") {
2442 if (FTy->getNumParams() != 1 ||
2443 !isa<PointerType>(FTy->getParamType(0)))
2446 setDoesNotCapture(F, 1);
2450 if (Name == "htonl" ||
2453 setDoesNotAccessMemory(F);
2457 if (Name == "ntohl" ||
2460 setDoesNotAccessMemory(F);
2464 if (Name == "lstat") {
2465 if (FTy->getNumParams() != 2 ||
2466 !isa<PointerType>(FTy->getParamType(0)) ||
2467 !isa<PointerType>(FTy->getParamType(1)))
2470 setDoesNotCapture(F, 1);
2471 setDoesNotCapture(F, 2);
2472 } else if (Name == "lchown") {
2473 if (FTy->getNumParams() != 3 ||
2474 !isa<PointerType>(FTy->getParamType(0)))
2477 setDoesNotCapture(F, 1);
2481 if (Name == "qsort") {
2482 if (FTy->getNumParams() != 4 ||
2483 !isa<PointerType>(FTy->getParamType(3)))
2485 // May throw; places call through function pointer.
2486 setDoesNotCapture(F, 4);
2490 if (Name == "__strdup" ||
2491 Name == "__strndup") {
2492 if (FTy->getNumParams() < 1 ||
2493 !isa<PointerType>(FTy->getReturnType()) ||
2494 !isa<PointerType>(FTy->getParamType(0)))
2497 setDoesNotAlias(F, 0);
2498 setDoesNotCapture(F, 1);
2499 } else if (Name == "__strtok_r") {
2500 if (FTy->getNumParams() != 3 ||
2501 !isa<PointerType>(FTy->getParamType(1)))
2504 setDoesNotCapture(F, 2);
2505 } else if (Name == "_IO_getc") {
2506 if (FTy->getNumParams() != 1 ||
2507 !isa<PointerType>(FTy->getParamType(0)))
2510 setDoesNotCapture(F, 1);
2511 } else if (Name == "_IO_putc") {
2512 if (FTy->getNumParams() != 2 ||
2513 !isa<PointerType>(FTy->getParamType(1)))
2516 setDoesNotCapture(F, 2);
2520 if (Name == "\1__isoc99_scanf") {
2521 if (FTy->getNumParams() < 1 ||
2522 !isa<PointerType>(FTy->getParamType(0)))
2525 setDoesNotCapture(F, 1);
2526 } else if (Name == "\1stat64" ||
2527 Name == "\1lstat64" ||
2528 Name == "\1statvfs64" ||
2529 Name == "\1__isoc99_sscanf") {
2530 if (FTy->getNumParams() < 1 ||
2531 !isa<PointerType>(FTy->getParamType(0)) ||
2532 !isa<PointerType>(FTy->getParamType(1)))
2535 setDoesNotCapture(F, 1);
2536 setDoesNotCapture(F, 2);
2537 } else if (Name == "\1fopen64") {
2538 if (FTy->getNumParams() != 2 ||
2539 !isa<PointerType>(FTy->getReturnType()) ||
2540 !isa<PointerType>(FTy->getParamType(0)) ||
2541 !isa<PointerType>(FTy->getParamType(1)))
2544 setDoesNotAlias(F, 0);
2545 setDoesNotCapture(F, 1);
2546 setDoesNotCapture(F, 2);
2547 } else if (Name == "\1fseeko64" ||
2548 Name == "\1ftello64") {
2549 if (FTy->getNumParams() == 0 ||
2550 !isa<PointerType>(FTy->getParamType(0)))
2553 setDoesNotCapture(F, 1);
2554 } else if (Name == "\1tmpfile64") {
2555 if (!isa<PointerType>(FTy->getReturnType()))
2558 setDoesNotAlias(F, 0);
2559 } else if (Name == "\1fstat64" ||
2560 Name == "\1fstatvfs64") {
2561 if (FTy->getNumParams() != 2 ||
2562 !isa<PointerType>(FTy->getParamType(1)))
2565 setDoesNotCapture(F, 2);
2566 } else if (Name == "\1open64") {
2567 if (FTy->getNumParams() < 2 ||
2568 !isa<PointerType>(FTy->getParamType(0)))
2570 // May throw; "open" is a valid pthread cancellation point.
2571 setDoesNotCapture(F, 1);
2580 // Additional cases that we need to add to this file:
2583 // * cbrt(expN(X)) -> expN(x/3)
2584 // * cbrt(sqrt(x)) -> pow(x,1/6)
2585 // * cbrt(sqrt(x)) -> pow(x,1/9)
2588 // * cos(-x) -> cos(x)
2591 // * exp(log(x)) -> x
2594 // * log(exp(x)) -> x
2595 // * log(x**y) -> y*log(x)
2596 // * log(exp(y)) -> y*log(e)
2597 // * log(exp2(y)) -> y*log(2)
2598 // * log(exp10(y)) -> y*log(10)
2599 // * log(sqrt(x)) -> 0.5*log(x)
2600 // * log(pow(x,y)) -> y*log(x)
2602 // lround, lroundf, lroundl:
2603 // * lround(cnst) -> cnst'
2606 // * pow(exp(x),y) -> exp(x*y)
2607 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2608 // * pow(pow(x,y),z)-> pow(x,y*z)
2611 // * puts("") -> putchar("\n")
2613 // round, roundf, roundl:
2614 // * round(cnst) -> cnst'
2617 // * signbit(cnst) -> cnst'
2618 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2620 // sqrt, sqrtf, sqrtl:
2621 // * sqrt(expN(x)) -> expN(x*0.5)
2622 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2623 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2626 // * stpcpy(str, "literal") ->
2627 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2629 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2630 // (if c is a constant integer and s is a constant string)
2631 // * strrchr(s1,0) -> strchr(s1,0)
2634 // * strpbrk(s,a) -> offset_in_for(s,a)
2635 // (if s and a are both constant strings)
2636 // * strpbrk(s,"") -> 0
2637 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2640 // * strspn(s,a) -> const_int (if both args are constant)
2641 // * strspn("",a) -> 0
2642 // * strspn(s,"") -> 0
2643 // * strcspn(s,a) -> const_int (if both args are constant)
2644 // * strcspn("",a) -> 0
2645 // * strcspn(s,"") -> strlen(a)
2648 // * strstr(x,x) -> x
2649 // * strstr(x, "") -> x
2650 // * strstr(x, "a") -> strchr(x, 'a')
2651 // * strstr(s1,s2) -> result (if s1 and s2 are constant strings)
2654 // * tan(atan(x)) -> x
2656 // trunc, truncf, truncl:
2657 // * trunc(cnst) -> cnst'