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 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
85 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
86 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
88 /// EmitMemCmp - Emit a call to the memcmp function.
89 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
91 /// EmitMemSet - Emit a call to the memset function
92 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
94 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
95 /// 'floor'). This function is known to take a single of type matching 'Op'
96 /// and returns one value with the same type. If 'Op' is a long double, 'l'
97 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
98 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
99 const AttrListPtr &Attrs);
101 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
103 void EmitPutChar(Value *Char, IRBuilder<> &B);
105 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
107 void EmitPutS(Value *Str, IRBuilder<> &B);
109 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
110 /// an i32, and File is a pointer to FILE.
111 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
113 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
114 /// pointer and File is a pointer to FILE.
115 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
117 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
118 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
119 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
122 } // End anonymous namespace.
124 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
125 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
127 B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
130 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
131 /// specified pointer. This always returns an integer value of size intptr_t.
132 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
133 Module *M = Caller->getParent();
134 AttributeWithIndex AWI[2];
135 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
136 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
137 Attribute::NoUnwind);
139 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
140 TD->getIntPtrType(*Context),
141 Type::getInt8PtrTy(*Context),
143 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
144 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
145 CI->setCallingConv(F->getCallingConv());
150 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
151 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
152 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
153 unsigned Align, IRBuilder<> &B) {
154 Module *M = Caller->getParent();
155 Intrinsic::ID IID = Intrinsic::memcpy;
157 Tys[0] = Len->getType();
158 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
159 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
160 ConstantInt::get(Type::getInt32Ty(*Context), Align));
163 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
164 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
165 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
166 Value *Len, IRBuilder<> &B) {
167 Module *M = Caller->getParent();
168 AttributeWithIndex AWI;
169 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
171 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
172 Type::getInt8PtrTy(*Context),
173 Type::getInt8PtrTy(*Context),
174 Type::getInt32Ty(*Context),
175 TD->getIntPtrType(*Context),
177 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
179 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
180 CI->setCallingConv(F->getCallingConv());
185 /// EmitMemCmp - Emit a call to the memcmp function.
186 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
187 Value *Len, IRBuilder<> &B) {
188 Module *M = Caller->getParent();
189 AttributeWithIndex AWI[3];
190 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
191 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
192 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
193 Attribute::NoUnwind);
195 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
196 Type::getInt32Ty(*Context),
197 Type::getInt8PtrTy(*Context),
198 Type::getInt8PtrTy(*Context),
199 TD->getIntPtrType(*Context), NULL);
200 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
203 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
204 CI->setCallingConv(F->getCallingConv());
209 /// EmitMemSet - Emit a call to the memset function
210 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
211 Value *Len, IRBuilder<> &B) {
212 Module *M = Caller->getParent();
213 Intrinsic::ID IID = Intrinsic::memset;
215 Tys[0] = Len->getType();
216 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
217 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
218 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
221 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
222 /// 'floor'). This function is known to take a single of type matching 'Op' and
223 /// returns one value with the same type. If 'Op' is a long double, 'l' is
224 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
225 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
227 const AttrListPtr &Attrs) {
229 if (!Op->getType()->isDoubleTy()) {
230 // If we need to add a suffix, copy into NameBuffer.
231 unsigned NameLen = strlen(Name);
232 assert(NameLen < sizeof(NameBuffer)-2);
233 memcpy(NameBuffer, Name, NameLen);
234 if (Op->getType()->isFloatTy())
235 NameBuffer[NameLen] = 'f'; // floorf
237 NameBuffer[NameLen] = 'l'; // floorl
238 NameBuffer[NameLen+1] = 0;
242 Module *M = Caller->getParent();
243 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
244 Op->getType(), NULL);
245 CallInst *CI = B.CreateCall(Callee, Op, Name);
246 CI->setAttributes(Attrs);
247 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
248 CI->setCallingConv(F->getCallingConv());
253 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
255 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
256 Module *M = Caller->getParent();
257 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
258 Type::getInt32Ty(*Context), NULL);
259 CallInst *CI = B.CreateCall(PutChar,
260 B.CreateIntCast(Char,
261 Type::getInt32Ty(*Context),
265 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
266 CI->setCallingConv(F->getCallingConv());
269 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
271 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
272 Module *M = Caller->getParent();
273 AttributeWithIndex AWI[2];
274 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
275 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
277 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
278 Type::getInt32Ty(*Context),
279 Type::getInt8PtrTy(*Context),
281 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
282 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
283 CI->setCallingConv(F->getCallingConv());
287 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
288 /// an integer and File is a pointer to FILE.
289 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
290 Module *M = Caller->getParent();
291 AttributeWithIndex AWI[2];
292 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
293 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
295 if (isa<PointerType>(File->getType()))
296 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
297 Type::getInt32Ty(*Context),
298 Type::getInt32Ty(*Context), File->getType(),
301 F = M->getOrInsertFunction("fputc",
302 Type::getInt32Ty(*Context),
303 Type::getInt32Ty(*Context),
304 File->getType(), NULL);
305 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), "chari");
306 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
308 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
309 CI->setCallingConv(Fn->getCallingConv());
312 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
313 /// pointer and File is a pointer to FILE.
314 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
315 Module *M = Caller->getParent();
316 AttributeWithIndex AWI[3];
317 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
318 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
319 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
321 if (isa<PointerType>(File->getType()))
322 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
323 Type::getInt32Ty(*Context),
324 Type::getInt8PtrTy(*Context),
325 File->getType(), NULL);
327 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
328 Type::getInt8PtrTy(*Context),
329 File->getType(), NULL);
330 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
332 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
333 CI->setCallingConv(Fn->getCallingConv());
336 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
337 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
338 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
340 Module *M = Caller->getParent();
341 AttributeWithIndex AWI[3];
342 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
343 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
344 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
346 if (isa<PointerType>(File->getType()))
347 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
348 TD->getIntPtrType(*Context),
349 Type::getInt8PtrTy(*Context),
350 TD->getIntPtrType(*Context),
351 TD->getIntPtrType(*Context),
352 File->getType(), NULL);
354 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
355 Type::getInt8PtrTy(*Context),
356 TD->getIntPtrType(*Context),
357 TD->getIntPtrType(*Context),
358 File->getType(), NULL);
359 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
360 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
362 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
363 CI->setCallingConv(Fn->getCallingConv());
366 //===----------------------------------------------------------------------===//
368 //===----------------------------------------------------------------------===//
370 /// GetStringLengthH - If we can compute the length of the string pointed to by
371 /// the specified pointer, return 'len+1'. If we can't, return 0.
372 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
373 // Look through noop bitcast instructions.
374 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
375 return GetStringLengthH(BCI->getOperand(0), PHIs);
377 // If this is a PHI node, there are two cases: either we have already seen it
379 if (PHINode *PN = dyn_cast<PHINode>(V)) {
380 if (!PHIs.insert(PN))
381 return ~0ULL; // already in the set.
383 // If it was new, see if all the input strings are the same length.
384 uint64_t LenSoFar = ~0ULL;
385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
386 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
387 if (Len == 0) return 0; // Unknown length -> unknown.
389 if (Len == ~0ULL) continue;
391 if (Len != LenSoFar && LenSoFar != ~0ULL)
392 return 0; // Disagree -> unknown.
396 // Success, all agree.
400 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
401 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
402 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
403 if (Len1 == 0) return 0;
404 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
405 if (Len2 == 0) return 0;
406 if (Len1 == ~0ULL) return Len2;
407 if (Len2 == ~0ULL) return Len1;
408 if (Len1 != Len2) return 0;
412 // If the value is not a GEP instruction nor a constant expression with a
413 // GEP instruction, then return unknown.
415 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
417 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
418 if (CE->getOpcode() != Instruction::GetElementPtr)
425 // Make sure the GEP has exactly three arguments.
426 if (GEP->getNumOperands() != 3)
429 // Check to make sure that the first operand of the GEP is an integer and
430 // has value 0 so that we are sure we're indexing into the initializer.
431 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
437 // If the second index isn't a ConstantInt, then this is a variable index
438 // into the array. If this occurs, we can't say anything meaningful about
440 uint64_t StartIdx = 0;
441 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
442 StartIdx = CI->getZExtValue();
446 // The GEP instruction, constant or instruction, must reference a global
447 // variable that is a constant and is initialized. The referenced constant
448 // initializer is the array that we'll use for optimization.
449 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
450 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
451 GV->mayBeOverridden())
453 Constant *GlobalInit = GV->getInitializer();
455 // Handle the ConstantAggregateZero case, which is a degenerate case. The
456 // initializer is constant zero so the length of the string must be zero.
457 if (isa<ConstantAggregateZero>(GlobalInit))
458 return 1; // Len = 0 offset by 1.
460 // Must be a Constant Array
461 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
463 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
466 // Get the number of elements in the array
467 uint64_t NumElts = Array->getType()->getNumElements();
469 // Traverse the constant array from StartIdx (derived above) which is
470 // the place the GEP refers to in the array.
471 for (unsigned i = StartIdx; i != NumElts; ++i) {
472 Constant *Elt = Array->getOperand(i);
473 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
474 if (!CI) // This array isn't suitable, non-int initializer.
477 return i-StartIdx+1; // We found end of string, success!
480 return 0; // The array isn't null terminated, conservatively return 'unknown'.
483 /// GetStringLength - If we can compute the length of the string pointed to by
484 /// the specified pointer, return 'len+1'. If we can't, return 0.
485 static uint64_t GetStringLength(Value *V) {
486 if (!isa<PointerType>(V->getType())) return 0;
488 SmallPtrSet<PHINode*, 32> PHIs;
489 uint64_t Len = GetStringLengthH(V, PHIs);
490 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
491 // an empty string as a length.
492 return Len == ~0ULL ? 1 : Len;
495 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
496 /// value is equal or not-equal to zero.
497 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
498 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
500 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
501 if (IC->isEquality())
502 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
503 if (C->isNullValue())
505 // Unknown instruction.
511 //===----------------------------------------------------------------------===//
512 // Miscellaneous LibCall/Intrinsic Optimizations
513 //===----------------------------------------------------------------------===//
516 struct SizeOpt : public LibCallOptimization {
517 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
518 // TODO: We can do more with this, but delaying to here should be no change
520 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
522 if (!Const) return 0;
524 if (Const->getZExtValue() < 2)
525 return Constant::getAllOnesValue(Const->getType());
527 return ConstantInt::get(Const->getType(), 0);
532 //===----------------------------------------------------------------------===//
533 // String and Memory LibCall Optimizations
534 //===----------------------------------------------------------------------===//
536 //===---------------------------------------===//
537 // 'strcat' Optimizations
539 struct StrCatOpt : public LibCallOptimization {
540 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
541 // Verify the "strcat" function prototype.
542 const FunctionType *FT = Callee->getFunctionType();
543 if (FT->getNumParams() != 2 ||
544 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
545 FT->getParamType(0) != FT->getReturnType() ||
546 FT->getParamType(1) != FT->getReturnType())
549 // Extract some information from the instruction
550 Value *Dst = CI->getOperand(1);
551 Value *Src = CI->getOperand(2);
553 // See if we can get the length of the input string.
554 uint64_t Len = GetStringLength(Src);
555 if (Len == 0) return 0;
556 --Len; // Unbias length.
558 // Handle the simple, do-nothing case: strcat(x, "") -> x
562 // These optimizations require TargetData.
565 EmitStrLenMemCpy(Src, Dst, Len, B);
569 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
570 // We need to find the end of the destination string. That's where the
571 // memory is to be moved to. We just generate a call to strlen.
572 Value *DstLen = EmitStrLen(Dst, B);
574 // Now that we have the destination's length, we must index into the
575 // destination's pointer to get the actual memcpy destination (end of
576 // the string .. we're concatenating).
577 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
579 // We have enough information to now generate the memcpy call to do the
580 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
581 EmitMemCpy(CpyDst, Src,
582 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
586 //===---------------------------------------===//
587 // 'strncat' Optimizations
589 struct StrNCatOpt : public StrCatOpt {
590 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
591 // Verify the "strncat" function prototype.
592 const FunctionType *FT = Callee->getFunctionType();
593 if (FT->getNumParams() != 3 ||
594 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
595 FT->getParamType(0) != FT->getReturnType() ||
596 FT->getParamType(1) != FT->getReturnType() ||
597 !isa<IntegerType>(FT->getParamType(2)))
600 // Extract some information from the instruction
601 Value *Dst = CI->getOperand(1);
602 Value *Src = CI->getOperand(2);
605 // We don't do anything if length is not constant
606 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
607 Len = LengthArg->getZExtValue();
611 // See if we can get the length of the input string.
612 uint64_t SrcLen = GetStringLength(Src);
613 if (SrcLen == 0) return 0;
614 --SrcLen; // Unbias length.
616 // Handle the simple, do-nothing cases:
617 // strncat(x, "", c) -> x
618 // strncat(x, c, 0) -> x
619 if (SrcLen == 0 || Len == 0) return Dst;
621 // These optimizations require TargetData.
624 // We don't optimize this case
625 if (Len < SrcLen) return 0;
627 // strncat(x, s, c) -> strcat(x, s)
628 // s is constant so the strcat can be optimized further
629 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
634 //===---------------------------------------===//
635 // 'strchr' Optimizations
637 struct StrChrOpt : public LibCallOptimization {
638 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
639 // Verify the "strchr" function prototype.
640 const FunctionType *FT = Callee->getFunctionType();
641 if (FT->getNumParams() != 2 ||
642 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
643 FT->getParamType(0) != FT->getReturnType())
646 Value *SrcStr = CI->getOperand(1);
648 // If the second operand is non-constant, see if we can compute the length
649 // of the input string and turn this into memchr.
650 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
652 // These optimizations require TargetData.
655 uint64_t Len = GetStringLength(SrcStr);
657 FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs i32.
660 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
661 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
664 // Otherwise, the character is a constant, see if the first argument is
665 // a string literal. If so, we can constant fold.
667 if (!GetConstantStringInfo(SrcStr, Str))
670 // strchr can find the nul character.
672 char CharValue = CharC->getSExtValue();
674 // Compute the offset.
677 if (i == Str.size()) // Didn't find the char. strchr returns null.
678 return Constant::getNullValue(CI->getType());
679 // Did we find our match?
680 if (Str[i] == CharValue)
685 // strchr(s+n,c) -> gep(s+n+i,c)
686 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
687 return B.CreateGEP(SrcStr, Idx, "strchr");
691 //===---------------------------------------===//
692 // 'strcmp' Optimizations
694 struct StrCmpOpt : public LibCallOptimization {
695 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
696 // Verify the "strcmp" function prototype.
697 const FunctionType *FT = Callee->getFunctionType();
698 if (FT->getNumParams() != 2 ||
699 FT->getReturnType() != Type::getInt32Ty(*Context) ||
700 FT->getParamType(0) != FT->getParamType(1) ||
701 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
704 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
705 if (Str1P == Str2P) // strcmp(x,x) -> 0
706 return ConstantInt::get(CI->getType(), 0);
708 std::string Str1, Str2;
709 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
710 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
712 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
713 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
715 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
716 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
718 // strcmp(x, y) -> cnst (if both x and y are constant strings)
719 if (HasStr1 && HasStr2)
720 return ConstantInt::get(CI->getType(),
721 strcmp(Str1.c_str(),Str2.c_str()));
723 // strcmp(P, "x") -> memcmp(P, "x", 2)
724 uint64_t Len1 = GetStringLength(Str1P);
725 uint64_t Len2 = GetStringLength(Str2P);
727 // These optimizations require TargetData.
730 return EmitMemCmp(Str1P, Str2P,
731 ConstantInt::get(TD->getIntPtrType(*Context),
732 std::min(Len1, Len2)), B);
739 //===---------------------------------------===//
740 // 'strncmp' Optimizations
742 struct StrNCmpOpt : public LibCallOptimization {
743 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
744 // Verify the "strncmp" function prototype.
745 const FunctionType *FT = Callee->getFunctionType();
746 if (FT->getNumParams() != 3 ||
747 FT->getReturnType() != Type::getInt32Ty(*Context) ||
748 FT->getParamType(0) != FT->getParamType(1) ||
749 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
750 !isa<IntegerType>(FT->getParamType(2)))
753 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
754 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
755 return ConstantInt::get(CI->getType(), 0);
757 // Get the length argument if it is constant.
759 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
760 Length = LengthArg->getZExtValue();
764 if (Length == 0) // strncmp(x,y,0) -> 0
765 return ConstantInt::get(CI->getType(), 0);
767 std::string Str1, Str2;
768 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
769 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
771 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
772 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
774 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
775 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
777 // strncmp(x, y) -> cnst (if both x and y are constant strings)
778 if (HasStr1 && HasStr2)
779 return ConstantInt::get(CI->getType(),
780 strncmp(Str1.c_str(), Str2.c_str(), Length));
786 //===---------------------------------------===//
787 // 'strcpy' Optimizations
789 struct StrCpyOpt : public LibCallOptimization {
790 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
791 // Verify the "strcpy" function prototype.
792 const FunctionType *FT = Callee->getFunctionType();
793 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
794 FT->getParamType(0) != FT->getParamType(1) ||
795 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
798 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
799 if (Dst == Src) // strcpy(x,x) -> x
802 // These optimizations require TargetData.
805 // See if we can get the length of the input string.
806 uint64_t Len = GetStringLength(Src);
807 if (Len == 0) return 0;
809 // We have enough information to now generate the memcpy call to do the
810 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
812 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
817 //===---------------------------------------===//
818 // 'strncpy' Optimizations
820 struct StrNCpyOpt : public LibCallOptimization {
821 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
822 const FunctionType *FT = Callee->getFunctionType();
823 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
824 FT->getParamType(0) != FT->getParamType(1) ||
825 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
826 !isa<IntegerType>(FT->getParamType(2)))
829 Value *Dst = CI->getOperand(1);
830 Value *Src = CI->getOperand(2);
831 Value *LenOp = CI->getOperand(3);
833 // See if we can get the length of the input string.
834 uint64_t SrcLen = GetStringLength(Src);
835 if (SrcLen == 0) return 0;
839 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
840 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
846 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
847 Len = LengthArg->getZExtValue();
851 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
853 // These optimizations require TargetData.
856 // Let strncpy handle the zero padding
857 if (Len > SrcLen+1) return 0;
859 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
861 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
867 //===---------------------------------------===//
868 // 'strlen' Optimizations
870 struct StrLenOpt : public LibCallOptimization {
871 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
872 const FunctionType *FT = Callee->getFunctionType();
873 if (FT->getNumParams() != 1 ||
874 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
875 !isa<IntegerType>(FT->getReturnType()))
878 Value *Src = CI->getOperand(1);
880 // Constant folding: strlen("xyz") -> 3
881 if (uint64_t Len = GetStringLength(Src))
882 return ConstantInt::get(CI->getType(), Len-1);
884 // Handle strlen(p) != 0.
885 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
887 // strlen(x) != 0 --> *x != 0
888 // strlen(x) == 0 --> *x == 0
889 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
893 //===---------------------------------------===//
894 // 'strto*' Optimizations
896 struct StrToOpt : public LibCallOptimization {
897 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
898 const FunctionType *FT = Callee->getFunctionType();
899 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
900 !isa<PointerType>(FT->getParamType(0)) ||
901 !isa<PointerType>(FT->getParamType(1)))
904 Value *EndPtr = CI->getOperand(2);
905 if (isa<ConstantPointerNull>(EndPtr)) {
906 CI->setOnlyReadsMemory();
907 CI->addAttribute(1, Attribute::NoCapture);
915 //===---------------------------------------===//
916 // 'memcmp' Optimizations
918 struct MemCmpOpt : public LibCallOptimization {
919 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
920 const FunctionType *FT = Callee->getFunctionType();
921 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
922 !isa<PointerType>(FT->getParamType(1)) ||
923 FT->getReturnType() != Type::getInt32Ty(*Context))
926 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
928 if (LHS == RHS) // memcmp(s,s,x) -> 0
929 return Constant::getNullValue(CI->getType());
931 // Make sure we have a constant length.
932 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
934 uint64_t Len = LenC->getZExtValue();
936 if (Len == 0) // memcmp(s1,s2,0) -> 0
937 return Constant::getNullValue(CI->getType());
939 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
940 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
941 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
942 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
945 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
946 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
947 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
948 const Type *PTy = PointerType::getUnqual(Len == 2 ?
949 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
950 LHS = B.CreateBitCast(LHS, PTy, "tmp");
951 RHS = B.CreateBitCast(RHS, PTy, "tmp");
952 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
953 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
954 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
955 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
962 //===---------------------------------------===//
963 // 'memcpy' Optimizations
965 struct MemCpyOpt : public LibCallOptimization {
966 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
967 // These optimizations require TargetData.
970 const FunctionType *FT = Callee->getFunctionType();
971 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
972 !isa<PointerType>(FT->getParamType(0)) ||
973 !isa<PointerType>(FT->getParamType(1)) ||
974 FT->getParamType(2) != TD->getIntPtrType(*Context))
977 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
978 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
979 return CI->getOperand(1);
983 //===---------------------------------------===//
984 // 'memmove' Optimizations
986 struct MemMoveOpt : public LibCallOptimization {
987 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
988 // These optimizations require TargetData.
991 const FunctionType *FT = Callee->getFunctionType();
992 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
993 !isa<PointerType>(FT->getParamType(0)) ||
994 !isa<PointerType>(FT->getParamType(1)) ||
995 FT->getParamType(2) != TD->getIntPtrType(*Context))
998 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
999 Module *M = Caller->getParent();
1000 Intrinsic::ID IID = Intrinsic::memmove;
1002 Tys[0] = TD->getIntPtrType(*Context);
1003 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
1004 Value *Dst = CastToCStr(CI->getOperand(1), B);
1005 Value *Src = CastToCStr(CI->getOperand(2), B);
1006 Value *Size = CI->getOperand(3);
1007 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
1008 B.CreateCall4(MemMove, Dst, Src, Size, Align);
1009 return CI->getOperand(1);
1013 //===---------------------------------------===//
1014 // 'memset' Optimizations
1016 struct MemSetOpt : public LibCallOptimization {
1017 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1018 // These optimizations require TargetData.
1021 const FunctionType *FT = Callee->getFunctionType();
1022 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1023 !isa<PointerType>(FT->getParamType(0)) ||
1024 !isa<IntegerType>(FT->getParamType(1)) ||
1025 FT->getParamType(2) != TD->getIntPtrType(*Context))
1028 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1029 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1031 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1032 return CI->getOperand(1);
1036 //===----------------------------------------------------------------------===//
1037 // Math Library Optimizations
1038 //===----------------------------------------------------------------------===//
1040 //===---------------------------------------===//
1041 // 'pow*' Optimizations
1043 struct PowOpt : public LibCallOptimization {
1044 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1045 const FunctionType *FT = Callee->getFunctionType();
1046 // Just make sure this has 2 arguments of the same FP type, which match the
1048 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1049 FT->getParamType(0) != FT->getParamType(1) ||
1050 !FT->getParamType(0)->isFloatingPoint())
1053 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1054 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1055 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1057 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1058 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1061 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1062 if (Op2C == 0) return 0;
1064 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1065 return ConstantFP::get(CI->getType(), 1.0);
1067 if (Op2C->isExactlyValue(0.5)) {
1068 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1069 // This is faster than calling pow, and still handles negative zero
1070 // and negative infinite correctly.
1071 // TODO: In fast-math mode, this could be just sqrt(x).
1072 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1073 Value *Inf = ConstantFP::getInfinity(CI->getType());
1074 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1075 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1076 Callee->getAttributes());
1077 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1078 Callee->getAttributes());
1079 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1080 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1084 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1086 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1087 return B.CreateFMul(Op1, Op1, "pow2");
1088 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1089 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1095 //===---------------------------------------===//
1096 // 'exp2' Optimizations
1098 struct Exp2Opt : public LibCallOptimization {
1099 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1100 const FunctionType *FT = Callee->getFunctionType();
1101 // Just make sure this has 1 argument of FP type, which matches the
1103 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1104 !FT->getParamType(0)->isFloatingPoint())
1107 Value *Op = CI->getOperand(1);
1108 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1109 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1110 Value *LdExpArg = 0;
1111 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1112 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1113 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1114 Type::getInt32Ty(*Context), "tmp");
1115 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1116 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1117 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1118 Type::getInt32Ty(*Context), "tmp");
1123 if (Op->getType()->isFloatTy())
1125 else if (Op->getType()->isDoubleTy())
1130 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1131 if (!Op->getType()->isFloatTy())
1132 One = ConstantExpr::getFPExtend(One, Op->getType());
1134 Module *M = Caller->getParent();
1135 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1137 Type::getInt32Ty(*Context),NULL);
1138 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1139 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1140 CI->setCallingConv(F->getCallingConv());
1148 //===---------------------------------------===//
1149 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1151 struct UnaryDoubleFPOpt : public LibCallOptimization {
1152 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1153 const FunctionType *FT = Callee->getFunctionType();
1154 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1155 !FT->getParamType(0)->isDoubleTy())
1158 // If this is something like 'floor((double)floatval)', convert to floorf.
1159 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1160 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1163 // floor((double)floatval) -> (double)floorf(floatval)
1164 Value *V = Cast->getOperand(0);
1165 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1166 Callee->getAttributes());
1167 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1171 //===----------------------------------------------------------------------===//
1172 // Integer Optimizations
1173 //===----------------------------------------------------------------------===//
1175 //===---------------------------------------===//
1176 // 'ffs*' Optimizations
1178 struct FFSOpt : public LibCallOptimization {
1179 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1180 const FunctionType *FT = Callee->getFunctionType();
1181 // Just make sure this has 2 arguments of the same FP type, which match the
1183 if (FT->getNumParams() != 1 ||
1184 FT->getReturnType() != Type::getInt32Ty(*Context) ||
1185 !isa<IntegerType>(FT->getParamType(0)))
1188 Value *Op = CI->getOperand(1);
1191 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1192 if (CI->getValue() == 0) // ffs(0) -> 0.
1193 return Constant::getNullValue(CI->getType());
1194 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1195 CI->getValue().countTrailingZeros()+1);
1198 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1199 const Type *ArgType = Op->getType();
1200 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1201 Intrinsic::cttz, &ArgType, 1);
1202 Value *V = B.CreateCall(F, Op, "cttz");
1203 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1204 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1206 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1207 return B.CreateSelect(Cond, V,
1208 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1212 //===---------------------------------------===//
1213 // 'isdigit' Optimizations
1215 struct IsDigitOpt : public LibCallOptimization {
1216 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1217 const FunctionType *FT = Callee->getFunctionType();
1218 // We require integer(i32)
1219 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1220 FT->getParamType(0) != Type::getInt32Ty(*Context))
1223 // isdigit(c) -> (c-'0') <u 10
1224 Value *Op = CI->getOperand(1);
1225 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1227 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1229 return B.CreateZExt(Op, CI->getType());
1233 //===---------------------------------------===//
1234 // 'isascii' Optimizations
1236 struct IsAsciiOpt : public LibCallOptimization {
1237 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1238 const FunctionType *FT = Callee->getFunctionType();
1239 // We require integer(i32)
1240 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1241 FT->getParamType(0) != Type::getInt32Ty(*Context))
1244 // isascii(c) -> c <u 128
1245 Value *Op = CI->getOperand(1);
1246 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1248 return B.CreateZExt(Op, CI->getType());
1252 //===---------------------------------------===//
1253 // 'abs', 'labs', 'llabs' Optimizations
1255 struct AbsOpt : public LibCallOptimization {
1256 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1257 const FunctionType *FT = Callee->getFunctionType();
1258 // We require integer(integer) where the types agree.
1259 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1260 FT->getParamType(0) != FT->getReturnType())
1263 // abs(x) -> x >s -1 ? x : -x
1264 Value *Op = CI->getOperand(1);
1265 Value *Pos = B.CreateICmpSGT(Op,
1266 Constant::getAllOnesValue(Op->getType()),
1268 Value *Neg = B.CreateNeg(Op, "neg");
1269 return B.CreateSelect(Pos, Op, Neg);
1274 //===---------------------------------------===//
1275 // 'toascii' Optimizations
1277 struct ToAsciiOpt : public LibCallOptimization {
1278 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1279 const FunctionType *FT = Callee->getFunctionType();
1280 // We require i32(i32)
1281 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1282 FT->getParamType(0) != Type::getInt32Ty(*Context))
1285 // isascii(c) -> c & 0x7f
1286 return B.CreateAnd(CI->getOperand(1),
1287 ConstantInt::get(CI->getType(),0x7F));
1291 //===----------------------------------------------------------------------===//
1292 // Formatting and IO Optimizations
1293 //===----------------------------------------------------------------------===//
1295 //===---------------------------------------===//
1296 // 'printf' Optimizations
1298 struct PrintFOpt : public LibCallOptimization {
1299 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1300 // Require one fixed pointer argument and an integer/void result.
1301 const FunctionType *FT = Callee->getFunctionType();
1302 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1303 !(isa<IntegerType>(FT->getReturnType()) ||
1304 FT->getReturnType()->isVoidTy()))
1307 // Check for a fixed format string.
1308 std::string FormatStr;
1309 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1312 // Empty format string -> noop.
1313 if (FormatStr.empty()) // Tolerate printf's declared void.
1314 return CI->use_empty() ? (Value*)CI :
1315 ConstantInt::get(CI->getType(), 0);
1317 // printf("x") -> putchar('x'), even for '%'.
1318 if (FormatStr.size() == 1) {
1319 EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context), FormatStr[0]), B);
1320 return CI->use_empty() ? (Value*)CI :
1321 ConstantInt::get(CI->getType(), 1);
1324 // printf("foo\n") --> puts("foo")
1325 if (FormatStr[FormatStr.size()-1] == '\n' &&
1326 FormatStr.find('%') == std::string::npos) { // no format characters.
1327 // Create a string literal with no \n on it. We expect the constant merge
1328 // pass to be run after this pass, to merge duplicate strings.
1329 FormatStr.erase(FormatStr.end()-1);
1330 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1331 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1332 GlobalVariable::InternalLinkage, C, "str");
1334 return CI->use_empty() ? (Value*)CI :
1335 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1338 // Optimize specific format strings.
1339 // printf("%c", chr) --> putchar(*(i8*)dst)
1340 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1341 isa<IntegerType>(CI->getOperand(2)->getType())) {
1342 EmitPutChar(CI->getOperand(2), B);
1343 return CI->use_empty() ? (Value*)CI :
1344 ConstantInt::get(CI->getType(), 1);
1347 // printf("%s\n", str) --> puts(str)
1348 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1349 isa<PointerType>(CI->getOperand(2)->getType()) &&
1351 EmitPutS(CI->getOperand(2), B);
1358 //===---------------------------------------===//
1359 // 'sprintf' Optimizations
1361 struct SPrintFOpt : public LibCallOptimization {
1362 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1363 // Require two fixed pointer arguments and an integer result.
1364 const FunctionType *FT = Callee->getFunctionType();
1365 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1366 !isa<PointerType>(FT->getParamType(1)) ||
1367 !isa<IntegerType>(FT->getReturnType()))
1370 // Check for a fixed format string.
1371 std::string FormatStr;
1372 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1375 // If we just have a format string (nothing else crazy) transform it.
1376 if (CI->getNumOperands() == 3) {
1377 // Make sure there's no % in the constant array. We could try to handle
1378 // %% -> % in the future if we cared.
1379 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1380 if (FormatStr[i] == '%')
1381 return 0; // we found a format specifier, bail out.
1383 // These optimizations require TargetData.
1386 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1387 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1388 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1389 return ConstantInt::get(CI->getType(), FormatStr.size());
1392 // The remaining optimizations require the format string to be "%s" or "%c"
1393 // and have an extra operand.
1394 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1397 // Decode the second character of the format string.
1398 if (FormatStr[1] == 'c') {
1399 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1400 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1401 Value *V = B.CreateTrunc(CI->getOperand(3),
1402 Type::getInt8Ty(*Context), "char");
1403 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1404 B.CreateStore(V, Ptr);
1405 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1407 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1409 return ConstantInt::get(CI->getType(), 1);
1412 if (FormatStr[1] == 's') {
1413 // These optimizations require TargetData.
1416 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1417 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1419 Value *Len = EmitStrLen(CI->getOperand(3), B);
1420 Value *IncLen = B.CreateAdd(Len,
1421 ConstantInt::get(Len->getType(), 1),
1423 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1425 // The sprintf result is the unincremented number of bytes in the string.
1426 return B.CreateIntCast(Len, CI->getType(), false);
1432 //===---------------------------------------===//
1433 // 'fwrite' Optimizations
1435 struct FWriteOpt : public LibCallOptimization {
1436 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1437 // Require a pointer, an integer, an integer, a pointer, returning integer.
1438 const FunctionType *FT = Callee->getFunctionType();
1439 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1440 !isa<IntegerType>(FT->getParamType(1)) ||
1441 !isa<IntegerType>(FT->getParamType(2)) ||
1442 !isa<PointerType>(FT->getParamType(3)) ||
1443 !isa<IntegerType>(FT->getReturnType()))
1446 // Get the element size and count.
1447 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1448 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1449 if (!SizeC || !CountC) return 0;
1450 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1452 // If this is writing zero records, remove the call (it's a noop).
1454 return ConstantInt::get(CI->getType(), 0);
1456 // If this is writing one byte, turn it into fputc.
1457 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1458 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1459 EmitFPutC(Char, CI->getOperand(4), B);
1460 return ConstantInt::get(CI->getType(), 1);
1467 //===---------------------------------------===//
1468 // 'fputs' Optimizations
1470 struct FPutsOpt : public LibCallOptimization {
1471 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1472 // These optimizations require TargetData.
1475 // Require two pointers. Also, we can't optimize if return value is used.
1476 const FunctionType *FT = Callee->getFunctionType();
1477 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1478 !isa<PointerType>(FT->getParamType(1)) ||
1482 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1483 uint64_t Len = GetStringLength(CI->getOperand(1));
1485 EmitFWrite(CI->getOperand(1),
1486 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1487 CI->getOperand(2), B);
1488 return CI; // Known to have no uses (see above).
1492 //===---------------------------------------===//
1493 // 'fprintf' Optimizations
1495 struct FPrintFOpt : public LibCallOptimization {
1496 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1497 // Require two fixed paramters as pointers and integer result.
1498 const FunctionType *FT = Callee->getFunctionType();
1499 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1500 !isa<PointerType>(FT->getParamType(1)) ||
1501 !isa<IntegerType>(FT->getReturnType()))
1504 // All the optimizations depend on the format string.
1505 std::string FormatStr;
1506 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1509 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1510 if (CI->getNumOperands() == 3) {
1511 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1512 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1513 return 0; // We found a format specifier.
1515 // These optimizations require TargetData.
1518 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
1520 CI->getOperand(1), B);
1521 return ConstantInt::get(CI->getType(), FormatStr.size());
1524 // The remaining optimizations require the format string to be "%s" or "%c"
1525 // and have an extra operand.
1526 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1529 // Decode the second character of the format string.
1530 if (FormatStr[1] == 'c') {
1531 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1532 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1533 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1534 return ConstantInt::get(CI->getType(), 1);
1537 if (FormatStr[1] == 's') {
1538 // fprintf(F, "%s", str) -> fputs(str, F)
1539 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1541 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1548 } // end anonymous namespace.
1550 //===----------------------------------------------------------------------===//
1551 // SimplifyLibCalls Pass Implementation
1552 //===----------------------------------------------------------------------===//
1555 /// This pass optimizes well known library functions from libc and libm.
1557 class SimplifyLibCalls : public FunctionPass {
1558 StringMap<LibCallOptimization*> Optimizations;
1559 // String and Memory LibCall Optimizations
1560 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1561 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1562 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1564 // Math Library Optimizations
1565 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1566 // Integer Optimizations
1567 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1569 // Formatting and IO Optimizations
1570 SPrintFOpt SPrintF; PrintFOpt PrintF;
1571 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1574 bool Modified; // This is only used by doInitialization.
1576 static char ID; // Pass identification
1577 SimplifyLibCalls() : FunctionPass(&ID) {}
1579 void InitOptimizations();
1580 bool runOnFunction(Function &F);
1582 void setDoesNotAccessMemory(Function &F);
1583 void setOnlyReadsMemory(Function &F);
1584 void setDoesNotThrow(Function &F);
1585 void setDoesNotCapture(Function &F, unsigned n);
1586 void setDoesNotAlias(Function &F, unsigned n);
1587 bool doInitialization(Module &M);
1589 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1592 char SimplifyLibCalls::ID = 0;
1593 } // end anonymous namespace.
1595 static RegisterPass<SimplifyLibCalls>
1596 X("simplify-libcalls", "Simplify well-known library calls");
1598 // Public interface to the Simplify LibCalls pass.
1599 FunctionPass *llvm::createSimplifyLibCallsPass() {
1600 return new SimplifyLibCalls();
1603 /// Optimizations - Populate the Optimizations map with all the optimizations
1605 void SimplifyLibCalls::InitOptimizations() {
1606 // String and Memory LibCall Optimizations
1607 Optimizations["strcat"] = &StrCat;
1608 Optimizations["strncat"] = &StrNCat;
1609 Optimizations["strchr"] = &StrChr;
1610 Optimizations["strcmp"] = &StrCmp;
1611 Optimizations["strncmp"] = &StrNCmp;
1612 Optimizations["strcpy"] = &StrCpy;
1613 Optimizations["strncpy"] = &StrNCpy;
1614 Optimizations["strlen"] = &StrLen;
1615 Optimizations["strtol"] = &StrTo;
1616 Optimizations["strtod"] = &StrTo;
1617 Optimizations["strtof"] = &StrTo;
1618 Optimizations["strtoul"] = &StrTo;
1619 Optimizations["strtoll"] = &StrTo;
1620 Optimizations["strtold"] = &StrTo;
1621 Optimizations["strtoull"] = &StrTo;
1622 Optimizations["memcmp"] = &MemCmp;
1623 Optimizations["memcpy"] = &MemCpy;
1624 Optimizations["memmove"] = &MemMove;
1625 Optimizations["memset"] = &MemSet;
1627 // Math Library Optimizations
1628 Optimizations["powf"] = &Pow;
1629 Optimizations["pow"] = &Pow;
1630 Optimizations["powl"] = &Pow;
1631 Optimizations["llvm.pow.f32"] = &Pow;
1632 Optimizations["llvm.pow.f64"] = &Pow;
1633 Optimizations["llvm.pow.f80"] = &Pow;
1634 Optimizations["llvm.pow.f128"] = &Pow;
1635 Optimizations["llvm.pow.ppcf128"] = &Pow;
1636 Optimizations["exp2l"] = &Exp2;
1637 Optimizations["exp2"] = &Exp2;
1638 Optimizations["exp2f"] = &Exp2;
1639 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1640 Optimizations["llvm.exp2.f128"] = &Exp2;
1641 Optimizations["llvm.exp2.f80"] = &Exp2;
1642 Optimizations["llvm.exp2.f64"] = &Exp2;
1643 Optimizations["llvm.exp2.f32"] = &Exp2;
1646 Optimizations["floor"] = &UnaryDoubleFP;
1649 Optimizations["ceil"] = &UnaryDoubleFP;
1652 Optimizations["round"] = &UnaryDoubleFP;
1655 Optimizations["rint"] = &UnaryDoubleFP;
1657 #ifdef HAVE_NEARBYINTF
1658 Optimizations["nearbyint"] = &UnaryDoubleFP;
1661 // Integer Optimizations
1662 Optimizations["ffs"] = &FFS;
1663 Optimizations["ffsl"] = &FFS;
1664 Optimizations["ffsll"] = &FFS;
1665 Optimizations["abs"] = &Abs;
1666 Optimizations["labs"] = &Abs;
1667 Optimizations["llabs"] = &Abs;
1668 Optimizations["isdigit"] = &IsDigit;
1669 Optimizations["isascii"] = &IsAscii;
1670 Optimizations["toascii"] = &ToAscii;
1672 // Formatting and IO Optimizations
1673 Optimizations["sprintf"] = &SPrintF;
1674 Optimizations["printf"] = &PrintF;
1675 Optimizations["fwrite"] = &FWrite;
1676 Optimizations["fputs"] = &FPuts;
1677 Optimizations["fprintf"] = &FPrintF;
1680 Optimizations["llvm.objectsize"] = &ObjectSize;
1684 /// runOnFunction - Top level algorithm.
1686 bool SimplifyLibCalls::runOnFunction(Function &F) {
1687 if (Optimizations.empty())
1688 InitOptimizations();
1690 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1692 IRBuilder<> Builder(F.getContext());
1694 bool Changed = false;
1695 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1696 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1697 // Ignore non-calls.
1698 CallInst *CI = dyn_cast<CallInst>(I++);
1701 // Ignore indirect calls and calls to non-external functions.
1702 Function *Callee = CI->getCalledFunction();
1703 if (Callee == 0 || !Callee->isDeclaration() ||
1704 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1707 // Ignore unknown calls.
1708 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1711 // Set the builder to the instruction after the call.
1712 Builder.SetInsertPoint(BB, I);
1714 // Try to optimize this call.
1715 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1716 if (Result == 0) continue;
1718 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1719 errs() << " into: " << *Result << "\n");
1721 // Something changed!
1725 // Inspect the instruction after the call (which was potentially just
1729 if (CI != Result && !CI->use_empty()) {
1730 CI->replaceAllUsesWith(Result);
1731 if (!Result->hasName())
1732 Result->takeName(CI);
1734 CI->eraseFromParent();
1740 // Utility methods for doInitialization.
1742 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1743 if (!F.doesNotAccessMemory()) {
1744 F.setDoesNotAccessMemory();
1749 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1750 if (!F.onlyReadsMemory()) {
1751 F.setOnlyReadsMemory();
1756 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1757 if (!F.doesNotThrow()) {
1758 F.setDoesNotThrow();
1763 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1764 if (!F.doesNotCapture(n)) {
1765 F.setDoesNotCapture(n);
1770 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1771 if (!F.doesNotAlias(n)) {
1772 F.setDoesNotAlias(n);
1778 /// doInitialization - Add attributes to well-known functions.
1780 bool SimplifyLibCalls::doInitialization(Module &M) {
1782 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1784 if (!F.isDeclaration())
1790 const FunctionType *FTy = F.getFunctionType();
1792 StringRef Name = F.getName();
1795 if (Name == "strlen") {
1796 if (FTy->getNumParams() != 1 ||
1797 !isa<PointerType>(FTy->getParamType(0)))
1799 setOnlyReadsMemory(F);
1801 setDoesNotCapture(F, 1);
1802 } else if (Name == "strcpy" ||
1808 Name == "strtoul" ||
1809 Name == "strtoll" ||
1810 Name == "strtold" ||
1811 Name == "strncat" ||
1812 Name == "strncpy" ||
1813 Name == "strtoull") {
1814 if (FTy->getNumParams() < 2 ||
1815 !isa<PointerType>(FTy->getParamType(1)))
1818 setDoesNotCapture(F, 2);
1819 } else if (Name == "strxfrm") {
1820 if (FTy->getNumParams() != 3 ||
1821 !isa<PointerType>(FTy->getParamType(0)) ||
1822 !isa<PointerType>(FTy->getParamType(1)))
1825 setDoesNotCapture(F, 1);
1826 setDoesNotCapture(F, 2);
1827 } else if (Name == "strcmp" ||
1829 Name == "strncmp" ||
1830 Name ==" strcspn" ||
1831 Name == "strcoll" ||
1832 Name == "strcasecmp" ||
1833 Name == "strncasecmp") {
1834 if (FTy->getNumParams() < 2 ||
1835 !isa<PointerType>(FTy->getParamType(0)) ||
1836 !isa<PointerType>(FTy->getParamType(1)))
1838 setOnlyReadsMemory(F);
1840 setDoesNotCapture(F, 1);
1841 setDoesNotCapture(F, 2);
1842 } else if (Name == "strstr" ||
1843 Name == "strpbrk") {
1844 if (FTy->getNumParams() != 2 ||
1845 !isa<PointerType>(FTy->getParamType(1)))
1847 setOnlyReadsMemory(F);
1849 setDoesNotCapture(F, 2);
1850 } else if (Name == "strtok" ||
1851 Name == "strtok_r") {
1852 if (FTy->getNumParams() < 2 ||
1853 !isa<PointerType>(FTy->getParamType(1)))
1856 setDoesNotCapture(F, 2);
1857 } else if (Name == "scanf" ||
1859 Name == "setvbuf") {
1860 if (FTy->getNumParams() < 1 ||
1861 !isa<PointerType>(FTy->getParamType(0)))
1864 setDoesNotCapture(F, 1);
1865 } else if (Name == "strdup" ||
1866 Name == "strndup") {
1867 if (FTy->getNumParams() < 1 ||
1868 !isa<PointerType>(FTy->getReturnType()) ||
1869 !isa<PointerType>(FTy->getParamType(0)))
1872 setDoesNotAlias(F, 0);
1873 setDoesNotCapture(F, 1);
1874 } else if (Name == "stat" ||
1876 Name == "sprintf" ||
1877 Name == "statvfs") {
1878 if (FTy->getNumParams() < 2 ||
1879 !isa<PointerType>(FTy->getParamType(0)) ||
1880 !isa<PointerType>(FTy->getParamType(1)))
1883 setDoesNotCapture(F, 1);
1884 setDoesNotCapture(F, 2);
1885 } else if (Name == "snprintf") {
1886 if (FTy->getNumParams() != 3 ||
1887 !isa<PointerType>(FTy->getParamType(0)) ||
1888 !isa<PointerType>(FTy->getParamType(2)))
1891 setDoesNotCapture(F, 1);
1892 setDoesNotCapture(F, 3);
1893 } else if (Name == "setitimer") {
1894 if (FTy->getNumParams() != 3 ||
1895 !isa<PointerType>(FTy->getParamType(1)) ||
1896 !isa<PointerType>(FTy->getParamType(2)))
1899 setDoesNotCapture(F, 2);
1900 setDoesNotCapture(F, 3);
1901 } else if (Name == "system") {
1902 if (FTy->getNumParams() != 1 ||
1903 !isa<PointerType>(FTy->getParamType(0)))
1905 // May throw; "system" is a valid pthread cancellation point.
1906 setDoesNotCapture(F, 1);
1910 if (Name == "malloc") {
1911 if (FTy->getNumParams() != 1 ||
1912 !isa<PointerType>(FTy->getReturnType()))
1915 setDoesNotAlias(F, 0);
1916 } else if (Name == "memcmp") {
1917 if (FTy->getNumParams() != 3 ||
1918 !isa<PointerType>(FTy->getParamType(0)) ||
1919 !isa<PointerType>(FTy->getParamType(1)))
1921 setOnlyReadsMemory(F);
1923 setDoesNotCapture(F, 1);
1924 setDoesNotCapture(F, 2);
1925 } else if (Name == "memchr" ||
1926 Name == "memrchr") {
1927 if (FTy->getNumParams() != 3)
1929 setOnlyReadsMemory(F);
1931 } else if (Name == "modf" ||
1935 Name == "memccpy" ||
1936 Name == "memmove") {
1937 if (FTy->getNumParams() < 2 ||
1938 !isa<PointerType>(FTy->getParamType(1)))
1941 setDoesNotCapture(F, 2);
1942 } else if (Name == "memalign") {
1943 if (!isa<PointerType>(FTy->getReturnType()))
1945 setDoesNotAlias(F, 0);
1946 } else if (Name == "mkdir" ||
1948 if (FTy->getNumParams() == 0 ||
1949 !isa<PointerType>(FTy->getParamType(0)))
1952 setDoesNotCapture(F, 1);
1956 if (Name == "realloc") {
1957 if (FTy->getNumParams() != 2 ||
1958 !isa<PointerType>(FTy->getParamType(0)) ||
1959 !isa<PointerType>(FTy->getReturnType()))
1962 setDoesNotAlias(F, 0);
1963 setDoesNotCapture(F, 1);
1964 } else if (Name == "read") {
1965 if (FTy->getNumParams() != 3 ||
1966 !isa<PointerType>(FTy->getParamType(1)))
1968 // May throw; "read" is a valid pthread cancellation point.
1969 setDoesNotCapture(F, 2);
1970 } else if (Name == "rmdir" ||
1973 Name == "realpath") {
1974 if (FTy->getNumParams() < 1 ||
1975 !isa<PointerType>(FTy->getParamType(0)))
1978 setDoesNotCapture(F, 1);
1979 } else if (Name == "rename" ||
1980 Name == "readlink") {
1981 if (FTy->getNumParams() < 2 ||
1982 !isa<PointerType>(FTy->getParamType(0)) ||
1983 !isa<PointerType>(FTy->getParamType(1)))
1986 setDoesNotCapture(F, 1);
1987 setDoesNotCapture(F, 2);
1991 if (Name == "write") {
1992 if (FTy->getNumParams() != 3 ||
1993 !isa<PointerType>(FTy->getParamType(1)))
1995 // May throw; "write" is a valid pthread cancellation point.
1996 setDoesNotCapture(F, 2);
2000 if (Name == "bcopy") {
2001 if (FTy->getNumParams() != 3 ||
2002 !isa<PointerType>(FTy->getParamType(0)) ||
2003 !isa<PointerType>(FTy->getParamType(1)))
2006 setDoesNotCapture(F, 1);
2007 setDoesNotCapture(F, 2);
2008 } else if (Name == "bcmp") {
2009 if (FTy->getNumParams() != 3 ||
2010 !isa<PointerType>(FTy->getParamType(0)) ||
2011 !isa<PointerType>(FTy->getParamType(1)))
2014 setOnlyReadsMemory(F);
2015 setDoesNotCapture(F, 1);
2016 setDoesNotCapture(F, 2);
2017 } else if (Name == "bzero") {
2018 if (FTy->getNumParams() != 2 ||
2019 !isa<PointerType>(FTy->getParamType(0)))
2022 setDoesNotCapture(F, 1);
2026 if (Name == "calloc") {
2027 if (FTy->getNumParams() != 2 ||
2028 !isa<PointerType>(FTy->getReturnType()))
2031 setDoesNotAlias(F, 0);
2032 } else if (Name == "chmod" ||
2034 Name == "ctermid" ||
2035 Name == "clearerr" ||
2036 Name == "closedir") {
2037 if (FTy->getNumParams() == 0 ||
2038 !isa<PointerType>(FTy->getParamType(0)))
2041 setDoesNotCapture(F, 1);
2045 if (Name == "atoi" ||
2049 if (FTy->getNumParams() != 1 ||
2050 !isa<PointerType>(FTy->getParamType(0)))
2053 setOnlyReadsMemory(F);
2054 setDoesNotCapture(F, 1);
2055 } else if (Name == "access") {
2056 if (FTy->getNumParams() != 2 ||
2057 !isa<PointerType>(FTy->getParamType(0)))
2060 setDoesNotCapture(F, 1);
2064 if (Name == "fopen") {
2065 if (FTy->getNumParams() != 2 ||
2066 !isa<PointerType>(FTy->getReturnType()) ||
2067 !isa<PointerType>(FTy->getParamType(0)) ||
2068 !isa<PointerType>(FTy->getParamType(1)))
2071 setDoesNotAlias(F, 0);
2072 setDoesNotCapture(F, 1);
2073 setDoesNotCapture(F, 2);
2074 } else if (Name == "fdopen") {
2075 if (FTy->getNumParams() != 2 ||
2076 !isa<PointerType>(FTy->getReturnType()) ||
2077 !isa<PointerType>(FTy->getParamType(1)))
2080 setDoesNotAlias(F, 0);
2081 setDoesNotCapture(F, 2);
2082 } else if (Name == "feof" ||
2092 Name == "fsetpos" ||
2093 Name == "flockfile" ||
2094 Name == "funlockfile" ||
2095 Name == "ftrylockfile") {
2096 if (FTy->getNumParams() == 0 ||
2097 !isa<PointerType>(FTy->getParamType(0)))
2100 setDoesNotCapture(F, 1);
2101 } else if (Name == "ferror") {
2102 if (FTy->getNumParams() != 1 ||
2103 !isa<PointerType>(FTy->getParamType(0)))
2106 setDoesNotCapture(F, 1);
2107 setOnlyReadsMemory(F);
2108 } else if (Name == "fputc" ||
2113 Name == "fstatvfs") {
2114 if (FTy->getNumParams() != 2 ||
2115 !isa<PointerType>(FTy->getParamType(1)))
2118 setDoesNotCapture(F, 2);
2119 } else if (Name == "fgets") {
2120 if (FTy->getNumParams() != 3 ||
2121 !isa<PointerType>(FTy->getParamType(0)) ||
2122 !isa<PointerType>(FTy->getParamType(2)))
2125 setDoesNotCapture(F, 3);
2126 } else if (Name == "fread" ||
2128 if (FTy->getNumParams() != 4 ||
2129 !isa<PointerType>(FTy->getParamType(0)) ||
2130 !isa<PointerType>(FTy->getParamType(3)))
2133 setDoesNotCapture(F, 1);
2134 setDoesNotCapture(F, 4);
2135 } else if (Name == "fputs" ||
2137 Name == "fprintf" ||
2138 Name == "fgetpos") {
2139 if (FTy->getNumParams() < 2 ||
2140 !isa<PointerType>(FTy->getParamType(0)) ||
2141 !isa<PointerType>(FTy->getParamType(1)))
2144 setDoesNotCapture(F, 1);
2145 setDoesNotCapture(F, 2);
2149 if (Name == "getc" ||
2150 Name == "getlogin_r" ||
2151 Name == "getc_unlocked") {
2152 if (FTy->getNumParams() == 0 ||
2153 !isa<PointerType>(FTy->getParamType(0)))
2156 setDoesNotCapture(F, 1);
2157 } else if (Name == "getenv") {
2158 if (FTy->getNumParams() != 1 ||
2159 !isa<PointerType>(FTy->getParamType(0)))
2162 setOnlyReadsMemory(F);
2163 setDoesNotCapture(F, 1);
2164 } else if (Name == "gets" ||
2165 Name == "getchar") {
2167 } else if (Name == "getitimer") {
2168 if (FTy->getNumParams() != 2 ||
2169 !isa<PointerType>(FTy->getParamType(1)))
2172 setDoesNotCapture(F, 2);
2173 } else if (Name == "getpwnam") {
2174 if (FTy->getNumParams() != 1 ||
2175 !isa<PointerType>(FTy->getParamType(0)))
2178 setDoesNotCapture(F, 1);
2182 if (Name == "ungetc") {
2183 if (FTy->getNumParams() != 2 ||
2184 !isa<PointerType>(FTy->getParamType(1)))
2187 setDoesNotCapture(F, 2);
2188 } else if (Name == "uname" ||
2190 Name == "unsetenv") {
2191 if (FTy->getNumParams() != 1 ||
2192 !isa<PointerType>(FTy->getParamType(0)))
2195 setDoesNotCapture(F, 1);
2196 } else if (Name == "utime" ||
2198 if (FTy->getNumParams() != 2 ||
2199 !isa<PointerType>(FTy->getParamType(0)) ||
2200 !isa<PointerType>(FTy->getParamType(1)))
2203 setDoesNotCapture(F, 1);
2204 setDoesNotCapture(F, 2);
2208 if (Name == "putc") {
2209 if (FTy->getNumParams() != 2 ||
2210 !isa<PointerType>(FTy->getParamType(1)))
2213 setDoesNotCapture(F, 2);
2214 } else if (Name == "puts" ||
2217 if (FTy->getNumParams() != 1 ||
2218 !isa<PointerType>(FTy->getParamType(0)))
2221 setDoesNotCapture(F, 1);
2222 } else if (Name == "pread" ||
2224 if (FTy->getNumParams() != 4 ||
2225 !isa<PointerType>(FTy->getParamType(1)))
2227 // May throw; these are valid pthread cancellation points.
2228 setDoesNotCapture(F, 2);
2229 } else if (Name == "putchar") {
2231 } else if (Name == "popen") {
2232 if (FTy->getNumParams() != 2 ||
2233 !isa<PointerType>(FTy->getReturnType()) ||
2234 !isa<PointerType>(FTy->getParamType(0)) ||
2235 !isa<PointerType>(FTy->getParamType(1)))
2238 setDoesNotAlias(F, 0);
2239 setDoesNotCapture(F, 1);
2240 setDoesNotCapture(F, 2);
2241 } else if (Name == "pclose") {
2242 if (FTy->getNumParams() != 1 ||
2243 !isa<PointerType>(FTy->getParamType(0)))
2246 setDoesNotCapture(F, 1);
2250 if (Name == "vscanf") {
2251 if (FTy->getNumParams() != 2 ||
2252 !isa<PointerType>(FTy->getParamType(1)))
2255 setDoesNotCapture(F, 1);
2256 } else if (Name == "vsscanf" ||
2257 Name == "vfscanf") {
2258 if (FTy->getNumParams() != 3 ||
2259 !isa<PointerType>(FTy->getParamType(1)) ||
2260 !isa<PointerType>(FTy->getParamType(2)))
2263 setDoesNotCapture(F, 1);
2264 setDoesNotCapture(F, 2);
2265 } else if (Name == "valloc") {
2266 if (!isa<PointerType>(FTy->getReturnType()))
2269 setDoesNotAlias(F, 0);
2270 } else if (Name == "vprintf") {
2271 if (FTy->getNumParams() != 2 ||
2272 !isa<PointerType>(FTy->getParamType(0)))
2275 setDoesNotCapture(F, 1);
2276 } else if (Name == "vfprintf" ||
2277 Name == "vsprintf") {
2278 if (FTy->getNumParams() != 3 ||
2279 !isa<PointerType>(FTy->getParamType(0)) ||
2280 !isa<PointerType>(FTy->getParamType(1)))
2283 setDoesNotCapture(F, 1);
2284 setDoesNotCapture(F, 2);
2285 } else if (Name == "vsnprintf") {
2286 if (FTy->getNumParams() != 4 ||
2287 !isa<PointerType>(FTy->getParamType(0)) ||
2288 !isa<PointerType>(FTy->getParamType(2)))
2291 setDoesNotCapture(F, 1);
2292 setDoesNotCapture(F, 3);
2296 if (Name == "open") {
2297 if (FTy->getNumParams() < 2 ||
2298 !isa<PointerType>(FTy->getParamType(0)))
2300 // May throw; "open" is a valid pthread cancellation point.
2301 setDoesNotCapture(F, 1);
2302 } else if (Name == "opendir") {
2303 if (FTy->getNumParams() != 1 ||
2304 !isa<PointerType>(FTy->getReturnType()) ||
2305 !isa<PointerType>(FTy->getParamType(0)))
2308 setDoesNotAlias(F, 0);
2309 setDoesNotCapture(F, 1);
2313 if (Name == "tmpfile") {
2314 if (!isa<PointerType>(FTy->getReturnType()))
2317 setDoesNotAlias(F, 0);
2318 } else if (Name == "times") {
2319 if (FTy->getNumParams() != 1 ||
2320 !isa<PointerType>(FTy->getParamType(0)))
2323 setDoesNotCapture(F, 1);
2327 if (Name == "htonl" ||
2330 setDoesNotAccessMemory(F);
2334 if (Name == "ntohl" ||
2337 setDoesNotAccessMemory(F);
2341 if (Name == "lstat") {
2342 if (FTy->getNumParams() != 2 ||
2343 !isa<PointerType>(FTy->getParamType(0)) ||
2344 !isa<PointerType>(FTy->getParamType(1)))
2347 setDoesNotCapture(F, 1);
2348 setDoesNotCapture(F, 2);
2349 } else if (Name == "lchown") {
2350 if (FTy->getNumParams() != 3 ||
2351 !isa<PointerType>(FTy->getParamType(0)))
2354 setDoesNotCapture(F, 1);
2358 if (Name == "qsort") {
2359 if (FTy->getNumParams() != 4 ||
2360 !isa<PointerType>(FTy->getParamType(3)))
2362 // May throw; places call through function pointer.
2363 setDoesNotCapture(F, 4);
2367 if (Name == "__strdup" ||
2368 Name == "__strndup") {
2369 if (FTy->getNumParams() < 1 ||
2370 !isa<PointerType>(FTy->getReturnType()) ||
2371 !isa<PointerType>(FTy->getParamType(0)))
2374 setDoesNotAlias(F, 0);
2375 setDoesNotCapture(F, 1);
2376 } else if (Name == "__strtok_r") {
2377 if (FTy->getNumParams() != 3 ||
2378 !isa<PointerType>(FTy->getParamType(1)))
2381 setDoesNotCapture(F, 2);
2382 } else if (Name == "_IO_getc") {
2383 if (FTy->getNumParams() != 1 ||
2384 !isa<PointerType>(FTy->getParamType(0)))
2387 setDoesNotCapture(F, 1);
2388 } else if (Name == "_IO_putc") {
2389 if (FTy->getNumParams() != 2 ||
2390 !isa<PointerType>(FTy->getParamType(1)))
2393 setDoesNotCapture(F, 2);
2397 if (Name == "\1__isoc99_scanf") {
2398 if (FTy->getNumParams() < 1 ||
2399 !isa<PointerType>(FTy->getParamType(0)))
2402 setDoesNotCapture(F, 1);
2403 } else if (Name == "\1stat64" ||
2404 Name == "\1lstat64" ||
2405 Name == "\1statvfs64" ||
2406 Name == "\1__isoc99_sscanf") {
2407 if (FTy->getNumParams() < 1 ||
2408 !isa<PointerType>(FTy->getParamType(0)) ||
2409 !isa<PointerType>(FTy->getParamType(1)))
2412 setDoesNotCapture(F, 1);
2413 setDoesNotCapture(F, 2);
2414 } else if (Name == "\1fopen64") {
2415 if (FTy->getNumParams() != 2 ||
2416 !isa<PointerType>(FTy->getReturnType()) ||
2417 !isa<PointerType>(FTy->getParamType(0)) ||
2418 !isa<PointerType>(FTy->getParamType(1)))
2421 setDoesNotAlias(F, 0);
2422 setDoesNotCapture(F, 1);
2423 setDoesNotCapture(F, 2);
2424 } else if (Name == "\1fseeko64" ||
2425 Name == "\1ftello64") {
2426 if (FTy->getNumParams() == 0 ||
2427 !isa<PointerType>(FTy->getParamType(0)))
2430 setDoesNotCapture(F, 1);
2431 } else if (Name == "\1tmpfile64") {
2432 if (!isa<PointerType>(FTy->getReturnType()))
2435 setDoesNotAlias(F, 0);
2436 } else if (Name == "\1fstat64" ||
2437 Name == "\1fstatvfs64") {
2438 if (FTy->getNumParams() != 2 ||
2439 !isa<PointerType>(FTy->getParamType(1)))
2442 setDoesNotCapture(F, 2);
2443 } else if (Name == "\1open64") {
2444 if (FTy->getNumParams() < 2 ||
2445 !isa<PointerType>(FTy->getParamType(0)))
2447 // May throw; "open" is a valid pthread cancellation point.
2448 setDoesNotCapture(F, 1);
2457 // Additional cases that we need to add to this file:
2460 // * cbrt(expN(X)) -> expN(x/3)
2461 // * cbrt(sqrt(x)) -> pow(x,1/6)
2462 // * cbrt(sqrt(x)) -> pow(x,1/9)
2465 // * cos(-x) -> cos(x)
2468 // * exp(log(x)) -> x
2471 // * log(exp(x)) -> x
2472 // * log(x**y) -> y*log(x)
2473 // * log(exp(y)) -> y*log(e)
2474 // * log(exp2(y)) -> y*log(2)
2475 // * log(exp10(y)) -> y*log(10)
2476 // * log(sqrt(x)) -> 0.5*log(x)
2477 // * log(pow(x,y)) -> y*log(x)
2479 // lround, lroundf, lroundl:
2480 // * lround(cnst) -> cnst'
2483 // * memcmp(x,y,l) -> cnst
2484 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2487 // * pow(exp(x),y) -> exp(x*y)
2488 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2489 // * pow(pow(x,y),z)-> pow(x,y*z)
2492 // * puts("") -> putchar("\n")
2494 // round, roundf, roundl:
2495 // * round(cnst) -> cnst'
2498 // * signbit(cnst) -> cnst'
2499 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2501 // sqrt, sqrtf, sqrtl:
2502 // * sqrt(expN(x)) -> expN(x*0.5)
2503 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2504 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2507 // * stpcpy(str, "literal") ->
2508 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2510 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2511 // (if c is a constant integer and s is a constant string)
2512 // * strrchr(s1,0) -> strchr(s1,0)
2515 // * strpbrk(s,a) -> offset_in_for(s,a)
2516 // (if s and a are both constant strings)
2517 // * strpbrk(s,"") -> 0
2518 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2521 // * strspn(s,a) -> const_int (if both args are constant)
2522 // * strspn("",a) -> 0
2523 // * strspn(s,"") -> 0
2524 // * strcspn(s,a) -> const_int (if both args are constant)
2525 // * strcspn("",a) -> 0
2526 // * strcspn(s,"") -> strlen(a)
2529 // * strstr(x,x) -> x
2530 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2531 // (if s1 and s2 are constant strings)
2534 // * tan(atan(x)) -> x
2536 // trunc, truncf, truncl:
2537 // * trunc(cnst) -> cnst'