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' (e.g.
105 /// 'floor'). This function is known to take a single of type matching 'Op'
106 /// and returns one value with the same type. If 'Op' is a long double, 'l'
107 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
108 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
109 const AttrListPtr &Attrs);
111 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
113 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
115 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
117 void EmitPutS(Value *Str, IRBuilder<> &B);
119 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
120 /// an i32, and File is a pointer to FILE.
121 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
123 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
124 /// pointer and File is a pointer to FILE.
125 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
127 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
128 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
129 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
132 } // End anonymous namespace.
134 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
135 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
136 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
139 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
140 /// specified pointer. This always returns an integer value of size intptr_t.
141 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
142 Module *M = Caller->getParent();
143 AttributeWithIndex AWI[2];
144 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
145 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
146 Attribute::NoUnwind);
148 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
149 TD->getIntPtrType(*Context),
150 Type::getInt8PtrTy(*Context),
152 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
153 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
154 CI->setCallingConv(F->getCallingConv());
159 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
160 /// specified pointer and character. Ptr is required to be some pointer type,
161 /// and the return value has 'i8*' type.
162 Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
163 Module *M = Caller->getParent();
164 AttributeWithIndex AWI =
165 AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
167 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
168 const Type *I32Ty = Type::getInt32Ty(*Context);
169 Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
170 I8Ptr, I8Ptr, I32Ty, NULL);
171 CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
172 ConstantInt::get(I32Ty, C), "strchr");
173 if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
174 CI->setCallingConv(F->getCallingConv());
179 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
180 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
181 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
182 unsigned Align, IRBuilder<> &B) {
183 Module *M = Caller->getParent();
184 const Type *Ty = Len->getType();
185 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
186 Dst = CastToCStr(Dst, B);
187 Src = CastToCStr(Src, B);
188 return B.CreateCall4(MemCpy, Dst, Src, Len,
189 ConstantInt::get(Type::getInt32Ty(*Context), Align));
192 /// EmitMemMove - Emit a call to the memmove function to the builder. This
193 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
194 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
195 unsigned Align, IRBuilder<> &B) {
196 Module *M = Caller->getParent();
197 const Type *Ty = TD->getIntPtrType(*Context);
198 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
199 Dst = CastToCStr(Dst, B);
200 Src = CastToCStr(Src, B);
201 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
202 return B.CreateCall4(MemMove, Dst, Src, Len, A);
205 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
206 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
207 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
208 Value *Len, IRBuilder<> &B) {
209 Module *M = Caller->getParent();
210 AttributeWithIndex AWI;
211 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
213 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
214 Type::getInt8PtrTy(*Context),
215 Type::getInt8PtrTy(*Context),
216 Type::getInt32Ty(*Context),
217 TD->getIntPtrType(*Context),
219 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
221 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
222 CI->setCallingConv(F->getCallingConv());
227 /// EmitMemCmp - Emit a call to the memcmp function.
228 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
229 Value *Len, IRBuilder<> &B) {
230 Module *M = Caller->getParent();
231 AttributeWithIndex AWI[3];
232 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
233 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
234 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
235 Attribute::NoUnwind);
237 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
238 Type::getInt32Ty(*Context),
239 Type::getInt8PtrTy(*Context),
240 Type::getInt8PtrTy(*Context),
241 TD->getIntPtrType(*Context), NULL);
242 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
245 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
246 CI->setCallingConv(F->getCallingConv());
251 /// EmitMemSet - Emit a call to the memset function
252 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
253 Value *Len, IRBuilder<> &B) {
254 Module *M = Caller->getParent();
255 Intrinsic::ID IID = Intrinsic::memset;
257 Tys[0] = Len->getType();
258 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
259 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
260 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
263 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
264 /// 'floor'). This function is known to take a single of type matching 'Op' and
265 /// returns one value with the same type. If 'Op' is a long double, 'l' is
266 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
267 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
269 const AttrListPtr &Attrs) {
271 if (!Op->getType()->isDoubleTy()) {
272 // If we need to add a suffix, copy into NameBuffer.
273 unsigned NameLen = strlen(Name);
274 assert(NameLen < sizeof(NameBuffer)-2);
275 memcpy(NameBuffer, Name, NameLen);
276 if (Op->getType()->isFloatTy())
277 NameBuffer[NameLen] = 'f'; // floorf
279 NameBuffer[NameLen] = 'l'; // floorl
280 NameBuffer[NameLen+1] = 0;
284 Module *M = Caller->getParent();
285 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
286 Op->getType(), NULL);
287 CallInst *CI = B.CreateCall(Callee, Op, Name);
288 CI->setAttributes(Attrs);
289 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
290 CI->setCallingConv(F->getCallingConv());
295 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
297 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
298 Module *M = Caller->getParent();
299 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
300 Type::getInt32Ty(*Context), NULL);
301 CallInst *CI = B.CreateCall(PutChar,
302 B.CreateIntCast(Char,
303 Type::getInt32Ty(*Context),
308 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
309 CI->setCallingConv(F->getCallingConv());
313 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
315 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
316 Module *M = Caller->getParent();
317 AttributeWithIndex AWI[2];
318 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
319 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
321 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
322 Type::getInt32Ty(*Context),
323 Type::getInt8PtrTy(*Context),
325 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
326 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
327 CI->setCallingConv(F->getCallingConv());
331 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
332 /// an integer and File is a pointer to FILE.
333 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
334 Module *M = Caller->getParent();
335 AttributeWithIndex AWI[2];
336 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
337 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
339 if (isa<PointerType>(File->getType()))
340 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
341 Type::getInt32Ty(*Context),
342 Type::getInt32Ty(*Context), File->getType(),
345 F = M->getOrInsertFunction("fputc",
346 Type::getInt32Ty(*Context),
347 Type::getInt32Ty(*Context),
348 File->getType(), NULL);
349 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
351 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
353 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
354 CI->setCallingConv(Fn->getCallingConv());
357 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
358 /// pointer and File is a pointer to FILE.
359 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
360 Module *M = Caller->getParent();
361 AttributeWithIndex AWI[3];
362 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
363 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
364 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
366 if (isa<PointerType>(File->getType()))
367 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
368 Type::getInt32Ty(*Context),
369 Type::getInt8PtrTy(*Context),
370 File->getType(), NULL);
372 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
373 Type::getInt8PtrTy(*Context),
374 File->getType(), NULL);
375 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
377 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
378 CI->setCallingConv(Fn->getCallingConv());
381 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
382 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
383 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
385 Module *M = Caller->getParent();
386 AttributeWithIndex AWI[3];
387 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
388 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
389 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
391 if (isa<PointerType>(File->getType()))
392 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
393 TD->getIntPtrType(*Context),
394 Type::getInt8PtrTy(*Context),
395 TD->getIntPtrType(*Context),
396 TD->getIntPtrType(*Context),
397 File->getType(), NULL);
399 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
400 Type::getInt8PtrTy(*Context),
401 TD->getIntPtrType(*Context),
402 TD->getIntPtrType(*Context),
403 File->getType(), NULL);
404 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
405 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
407 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
408 CI->setCallingConv(Fn->getCallingConv());
411 //===----------------------------------------------------------------------===//
413 //===----------------------------------------------------------------------===//
415 /// GetStringLengthH - If we can compute the length of the string pointed to by
416 /// the specified pointer, return 'len+1'. If we can't, return 0.
417 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
418 // Look through noop bitcast instructions.
419 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
420 return GetStringLengthH(BCI->getOperand(0), PHIs);
422 // If this is a PHI node, there are two cases: either we have already seen it
424 if (PHINode *PN = dyn_cast<PHINode>(V)) {
425 if (!PHIs.insert(PN))
426 return ~0ULL; // already in the set.
428 // If it was new, see if all the input strings are the same length.
429 uint64_t LenSoFar = ~0ULL;
430 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
431 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
432 if (Len == 0) return 0; // Unknown length -> unknown.
434 if (Len == ~0ULL) continue;
436 if (Len != LenSoFar && LenSoFar != ~0ULL)
437 return 0; // Disagree -> unknown.
441 // Success, all agree.
445 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
446 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
447 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
448 if (Len1 == 0) return 0;
449 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
450 if (Len2 == 0) return 0;
451 if (Len1 == ~0ULL) return Len2;
452 if (Len2 == ~0ULL) return Len1;
453 if (Len1 != Len2) return 0;
457 // If the value is not a GEP instruction nor a constant expression with a
458 // GEP instruction, then return unknown.
460 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
462 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
463 if (CE->getOpcode() != Instruction::GetElementPtr)
470 // Make sure the GEP has exactly three arguments.
471 if (GEP->getNumOperands() != 3)
474 // Check to make sure that the first operand of the GEP is an integer and
475 // has value 0 so that we are sure we're indexing into the initializer.
476 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
482 // If the second index isn't a ConstantInt, then this is a variable index
483 // into the array. If this occurs, we can't say anything meaningful about
485 uint64_t StartIdx = 0;
486 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
487 StartIdx = CI->getZExtValue();
491 // The GEP instruction, constant or instruction, must reference a global
492 // variable that is a constant and is initialized. The referenced constant
493 // initializer is the array that we'll use for optimization.
494 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
495 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
496 GV->mayBeOverridden())
498 Constant *GlobalInit = GV->getInitializer();
500 // Handle the ConstantAggregateZero case, which is a degenerate case. The
501 // initializer is constant zero so the length of the string must be zero.
502 if (isa<ConstantAggregateZero>(GlobalInit))
503 return 1; // Len = 0 offset by 1.
505 // Must be a Constant Array
506 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
508 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
511 // Get the number of elements in the array
512 uint64_t NumElts = Array->getType()->getNumElements();
514 // Traverse the constant array from StartIdx (derived above) which is
515 // the place the GEP refers to in the array.
516 for (unsigned i = StartIdx; i != NumElts; ++i) {
517 Constant *Elt = Array->getOperand(i);
518 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
519 if (!CI) // This array isn't suitable, non-int initializer.
522 return i-StartIdx+1; // We found end of string, success!
525 return 0; // The array isn't null terminated, conservatively return 'unknown'.
528 /// GetStringLength - If we can compute the length of the string pointed to by
529 /// the specified pointer, return 'len+1'. If we can't, return 0.
530 static uint64_t GetStringLength(Value *V) {
531 if (!isa<PointerType>(V->getType())) return 0;
533 SmallPtrSet<PHINode*, 32> PHIs;
534 uint64_t Len = GetStringLengthH(V, PHIs);
535 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
536 // an empty string as a length.
537 return Len == ~0ULL ? 1 : Len;
540 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
541 /// value is equal or not-equal to zero.
542 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
543 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
545 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
546 if (IC->isEquality())
547 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
548 if (C->isNullValue())
550 // Unknown instruction.
556 //===----------------------------------------------------------------------===//
557 // String and Memory LibCall Optimizations
558 //===----------------------------------------------------------------------===//
560 //===---------------------------------------===//
561 // 'strcat' Optimizations
563 struct StrCatOpt : public LibCallOptimization {
564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
565 // Verify the "strcat" function prototype.
566 const FunctionType *FT = Callee->getFunctionType();
567 if (FT->getNumParams() != 2 ||
568 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
569 FT->getParamType(0) != FT->getReturnType() ||
570 FT->getParamType(1) != FT->getReturnType())
573 // Extract some information from the instruction
574 Value *Dst = CI->getOperand(1);
575 Value *Src = CI->getOperand(2);
577 // See if we can get the length of the input string.
578 uint64_t Len = GetStringLength(Src);
579 if (Len == 0) return 0;
580 --Len; // Unbias length.
582 // Handle the simple, do-nothing case: strcat(x, "") -> x
586 // These optimizations require TargetData.
589 EmitStrLenMemCpy(Src, Dst, Len, B);
593 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
594 // We need to find the end of the destination string. That's where the
595 // memory is to be moved to. We just generate a call to strlen.
596 Value *DstLen = EmitStrLen(Dst, B);
598 // Now that we have the destination's length, we must index into the
599 // destination's pointer to get the actual memcpy destination (end of
600 // the string .. we're concatenating).
601 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
603 // We have enough information to now generate the memcpy call to do the
604 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
605 EmitMemCpy(CpyDst, Src,
606 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
610 //===---------------------------------------===//
611 // 'strncat' Optimizations
613 struct StrNCatOpt : public StrCatOpt {
614 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
615 // Verify the "strncat" function prototype.
616 const FunctionType *FT = Callee->getFunctionType();
617 if (FT->getNumParams() != 3 ||
618 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
619 FT->getParamType(0) != FT->getReturnType() ||
620 FT->getParamType(1) != FT->getReturnType() ||
621 !isa<IntegerType>(FT->getParamType(2)))
624 // Extract some information from the instruction
625 Value *Dst = CI->getOperand(1);
626 Value *Src = CI->getOperand(2);
629 // We don't do anything if length is not constant
630 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
631 Len = LengthArg->getZExtValue();
635 // See if we can get the length of the input string.
636 uint64_t SrcLen = GetStringLength(Src);
637 if (SrcLen == 0) return 0;
638 --SrcLen; // Unbias length.
640 // Handle the simple, do-nothing cases:
641 // strncat(x, "", c) -> x
642 // strncat(x, c, 0) -> x
643 if (SrcLen == 0 || Len == 0) return Dst;
645 // These optimizations require TargetData.
648 // We don't optimize this case
649 if (Len < SrcLen) return 0;
651 // strncat(x, s, c) -> strcat(x, s)
652 // s is constant so the strcat can be optimized further
653 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
658 //===---------------------------------------===//
659 // 'strchr' Optimizations
661 struct StrChrOpt : public LibCallOptimization {
662 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
663 // Verify the "strchr" function prototype.
664 const FunctionType *FT = Callee->getFunctionType();
665 if (FT->getNumParams() != 2 ||
666 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
667 FT->getParamType(0) != FT->getReturnType())
670 Value *SrcStr = CI->getOperand(1);
672 // If the second operand is non-constant, see if we can compute the length
673 // of the input string and turn this into memchr.
674 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
676 // These optimizations require TargetData.
679 uint64_t Len = GetStringLength(SrcStr);
681 FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs i32.
684 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
685 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
688 // Otherwise, the character is a constant, see if the first argument is
689 // a string literal. If so, we can constant fold.
691 if (!GetConstantStringInfo(SrcStr, Str))
694 // strchr can find the nul character.
696 char CharValue = CharC->getSExtValue();
698 // Compute the offset.
701 if (i == Str.size()) // Didn't find the char. strchr returns null.
702 return Constant::getNullValue(CI->getType());
703 // Did we find our match?
704 if (Str[i] == CharValue)
709 // strchr(s+n,c) -> gep(s+n+i,c)
710 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
711 return B.CreateGEP(SrcStr, Idx, "strchr");
715 //===---------------------------------------===//
716 // 'strcmp' Optimizations
718 struct StrCmpOpt : public LibCallOptimization {
719 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
720 // Verify the "strcmp" function prototype.
721 const FunctionType *FT = Callee->getFunctionType();
722 if (FT->getNumParams() != 2 ||
723 FT->getReturnType() != Type::getInt32Ty(*Context) ||
724 FT->getParamType(0) != FT->getParamType(1) ||
725 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
728 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
729 if (Str1P == Str2P) // strcmp(x,x) -> 0
730 return ConstantInt::get(CI->getType(), 0);
732 std::string Str1, Str2;
733 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
734 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
736 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
737 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
739 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
740 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
742 // strcmp(x, y) -> cnst (if both x and y are constant strings)
743 if (HasStr1 && HasStr2)
744 return ConstantInt::get(CI->getType(),
745 strcmp(Str1.c_str(),Str2.c_str()));
747 // strcmp(P, "x") -> memcmp(P, "x", 2)
748 uint64_t Len1 = GetStringLength(Str1P);
749 uint64_t Len2 = GetStringLength(Str2P);
751 // These optimizations require TargetData.
754 return EmitMemCmp(Str1P, Str2P,
755 ConstantInt::get(TD->getIntPtrType(*Context),
756 std::min(Len1, Len2)), B);
763 //===---------------------------------------===//
764 // 'strncmp' Optimizations
766 struct StrNCmpOpt : public LibCallOptimization {
767 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
768 // Verify the "strncmp" function prototype.
769 const FunctionType *FT = Callee->getFunctionType();
770 if (FT->getNumParams() != 3 ||
771 FT->getReturnType() != Type::getInt32Ty(*Context) ||
772 FT->getParamType(0) != FT->getParamType(1) ||
773 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
774 !isa<IntegerType>(FT->getParamType(2)))
777 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
778 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
779 return ConstantInt::get(CI->getType(), 0);
781 // Get the length argument if it is constant.
783 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
784 Length = LengthArg->getZExtValue();
788 if (Length == 0) // strncmp(x,y,0) -> 0
789 return ConstantInt::get(CI->getType(), 0);
791 std::string Str1, Str2;
792 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
793 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
795 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
796 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
798 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
799 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
801 // strncmp(x, y) -> cnst (if both x and y are constant strings)
802 if (HasStr1 && HasStr2)
803 return ConstantInt::get(CI->getType(),
804 strncmp(Str1.c_str(), Str2.c_str(), Length));
810 //===---------------------------------------===//
811 // 'strcpy' Optimizations
813 struct StrCpyOpt : public LibCallOptimization {
814 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
815 // Verify the "strcpy" function prototype.
816 const FunctionType *FT = Callee->getFunctionType();
817 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
818 FT->getParamType(0) != FT->getParamType(1) ||
819 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
822 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
823 if (Dst == Src) // strcpy(x,x) -> x
826 // These optimizations require TargetData.
829 // See if we can get the length of the input string.
830 uint64_t Len = GetStringLength(Src);
831 if (Len == 0) return 0;
833 // We have enough information to now generate the memcpy call to do the
834 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
836 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
841 //===---------------------------------------===//
842 // 'strncpy' Optimizations
844 struct StrNCpyOpt : public LibCallOptimization {
845 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
846 const FunctionType *FT = Callee->getFunctionType();
847 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
848 FT->getParamType(0) != FT->getParamType(1) ||
849 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
850 !isa<IntegerType>(FT->getParamType(2)))
853 Value *Dst = CI->getOperand(1);
854 Value *Src = CI->getOperand(2);
855 Value *LenOp = CI->getOperand(3);
857 // See if we can get the length of the input string.
858 uint64_t SrcLen = GetStringLength(Src);
859 if (SrcLen == 0) return 0;
863 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
864 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
870 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
871 Len = LengthArg->getZExtValue();
875 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
877 // These optimizations require TargetData.
880 // Let strncpy handle the zero padding
881 if (Len > SrcLen+1) return 0;
883 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
885 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
891 //===---------------------------------------===//
892 // 'strlen' Optimizations
894 struct StrLenOpt : public LibCallOptimization {
895 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
896 const FunctionType *FT = Callee->getFunctionType();
897 if (FT->getNumParams() != 1 ||
898 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
899 !isa<IntegerType>(FT->getReturnType()))
902 Value *Src = CI->getOperand(1);
904 // Constant folding: strlen("xyz") -> 3
905 if (uint64_t Len = GetStringLength(Src))
906 return ConstantInt::get(CI->getType(), Len-1);
908 // strlen(x) != 0 --> *x != 0
909 // strlen(x) == 0 --> *x == 0
910 if (IsOnlyUsedInZeroEqualityComparison(CI))
911 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
916 //===---------------------------------------===//
917 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
919 struct StrToOpt : public LibCallOptimization {
920 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
921 const FunctionType *FT = Callee->getFunctionType();
922 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
923 !isa<PointerType>(FT->getParamType(0)) ||
924 !isa<PointerType>(FT->getParamType(1)))
927 Value *EndPtr = CI->getOperand(2);
928 if (isa<ConstantPointerNull>(EndPtr)) {
929 CI->setOnlyReadsMemory();
930 CI->addAttribute(1, Attribute::NoCapture);
937 //===---------------------------------------===//
938 // 'strstr' Optimizations
940 struct StrStrOpt : public LibCallOptimization {
941 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
942 const FunctionType *FT = Callee->getFunctionType();
943 if (FT->getNumParams() != 2 ||
944 !isa<PointerType>(FT->getParamType(0)) ||
945 !isa<PointerType>(FT->getParamType(1)) ||
946 !isa<PointerType>(FT->getReturnType()))
949 // fold strstr(x, x) -> x.
950 if (CI->getOperand(1) == CI->getOperand(2))
951 return B.CreateBitCast(CI->getOperand(1), CI->getType());
953 // See if either input string is a constant string.
954 std::string SearchStr, ToFindStr;
955 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
956 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
958 // fold strstr(x, "") -> x.
959 if (HasStr2 && ToFindStr.empty())
960 return B.CreateBitCast(CI->getOperand(1), CI->getType());
962 // If both strings are known, constant fold it.
963 if (HasStr1 && HasStr2) {
964 std::string::size_type Offset = SearchStr.find(ToFindStr);
966 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
967 return Constant::getNullValue(CI->getType());
969 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
970 Value *Result = CastToCStr(CI->getOperand(1), B);
971 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
972 return B.CreateBitCast(Result, CI->getType());
975 // fold strstr(x, "y") -> strchr(x, 'y').
976 if (HasStr2 && ToFindStr.size() == 1)
977 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
984 //===---------------------------------------===//
985 // 'memcmp' Optimizations
987 struct MemCmpOpt : public LibCallOptimization {
988 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
989 const FunctionType *FT = Callee->getFunctionType();
990 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
991 !isa<PointerType>(FT->getParamType(1)) ||
992 FT->getReturnType() != Type::getInt32Ty(*Context))
995 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
997 if (LHS == RHS) // memcmp(s,s,x) -> 0
998 return Constant::getNullValue(CI->getType());
1000 // Make sure we have a constant length.
1001 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1002 if (!LenC) return 0;
1003 uint64_t Len = LenC->getZExtValue();
1005 if (Len == 0) // memcmp(s1,s2,0) -> 0
1006 return Constant::getNullValue(CI->getType());
1008 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1009 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1010 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
1011 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
1014 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
1015 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
1016 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
1017 const Type *PTy = PointerType::getUnqual(Len == 2 ?
1018 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
1019 LHS = B.CreateBitCast(LHS, PTy, "tmp");
1020 RHS = B.CreateBitCast(RHS, PTy, "tmp");
1021 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
1022 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
1023 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
1024 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
1027 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1028 std::string LHSStr, RHSStr;
1029 if (GetConstantStringInfo(LHS, LHSStr) &&
1030 GetConstantStringInfo(RHS, RHSStr)) {
1031 // Make sure we're not reading out-of-bounds memory.
1032 if (Len > LHSStr.length() || Len > RHSStr.length())
1034 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1035 return ConstantInt::get(CI->getType(), Ret);
1042 //===---------------------------------------===//
1043 // 'memcpy' Optimizations
1045 struct MemCpyOpt : public LibCallOptimization {
1046 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1047 // These optimizations require TargetData.
1050 const FunctionType *FT = Callee->getFunctionType();
1051 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1052 !isa<PointerType>(FT->getParamType(0)) ||
1053 !isa<PointerType>(FT->getParamType(1)) ||
1054 FT->getParamType(2) != TD->getIntPtrType(*Context))
1057 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1058 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1059 return CI->getOperand(1);
1063 //===---------------------------------------===//
1064 // 'memmove' Optimizations
1066 struct MemMoveOpt : public LibCallOptimization {
1067 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1068 // These optimizations require TargetData.
1071 const FunctionType *FT = Callee->getFunctionType();
1072 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1073 !isa<PointerType>(FT->getParamType(0)) ||
1074 !isa<PointerType>(FT->getParamType(1)) ||
1075 FT->getParamType(2) != TD->getIntPtrType(*Context))
1078 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1079 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1080 return CI->getOperand(1);
1084 //===---------------------------------------===//
1085 // 'memset' Optimizations
1087 struct MemSetOpt : public LibCallOptimization {
1088 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1089 // These optimizations require TargetData.
1092 const FunctionType *FT = Callee->getFunctionType();
1093 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1094 !isa<PointerType>(FT->getParamType(0)) ||
1095 !isa<IntegerType>(FT->getParamType(1)) ||
1096 FT->getParamType(2) != TD->getIntPtrType(*Context))
1099 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1100 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1102 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1103 return CI->getOperand(1);
1107 //===----------------------------------------------------------------------===//
1108 // Object Size Checking Optimizations
1109 //===----------------------------------------------------------------------===//
1111 //===---------------------------------------===//
1114 struct SizeOpt : public LibCallOptimization {
1115 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1116 // TODO: We can do more with this, but delaying to here should be no change
1118 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
1120 if (!Const) return 0;
1122 const Type *Ty = Callee->getFunctionType()->getReturnType();
1124 if (Const->getZExtValue() == 0)
1125 return Constant::getAllOnesValue(Ty);
1127 return ConstantInt::get(Ty, 0);
1132 //===---------------------------------------===//
1133 // 'memcpy_chk' Optimizations
1135 struct MemCpyChkOpt : public LibCallOptimization {
1136 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1137 // These optimizations require TargetData.
1140 const FunctionType *FT = Callee->getFunctionType();
1141 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1142 !isa<PointerType>(FT->getParamType(0)) ||
1143 !isa<PointerType>(FT->getParamType(1)) ||
1144 !isa<IntegerType>(FT->getParamType(3)) ||
1145 FT->getParamType(2) != TD->getIntPtrType(*Context))
1148 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1151 if (SizeCI->isAllOnesValue()) {
1152 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1153 return CI->getOperand(1);
1160 //===---------------------------------------===//
1161 // 'memset_chk' Optimizations
1163 struct MemSetChkOpt : public LibCallOptimization {
1164 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1165 // These optimizations require TargetData.
1168 const FunctionType *FT = Callee->getFunctionType();
1169 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1170 !isa<PointerType>(FT->getParamType(0)) ||
1171 !isa<IntegerType>(FT->getParamType(1)) ||
1172 !isa<IntegerType>(FT->getParamType(3)) ||
1173 FT->getParamType(2) != TD->getIntPtrType(*Context))
1176 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1179 if (SizeCI->isAllOnesValue()) {
1180 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1182 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1183 return CI->getOperand(1);
1190 //===---------------------------------------===//
1191 // 'memmove_chk' Optimizations
1193 struct MemMoveChkOpt : public LibCallOptimization {
1194 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1195 // These optimizations require TargetData.
1198 const FunctionType *FT = Callee->getFunctionType();
1199 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1200 !isa<PointerType>(FT->getParamType(0)) ||
1201 !isa<PointerType>(FT->getParamType(1)) ||
1202 !isa<IntegerType>(FT->getParamType(3)) ||
1203 FT->getParamType(2) != TD->getIntPtrType(*Context))
1206 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1209 if (SizeCI->isAllOnesValue()) {
1210 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1212 return CI->getOperand(1);
1219 //===----------------------------------------------------------------------===//
1220 // Math Library Optimizations
1221 //===----------------------------------------------------------------------===//
1223 //===---------------------------------------===//
1224 // 'pow*' Optimizations
1226 struct PowOpt : public LibCallOptimization {
1227 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1228 const FunctionType *FT = Callee->getFunctionType();
1229 // Just make sure this has 2 arguments of the same FP type, which match the
1231 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1232 FT->getParamType(0) != FT->getParamType(1) ||
1233 !FT->getParamType(0)->isFloatingPoint())
1236 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1237 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1238 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1240 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1241 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1244 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1245 if (Op2C == 0) return 0;
1247 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1248 return ConstantFP::get(CI->getType(), 1.0);
1250 if (Op2C->isExactlyValue(0.5)) {
1251 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1252 // This is faster than calling pow, and still handles negative zero
1253 // and negative infinite correctly.
1254 // TODO: In fast-math mode, this could be just sqrt(x).
1255 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1256 Value *Inf = ConstantFP::getInfinity(CI->getType());
1257 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1258 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1259 Callee->getAttributes());
1260 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1261 Callee->getAttributes());
1262 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1263 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1267 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1269 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1270 return B.CreateFMul(Op1, Op1, "pow2");
1271 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1272 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1278 //===---------------------------------------===//
1279 // 'exp2' Optimizations
1281 struct Exp2Opt : public LibCallOptimization {
1282 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1283 const FunctionType *FT = Callee->getFunctionType();
1284 // Just make sure this has 1 argument of FP type, which matches the
1286 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1287 !FT->getParamType(0)->isFloatingPoint())
1290 Value *Op = CI->getOperand(1);
1291 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1292 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1293 Value *LdExpArg = 0;
1294 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1295 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1296 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1297 Type::getInt32Ty(*Context), "tmp");
1298 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1299 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1300 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1301 Type::getInt32Ty(*Context), "tmp");
1306 if (Op->getType()->isFloatTy())
1308 else if (Op->getType()->isDoubleTy())
1313 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1314 if (!Op->getType()->isFloatTy())
1315 One = ConstantExpr::getFPExtend(One, Op->getType());
1317 Module *M = Caller->getParent();
1318 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1320 Type::getInt32Ty(*Context),NULL);
1321 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1322 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1323 CI->setCallingConv(F->getCallingConv());
1331 //===---------------------------------------===//
1332 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1334 struct UnaryDoubleFPOpt : public LibCallOptimization {
1335 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1336 const FunctionType *FT = Callee->getFunctionType();
1337 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1338 !FT->getParamType(0)->isDoubleTy())
1341 // If this is something like 'floor((double)floatval)', convert to floorf.
1342 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1343 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1346 // floor((double)floatval) -> (double)floorf(floatval)
1347 Value *V = Cast->getOperand(0);
1348 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1349 Callee->getAttributes());
1350 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1354 //===----------------------------------------------------------------------===//
1355 // Integer Optimizations
1356 //===----------------------------------------------------------------------===//
1358 //===---------------------------------------===//
1359 // 'ffs*' Optimizations
1361 struct FFSOpt : public LibCallOptimization {
1362 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1363 const FunctionType *FT = Callee->getFunctionType();
1364 // Just make sure this has 2 arguments of the same FP type, which match the
1366 if (FT->getNumParams() != 1 ||
1367 FT->getReturnType() != Type::getInt32Ty(*Context) ||
1368 !isa<IntegerType>(FT->getParamType(0)))
1371 Value *Op = CI->getOperand(1);
1374 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1375 if (CI->getValue() == 0) // ffs(0) -> 0.
1376 return Constant::getNullValue(CI->getType());
1377 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1378 CI->getValue().countTrailingZeros()+1);
1381 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1382 const Type *ArgType = Op->getType();
1383 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1384 Intrinsic::cttz, &ArgType, 1);
1385 Value *V = B.CreateCall(F, Op, "cttz");
1386 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1387 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1389 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1390 return B.CreateSelect(Cond, V,
1391 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1395 //===---------------------------------------===//
1396 // 'isdigit' Optimizations
1398 struct IsDigitOpt : public LibCallOptimization {
1399 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1400 const FunctionType *FT = Callee->getFunctionType();
1401 // We require integer(i32)
1402 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1403 FT->getParamType(0) != Type::getInt32Ty(*Context))
1406 // isdigit(c) -> (c-'0') <u 10
1407 Value *Op = CI->getOperand(1);
1408 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1410 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1412 return B.CreateZExt(Op, CI->getType());
1416 //===---------------------------------------===//
1417 // 'isascii' Optimizations
1419 struct IsAsciiOpt : public LibCallOptimization {
1420 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1421 const FunctionType *FT = Callee->getFunctionType();
1422 // We require integer(i32)
1423 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1424 FT->getParamType(0) != Type::getInt32Ty(*Context))
1427 // isascii(c) -> c <u 128
1428 Value *Op = CI->getOperand(1);
1429 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1431 return B.CreateZExt(Op, CI->getType());
1435 //===---------------------------------------===//
1436 // 'abs', 'labs', 'llabs' Optimizations
1438 struct AbsOpt : public LibCallOptimization {
1439 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1440 const FunctionType *FT = Callee->getFunctionType();
1441 // We require integer(integer) where the types agree.
1442 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1443 FT->getParamType(0) != FT->getReturnType())
1446 // abs(x) -> x >s -1 ? x : -x
1447 Value *Op = CI->getOperand(1);
1448 Value *Pos = B.CreateICmpSGT(Op,
1449 Constant::getAllOnesValue(Op->getType()),
1451 Value *Neg = B.CreateNeg(Op, "neg");
1452 return B.CreateSelect(Pos, Op, Neg);
1457 //===---------------------------------------===//
1458 // 'toascii' Optimizations
1460 struct ToAsciiOpt : public LibCallOptimization {
1461 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1462 const FunctionType *FT = Callee->getFunctionType();
1463 // We require i32(i32)
1464 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1465 FT->getParamType(0) != Type::getInt32Ty(*Context))
1468 // isascii(c) -> c & 0x7f
1469 return B.CreateAnd(CI->getOperand(1),
1470 ConstantInt::get(CI->getType(),0x7F));
1474 //===----------------------------------------------------------------------===//
1475 // Formatting and IO Optimizations
1476 //===----------------------------------------------------------------------===//
1478 //===---------------------------------------===//
1479 // 'printf' Optimizations
1481 struct PrintFOpt : public LibCallOptimization {
1482 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1483 // Require one fixed pointer argument and an integer/void result.
1484 const FunctionType *FT = Callee->getFunctionType();
1485 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1486 !(isa<IntegerType>(FT->getReturnType()) ||
1487 FT->getReturnType()->isVoidTy()))
1490 // Check for a fixed format string.
1491 std::string FormatStr;
1492 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1495 // Empty format string -> noop.
1496 if (FormatStr.empty()) // Tolerate printf's declared void.
1497 return CI->use_empty() ? (Value*)CI :
1498 ConstantInt::get(CI->getType(), 0);
1500 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1501 // in case there is an error writing to stdout.
1502 if (FormatStr.size() == 1) {
1503 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1505 if (CI->use_empty()) return CI;
1506 return B.CreateIntCast(Res, CI->getType(), true);
1509 // printf("foo\n") --> puts("foo")
1510 if (FormatStr[FormatStr.size()-1] == '\n' &&
1511 FormatStr.find('%') == std::string::npos) { // no format characters.
1512 // Create a string literal with no \n on it. We expect the constant merge
1513 // pass to be run after this pass, to merge duplicate strings.
1514 FormatStr.erase(FormatStr.end()-1);
1515 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1516 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1517 GlobalVariable::InternalLinkage, C, "str");
1519 return CI->use_empty() ? (Value*)CI :
1520 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1523 // Optimize specific format strings.
1524 // printf("%c", chr) --> putchar(*(i8*)dst)
1525 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1526 isa<IntegerType>(CI->getOperand(2)->getType())) {
1527 Value *Res = EmitPutChar(CI->getOperand(2), B);
1529 if (CI->use_empty()) return CI;
1530 return B.CreateIntCast(Res, CI->getType(), true);
1533 // printf("%s\n", str) --> puts(str)
1534 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1535 isa<PointerType>(CI->getOperand(2)->getType()) &&
1537 EmitPutS(CI->getOperand(2), B);
1544 //===---------------------------------------===//
1545 // 'sprintf' Optimizations
1547 struct SPrintFOpt : public LibCallOptimization {
1548 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1549 // Require two fixed pointer arguments and an integer result.
1550 const FunctionType *FT = Callee->getFunctionType();
1551 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1552 !isa<PointerType>(FT->getParamType(1)) ||
1553 !isa<IntegerType>(FT->getReturnType()))
1556 // Check for a fixed format string.
1557 std::string FormatStr;
1558 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1561 // If we just have a format string (nothing else crazy) transform it.
1562 if (CI->getNumOperands() == 3) {
1563 // Make sure there's no % in the constant array. We could try to handle
1564 // %% -> % in the future if we cared.
1565 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1566 if (FormatStr[i] == '%')
1567 return 0; // we found a format specifier, bail out.
1569 // These optimizations require TargetData.
1572 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1573 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1574 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1575 return ConstantInt::get(CI->getType(), FormatStr.size());
1578 // The remaining optimizations require the format string to be "%s" or "%c"
1579 // and have an extra operand.
1580 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1583 // Decode the second character of the format string.
1584 if (FormatStr[1] == 'c') {
1585 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1586 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1587 Value *V = B.CreateTrunc(CI->getOperand(3),
1588 Type::getInt8Ty(*Context), "char");
1589 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1590 B.CreateStore(V, Ptr);
1591 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1593 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1595 return ConstantInt::get(CI->getType(), 1);
1598 if (FormatStr[1] == 's') {
1599 // These optimizations require TargetData.
1602 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1603 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1605 Value *Len = EmitStrLen(CI->getOperand(3), B);
1606 Value *IncLen = B.CreateAdd(Len,
1607 ConstantInt::get(Len->getType(), 1),
1609 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1611 // The sprintf result is the unincremented number of bytes in the string.
1612 return B.CreateIntCast(Len, CI->getType(), false);
1618 //===---------------------------------------===//
1619 // 'fwrite' Optimizations
1621 struct FWriteOpt : public LibCallOptimization {
1622 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1623 // Require a pointer, an integer, an integer, a pointer, returning integer.
1624 const FunctionType *FT = Callee->getFunctionType();
1625 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1626 !isa<IntegerType>(FT->getParamType(1)) ||
1627 !isa<IntegerType>(FT->getParamType(2)) ||
1628 !isa<PointerType>(FT->getParamType(3)) ||
1629 !isa<IntegerType>(FT->getReturnType()))
1632 // Get the element size and count.
1633 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1634 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1635 if (!SizeC || !CountC) return 0;
1636 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1638 // If this is writing zero records, remove the call (it's a noop).
1640 return ConstantInt::get(CI->getType(), 0);
1642 // If this is writing one byte, turn it into fputc.
1643 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1644 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1645 EmitFPutC(Char, CI->getOperand(4), B);
1646 return ConstantInt::get(CI->getType(), 1);
1653 //===---------------------------------------===//
1654 // 'fputs' Optimizations
1656 struct FPutsOpt : public LibCallOptimization {
1657 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1658 // These optimizations require TargetData.
1661 // Require two pointers. Also, we can't optimize if return value is used.
1662 const FunctionType *FT = Callee->getFunctionType();
1663 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1664 !isa<PointerType>(FT->getParamType(1)) ||
1668 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1669 uint64_t Len = GetStringLength(CI->getOperand(1));
1671 EmitFWrite(CI->getOperand(1),
1672 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1673 CI->getOperand(2), B);
1674 return CI; // Known to have no uses (see above).
1678 //===---------------------------------------===//
1679 // 'fprintf' Optimizations
1681 struct FPrintFOpt : public LibCallOptimization {
1682 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1683 // Require two fixed paramters as pointers and integer result.
1684 const FunctionType *FT = Callee->getFunctionType();
1685 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1686 !isa<PointerType>(FT->getParamType(1)) ||
1687 !isa<IntegerType>(FT->getReturnType()))
1690 // All the optimizations depend on the format string.
1691 std::string FormatStr;
1692 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1695 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1696 if (CI->getNumOperands() == 3) {
1697 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1698 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1699 return 0; // We found a format specifier.
1701 // These optimizations require TargetData.
1704 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
1706 CI->getOperand(1), B);
1707 return ConstantInt::get(CI->getType(), FormatStr.size());
1710 // The remaining optimizations require the format string to be "%s" or "%c"
1711 // and have an extra operand.
1712 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1715 // Decode the second character of the format string.
1716 if (FormatStr[1] == 'c') {
1717 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1718 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1719 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1720 return ConstantInt::get(CI->getType(), 1);
1723 if (FormatStr[1] == 's') {
1724 // fprintf(F, "%s", str) -> fputs(str, F)
1725 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1727 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1734 } // end anonymous namespace.
1736 //===----------------------------------------------------------------------===//
1737 // SimplifyLibCalls Pass Implementation
1738 //===----------------------------------------------------------------------===//
1741 /// This pass optimizes well known library functions from libc and libm.
1743 class SimplifyLibCalls : public FunctionPass {
1744 StringMap<LibCallOptimization*> Optimizations;
1745 // String and Memory LibCall Optimizations
1746 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1747 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1748 StrToOpt StrTo; StrStrOpt StrStr;
1749 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1750 // Math Library Optimizations
1751 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1752 // Integer Optimizations
1753 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1755 // Formatting and IO Optimizations
1756 SPrintFOpt SPrintF; PrintFOpt PrintF;
1757 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1759 // Object Size Checking
1761 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1763 bool Modified; // This is only used by doInitialization.
1765 static char ID; // Pass identification
1766 SimplifyLibCalls() : FunctionPass(&ID) {}
1768 void InitOptimizations();
1769 bool runOnFunction(Function &F);
1771 void setDoesNotAccessMemory(Function &F);
1772 void setOnlyReadsMemory(Function &F);
1773 void setDoesNotThrow(Function &F);
1774 void setDoesNotCapture(Function &F, unsigned n);
1775 void setDoesNotAlias(Function &F, unsigned n);
1776 bool doInitialization(Module &M);
1778 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1781 char SimplifyLibCalls::ID = 0;
1782 } // end anonymous namespace.
1784 static RegisterPass<SimplifyLibCalls>
1785 X("simplify-libcalls", "Simplify well-known library calls");
1787 // Public interface to the Simplify LibCalls pass.
1788 FunctionPass *llvm::createSimplifyLibCallsPass() {
1789 return new SimplifyLibCalls();
1792 /// Optimizations - Populate the Optimizations map with all the optimizations
1794 void SimplifyLibCalls::InitOptimizations() {
1795 // String and Memory LibCall Optimizations
1796 Optimizations["strcat"] = &StrCat;
1797 Optimizations["strncat"] = &StrNCat;
1798 Optimizations["strchr"] = &StrChr;
1799 Optimizations["strcmp"] = &StrCmp;
1800 Optimizations["strncmp"] = &StrNCmp;
1801 Optimizations["strcpy"] = &StrCpy;
1802 Optimizations["strncpy"] = &StrNCpy;
1803 Optimizations["strlen"] = &StrLen;
1804 Optimizations["strtol"] = &StrTo;
1805 Optimizations["strtod"] = &StrTo;
1806 Optimizations["strtof"] = &StrTo;
1807 Optimizations["strtoul"] = &StrTo;
1808 Optimizations["strtoll"] = &StrTo;
1809 Optimizations["strtold"] = &StrTo;
1810 Optimizations["strtoull"] = &StrTo;
1811 Optimizations["strstr"] = &StrStr;
1812 Optimizations["memcmp"] = &MemCmp;
1813 Optimizations["memcpy"] = &MemCpy;
1814 Optimizations["memmove"] = &MemMove;
1815 Optimizations["memset"] = &MemSet;
1817 // Math Library Optimizations
1818 Optimizations["powf"] = &Pow;
1819 Optimizations["pow"] = &Pow;
1820 Optimizations["powl"] = &Pow;
1821 Optimizations["llvm.pow.f32"] = &Pow;
1822 Optimizations["llvm.pow.f64"] = &Pow;
1823 Optimizations["llvm.pow.f80"] = &Pow;
1824 Optimizations["llvm.pow.f128"] = &Pow;
1825 Optimizations["llvm.pow.ppcf128"] = &Pow;
1826 Optimizations["exp2l"] = &Exp2;
1827 Optimizations["exp2"] = &Exp2;
1828 Optimizations["exp2f"] = &Exp2;
1829 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1830 Optimizations["llvm.exp2.f128"] = &Exp2;
1831 Optimizations["llvm.exp2.f80"] = &Exp2;
1832 Optimizations["llvm.exp2.f64"] = &Exp2;
1833 Optimizations["llvm.exp2.f32"] = &Exp2;
1836 Optimizations["floor"] = &UnaryDoubleFP;
1839 Optimizations["ceil"] = &UnaryDoubleFP;
1842 Optimizations["round"] = &UnaryDoubleFP;
1845 Optimizations["rint"] = &UnaryDoubleFP;
1847 #ifdef HAVE_NEARBYINTF
1848 Optimizations["nearbyint"] = &UnaryDoubleFP;
1851 // Integer Optimizations
1852 Optimizations["ffs"] = &FFS;
1853 Optimizations["ffsl"] = &FFS;
1854 Optimizations["ffsll"] = &FFS;
1855 Optimizations["abs"] = &Abs;
1856 Optimizations["labs"] = &Abs;
1857 Optimizations["llabs"] = &Abs;
1858 Optimizations["isdigit"] = &IsDigit;
1859 Optimizations["isascii"] = &IsAscii;
1860 Optimizations["toascii"] = &ToAscii;
1862 // Formatting and IO Optimizations
1863 Optimizations["sprintf"] = &SPrintF;
1864 Optimizations["printf"] = &PrintF;
1865 Optimizations["fwrite"] = &FWrite;
1866 Optimizations["fputs"] = &FPuts;
1867 Optimizations["fprintf"] = &FPrintF;
1869 // Object Size Checking
1870 Optimizations["llvm.objectsize.i32"] = &ObjectSize;
1871 Optimizations["llvm.objectsize.i64"] = &ObjectSize;
1872 Optimizations["__memcpy_chk"] = &MemCpyChk;
1873 Optimizations["__memset_chk"] = &MemSetChk;
1874 Optimizations["__memmove_chk"] = &MemMoveChk;
1878 /// runOnFunction - Top level algorithm.
1880 bool SimplifyLibCalls::runOnFunction(Function &F) {
1881 if (Optimizations.empty())
1882 InitOptimizations();
1884 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1886 IRBuilder<> Builder(F.getContext());
1888 bool Changed = false;
1889 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1890 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1891 // Ignore non-calls.
1892 CallInst *CI = dyn_cast<CallInst>(I++);
1895 // Ignore indirect calls and calls to non-external functions.
1896 Function *Callee = CI->getCalledFunction();
1897 if (Callee == 0 || !Callee->isDeclaration() ||
1898 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1901 // Ignore unknown calls.
1902 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1905 // Set the builder to the instruction after the call.
1906 Builder.SetInsertPoint(BB, I);
1908 // Try to optimize this call.
1909 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1910 if (Result == 0) continue;
1912 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1913 errs() << " into: " << *Result << "\n");
1915 // Something changed!
1919 // Inspect the instruction after the call (which was potentially just
1923 if (CI != Result && !CI->use_empty()) {
1924 CI->replaceAllUsesWith(Result);
1925 if (!Result->hasName())
1926 Result->takeName(CI);
1928 CI->eraseFromParent();
1934 // Utility methods for doInitialization.
1936 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1937 if (!F.doesNotAccessMemory()) {
1938 F.setDoesNotAccessMemory();
1943 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1944 if (!F.onlyReadsMemory()) {
1945 F.setOnlyReadsMemory();
1950 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1951 if (!F.doesNotThrow()) {
1952 F.setDoesNotThrow();
1957 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1958 if (!F.doesNotCapture(n)) {
1959 F.setDoesNotCapture(n);
1964 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1965 if (!F.doesNotAlias(n)) {
1966 F.setDoesNotAlias(n);
1972 /// doInitialization - Add attributes to well-known functions.
1974 bool SimplifyLibCalls::doInitialization(Module &M) {
1976 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1978 if (!F.isDeclaration())
1984 const FunctionType *FTy = F.getFunctionType();
1986 StringRef Name = F.getName();
1989 if (Name == "strlen") {
1990 if (FTy->getNumParams() != 1 ||
1991 !isa<PointerType>(FTy->getParamType(0)))
1993 setOnlyReadsMemory(F);
1995 setDoesNotCapture(F, 1);
1996 } else if (Name == "strcpy" ||
2002 Name == "strtoul" ||
2003 Name == "strtoll" ||
2004 Name == "strtold" ||
2005 Name == "strncat" ||
2006 Name == "strncpy" ||
2007 Name == "strtoull") {
2008 if (FTy->getNumParams() < 2 ||
2009 !isa<PointerType>(FTy->getParamType(1)))
2012 setDoesNotCapture(F, 2);
2013 } else if (Name == "strxfrm") {
2014 if (FTy->getNumParams() != 3 ||
2015 !isa<PointerType>(FTy->getParamType(0)) ||
2016 !isa<PointerType>(FTy->getParamType(1)))
2019 setDoesNotCapture(F, 1);
2020 setDoesNotCapture(F, 2);
2021 } else if (Name == "strcmp" ||
2023 Name == "strncmp" ||
2024 Name ==" strcspn" ||
2025 Name == "strcoll" ||
2026 Name == "strcasecmp" ||
2027 Name == "strncasecmp") {
2028 if (FTy->getNumParams() < 2 ||
2029 !isa<PointerType>(FTy->getParamType(0)) ||
2030 !isa<PointerType>(FTy->getParamType(1)))
2032 setOnlyReadsMemory(F);
2034 setDoesNotCapture(F, 1);
2035 setDoesNotCapture(F, 2);
2036 } else if (Name == "strstr" ||
2037 Name == "strpbrk") {
2038 if (FTy->getNumParams() != 2 ||
2039 !isa<PointerType>(FTy->getParamType(1)))
2041 setOnlyReadsMemory(F);
2043 setDoesNotCapture(F, 2);
2044 } else if (Name == "strtok" ||
2045 Name == "strtok_r") {
2046 if (FTy->getNumParams() < 2 ||
2047 !isa<PointerType>(FTy->getParamType(1)))
2050 setDoesNotCapture(F, 2);
2051 } else if (Name == "scanf" ||
2053 Name == "setvbuf") {
2054 if (FTy->getNumParams() < 1 ||
2055 !isa<PointerType>(FTy->getParamType(0)))
2058 setDoesNotCapture(F, 1);
2059 } else if (Name == "strdup" ||
2060 Name == "strndup") {
2061 if (FTy->getNumParams() < 1 ||
2062 !isa<PointerType>(FTy->getReturnType()) ||
2063 !isa<PointerType>(FTy->getParamType(0)))
2066 setDoesNotAlias(F, 0);
2067 setDoesNotCapture(F, 1);
2068 } else if (Name == "stat" ||
2070 Name == "sprintf" ||
2071 Name == "statvfs") {
2072 if (FTy->getNumParams() < 2 ||
2073 !isa<PointerType>(FTy->getParamType(0)) ||
2074 !isa<PointerType>(FTy->getParamType(1)))
2077 setDoesNotCapture(F, 1);
2078 setDoesNotCapture(F, 2);
2079 } else if (Name == "snprintf") {
2080 if (FTy->getNumParams() != 3 ||
2081 !isa<PointerType>(FTy->getParamType(0)) ||
2082 !isa<PointerType>(FTy->getParamType(2)))
2085 setDoesNotCapture(F, 1);
2086 setDoesNotCapture(F, 3);
2087 } else if (Name == "setitimer") {
2088 if (FTy->getNumParams() != 3 ||
2089 !isa<PointerType>(FTy->getParamType(1)) ||
2090 !isa<PointerType>(FTy->getParamType(2)))
2093 setDoesNotCapture(F, 2);
2094 setDoesNotCapture(F, 3);
2095 } else if (Name == "system") {
2096 if (FTy->getNumParams() != 1 ||
2097 !isa<PointerType>(FTy->getParamType(0)))
2099 // May throw; "system" is a valid pthread cancellation point.
2100 setDoesNotCapture(F, 1);
2104 if (Name == "malloc") {
2105 if (FTy->getNumParams() != 1 ||
2106 !isa<PointerType>(FTy->getReturnType()))
2109 setDoesNotAlias(F, 0);
2110 } else if (Name == "memcmp") {
2111 if (FTy->getNumParams() != 3 ||
2112 !isa<PointerType>(FTy->getParamType(0)) ||
2113 !isa<PointerType>(FTy->getParamType(1)))
2115 setOnlyReadsMemory(F);
2117 setDoesNotCapture(F, 1);
2118 setDoesNotCapture(F, 2);
2119 } else if (Name == "memchr" ||
2120 Name == "memrchr") {
2121 if (FTy->getNumParams() != 3)
2123 setOnlyReadsMemory(F);
2125 } else if (Name == "modf" ||
2129 Name == "memccpy" ||
2130 Name == "memmove") {
2131 if (FTy->getNumParams() < 2 ||
2132 !isa<PointerType>(FTy->getParamType(1)))
2135 setDoesNotCapture(F, 2);
2136 } else if (Name == "memalign") {
2137 if (!isa<PointerType>(FTy->getReturnType()))
2139 setDoesNotAlias(F, 0);
2140 } else if (Name == "mkdir" ||
2142 if (FTy->getNumParams() == 0 ||
2143 !isa<PointerType>(FTy->getParamType(0)))
2146 setDoesNotCapture(F, 1);
2150 if (Name == "realloc") {
2151 if (FTy->getNumParams() != 2 ||
2152 !isa<PointerType>(FTy->getParamType(0)) ||
2153 !isa<PointerType>(FTy->getReturnType()))
2156 setDoesNotAlias(F, 0);
2157 setDoesNotCapture(F, 1);
2158 } else if (Name == "read") {
2159 if (FTy->getNumParams() != 3 ||
2160 !isa<PointerType>(FTy->getParamType(1)))
2162 // May throw; "read" is a valid pthread cancellation point.
2163 setDoesNotCapture(F, 2);
2164 } else if (Name == "rmdir" ||
2167 Name == "realpath") {
2168 if (FTy->getNumParams() < 1 ||
2169 !isa<PointerType>(FTy->getParamType(0)))
2172 setDoesNotCapture(F, 1);
2173 } else if (Name == "rename" ||
2174 Name == "readlink") {
2175 if (FTy->getNumParams() < 2 ||
2176 !isa<PointerType>(FTy->getParamType(0)) ||
2177 !isa<PointerType>(FTy->getParamType(1)))
2180 setDoesNotCapture(F, 1);
2181 setDoesNotCapture(F, 2);
2185 if (Name == "write") {
2186 if (FTy->getNumParams() != 3 ||
2187 !isa<PointerType>(FTy->getParamType(1)))
2189 // May throw; "write" is a valid pthread cancellation point.
2190 setDoesNotCapture(F, 2);
2194 if (Name == "bcopy") {
2195 if (FTy->getNumParams() != 3 ||
2196 !isa<PointerType>(FTy->getParamType(0)) ||
2197 !isa<PointerType>(FTy->getParamType(1)))
2200 setDoesNotCapture(F, 1);
2201 setDoesNotCapture(F, 2);
2202 } else if (Name == "bcmp") {
2203 if (FTy->getNumParams() != 3 ||
2204 !isa<PointerType>(FTy->getParamType(0)) ||
2205 !isa<PointerType>(FTy->getParamType(1)))
2208 setOnlyReadsMemory(F);
2209 setDoesNotCapture(F, 1);
2210 setDoesNotCapture(F, 2);
2211 } else if (Name == "bzero") {
2212 if (FTy->getNumParams() != 2 ||
2213 !isa<PointerType>(FTy->getParamType(0)))
2216 setDoesNotCapture(F, 1);
2220 if (Name == "calloc") {
2221 if (FTy->getNumParams() != 2 ||
2222 !isa<PointerType>(FTy->getReturnType()))
2225 setDoesNotAlias(F, 0);
2226 } else if (Name == "chmod" ||
2228 Name == "ctermid" ||
2229 Name == "clearerr" ||
2230 Name == "closedir") {
2231 if (FTy->getNumParams() == 0 ||
2232 !isa<PointerType>(FTy->getParamType(0)))
2235 setDoesNotCapture(F, 1);
2239 if (Name == "atoi" ||
2243 if (FTy->getNumParams() != 1 ||
2244 !isa<PointerType>(FTy->getParamType(0)))
2247 setOnlyReadsMemory(F);
2248 setDoesNotCapture(F, 1);
2249 } else if (Name == "access") {
2250 if (FTy->getNumParams() != 2 ||
2251 !isa<PointerType>(FTy->getParamType(0)))
2254 setDoesNotCapture(F, 1);
2258 if (Name == "fopen") {
2259 if (FTy->getNumParams() != 2 ||
2260 !isa<PointerType>(FTy->getReturnType()) ||
2261 !isa<PointerType>(FTy->getParamType(0)) ||
2262 !isa<PointerType>(FTy->getParamType(1)))
2265 setDoesNotAlias(F, 0);
2266 setDoesNotCapture(F, 1);
2267 setDoesNotCapture(F, 2);
2268 } else if (Name == "fdopen") {
2269 if (FTy->getNumParams() != 2 ||
2270 !isa<PointerType>(FTy->getReturnType()) ||
2271 !isa<PointerType>(FTy->getParamType(1)))
2274 setDoesNotAlias(F, 0);
2275 setDoesNotCapture(F, 2);
2276 } else if (Name == "feof" ||
2286 Name == "fsetpos" ||
2287 Name == "flockfile" ||
2288 Name == "funlockfile" ||
2289 Name == "ftrylockfile") {
2290 if (FTy->getNumParams() == 0 ||
2291 !isa<PointerType>(FTy->getParamType(0)))
2294 setDoesNotCapture(F, 1);
2295 } else if (Name == "ferror") {
2296 if (FTy->getNumParams() != 1 ||
2297 !isa<PointerType>(FTy->getParamType(0)))
2300 setDoesNotCapture(F, 1);
2301 setOnlyReadsMemory(F);
2302 } else if (Name == "fputc" ||
2307 Name == "fstatvfs") {
2308 if (FTy->getNumParams() != 2 ||
2309 !isa<PointerType>(FTy->getParamType(1)))
2312 setDoesNotCapture(F, 2);
2313 } else if (Name == "fgets") {
2314 if (FTy->getNumParams() != 3 ||
2315 !isa<PointerType>(FTy->getParamType(0)) ||
2316 !isa<PointerType>(FTy->getParamType(2)))
2319 setDoesNotCapture(F, 3);
2320 } else if (Name == "fread" ||
2322 if (FTy->getNumParams() != 4 ||
2323 !isa<PointerType>(FTy->getParamType(0)) ||
2324 !isa<PointerType>(FTy->getParamType(3)))
2327 setDoesNotCapture(F, 1);
2328 setDoesNotCapture(F, 4);
2329 } else if (Name == "fputs" ||
2331 Name == "fprintf" ||
2332 Name == "fgetpos") {
2333 if (FTy->getNumParams() < 2 ||
2334 !isa<PointerType>(FTy->getParamType(0)) ||
2335 !isa<PointerType>(FTy->getParamType(1)))
2338 setDoesNotCapture(F, 1);
2339 setDoesNotCapture(F, 2);
2343 if (Name == "getc" ||
2344 Name == "getlogin_r" ||
2345 Name == "getc_unlocked") {
2346 if (FTy->getNumParams() == 0 ||
2347 !isa<PointerType>(FTy->getParamType(0)))
2350 setDoesNotCapture(F, 1);
2351 } else if (Name == "getenv") {
2352 if (FTy->getNumParams() != 1 ||
2353 !isa<PointerType>(FTy->getParamType(0)))
2356 setOnlyReadsMemory(F);
2357 setDoesNotCapture(F, 1);
2358 } else if (Name == "gets" ||
2359 Name == "getchar") {
2361 } else if (Name == "getitimer") {
2362 if (FTy->getNumParams() != 2 ||
2363 !isa<PointerType>(FTy->getParamType(1)))
2366 setDoesNotCapture(F, 2);
2367 } else if (Name == "getpwnam") {
2368 if (FTy->getNumParams() != 1 ||
2369 !isa<PointerType>(FTy->getParamType(0)))
2372 setDoesNotCapture(F, 1);
2376 if (Name == "ungetc") {
2377 if (FTy->getNumParams() != 2 ||
2378 !isa<PointerType>(FTy->getParamType(1)))
2381 setDoesNotCapture(F, 2);
2382 } else if (Name == "uname" ||
2384 Name == "unsetenv") {
2385 if (FTy->getNumParams() != 1 ||
2386 !isa<PointerType>(FTy->getParamType(0)))
2389 setDoesNotCapture(F, 1);
2390 } else if (Name == "utime" ||
2392 if (FTy->getNumParams() != 2 ||
2393 !isa<PointerType>(FTy->getParamType(0)) ||
2394 !isa<PointerType>(FTy->getParamType(1)))
2397 setDoesNotCapture(F, 1);
2398 setDoesNotCapture(F, 2);
2402 if (Name == "putc") {
2403 if (FTy->getNumParams() != 2 ||
2404 !isa<PointerType>(FTy->getParamType(1)))
2407 setDoesNotCapture(F, 2);
2408 } else if (Name == "puts" ||
2411 if (FTy->getNumParams() != 1 ||
2412 !isa<PointerType>(FTy->getParamType(0)))
2415 setDoesNotCapture(F, 1);
2416 } else if (Name == "pread" ||
2418 if (FTy->getNumParams() != 4 ||
2419 !isa<PointerType>(FTy->getParamType(1)))
2421 // May throw; these are valid pthread cancellation points.
2422 setDoesNotCapture(F, 2);
2423 } else if (Name == "putchar") {
2425 } else if (Name == "popen") {
2426 if (FTy->getNumParams() != 2 ||
2427 !isa<PointerType>(FTy->getReturnType()) ||
2428 !isa<PointerType>(FTy->getParamType(0)) ||
2429 !isa<PointerType>(FTy->getParamType(1)))
2432 setDoesNotAlias(F, 0);
2433 setDoesNotCapture(F, 1);
2434 setDoesNotCapture(F, 2);
2435 } else if (Name == "pclose") {
2436 if (FTy->getNumParams() != 1 ||
2437 !isa<PointerType>(FTy->getParamType(0)))
2440 setDoesNotCapture(F, 1);
2444 if (Name == "vscanf") {
2445 if (FTy->getNumParams() != 2 ||
2446 !isa<PointerType>(FTy->getParamType(1)))
2449 setDoesNotCapture(F, 1);
2450 } else if (Name == "vsscanf" ||
2451 Name == "vfscanf") {
2452 if (FTy->getNumParams() != 3 ||
2453 !isa<PointerType>(FTy->getParamType(1)) ||
2454 !isa<PointerType>(FTy->getParamType(2)))
2457 setDoesNotCapture(F, 1);
2458 setDoesNotCapture(F, 2);
2459 } else if (Name == "valloc") {
2460 if (!isa<PointerType>(FTy->getReturnType()))
2463 setDoesNotAlias(F, 0);
2464 } else if (Name == "vprintf") {
2465 if (FTy->getNumParams() != 2 ||
2466 !isa<PointerType>(FTy->getParamType(0)))
2469 setDoesNotCapture(F, 1);
2470 } else if (Name == "vfprintf" ||
2471 Name == "vsprintf") {
2472 if (FTy->getNumParams() != 3 ||
2473 !isa<PointerType>(FTy->getParamType(0)) ||
2474 !isa<PointerType>(FTy->getParamType(1)))
2477 setDoesNotCapture(F, 1);
2478 setDoesNotCapture(F, 2);
2479 } else if (Name == "vsnprintf") {
2480 if (FTy->getNumParams() != 4 ||
2481 !isa<PointerType>(FTy->getParamType(0)) ||
2482 !isa<PointerType>(FTy->getParamType(2)))
2485 setDoesNotCapture(F, 1);
2486 setDoesNotCapture(F, 3);
2490 if (Name == "open") {
2491 if (FTy->getNumParams() < 2 ||
2492 !isa<PointerType>(FTy->getParamType(0)))
2494 // May throw; "open" is a valid pthread cancellation point.
2495 setDoesNotCapture(F, 1);
2496 } else if (Name == "opendir") {
2497 if (FTy->getNumParams() != 1 ||
2498 !isa<PointerType>(FTy->getReturnType()) ||
2499 !isa<PointerType>(FTy->getParamType(0)))
2502 setDoesNotAlias(F, 0);
2503 setDoesNotCapture(F, 1);
2507 if (Name == "tmpfile") {
2508 if (!isa<PointerType>(FTy->getReturnType()))
2511 setDoesNotAlias(F, 0);
2512 } else if (Name == "times") {
2513 if (FTy->getNumParams() != 1 ||
2514 !isa<PointerType>(FTy->getParamType(0)))
2517 setDoesNotCapture(F, 1);
2521 if (Name == "htonl" ||
2524 setDoesNotAccessMemory(F);
2528 if (Name == "ntohl" ||
2531 setDoesNotAccessMemory(F);
2535 if (Name == "lstat") {
2536 if (FTy->getNumParams() != 2 ||
2537 !isa<PointerType>(FTy->getParamType(0)) ||
2538 !isa<PointerType>(FTy->getParamType(1)))
2541 setDoesNotCapture(F, 1);
2542 setDoesNotCapture(F, 2);
2543 } else if (Name == "lchown") {
2544 if (FTy->getNumParams() != 3 ||
2545 !isa<PointerType>(FTy->getParamType(0)))
2548 setDoesNotCapture(F, 1);
2552 if (Name == "qsort") {
2553 if (FTy->getNumParams() != 4 ||
2554 !isa<PointerType>(FTy->getParamType(3)))
2556 // May throw; places call through function pointer.
2557 setDoesNotCapture(F, 4);
2561 if (Name == "__strdup" ||
2562 Name == "__strndup") {
2563 if (FTy->getNumParams() < 1 ||
2564 !isa<PointerType>(FTy->getReturnType()) ||
2565 !isa<PointerType>(FTy->getParamType(0)))
2568 setDoesNotAlias(F, 0);
2569 setDoesNotCapture(F, 1);
2570 } else if (Name == "__strtok_r") {
2571 if (FTy->getNumParams() != 3 ||
2572 !isa<PointerType>(FTy->getParamType(1)))
2575 setDoesNotCapture(F, 2);
2576 } else if (Name == "_IO_getc") {
2577 if (FTy->getNumParams() != 1 ||
2578 !isa<PointerType>(FTy->getParamType(0)))
2581 setDoesNotCapture(F, 1);
2582 } else if (Name == "_IO_putc") {
2583 if (FTy->getNumParams() != 2 ||
2584 !isa<PointerType>(FTy->getParamType(1)))
2587 setDoesNotCapture(F, 2);
2591 if (Name == "\1__isoc99_scanf") {
2592 if (FTy->getNumParams() < 1 ||
2593 !isa<PointerType>(FTy->getParamType(0)))
2596 setDoesNotCapture(F, 1);
2597 } else if (Name == "\1stat64" ||
2598 Name == "\1lstat64" ||
2599 Name == "\1statvfs64" ||
2600 Name == "\1__isoc99_sscanf") {
2601 if (FTy->getNumParams() < 1 ||
2602 !isa<PointerType>(FTy->getParamType(0)) ||
2603 !isa<PointerType>(FTy->getParamType(1)))
2606 setDoesNotCapture(F, 1);
2607 setDoesNotCapture(F, 2);
2608 } else if (Name == "\1fopen64") {
2609 if (FTy->getNumParams() != 2 ||
2610 !isa<PointerType>(FTy->getReturnType()) ||
2611 !isa<PointerType>(FTy->getParamType(0)) ||
2612 !isa<PointerType>(FTy->getParamType(1)))
2615 setDoesNotAlias(F, 0);
2616 setDoesNotCapture(F, 1);
2617 setDoesNotCapture(F, 2);
2618 } else if (Name == "\1fseeko64" ||
2619 Name == "\1ftello64") {
2620 if (FTy->getNumParams() == 0 ||
2621 !isa<PointerType>(FTy->getParamType(0)))
2624 setDoesNotCapture(F, 1);
2625 } else if (Name == "\1tmpfile64") {
2626 if (!isa<PointerType>(FTy->getReturnType()))
2629 setDoesNotAlias(F, 0);
2630 } else if (Name == "\1fstat64" ||
2631 Name == "\1fstatvfs64") {
2632 if (FTy->getNumParams() != 2 ||
2633 !isa<PointerType>(FTy->getParamType(1)))
2636 setDoesNotCapture(F, 2);
2637 } else if (Name == "\1open64") {
2638 if (FTy->getNumParams() < 2 ||
2639 !isa<PointerType>(FTy->getParamType(0)))
2641 // May throw; "open" is a valid pthread cancellation point.
2642 setDoesNotCapture(F, 1);
2651 // Additional cases that we need to add to this file:
2654 // * cbrt(expN(X)) -> expN(x/3)
2655 // * cbrt(sqrt(x)) -> pow(x,1/6)
2656 // * cbrt(sqrt(x)) -> pow(x,1/9)
2659 // * cos(-x) -> cos(x)
2662 // * exp(log(x)) -> x
2665 // * log(exp(x)) -> x
2666 // * log(x**y) -> y*log(x)
2667 // * log(exp(y)) -> y*log(e)
2668 // * log(exp2(y)) -> y*log(2)
2669 // * log(exp10(y)) -> y*log(10)
2670 // * log(sqrt(x)) -> 0.5*log(x)
2671 // * log(pow(x,y)) -> y*log(x)
2673 // lround, lroundf, lroundl:
2674 // * lround(cnst) -> cnst'
2677 // * pow(exp(x),y) -> exp(x*y)
2678 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2679 // * pow(pow(x,y),z)-> pow(x,y*z)
2682 // * puts("") -> putchar("\n")
2684 // round, roundf, roundl:
2685 // * round(cnst) -> cnst'
2688 // * signbit(cnst) -> cnst'
2689 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2691 // sqrt, sqrtf, sqrtl:
2692 // * sqrt(expN(x)) -> expN(x*0.5)
2693 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2694 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2697 // * stpcpy(str, "literal") ->
2698 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2700 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2701 // (if c is a constant integer and s is a constant string)
2702 // * strrchr(s1,0) -> strchr(s1,0)
2705 // * strpbrk(s,a) -> offset_in_for(s,a)
2706 // (if s and a are both constant strings)
2707 // * strpbrk(s,"") -> 0
2708 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2711 // * strspn(s,a) -> const_int (if both args are constant)
2712 // * strspn("",a) -> 0
2713 // * strspn(s,"") -> 0
2714 // * strcspn(s,a) -> const_int (if both args are constant)
2715 // * strcspn("",a) -> 0
2716 // * strcspn(s,"") -> strlen(a)
2719 // * tan(atan(x)) -> x
2721 // trunc, truncf, truncl:
2722 // * trunc(cnst) -> cnst'