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 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
80 /// specified pointer and character. Ptr is required to be some pointer type,
81 /// and the return value has 'i8*' type.
82 Value *EmitStrChr(Value *Ptr, char C, IRBuilder<> &B);
84 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
85 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
86 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
87 unsigned Align, IRBuilder<> &B);
89 /// EmitMemMove - Emit a call to the memmove function to the builder. This
90 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
91 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
92 unsigned Align, IRBuilder<> &B);
94 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
95 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
96 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
98 /// EmitMemCmp - Emit a call to the memcmp function.
99 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
101 /// EmitMemSet - Emit a call to the memset function
102 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
104 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name'
105 /// (e.g. 'floor'). This function is known to take a single of type matching
106 /// 'Op' and returns one value with the same type. If 'Op' is a long double,
107 /// 'l' is added as the suffix of name, if 'Op' is a float, we add a 'f'
109 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
110 const AttrListPtr &Attrs);
112 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
114 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
116 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
118 void EmitPutS(Value *Str, IRBuilder<> &B);
120 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
121 /// an i32, and File is a pointer to FILE.
122 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
124 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
125 /// pointer and File is a pointer to FILE.
126 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
128 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
129 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
130 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
133 } // End anonymous namespace.
135 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
136 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
137 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
140 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
141 /// specified pointer. This always returns an integer value of size intptr_t.
142 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
143 Module *M = Caller->getParent();
144 AttributeWithIndex AWI[2];
145 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
146 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
147 Attribute::NoUnwind);
149 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
150 TD->getIntPtrType(*Context),
151 Type::getInt8PtrTy(*Context),
153 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
154 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
155 CI->setCallingConv(F->getCallingConv());
160 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
161 /// specified pointer and character. Ptr is required to be some pointer type,
162 /// and the return value has 'i8*' type.
163 Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
164 Module *M = Caller->getParent();
165 AttributeWithIndex AWI =
166 AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
168 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
169 const Type *I32Ty = Type::getInt32Ty(*Context);
170 Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
171 I8Ptr, I8Ptr, I32Ty, NULL);
172 CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
173 ConstantInt::get(I32Ty, C), "strchr");
174 if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
175 CI->setCallingConv(F->getCallingConv());
180 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
181 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
182 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
183 unsigned Align, IRBuilder<> &B) {
184 Module *M = Caller->getParent();
185 const Type *Ty = Len->getType();
186 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
187 Dst = CastToCStr(Dst, B);
188 Src = CastToCStr(Src, B);
189 return B.CreateCall4(MemCpy, Dst, Src, Len,
190 ConstantInt::get(Type::getInt32Ty(*Context), Align));
193 /// EmitMemMove - Emit a call to the memmove function to the builder. This
194 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
195 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
196 unsigned Align, IRBuilder<> &B) {
197 Module *M = Caller->getParent();
198 const Type *Ty = TD->getIntPtrType(*Context);
199 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
200 Dst = CastToCStr(Dst, B);
201 Src = CastToCStr(Src, B);
202 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
203 return B.CreateCall4(MemMove, Dst, Src, Len, A);
206 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
207 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
208 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
209 Value *Len, IRBuilder<> &B) {
210 Module *M = Caller->getParent();
211 AttributeWithIndex AWI;
212 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
214 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
215 Type::getInt8PtrTy(*Context),
216 Type::getInt8PtrTy(*Context),
217 Type::getInt32Ty(*Context),
218 TD->getIntPtrType(*Context),
220 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
222 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
223 CI->setCallingConv(F->getCallingConv());
228 /// EmitMemCmp - Emit a call to the memcmp function.
229 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
230 Value *Len, IRBuilder<> &B) {
231 Module *M = Caller->getParent();
232 AttributeWithIndex AWI[3];
233 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
234 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
235 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
236 Attribute::NoUnwind);
238 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
239 Type::getInt32Ty(*Context),
240 Type::getInt8PtrTy(*Context),
241 Type::getInt8PtrTy(*Context),
242 TD->getIntPtrType(*Context), NULL);
243 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
246 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
247 CI->setCallingConv(F->getCallingConv());
252 /// EmitMemSet - Emit a call to the memset function
253 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
254 Value *Len, IRBuilder<> &B) {
255 Module *M = Caller->getParent();
256 Intrinsic::ID IID = Intrinsic::memset;
258 Tys[0] = Len->getType();
259 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
260 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
261 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
264 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
265 /// 'floor'). This function is known to take a single of type matching 'Op' and
266 /// returns one value with the same type. If 'Op' is a long double, 'l' is
267 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
268 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
270 const AttrListPtr &Attrs) {
272 if (!Op->getType()->isDoubleTy()) {
273 // If we need to add a suffix, copy into NameBuffer.
274 unsigned NameLen = strlen(Name);
275 assert(NameLen < sizeof(NameBuffer)-2);
276 memcpy(NameBuffer, Name, NameLen);
277 if (Op->getType()->isFloatTy())
278 NameBuffer[NameLen] = 'f'; // floorf
280 NameBuffer[NameLen] = 'l'; // floorl
281 NameBuffer[NameLen+1] = 0;
285 Module *M = Caller->getParent();
286 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
287 Op->getType(), NULL);
288 CallInst *CI = B.CreateCall(Callee, Op, Name);
289 CI->setAttributes(Attrs);
290 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
291 CI->setCallingConv(F->getCallingConv());
296 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
298 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
299 Module *M = Caller->getParent();
300 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
301 Type::getInt32Ty(*Context), NULL);
302 CallInst *CI = B.CreateCall(PutChar,
303 B.CreateIntCast(Char,
304 Type::getInt32Ty(*Context),
309 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
310 CI->setCallingConv(F->getCallingConv());
314 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
316 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
317 Module *M = Caller->getParent();
318 AttributeWithIndex AWI[2];
319 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
320 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
322 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
323 Type::getInt32Ty(*Context),
324 Type::getInt8PtrTy(*Context),
326 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
327 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
328 CI->setCallingConv(F->getCallingConv());
332 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
333 /// an integer and File is a pointer to FILE.
334 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
335 Module *M = Caller->getParent();
336 AttributeWithIndex AWI[2];
337 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
338 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
340 if (isa<PointerType>(File->getType()))
341 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
342 Type::getInt32Ty(*Context),
343 Type::getInt32Ty(*Context), File->getType(),
346 F = M->getOrInsertFunction("fputc",
347 Type::getInt32Ty(*Context),
348 Type::getInt32Ty(*Context),
349 File->getType(), NULL);
350 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
352 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
354 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
355 CI->setCallingConv(Fn->getCallingConv());
358 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
359 /// pointer and File is a pointer to FILE.
360 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
361 Module *M = Caller->getParent();
362 AttributeWithIndex AWI[3];
363 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
364 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
365 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
367 if (isa<PointerType>(File->getType()))
368 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
369 Type::getInt32Ty(*Context),
370 Type::getInt8PtrTy(*Context),
371 File->getType(), NULL);
373 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
374 Type::getInt8PtrTy(*Context),
375 File->getType(), NULL);
376 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
378 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
379 CI->setCallingConv(Fn->getCallingConv());
382 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
383 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
384 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
386 Module *M = Caller->getParent();
387 AttributeWithIndex AWI[3];
388 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
389 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
390 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
392 if (isa<PointerType>(File->getType()))
393 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
394 TD->getIntPtrType(*Context),
395 Type::getInt8PtrTy(*Context),
396 TD->getIntPtrType(*Context),
397 TD->getIntPtrType(*Context),
398 File->getType(), NULL);
400 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
401 Type::getInt8PtrTy(*Context),
402 TD->getIntPtrType(*Context),
403 TD->getIntPtrType(*Context),
404 File->getType(), NULL);
405 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
406 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
408 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
409 CI->setCallingConv(Fn->getCallingConv());
412 //===----------------------------------------------------------------------===//
414 //===----------------------------------------------------------------------===//
416 /// GetStringLengthH - If we can compute the length of the string pointed to by
417 /// the specified pointer, return 'len+1'. If we can't, return 0.
418 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
419 // Look through noop bitcast instructions.
420 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
421 return GetStringLengthH(BCI->getOperand(0), PHIs);
423 // If this is a PHI node, there are two cases: either we have already seen it
425 if (PHINode *PN = dyn_cast<PHINode>(V)) {
426 if (!PHIs.insert(PN))
427 return ~0ULL; // already in the set.
429 // If it was new, see if all the input strings are the same length.
430 uint64_t LenSoFar = ~0ULL;
431 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
432 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
433 if (Len == 0) return 0; // Unknown length -> unknown.
435 if (Len == ~0ULL) continue;
437 if (Len != LenSoFar && LenSoFar != ~0ULL)
438 return 0; // Disagree -> unknown.
442 // Success, all agree.
446 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
447 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
448 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
449 if (Len1 == 0) return 0;
450 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
451 if (Len2 == 0) return 0;
452 if (Len1 == ~0ULL) return Len2;
453 if (Len2 == ~0ULL) return Len1;
454 if (Len1 != Len2) return 0;
458 // If the value is not a GEP instruction nor a constant expression with a
459 // GEP instruction, then return unknown.
461 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
463 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
464 if (CE->getOpcode() != Instruction::GetElementPtr)
471 // Make sure the GEP has exactly three arguments.
472 if (GEP->getNumOperands() != 3)
475 // Check to make sure that the first operand of the GEP is an integer and
476 // has value 0 so that we are sure we're indexing into the initializer.
477 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
483 // If the second index isn't a ConstantInt, then this is a variable index
484 // into the array. If this occurs, we can't say anything meaningful about
486 uint64_t StartIdx = 0;
487 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
488 StartIdx = CI->getZExtValue();
492 // The GEP instruction, constant or instruction, must reference a global
493 // variable that is a constant and is initialized. The referenced constant
494 // initializer is the array that we'll use for optimization.
495 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
496 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
497 GV->mayBeOverridden())
499 Constant *GlobalInit = GV->getInitializer();
501 // Handle the ConstantAggregateZero case, which is a degenerate case. The
502 // initializer is constant zero so the length of the string must be zero.
503 if (isa<ConstantAggregateZero>(GlobalInit))
504 return 1; // Len = 0 offset by 1.
506 // Must be a Constant Array
507 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
509 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
512 // Get the number of elements in the array
513 uint64_t NumElts = Array->getType()->getNumElements();
515 // Traverse the constant array from StartIdx (derived above) which is
516 // the place the GEP refers to in the array.
517 for (unsigned i = StartIdx; i != NumElts; ++i) {
518 Constant *Elt = Array->getOperand(i);
519 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
520 if (!CI) // This array isn't suitable, non-int initializer.
523 return i-StartIdx+1; // We found end of string, success!
526 return 0; // The array isn't null terminated, conservatively return 'unknown'.
529 /// GetStringLength - If we can compute the length of the string pointed to by
530 /// the specified pointer, return 'len+1'. If we can't, return 0.
531 static uint64_t GetStringLength(Value *V) {
532 if (!isa<PointerType>(V->getType())) return 0;
534 SmallPtrSet<PHINode*, 32> PHIs;
535 uint64_t Len = GetStringLengthH(V, PHIs);
536 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
537 // an empty string as a length.
538 return Len == ~0ULL ? 1 : Len;
541 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
542 /// value is equal or not-equal to zero.
543 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
544 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
546 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
547 if (IC->isEquality())
548 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
549 if (C->isNullValue())
551 // Unknown instruction.
557 //===----------------------------------------------------------------------===//
558 // String and Memory LibCall Optimizations
559 //===----------------------------------------------------------------------===//
561 //===---------------------------------------===//
562 // 'strcat' Optimizations
564 struct StrCatOpt : public LibCallOptimization {
565 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
566 // Verify the "strcat" function prototype.
567 const FunctionType *FT = Callee->getFunctionType();
568 if (FT->getNumParams() != 2 ||
569 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
570 FT->getParamType(0) != FT->getReturnType() ||
571 FT->getParamType(1) != FT->getReturnType())
574 // Extract some information from the instruction
575 Value *Dst = CI->getOperand(1);
576 Value *Src = CI->getOperand(2);
578 // See if we can get the length of the input string.
579 uint64_t Len = GetStringLength(Src);
580 if (Len == 0) return 0;
581 --Len; // Unbias length.
583 // Handle the simple, do-nothing case: strcat(x, "") -> x
587 // These optimizations require TargetData.
590 EmitStrLenMemCpy(Src, Dst, Len, B);
594 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
595 // We need to find the end of the destination string. That's where the
596 // memory is to be moved to. We just generate a call to strlen.
597 Value *DstLen = EmitStrLen(Dst, B);
599 // Now that we have the destination's length, we must index into the
600 // destination's pointer to get the actual memcpy destination (end of
601 // the string .. we're concatenating).
602 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
604 // We have enough information to now generate the memcpy call to do the
605 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
606 EmitMemCpy(CpyDst, Src,
607 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
611 //===---------------------------------------===//
612 // 'strncat' Optimizations
614 struct StrNCatOpt : public StrCatOpt {
615 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
616 // Verify the "strncat" function prototype.
617 const FunctionType *FT = Callee->getFunctionType();
618 if (FT->getNumParams() != 3 ||
619 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
620 FT->getParamType(0) != FT->getReturnType() ||
621 FT->getParamType(1) != FT->getReturnType() ||
622 !isa<IntegerType>(FT->getParamType(2)))
625 // Extract some information from the instruction
626 Value *Dst = CI->getOperand(1);
627 Value *Src = CI->getOperand(2);
630 // We don't do anything if length is not constant
631 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
632 Len = LengthArg->getZExtValue();
636 // See if we can get the length of the input string.
637 uint64_t SrcLen = GetStringLength(Src);
638 if (SrcLen == 0) return 0;
639 --SrcLen; // Unbias length.
641 // Handle the simple, do-nothing cases:
642 // strncat(x, "", c) -> x
643 // strncat(x, c, 0) -> x
644 if (SrcLen == 0 || Len == 0) return Dst;
646 // These optimizations require TargetData.
649 // We don't optimize this case
650 if (Len < SrcLen) return 0;
652 // strncat(x, s, c) -> strcat(x, s)
653 // s is constant so the strcat can be optimized further
654 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
659 //===---------------------------------------===//
660 // 'strchr' Optimizations
662 struct StrChrOpt : public LibCallOptimization {
663 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
664 // Verify the "strchr" function prototype.
665 const FunctionType *FT = Callee->getFunctionType();
666 if (FT->getNumParams() != 2 ||
667 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
668 FT->getParamType(0) != FT->getReturnType())
671 Value *SrcStr = CI->getOperand(1);
673 // If the second operand is non-constant, see if we can compute the length
674 // of the input string and turn this into memchr.
675 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
677 // These optimizations require TargetData.
680 uint64_t Len = GetStringLength(SrcStr);
682 FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs
686 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
687 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
690 // Otherwise, the character is a constant, see if the first argument is
691 // a string literal. If so, we can constant fold.
693 if (!GetConstantStringInfo(SrcStr, Str))
696 // strchr can find the nul character.
698 char CharValue = CharC->getSExtValue();
700 // Compute the offset.
703 if (i == Str.size()) // Didn't find the char. strchr returns null.
704 return Constant::getNullValue(CI->getType());
705 // Did we find our match?
706 if (Str[i] == CharValue)
711 // strchr(s+n,c) -> gep(s+n+i,c)
712 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
713 return B.CreateGEP(SrcStr, Idx, "strchr");
717 //===---------------------------------------===//
718 // 'strcmp' Optimizations
720 struct StrCmpOpt : public LibCallOptimization {
721 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
722 // Verify the "strcmp" function prototype.
723 const FunctionType *FT = Callee->getFunctionType();
724 if (FT->getNumParams() != 2 ||
725 FT->getReturnType() != Type::getInt32Ty(*Context) ||
726 FT->getParamType(0) != FT->getParamType(1) ||
727 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
730 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
731 if (Str1P == Str2P) // strcmp(x,x) -> 0
732 return ConstantInt::get(CI->getType(), 0);
734 std::string Str1, Str2;
735 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
736 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
738 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
739 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
741 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
742 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
744 // strcmp(x, y) -> cnst (if both x and y are constant strings)
745 if (HasStr1 && HasStr2)
746 return ConstantInt::get(CI->getType(),
747 strcmp(Str1.c_str(),Str2.c_str()));
749 // strcmp(P, "x") -> memcmp(P, "x", 2)
750 uint64_t Len1 = GetStringLength(Str1P);
751 uint64_t Len2 = GetStringLength(Str2P);
753 // These optimizations require TargetData.
756 return EmitMemCmp(Str1P, Str2P,
757 ConstantInt::get(TD->getIntPtrType(*Context),
758 std::min(Len1, Len2)), B);
765 //===---------------------------------------===//
766 // 'strncmp' Optimizations
768 struct StrNCmpOpt : public LibCallOptimization {
769 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
770 // Verify the "strncmp" function prototype.
771 const FunctionType *FT = Callee->getFunctionType();
772 if (FT->getNumParams() != 3 ||
773 FT->getReturnType() != Type::getInt32Ty(*Context) ||
774 FT->getParamType(0) != FT->getParamType(1) ||
775 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
776 !isa<IntegerType>(FT->getParamType(2)))
779 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
780 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
781 return ConstantInt::get(CI->getType(), 0);
783 // Get the length argument if it is constant.
785 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
786 Length = LengthArg->getZExtValue();
790 if (Length == 0) // strncmp(x,y,0) -> 0
791 return ConstantInt::get(CI->getType(), 0);
793 std::string Str1, Str2;
794 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
795 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
797 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
798 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
800 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
801 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
803 // strncmp(x, y) -> cnst (if both x and y are constant strings)
804 if (HasStr1 && HasStr2)
805 return ConstantInt::get(CI->getType(),
806 strncmp(Str1.c_str(), Str2.c_str(), Length));
812 //===---------------------------------------===//
813 // 'strcpy' Optimizations
815 struct StrCpyOpt : public LibCallOptimization {
816 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
817 // Verify the "strcpy" function prototype.
818 const FunctionType *FT = Callee->getFunctionType();
819 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
820 FT->getParamType(0) != FT->getParamType(1) ||
821 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
824 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
825 if (Dst == Src) // strcpy(x,x) -> x
828 // These optimizations require TargetData.
831 // See if we can get the length of the input string.
832 uint64_t Len = GetStringLength(Src);
833 if (Len == 0) return 0;
835 // We have enough information to now generate the memcpy call to do the
836 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
838 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
843 //===---------------------------------------===//
844 // 'strncpy' Optimizations
846 struct StrNCpyOpt : public LibCallOptimization {
847 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
848 const FunctionType *FT = Callee->getFunctionType();
849 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
850 FT->getParamType(0) != FT->getParamType(1) ||
851 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
852 !isa<IntegerType>(FT->getParamType(2)))
855 Value *Dst = CI->getOperand(1);
856 Value *Src = CI->getOperand(2);
857 Value *LenOp = CI->getOperand(3);
859 // See if we can get the length of the input string.
860 uint64_t SrcLen = GetStringLength(Src);
861 if (SrcLen == 0) return 0;
865 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
866 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
872 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
873 Len = LengthArg->getZExtValue();
877 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
879 // These optimizations require TargetData.
882 // Let strncpy handle the zero padding
883 if (Len > SrcLen+1) return 0;
885 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
887 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
893 //===---------------------------------------===//
894 // 'strlen' Optimizations
896 struct StrLenOpt : public LibCallOptimization {
897 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
898 const FunctionType *FT = Callee->getFunctionType();
899 if (FT->getNumParams() != 1 ||
900 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
901 !isa<IntegerType>(FT->getReturnType()))
904 Value *Src = CI->getOperand(1);
906 // Constant folding: strlen("xyz") -> 3
907 if (uint64_t Len = GetStringLength(Src))
908 return ConstantInt::get(CI->getType(), Len-1);
910 // strlen(x) != 0 --> *x != 0
911 // strlen(x) == 0 --> *x == 0
912 if (IsOnlyUsedInZeroEqualityComparison(CI))
913 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
918 //===---------------------------------------===//
919 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
921 struct StrToOpt : public LibCallOptimization {
922 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
923 const FunctionType *FT = Callee->getFunctionType();
924 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
925 !isa<PointerType>(FT->getParamType(0)) ||
926 !isa<PointerType>(FT->getParamType(1)))
929 Value *EndPtr = CI->getOperand(2);
930 if (isa<ConstantPointerNull>(EndPtr)) {
931 CI->setOnlyReadsMemory();
932 CI->addAttribute(1, Attribute::NoCapture);
939 //===---------------------------------------===//
940 // 'strstr' Optimizations
942 struct StrStrOpt : public LibCallOptimization {
943 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
944 const FunctionType *FT = Callee->getFunctionType();
945 if (FT->getNumParams() != 2 ||
946 !isa<PointerType>(FT->getParamType(0)) ||
947 !isa<PointerType>(FT->getParamType(1)) ||
948 !isa<PointerType>(FT->getReturnType()))
951 // fold strstr(x, x) -> x.
952 if (CI->getOperand(1) == CI->getOperand(2))
953 return B.CreateBitCast(CI->getOperand(1), CI->getType());
955 // See if either input string is a constant string.
956 std::string SearchStr, ToFindStr;
957 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
958 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
960 // fold strstr(x, "") -> x.
961 if (HasStr2 && ToFindStr.empty())
962 return B.CreateBitCast(CI->getOperand(1), CI->getType());
964 // If both strings are known, constant fold it.
965 if (HasStr1 && HasStr2) {
966 std::string::size_type Offset = SearchStr.find(ToFindStr);
968 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
969 return Constant::getNullValue(CI->getType());
971 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
972 Value *Result = CastToCStr(CI->getOperand(1), B);
973 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
974 return B.CreateBitCast(Result, CI->getType());
977 // fold strstr(x, "y") -> strchr(x, 'y').
978 if (HasStr2 && ToFindStr.size() == 1)
979 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
986 //===---------------------------------------===//
987 // 'memcmp' Optimizations
989 struct MemCmpOpt : public LibCallOptimization {
990 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
991 const FunctionType *FT = Callee->getFunctionType();
992 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
993 !isa<PointerType>(FT->getParamType(1)) ||
994 FT->getReturnType() != Type::getInt32Ty(*Context))
997 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
999 if (LHS == RHS) // memcmp(s,s,x) -> 0
1000 return Constant::getNullValue(CI->getType());
1002 // Make sure we have a constant length.
1003 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1004 if (!LenC) return 0;
1005 uint64_t Len = LenC->getZExtValue();
1007 if (Len == 0) // memcmp(s1,s2,0) -> 0
1008 return Constant::getNullValue(CI->getType());
1010 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1011 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1012 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
1013 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
1016 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1017 std::string LHSStr, RHSStr;
1018 if (GetConstantStringInfo(LHS, LHSStr) &&
1019 GetConstantStringInfo(RHS, RHSStr)) {
1020 // Make sure we're not reading out-of-bounds memory.
1021 if (Len > LHSStr.length() || Len > RHSStr.length())
1023 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1024 return ConstantInt::get(CI->getType(), Ret);
1031 //===---------------------------------------===//
1032 // 'memcpy' Optimizations
1034 struct MemCpyOpt : public LibCallOptimization {
1035 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1036 // These optimizations require TargetData.
1039 const FunctionType *FT = Callee->getFunctionType();
1040 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1041 !isa<PointerType>(FT->getParamType(0)) ||
1042 !isa<PointerType>(FT->getParamType(1)) ||
1043 FT->getParamType(2) != TD->getIntPtrType(*Context))
1046 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1047 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1048 return CI->getOperand(1);
1052 //===---------------------------------------===//
1053 // 'memmove' Optimizations
1055 struct MemMoveOpt : public LibCallOptimization {
1056 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1057 // These optimizations require TargetData.
1060 const FunctionType *FT = Callee->getFunctionType();
1061 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1062 !isa<PointerType>(FT->getParamType(0)) ||
1063 !isa<PointerType>(FT->getParamType(1)) ||
1064 FT->getParamType(2) != TD->getIntPtrType(*Context))
1067 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1068 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1069 return CI->getOperand(1);
1073 //===---------------------------------------===//
1074 // 'memset' Optimizations
1076 struct MemSetOpt : public LibCallOptimization {
1077 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1078 // These optimizations require TargetData.
1081 const FunctionType *FT = Callee->getFunctionType();
1082 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1083 !isa<PointerType>(FT->getParamType(0)) ||
1084 !isa<IntegerType>(FT->getParamType(1)) ||
1085 FT->getParamType(2) != TD->getIntPtrType(*Context))
1088 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1089 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1091 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1092 return CI->getOperand(1);
1096 //===----------------------------------------------------------------------===//
1097 // Object Size Checking Optimizations
1098 //===----------------------------------------------------------------------===//
1100 //===---------------------------------------===//
1103 struct SizeOpt : public LibCallOptimization {
1104 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1105 // TODO: We can do more with this, but delaying to here should be no change
1107 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
1109 if (!Const) return 0;
1111 const Type *Ty = Callee->getFunctionType()->getReturnType();
1113 if (Const->getZExtValue() == 0)
1114 return Constant::getAllOnesValue(Ty);
1116 return ConstantInt::get(Ty, 0);
1121 //===---------------------------------------===//
1122 // 'memcpy_chk' Optimizations
1124 struct MemCpyChkOpt : public LibCallOptimization {
1125 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1126 // These optimizations require TargetData.
1129 const FunctionType *FT = Callee->getFunctionType();
1130 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1131 !isa<PointerType>(FT->getParamType(0)) ||
1132 !isa<PointerType>(FT->getParamType(1)) ||
1133 !isa<IntegerType>(FT->getParamType(3)) ||
1134 FT->getParamType(2) != TD->getIntPtrType(*Context))
1137 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1140 if (SizeCI->isAllOnesValue()) {
1141 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1142 return CI->getOperand(1);
1149 //===---------------------------------------===//
1150 // 'memset_chk' Optimizations
1152 struct MemSetChkOpt : public LibCallOptimization {
1153 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1154 // These optimizations require TargetData.
1157 const FunctionType *FT = Callee->getFunctionType();
1158 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1159 !isa<PointerType>(FT->getParamType(0)) ||
1160 !isa<IntegerType>(FT->getParamType(1)) ||
1161 !isa<IntegerType>(FT->getParamType(3)) ||
1162 FT->getParamType(2) != TD->getIntPtrType(*Context))
1165 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1168 if (SizeCI->isAllOnesValue()) {
1169 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1171 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1172 return CI->getOperand(1);
1179 //===---------------------------------------===//
1180 // 'memmove_chk' Optimizations
1182 struct MemMoveChkOpt : public LibCallOptimization {
1183 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1184 // These optimizations require TargetData.
1187 const FunctionType *FT = Callee->getFunctionType();
1188 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1189 !isa<PointerType>(FT->getParamType(0)) ||
1190 !isa<PointerType>(FT->getParamType(1)) ||
1191 !isa<IntegerType>(FT->getParamType(3)) ||
1192 FT->getParamType(2) != TD->getIntPtrType(*Context))
1195 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1198 if (SizeCI->isAllOnesValue()) {
1199 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1201 return CI->getOperand(1);
1208 //===----------------------------------------------------------------------===//
1209 // Math Library Optimizations
1210 //===----------------------------------------------------------------------===//
1212 //===---------------------------------------===//
1213 // 'pow*' Optimizations
1215 struct PowOpt : public LibCallOptimization {
1216 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1217 const FunctionType *FT = Callee->getFunctionType();
1218 // Just make sure this has 2 arguments of the same FP type, which match the
1220 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1221 FT->getParamType(0) != FT->getParamType(1) ||
1222 !FT->getParamType(0)->isFloatingPoint())
1225 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1226 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1227 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1229 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1230 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1233 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1234 if (Op2C == 0) return 0;
1236 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1237 return ConstantFP::get(CI->getType(), 1.0);
1239 if (Op2C->isExactlyValue(0.5)) {
1240 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1241 // This is faster than calling pow, and still handles negative zero
1242 // and negative infinite correctly.
1243 // TODO: In fast-math mode, this could be just sqrt(x).
1244 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1245 Value *Inf = ConstantFP::getInfinity(CI->getType());
1246 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1247 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1248 Callee->getAttributes());
1249 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1250 Callee->getAttributes());
1251 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1252 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1256 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1258 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1259 return B.CreateFMul(Op1, Op1, "pow2");
1260 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1261 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1267 //===---------------------------------------===//
1268 // 'exp2' Optimizations
1270 struct Exp2Opt : public LibCallOptimization {
1271 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1272 const FunctionType *FT = Callee->getFunctionType();
1273 // Just make sure this has 1 argument of FP type, which matches the
1275 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1276 !FT->getParamType(0)->isFloatingPoint())
1279 Value *Op = CI->getOperand(1);
1280 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1281 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1282 Value *LdExpArg = 0;
1283 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1284 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1285 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1286 Type::getInt32Ty(*Context), "tmp");
1287 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1288 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1289 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1290 Type::getInt32Ty(*Context), "tmp");
1295 if (Op->getType()->isFloatTy())
1297 else if (Op->getType()->isDoubleTy())
1302 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1303 if (!Op->getType()->isFloatTy())
1304 One = ConstantExpr::getFPExtend(One, Op->getType());
1306 Module *M = Caller->getParent();
1307 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1309 Type::getInt32Ty(*Context),NULL);
1310 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1311 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1312 CI->setCallingConv(F->getCallingConv());
1320 //===---------------------------------------===//
1321 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1323 struct UnaryDoubleFPOpt : public LibCallOptimization {
1324 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1325 const FunctionType *FT = Callee->getFunctionType();
1326 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1327 !FT->getParamType(0)->isDoubleTy())
1330 // If this is something like 'floor((double)floatval)', convert to floorf.
1331 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1332 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1335 // floor((double)floatval) -> (double)floorf(floatval)
1336 Value *V = Cast->getOperand(0);
1337 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1338 Callee->getAttributes());
1339 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1343 //===----------------------------------------------------------------------===//
1344 // Integer Optimizations
1345 //===----------------------------------------------------------------------===//
1347 //===---------------------------------------===//
1348 // 'ffs*' Optimizations
1350 struct FFSOpt : public LibCallOptimization {
1351 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1352 const FunctionType *FT = Callee->getFunctionType();
1353 // Just make sure this has 2 arguments of the same FP type, which match the
1355 if (FT->getNumParams() != 1 ||
1356 FT->getReturnType() != Type::getInt32Ty(*Context) ||
1357 !isa<IntegerType>(FT->getParamType(0)))
1360 Value *Op = CI->getOperand(1);
1363 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1364 if (CI->getValue() == 0) // ffs(0) -> 0.
1365 return Constant::getNullValue(CI->getType());
1366 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1367 CI->getValue().countTrailingZeros()+1);
1370 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1371 const Type *ArgType = Op->getType();
1372 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1373 Intrinsic::cttz, &ArgType, 1);
1374 Value *V = B.CreateCall(F, Op, "cttz");
1375 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1376 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1378 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1379 return B.CreateSelect(Cond, V,
1380 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1384 //===---------------------------------------===//
1385 // 'isdigit' Optimizations
1387 struct IsDigitOpt : public LibCallOptimization {
1388 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1389 const FunctionType *FT = Callee->getFunctionType();
1390 // We require integer(i32)
1391 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1392 FT->getParamType(0) != Type::getInt32Ty(*Context))
1395 // isdigit(c) -> (c-'0') <u 10
1396 Value *Op = CI->getOperand(1);
1397 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1399 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1401 return B.CreateZExt(Op, CI->getType());
1405 //===---------------------------------------===//
1406 // 'isascii' Optimizations
1408 struct IsAsciiOpt : public LibCallOptimization {
1409 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1410 const FunctionType *FT = Callee->getFunctionType();
1411 // We require integer(i32)
1412 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1413 FT->getParamType(0) != Type::getInt32Ty(*Context))
1416 // isascii(c) -> c <u 128
1417 Value *Op = CI->getOperand(1);
1418 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1420 return B.CreateZExt(Op, CI->getType());
1424 //===---------------------------------------===//
1425 // 'abs', 'labs', 'llabs' Optimizations
1427 struct AbsOpt : public LibCallOptimization {
1428 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1429 const FunctionType *FT = Callee->getFunctionType();
1430 // We require integer(integer) where the types agree.
1431 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1432 FT->getParamType(0) != FT->getReturnType())
1435 // abs(x) -> x >s -1 ? x : -x
1436 Value *Op = CI->getOperand(1);
1437 Value *Pos = B.CreateICmpSGT(Op,
1438 Constant::getAllOnesValue(Op->getType()),
1440 Value *Neg = B.CreateNeg(Op, "neg");
1441 return B.CreateSelect(Pos, Op, Neg);
1446 //===---------------------------------------===//
1447 // 'toascii' Optimizations
1449 struct ToAsciiOpt : public LibCallOptimization {
1450 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1451 const FunctionType *FT = Callee->getFunctionType();
1452 // We require i32(i32)
1453 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1454 FT->getParamType(0) != Type::getInt32Ty(*Context))
1457 // isascii(c) -> c & 0x7f
1458 return B.CreateAnd(CI->getOperand(1),
1459 ConstantInt::get(CI->getType(),0x7F));
1463 //===----------------------------------------------------------------------===//
1464 // Formatting and IO Optimizations
1465 //===----------------------------------------------------------------------===//
1467 //===---------------------------------------===//
1468 // 'printf' Optimizations
1470 struct PrintFOpt : public LibCallOptimization {
1471 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1472 // Require one fixed pointer argument and an integer/void result.
1473 const FunctionType *FT = Callee->getFunctionType();
1474 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1475 !(isa<IntegerType>(FT->getReturnType()) ||
1476 FT->getReturnType()->isVoidTy()))
1479 // Check for a fixed format string.
1480 std::string FormatStr;
1481 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1484 // Empty format string -> noop.
1485 if (FormatStr.empty()) // Tolerate printf's declared void.
1486 return CI->use_empty() ? (Value*)CI :
1487 ConstantInt::get(CI->getType(), 0);
1489 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1490 // in case there is an error writing to stdout.
1491 if (FormatStr.size() == 1) {
1492 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1494 if (CI->use_empty()) return CI;
1495 return B.CreateIntCast(Res, CI->getType(), true);
1498 // printf("foo\n") --> puts("foo")
1499 if (FormatStr[FormatStr.size()-1] == '\n' &&
1500 FormatStr.find('%') == std::string::npos) { // no format characters.
1501 // Create a string literal with no \n on it. We expect the constant merge
1502 // pass to be run after this pass, to merge duplicate strings.
1503 FormatStr.erase(FormatStr.end()-1);
1504 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1505 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1506 GlobalVariable::InternalLinkage, C, "str");
1508 return CI->use_empty() ? (Value*)CI :
1509 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1512 // Optimize specific format strings.
1513 // printf("%c", chr) --> putchar(*(i8*)dst)
1514 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1515 isa<IntegerType>(CI->getOperand(2)->getType())) {
1516 Value *Res = EmitPutChar(CI->getOperand(2), B);
1518 if (CI->use_empty()) return CI;
1519 return B.CreateIntCast(Res, CI->getType(), true);
1522 // printf("%s\n", str) --> puts(str)
1523 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1524 isa<PointerType>(CI->getOperand(2)->getType()) &&
1526 EmitPutS(CI->getOperand(2), B);
1533 //===---------------------------------------===//
1534 // 'sprintf' Optimizations
1536 struct SPrintFOpt : public LibCallOptimization {
1537 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1538 // Require two fixed pointer arguments and an integer result.
1539 const FunctionType *FT = Callee->getFunctionType();
1540 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1541 !isa<PointerType>(FT->getParamType(1)) ||
1542 !isa<IntegerType>(FT->getReturnType()))
1545 // Check for a fixed format string.
1546 std::string FormatStr;
1547 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1550 // If we just have a format string (nothing else crazy) transform it.
1551 if (CI->getNumOperands() == 3) {
1552 // Make sure there's no % in the constant array. We could try to handle
1553 // %% -> % in the future if we cared.
1554 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1555 if (FormatStr[i] == '%')
1556 return 0; // we found a format specifier, bail out.
1558 // These optimizations require TargetData.
1561 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1562 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1564 (TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1565 return ConstantInt::get(CI->getType(), FormatStr.size());
1568 // The remaining optimizations require the format string to be "%s" or "%c"
1569 // and have an extra operand.
1570 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1573 // Decode the second character of the format string.
1574 if (FormatStr[1] == 'c') {
1575 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1576 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1577 Value *V = B.CreateTrunc(CI->getOperand(3),
1578 Type::getInt8Ty(*Context), "char");
1579 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1580 B.CreateStore(V, Ptr);
1581 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1583 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1585 return ConstantInt::get(CI->getType(), 1);
1588 if (FormatStr[1] == 's') {
1589 // These optimizations require TargetData.
1592 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1593 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1595 Value *Len = EmitStrLen(CI->getOperand(3), B);
1596 Value *IncLen = B.CreateAdd(Len,
1597 ConstantInt::get(Len->getType(), 1),
1599 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1601 // The sprintf result is the unincremented number of bytes in the string.
1602 return B.CreateIntCast(Len, CI->getType(), false);
1608 //===---------------------------------------===//
1609 // 'fwrite' Optimizations
1611 struct FWriteOpt : public LibCallOptimization {
1612 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1613 // Require a pointer, an integer, an integer, a pointer, returning integer.
1614 const FunctionType *FT = Callee->getFunctionType();
1615 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1616 !isa<IntegerType>(FT->getParamType(1)) ||
1617 !isa<IntegerType>(FT->getParamType(2)) ||
1618 !isa<PointerType>(FT->getParamType(3)) ||
1619 !isa<IntegerType>(FT->getReturnType()))
1622 // Get the element size and count.
1623 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1624 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1625 if (!SizeC || !CountC) return 0;
1626 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1628 // If this is writing zero records, remove the call (it's a noop).
1630 return ConstantInt::get(CI->getType(), 0);
1632 // If this is writing one byte, turn it into fputc.
1633 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1634 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1635 EmitFPutC(Char, CI->getOperand(4), B);
1636 return ConstantInt::get(CI->getType(), 1);
1643 //===---------------------------------------===//
1644 // 'fputs' Optimizations
1646 struct FPutsOpt : public LibCallOptimization {
1647 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1648 // These optimizations require TargetData.
1651 // Require two pointers. Also, we can't optimize if return value is used.
1652 const FunctionType *FT = Callee->getFunctionType();
1653 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1654 !isa<PointerType>(FT->getParamType(1)) ||
1658 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1659 uint64_t Len = GetStringLength(CI->getOperand(1));
1661 EmitFWrite(CI->getOperand(1),
1662 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1663 CI->getOperand(2), B);
1664 return CI; // Known to have no uses (see above).
1668 //===---------------------------------------===//
1669 // 'fprintf' Optimizations
1671 struct FPrintFOpt : public LibCallOptimization {
1672 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1673 // Require two fixed paramters as pointers and integer result.
1674 const FunctionType *FT = Callee->getFunctionType();
1675 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1676 !isa<PointerType>(FT->getParamType(1)) ||
1677 !isa<IntegerType>(FT->getReturnType()))
1680 // All the optimizations depend on the format string.
1681 std::string FormatStr;
1682 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1685 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1686 if (CI->getNumOperands() == 3) {
1687 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1688 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1689 return 0; // We found a format specifier.
1691 // These optimizations require TargetData.
1694 EmitFWrite(CI->getOperand(2),
1695 ConstantInt::get(TD->getIntPtrType(*Context),
1697 CI->getOperand(1), B);
1698 return ConstantInt::get(CI->getType(), FormatStr.size());
1701 // The remaining optimizations require the format string to be "%s" or "%c"
1702 // and have an extra operand.
1703 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1706 // Decode the second character of the format string.
1707 if (FormatStr[1] == 'c') {
1708 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1709 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1710 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1711 return ConstantInt::get(CI->getType(), 1);
1714 if (FormatStr[1] == 's') {
1715 // fprintf(F, "%s", str) -> fputs(str, F)
1716 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1718 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1725 } // end anonymous namespace.
1727 //===----------------------------------------------------------------------===//
1728 // SimplifyLibCalls Pass Implementation
1729 //===----------------------------------------------------------------------===//
1732 /// This pass optimizes well known library functions from libc and libm.
1734 class SimplifyLibCalls : public FunctionPass {
1735 StringMap<LibCallOptimization*> Optimizations;
1736 // String and Memory LibCall Optimizations
1737 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1738 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1739 StrToOpt StrTo; StrStrOpt StrStr;
1740 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1741 // Math Library Optimizations
1742 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1743 // Integer Optimizations
1744 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1746 // Formatting and IO Optimizations
1747 SPrintFOpt SPrintF; PrintFOpt PrintF;
1748 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1750 // Object Size Checking
1752 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1754 bool Modified; // This is only used by doInitialization.
1756 static char ID; // Pass identification
1757 SimplifyLibCalls() : FunctionPass(&ID) {}
1759 void InitOptimizations();
1760 bool runOnFunction(Function &F);
1762 void setDoesNotAccessMemory(Function &F);
1763 void setOnlyReadsMemory(Function &F);
1764 void setDoesNotThrow(Function &F);
1765 void setDoesNotCapture(Function &F, unsigned n);
1766 void setDoesNotAlias(Function &F, unsigned n);
1767 bool doInitialization(Module &M);
1769 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1772 char SimplifyLibCalls::ID = 0;
1773 } // end anonymous namespace.
1775 static RegisterPass<SimplifyLibCalls>
1776 X("simplify-libcalls", "Simplify well-known library calls");
1778 // Public interface to the Simplify LibCalls pass.
1779 FunctionPass *llvm::createSimplifyLibCallsPass() {
1780 return new SimplifyLibCalls();
1783 /// Optimizations - Populate the Optimizations map with all the optimizations
1785 void SimplifyLibCalls::InitOptimizations() {
1786 // String and Memory LibCall Optimizations
1787 Optimizations["strcat"] = &StrCat;
1788 Optimizations["strncat"] = &StrNCat;
1789 Optimizations["strchr"] = &StrChr;
1790 Optimizations["strcmp"] = &StrCmp;
1791 Optimizations["strncmp"] = &StrNCmp;
1792 Optimizations["strcpy"] = &StrCpy;
1793 Optimizations["strncpy"] = &StrNCpy;
1794 Optimizations["strlen"] = &StrLen;
1795 Optimizations["strtol"] = &StrTo;
1796 Optimizations["strtod"] = &StrTo;
1797 Optimizations["strtof"] = &StrTo;
1798 Optimizations["strtoul"] = &StrTo;
1799 Optimizations["strtoll"] = &StrTo;
1800 Optimizations["strtold"] = &StrTo;
1801 Optimizations["strtoull"] = &StrTo;
1802 Optimizations["strstr"] = &StrStr;
1803 Optimizations["memcmp"] = &MemCmp;
1804 Optimizations["memcpy"] = &MemCpy;
1805 Optimizations["memmove"] = &MemMove;
1806 Optimizations["memset"] = &MemSet;
1808 // Math Library Optimizations
1809 Optimizations["powf"] = &Pow;
1810 Optimizations["pow"] = &Pow;
1811 Optimizations["powl"] = &Pow;
1812 Optimizations["llvm.pow.f32"] = &Pow;
1813 Optimizations["llvm.pow.f64"] = &Pow;
1814 Optimizations["llvm.pow.f80"] = &Pow;
1815 Optimizations["llvm.pow.f128"] = &Pow;
1816 Optimizations["llvm.pow.ppcf128"] = &Pow;
1817 Optimizations["exp2l"] = &Exp2;
1818 Optimizations["exp2"] = &Exp2;
1819 Optimizations["exp2f"] = &Exp2;
1820 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1821 Optimizations["llvm.exp2.f128"] = &Exp2;
1822 Optimizations["llvm.exp2.f80"] = &Exp2;
1823 Optimizations["llvm.exp2.f64"] = &Exp2;
1824 Optimizations["llvm.exp2.f32"] = &Exp2;
1827 Optimizations["floor"] = &UnaryDoubleFP;
1830 Optimizations["ceil"] = &UnaryDoubleFP;
1833 Optimizations["round"] = &UnaryDoubleFP;
1836 Optimizations["rint"] = &UnaryDoubleFP;
1838 #ifdef HAVE_NEARBYINTF
1839 Optimizations["nearbyint"] = &UnaryDoubleFP;
1842 // Integer Optimizations
1843 Optimizations["ffs"] = &FFS;
1844 Optimizations["ffsl"] = &FFS;
1845 Optimizations["ffsll"] = &FFS;
1846 Optimizations["abs"] = &Abs;
1847 Optimizations["labs"] = &Abs;
1848 Optimizations["llabs"] = &Abs;
1849 Optimizations["isdigit"] = &IsDigit;
1850 Optimizations["isascii"] = &IsAscii;
1851 Optimizations["toascii"] = &ToAscii;
1853 // Formatting and IO Optimizations
1854 Optimizations["sprintf"] = &SPrintF;
1855 Optimizations["printf"] = &PrintF;
1856 Optimizations["fwrite"] = &FWrite;
1857 Optimizations["fputs"] = &FPuts;
1858 Optimizations["fprintf"] = &FPrintF;
1860 // Object Size Checking
1861 Optimizations["llvm.objectsize.i32"] = &ObjectSize;
1862 Optimizations["llvm.objectsize.i64"] = &ObjectSize;
1863 Optimizations["__memcpy_chk"] = &MemCpyChk;
1864 Optimizations["__memset_chk"] = &MemSetChk;
1865 Optimizations["__memmove_chk"] = &MemMoveChk;
1869 /// runOnFunction - Top level algorithm.
1871 bool SimplifyLibCalls::runOnFunction(Function &F) {
1872 if (Optimizations.empty())
1873 InitOptimizations();
1875 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1877 IRBuilder<> Builder(F.getContext());
1879 bool Changed = false;
1880 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1881 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1882 // Ignore non-calls.
1883 CallInst *CI = dyn_cast<CallInst>(I++);
1886 // Ignore indirect calls and calls to non-external functions.
1887 Function *Callee = CI->getCalledFunction();
1888 if (Callee == 0 || !Callee->isDeclaration() ||
1889 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1892 // Ignore unknown calls.
1893 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1896 // Set the builder to the instruction after the call.
1897 Builder.SetInsertPoint(BB, I);
1899 // Try to optimize this call.
1900 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1901 if (Result == 0) continue;
1903 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1904 errs() << " into: " << *Result << "\n");
1906 // Something changed!
1910 // Inspect the instruction after the call (which was potentially just
1914 if (CI != Result && !CI->use_empty()) {
1915 CI->replaceAllUsesWith(Result);
1916 if (!Result->hasName())
1917 Result->takeName(CI);
1919 CI->eraseFromParent();
1925 // Utility methods for doInitialization.
1927 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1928 if (!F.doesNotAccessMemory()) {
1929 F.setDoesNotAccessMemory();
1934 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1935 if (!F.onlyReadsMemory()) {
1936 F.setOnlyReadsMemory();
1941 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1942 if (!F.doesNotThrow()) {
1943 F.setDoesNotThrow();
1948 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1949 if (!F.doesNotCapture(n)) {
1950 F.setDoesNotCapture(n);
1955 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1956 if (!F.doesNotAlias(n)) {
1957 F.setDoesNotAlias(n);
1963 /// doInitialization - Add attributes to well-known functions.
1965 bool SimplifyLibCalls::doInitialization(Module &M) {
1967 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1969 if (!F.isDeclaration())
1975 const FunctionType *FTy = F.getFunctionType();
1977 StringRef Name = F.getName();
1980 if (Name == "strlen") {
1981 if (FTy->getNumParams() != 1 ||
1982 !isa<PointerType>(FTy->getParamType(0)))
1984 setOnlyReadsMemory(F);
1986 setDoesNotCapture(F, 1);
1987 } else if (Name == "strcpy" ||
1993 Name == "strtoul" ||
1994 Name == "strtoll" ||
1995 Name == "strtold" ||
1996 Name == "strncat" ||
1997 Name == "strncpy" ||
1998 Name == "strtoull") {
1999 if (FTy->getNumParams() < 2 ||
2000 !isa<PointerType>(FTy->getParamType(1)))
2003 setDoesNotCapture(F, 2);
2004 } else if (Name == "strxfrm") {
2005 if (FTy->getNumParams() != 3 ||
2006 !isa<PointerType>(FTy->getParamType(0)) ||
2007 !isa<PointerType>(FTy->getParamType(1)))
2010 setDoesNotCapture(F, 1);
2011 setDoesNotCapture(F, 2);
2012 } else if (Name == "strcmp" ||
2014 Name == "strncmp" ||
2015 Name ==" strcspn" ||
2016 Name == "strcoll" ||
2017 Name == "strcasecmp" ||
2018 Name == "strncasecmp") {
2019 if (FTy->getNumParams() < 2 ||
2020 !isa<PointerType>(FTy->getParamType(0)) ||
2021 !isa<PointerType>(FTy->getParamType(1)))
2023 setOnlyReadsMemory(F);
2025 setDoesNotCapture(F, 1);
2026 setDoesNotCapture(F, 2);
2027 } else if (Name == "strstr" ||
2028 Name == "strpbrk") {
2029 if (FTy->getNumParams() != 2 ||
2030 !isa<PointerType>(FTy->getParamType(1)))
2032 setOnlyReadsMemory(F);
2034 setDoesNotCapture(F, 2);
2035 } else if (Name == "strtok" ||
2036 Name == "strtok_r") {
2037 if (FTy->getNumParams() < 2 ||
2038 !isa<PointerType>(FTy->getParamType(1)))
2041 setDoesNotCapture(F, 2);
2042 } else if (Name == "scanf" ||
2044 Name == "setvbuf") {
2045 if (FTy->getNumParams() < 1 ||
2046 !isa<PointerType>(FTy->getParamType(0)))
2049 setDoesNotCapture(F, 1);
2050 } else if (Name == "strdup" ||
2051 Name == "strndup") {
2052 if (FTy->getNumParams() < 1 ||
2053 !isa<PointerType>(FTy->getReturnType()) ||
2054 !isa<PointerType>(FTy->getParamType(0)))
2057 setDoesNotAlias(F, 0);
2058 setDoesNotCapture(F, 1);
2059 } else if (Name == "stat" ||
2061 Name == "sprintf" ||
2062 Name == "statvfs") {
2063 if (FTy->getNumParams() < 2 ||
2064 !isa<PointerType>(FTy->getParamType(0)) ||
2065 !isa<PointerType>(FTy->getParamType(1)))
2068 setDoesNotCapture(F, 1);
2069 setDoesNotCapture(F, 2);
2070 } else if (Name == "snprintf") {
2071 if (FTy->getNumParams() != 3 ||
2072 !isa<PointerType>(FTy->getParamType(0)) ||
2073 !isa<PointerType>(FTy->getParamType(2)))
2076 setDoesNotCapture(F, 1);
2077 setDoesNotCapture(F, 3);
2078 } else if (Name == "setitimer") {
2079 if (FTy->getNumParams() != 3 ||
2080 !isa<PointerType>(FTy->getParamType(1)) ||
2081 !isa<PointerType>(FTy->getParamType(2)))
2084 setDoesNotCapture(F, 2);
2085 setDoesNotCapture(F, 3);
2086 } else if (Name == "system") {
2087 if (FTy->getNumParams() != 1 ||
2088 !isa<PointerType>(FTy->getParamType(0)))
2090 // May throw; "system" is a valid pthread cancellation point.
2091 setDoesNotCapture(F, 1);
2095 if (Name == "malloc") {
2096 if (FTy->getNumParams() != 1 ||
2097 !isa<PointerType>(FTy->getReturnType()))
2100 setDoesNotAlias(F, 0);
2101 } else if (Name == "memcmp") {
2102 if (FTy->getNumParams() != 3 ||
2103 !isa<PointerType>(FTy->getParamType(0)) ||
2104 !isa<PointerType>(FTy->getParamType(1)))
2106 setOnlyReadsMemory(F);
2108 setDoesNotCapture(F, 1);
2109 setDoesNotCapture(F, 2);
2110 } else if (Name == "memchr" ||
2111 Name == "memrchr") {
2112 if (FTy->getNumParams() != 3)
2114 setOnlyReadsMemory(F);
2116 } else if (Name == "modf" ||
2120 Name == "memccpy" ||
2121 Name == "memmove") {
2122 if (FTy->getNumParams() < 2 ||
2123 !isa<PointerType>(FTy->getParamType(1)))
2126 setDoesNotCapture(F, 2);
2127 } else if (Name == "memalign") {
2128 if (!isa<PointerType>(FTy->getReturnType()))
2130 setDoesNotAlias(F, 0);
2131 } else if (Name == "mkdir" ||
2133 if (FTy->getNumParams() == 0 ||
2134 !isa<PointerType>(FTy->getParamType(0)))
2137 setDoesNotCapture(F, 1);
2141 if (Name == "realloc") {
2142 if (FTy->getNumParams() != 2 ||
2143 !isa<PointerType>(FTy->getParamType(0)) ||
2144 !isa<PointerType>(FTy->getReturnType()))
2147 setDoesNotAlias(F, 0);
2148 setDoesNotCapture(F, 1);
2149 } else if (Name == "read") {
2150 if (FTy->getNumParams() != 3 ||
2151 !isa<PointerType>(FTy->getParamType(1)))
2153 // May throw; "read" is a valid pthread cancellation point.
2154 setDoesNotCapture(F, 2);
2155 } else if (Name == "rmdir" ||
2158 Name == "realpath") {
2159 if (FTy->getNumParams() < 1 ||
2160 !isa<PointerType>(FTy->getParamType(0)))
2163 setDoesNotCapture(F, 1);
2164 } else if (Name == "rename" ||
2165 Name == "readlink") {
2166 if (FTy->getNumParams() < 2 ||
2167 !isa<PointerType>(FTy->getParamType(0)) ||
2168 !isa<PointerType>(FTy->getParamType(1)))
2171 setDoesNotCapture(F, 1);
2172 setDoesNotCapture(F, 2);
2176 if (Name == "write") {
2177 if (FTy->getNumParams() != 3 ||
2178 !isa<PointerType>(FTy->getParamType(1)))
2180 // May throw; "write" is a valid pthread cancellation point.
2181 setDoesNotCapture(F, 2);
2185 if (Name == "bcopy") {
2186 if (FTy->getNumParams() != 3 ||
2187 !isa<PointerType>(FTy->getParamType(0)) ||
2188 !isa<PointerType>(FTy->getParamType(1)))
2191 setDoesNotCapture(F, 1);
2192 setDoesNotCapture(F, 2);
2193 } else if (Name == "bcmp") {
2194 if (FTy->getNumParams() != 3 ||
2195 !isa<PointerType>(FTy->getParamType(0)) ||
2196 !isa<PointerType>(FTy->getParamType(1)))
2199 setOnlyReadsMemory(F);
2200 setDoesNotCapture(F, 1);
2201 setDoesNotCapture(F, 2);
2202 } else if (Name == "bzero") {
2203 if (FTy->getNumParams() != 2 ||
2204 !isa<PointerType>(FTy->getParamType(0)))
2207 setDoesNotCapture(F, 1);
2211 if (Name == "calloc") {
2212 if (FTy->getNumParams() != 2 ||
2213 !isa<PointerType>(FTy->getReturnType()))
2216 setDoesNotAlias(F, 0);
2217 } else if (Name == "chmod" ||
2219 Name == "ctermid" ||
2220 Name == "clearerr" ||
2221 Name == "closedir") {
2222 if (FTy->getNumParams() == 0 ||
2223 !isa<PointerType>(FTy->getParamType(0)))
2226 setDoesNotCapture(F, 1);
2230 if (Name == "atoi" ||
2234 if (FTy->getNumParams() != 1 ||
2235 !isa<PointerType>(FTy->getParamType(0)))
2238 setOnlyReadsMemory(F);
2239 setDoesNotCapture(F, 1);
2240 } else if (Name == "access") {
2241 if (FTy->getNumParams() != 2 ||
2242 !isa<PointerType>(FTy->getParamType(0)))
2245 setDoesNotCapture(F, 1);
2249 if (Name == "fopen") {
2250 if (FTy->getNumParams() != 2 ||
2251 !isa<PointerType>(FTy->getReturnType()) ||
2252 !isa<PointerType>(FTy->getParamType(0)) ||
2253 !isa<PointerType>(FTy->getParamType(1)))
2256 setDoesNotAlias(F, 0);
2257 setDoesNotCapture(F, 1);
2258 setDoesNotCapture(F, 2);
2259 } else if (Name == "fdopen") {
2260 if (FTy->getNumParams() != 2 ||
2261 !isa<PointerType>(FTy->getReturnType()) ||
2262 !isa<PointerType>(FTy->getParamType(1)))
2265 setDoesNotAlias(F, 0);
2266 setDoesNotCapture(F, 2);
2267 } else if (Name == "feof" ||
2277 Name == "fsetpos" ||
2278 Name == "flockfile" ||
2279 Name == "funlockfile" ||
2280 Name == "ftrylockfile") {
2281 if (FTy->getNumParams() == 0 ||
2282 !isa<PointerType>(FTy->getParamType(0)))
2285 setDoesNotCapture(F, 1);
2286 } else if (Name == "ferror") {
2287 if (FTy->getNumParams() != 1 ||
2288 !isa<PointerType>(FTy->getParamType(0)))
2291 setDoesNotCapture(F, 1);
2292 setOnlyReadsMemory(F);
2293 } else if (Name == "fputc" ||
2298 Name == "fstatvfs") {
2299 if (FTy->getNumParams() != 2 ||
2300 !isa<PointerType>(FTy->getParamType(1)))
2303 setDoesNotCapture(F, 2);
2304 } else if (Name == "fgets") {
2305 if (FTy->getNumParams() != 3 ||
2306 !isa<PointerType>(FTy->getParamType(0)) ||
2307 !isa<PointerType>(FTy->getParamType(2)))
2310 setDoesNotCapture(F, 3);
2311 } else if (Name == "fread" ||
2313 if (FTy->getNumParams() != 4 ||
2314 !isa<PointerType>(FTy->getParamType(0)) ||
2315 !isa<PointerType>(FTy->getParamType(3)))
2318 setDoesNotCapture(F, 1);
2319 setDoesNotCapture(F, 4);
2320 } else if (Name == "fputs" ||
2322 Name == "fprintf" ||
2323 Name == "fgetpos") {
2324 if (FTy->getNumParams() < 2 ||
2325 !isa<PointerType>(FTy->getParamType(0)) ||
2326 !isa<PointerType>(FTy->getParamType(1)))
2329 setDoesNotCapture(F, 1);
2330 setDoesNotCapture(F, 2);
2334 if (Name == "getc" ||
2335 Name == "getlogin_r" ||
2336 Name == "getc_unlocked") {
2337 if (FTy->getNumParams() == 0 ||
2338 !isa<PointerType>(FTy->getParamType(0)))
2341 setDoesNotCapture(F, 1);
2342 } else if (Name == "getenv") {
2343 if (FTy->getNumParams() != 1 ||
2344 !isa<PointerType>(FTy->getParamType(0)))
2347 setOnlyReadsMemory(F);
2348 setDoesNotCapture(F, 1);
2349 } else if (Name == "gets" ||
2350 Name == "getchar") {
2352 } else if (Name == "getitimer") {
2353 if (FTy->getNumParams() != 2 ||
2354 !isa<PointerType>(FTy->getParamType(1)))
2357 setDoesNotCapture(F, 2);
2358 } else if (Name == "getpwnam") {
2359 if (FTy->getNumParams() != 1 ||
2360 !isa<PointerType>(FTy->getParamType(0)))
2363 setDoesNotCapture(F, 1);
2367 if (Name == "ungetc") {
2368 if (FTy->getNumParams() != 2 ||
2369 !isa<PointerType>(FTy->getParamType(1)))
2372 setDoesNotCapture(F, 2);
2373 } else if (Name == "uname" ||
2375 Name == "unsetenv") {
2376 if (FTy->getNumParams() != 1 ||
2377 !isa<PointerType>(FTy->getParamType(0)))
2380 setDoesNotCapture(F, 1);
2381 } else if (Name == "utime" ||
2383 if (FTy->getNumParams() != 2 ||
2384 !isa<PointerType>(FTy->getParamType(0)) ||
2385 !isa<PointerType>(FTy->getParamType(1)))
2388 setDoesNotCapture(F, 1);
2389 setDoesNotCapture(F, 2);
2393 if (Name == "putc") {
2394 if (FTy->getNumParams() != 2 ||
2395 !isa<PointerType>(FTy->getParamType(1)))
2398 setDoesNotCapture(F, 2);
2399 } else if (Name == "puts" ||
2402 if (FTy->getNumParams() != 1 ||
2403 !isa<PointerType>(FTy->getParamType(0)))
2406 setDoesNotCapture(F, 1);
2407 } else if (Name == "pread" ||
2409 if (FTy->getNumParams() != 4 ||
2410 !isa<PointerType>(FTy->getParamType(1)))
2412 // May throw; these are valid pthread cancellation points.
2413 setDoesNotCapture(F, 2);
2414 } else if (Name == "putchar") {
2416 } else if (Name == "popen") {
2417 if (FTy->getNumParams() != 2 ||
2418 !isa<PointerType>(FTy->getReturnType()) ||
2419 !isa<PointerType>(FTy->getParamType(0)) ||
2420 !isa<PointerType>(FTy->getParamType(1)))
2423 setDoesNotAlias(F, 0);
2424 setDoesNotCapture(F, 1);
2425 setDoesNotCapture(F, 2);
2426 } else if (Name == "pclose") {
2427 if (FTy->getNumParams() != 1 ||
2428 !isa<PointerType>(FTy->getParamType(0)))
2431 setDoesNotCapture(F, 1);
2435 if (Name == "vscanf") {
2436 if (FTy->getNumParams() != 2 ||
2437 !isa<PointerType>(FTy->getParamType(1)))
2440 setDoesNotCapture(F, 1);
2441 } else if (Name == "vsscanf" ||
2442 Name == "vfscanf") {
2443 if (FTy->getNumParams() != 3 ||
2444 !isa<PointerType>(FTy->getParamType(1)) ||
2445 !isa<PointerType>(FTy->getParamType(2)))
2448 setDoesNotCapture(F, 1);
2449 setDoesNotCapture(F, 2);
2450 } else if (Name == "valloc") {
2451 if (!isa<PointerType>(FTy->getReturnType()))
2454 setDoesNotAlias(F, 0);
2455 } else if (Name == "vprintf") {
2456 if (FTy->getNumParams() != 2 ||
2457 !isa<PointerType>(FTy->getParamType(0)))
2460 setDoesNotCapture(F, 1);
2461 } else if (Name == "vfprintf" ||
2462 Name == "vsprintf") {
2463 if (FTy->getNumParams() != 3 ||
2464 !isa<PointerType>(FTy->getParamType(0)) ||
2465 !isa<PointerType>(FTy->getParamType(1)))
2468 setDoesNotCapture(F, 1);
2469 setDoesNotCapture(F, 2);
2470 } else if (Name == "vsnprintf") {
2471 if (FTy->getNumParams() != 4 ||
2472 !isa<PointerType>(FTy->getParamType(0)) ||
2473 !isa<PointerType>(FTy->getParamType(2)))
2476 setDoesNotCapture(F, 1);
2477 setDoesNotCapture(F, 3);
2481 if (Name == "open") {
2482 if (FTy->getNumParams() < 2 ||
2483 !isa<PointerType>(FTy->getParamType(0)))
2485 // May throw; "open" is a valid pthread cancellation point.
2486 setDoesNotCapture(F, 1);
2487 } else if (Name == "opendir") {
2488 if (FTy->getNumParams() != 1 ||
2489 !isa<PointerType>(FTy->getReturnType()) ||
2490 !isa<PointerType>(FTy->getParamType(0)))
2493 setDoesNotAlias(F, 0);
2494 setDoesNotCapture(F, 1);
2498 if (Name == "tmpfile") {
2499 if (!isa<PointerType>(FTy->getReturnType()))
2502 setDoesNotAlias(F, 0);
2503 } else if (Name == "times") {
2504 if (FTy->getNumParams() != 1 ||
2505 !isa<PointerType>(FTy->getParamType(0)))
2508 setDoesNotCapture(F, 1);
2512 if (Name == "htonl" ||
2515 setDoesNotAccessMemory(F);
2519 if (Name == "ntohl" ||
2522 setDoesNotAccessMemory(F);
2526 if (Name == "lstat") {
2527 if (FTy->getNumParams() != 2 ||
2528 !isa<PointerType>(FTy->getParamType(0)) ||
2529 !isa<PointerType>(FTy->getParamType(1)))
2532 setDoesNotCapture(F, 1);
2533 setDoesNotCapture(F, 2);
2534 } else if (Name == "lchown") {
2535 if (FTy->getNumParams() != 3 ||
2536 !isa<PointerType>(FTy->getParamType(0)))
2539 setDoesNotCapture(F, 1);
2543 if (Name == "qsort") {
2544 if (FTy->getNumParams() != 4 ||
2545 !isa<PointerType>(FTy->getParamType(3)))
2547 // May throw; places call through function pointer.
2548 setDoesNotCapture(F, 4);
2552 if (Name == "__strdup" ||
2553 Name == "__strndup") {
2554 if (FTy->getNumParams() < 1 ||
2555 !isa<PointerType>(FTy->getReturnType()) ||
2556 !isa<PointerType>(FTy->getParamType(0)))
2559 setDoesNotAlias(F, 0);
2560 setDoesNotCapture(F, 1);
2561 } else if (Name == "__strtok_r") {
2562 if (FTy->getNumParams() != 3 ||
2563 !isa<PointerType>(FTy->getParamType(1)))
2566 setDoesNotCapture(F, 2);
2567 } else if (Name == "_IO_getc") {
2568 if (FTy->getNumParams() != 1 ||
2569 !isa<PointerType>(FTy->getParamType(0)))
2572 setDoesNotCapture(F, 1);
2573 } else if (Name == "_IO_putc") {
2574 if (FTy->getNumParams() != 2 ||
2575 !isa<PointerType>(FTy->getParamType(1)))
2578 setDoesNotCapture(F, 2);
2582 if (Name == "\1__isoc99_scanf") {
2583 if (FTy->getNumParams() < 1 ||
2584 !isa<PointerType>(FTy->getParamType(0)))
2587 setDoesNotCapture(F, 1);
2588 } else if (Name == "\1stat64" ||
2589 Name == "\1lstat64" ||
2590 Name == "\1statvfs64" ||
2591 Name == "\1__isoc99_sscanf") {
2592 if (FTy->getNumParams() < 1 ||
2593 !isa<PointerType>(FTy->getParamType(0)) ||
2594 !isa<PointerType>(FTy->getParamType(1)))
2597 setDoesNotCapture(F, 1);
2598 setDoesNotCapture(F, 2);
2599 } else if (Name == "\1fopen64") {
2600 if (FTy->getNumParams() != 2 ||
2601 !isa<PointerType>(FTy->getReturnType()) ||
2602 !isa<PointerType>(FTy->getParamType(0)) ||
2603 !isa<PointerType>(FTy->getParamType(1)))
2606 setDoesNotAlias(F, 0);
2607 setDoesNotCapture(F, 1);
2608 setDoesNotCapture(F, 2);
2609 } else if (Name == "\1fseeko64" ||
2610 Name == "\1ftello64") {
2611 if (FTy->getNumParams() == 0 ||
2612 !isa<PointerType>(FTy->getParamType(0)))
2615 setDoesNotCapture(F, 1);
2616 } else if (Name == "\1tmpfile64") {
2617 if (!isa<PointerType>(FTy->getReturnType()))
2620 setDoesNotAlias(F, 0);
2621 } else if (Name == "\1fstat64" ||
2622 Name == "\1fstatvfs64") {
2623 if (FTy->getNumParams() != 2 ||
2624 !isa<PointerType>(FTy->getParamType(1)))
2627 setDoesNotCapture(F, 2);
2628 } else if (Name == "\1open64") {
2629 if (FTy->getNumParams() < 2 ||
2630 !isa<PointerType>(FTy->getParamType(0)))
2632 // May throw; "open" is a valid pthread cancellation point.
2633 setDoesNotCapture(F, 1);
2642 // Additional cases that we need to add to this file:
2645 // * cbrt(expN(X)) -> expN(x/3)
2646 // * cbrt(sqrt(x)) -> pow(x,1/6)
2647 // * cbrt(sqrt(x)) -> pow(x,1/9)
2650 // * cos(-x) -> cos(x)
2653 // * exp(log(x)) -> x
2656 // * log(exp(x)) -> x
2657 // * log(x**y) -> y*log(x)
2658 // * log(exp(y)) -> y*log(e)
2659 // * log(exp2(y)) -> y*log(2)
2660 // * log(exp10(y)) -> y*log(10)
2661 // * log(sqrt(x)) -> 0.5*log(x)
2662 // * log(pow(x,y)) -> y*log(x)
2664 // lround, lroundf, lroundl:
2665 // * lround(cnst) -> cnst'
2668 // * pow(exp(x),y) -> exp(x*y)
2669 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2670 // * pow(pow(x,y),z)-> pow(x,y*z)
2673 // * puts("") -> putchar("\n")
2675 // round, roundf, roundl:
2676 // * round(cnst) -> cnst'
2679 // * signbit(cnst) -> cnst'
2680 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2682 // sqrt, sqrtf, sqrtl:
2683 // * sqrt(expN(x)) -> expN(x*0.5)
2684 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2685 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2688 // * stpcpy(str, "literal") ->
2689 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2691 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2692 // (if c is a constant integer and s is a constant string)
2693 // * strrchr(s1,0) -> strchr(s1,0)
2696 // * strpbrk(s,a) -> offset_in_for(s,a)
2697 // (if s and a are both constant strings)
2698 // * strpbrk(s,"") -> 0
2699 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2702 // * strspn(s,a) -> const_int (if both args are constant)
2703 // * strspn("",a) -> 0
2704 // * strspn(s,"") -> 0
2705 // * strcspn(s,a) -> const_int (if both args are constant)
2706 // * strcspn("",a) -> 0
2707 // * strcspn(s,"") -> strlen(a)
2710 // * tan(atan(x)) -> x
2712 // trunc, truncf, truncl:
2713 // * trunc(cnst) -> cnst'