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 // Handle strlen(p) != 0.
909 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
911 // strlen(x) != 0 --> *x != 0
912 // strlen(x) == 0 --> *x == 0
913 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
917 //===---------------------------------------===//
918 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
920 struct StrToOpt : public LibCallOptimization {
921 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
922 const FunctionType *FT = Callee->getFunctionType();
923 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
924 !isa<PointerType>(FT->getParamType(0)) ||
925 !isa<PointerType>(FT->getParamType(1)))
928 Value *EndPtr = CI->getOperand(2);
929 if (isa<ConstantPointerNull>(EndPtr)) {
930 CI->setOnlyReadsMemory();
931 CI->addAttribute(1, Attribute::NoCapture);
938 //===---------------------------------------===//
939 // 'strstr' Optimizations
941 struct StrStrOpt : public LibCallOptimization {
942 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
943 const FunctionType *FT = Callee->getFunctionType();
944 if (FT->getNumParams() != 2 ||
945 !isa<PointerType>(FT->getParamType(0)) ||
946 !isa<PointerType>(FT->getParamType(1)) ||
947 !isa<PointerType>(FT->getReturnType()))
950 // fold strstr(x, x) -> x.
951 if (CI->getOperand(1) == CI->getOperand(2))
952 return CI->getOperand(1);
954 // See if either input string is a constant string.
955 std::string SearchStr, ToFindStr;
956 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
957 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
959 // fold strstr(x, "") -> x.
960 if (HasStr2 && ToFindStr.empty())
961 return B.CreateBitCast(CI->getOperand(1), CI->getType());
963 // If both strings are known, constant fold it.
964 if (HasStr1 && HasStr2) {
965 std::string::size_type Offset = SearchStr.find(ToFindStr);
967 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
968 return Constant::getNullValue(CI->getType());
970 // strstr("abcd", "bc") -> gep((char*)"abcd", 2)
971 Value *Result = CastToCStr(CI->getOperand(1), B);
972 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
973 return B.CreateBitCast(Result, CI->getType());
976 // fold strstr(x, "y") -> strchr(x, 'y').
977 if (HasStr2 && ToFindStr.size() == 1)
978 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
985 //===---------------------------------------===//
986 // 'memcmp' Optimizations
988 struct MemCmpOpt : public LibCallOptimization {
989 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
990 const FunctionType *FT = Callee->getFunctionType();
991 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
992 !isa<PointerType>(FT->getParamType(1)) ||
993 FT->getReturnType() != Type::getInt32Ty(*Context))
996 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
998 if (LHS == RHS) // memcmp(s,s,x) -> 0
999 return Constant::getNullValue(CI->getType());
1001 // Make sure we have a constant length.
1002 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1003 if (!LenC) return 0;
1004 uint64_t Len = LenC->getZExtValue();
1006 if (Len == 0) // memcmp(s1,s2,0) -> 0
1007 return Constant::getNullValue(CI->getType());
1009 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1010 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1011 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
1012 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
1015 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
1016 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
1017 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
1018 const Type *PTy = PointerType::getUnqual(Len == 2 ?
1019 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
1020 LHS = B.CreateBitCast(LHS, PTy, "tmp");
1021 RHS = B.CreateBitCast(RHS, PTy, "tmp");
1022 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
1023 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
1024 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
1025 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
1028 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1029 std::string LHSStr, RHSStr;
1030 if (GetConstantStringInfo(LHS, LHSStr) &&
1031 GetConstantStringInfo(RHS, RHSStr)) {
1032 // Make sure we're not reading out-of-bounds memory.
1033 if (Len > LHSStr.length() || Len > RHSStr.length())
1035 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1036 return ConstantInt::get(CI->getType(), Ret);
1043 //===---------------------------------------===//
1044 // 'memcpy' Optimizations
1046 struct MemCpyOpt : public LibCallOptimization {
1047 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1048 // These optimizations require TargetData.
1051 const FunctionType *FT = Callee->getFunctionType();
1052 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1053 !isa<PointerType>(FT->getParamType(0)) ||
1054 !isa<PointerType>(FT->getParamType(1)) ||
1055 FT->getParamType(2) != TD->getIntPtrType(*Context))
1058 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1059 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1060 return CI->getOperand(1);
1064 //===---------------------------------------===//
1065 // 'memmove' Optimizations
1067 struct MemMoveOpt : public LibCallOptimization {
1068 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1069 // These optimizations require TargetData.
1072 const FunctionType *FT = Callee->getFunctionType();
1073 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1074 !isa<PointerType>(FT->getParamType(0)) ||
1075 !isa<PointerType>(FT->getParamType(1)) ||
1076 FT->getParamType(2) != TD->getIntPtrType(*Context))
1079 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1080 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1081 return CI->getOperand(1);
1085 //===---------------------------------------===//
1086 // 'memset' Optimizations
1088 struct MemSetOpt : public LibCallOptimization {
1089 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1090 // These optimizations require TargetData.
1093 const FunctionType *FT = Callee->getFunctionType();
1094 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1095 !isa<PointerType>(FT->getParamType(0)) ||
1096 !isa<IntegerType>(FT->getParamType(1)) ||
1097 FT->getParamType(2) != TD->getIntPtrType(*Context))
1100 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1101 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1103 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1104 return CI->getOperand(1);
1108 //===----------------------------------------------------------------------===//
1109 // Object Size Checking Optimizations
1110 //===----------------------------------------------------------------------===//
1112 //===---------------------------------------===//
1115 struct SizeOpt : public LibCallOptimization {
1116 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1117 // TODO: We can do more with this, but delaying to here should be no change
1119 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
1121 if (!Const) return 0;
1123 const Type *Ty = Callee->getFunctionType()->getReturnType();
1125 if (Const->getZExtValue() < 2)
1126 return Constant::getAllOnesValue(Ty);
1128 return ConstantInt::get(Ty, 0);
1133 //===---------------------------------------===//
1134 // 'memcpy_chk' Optimizations
1136 struct MemCpyChkOpt : public LibCallOptimization {
1137 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1138 // These optimizations require TargetData.
1141 const FunctionType *FT = Callee->getFunctionType();
1142 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1143 !isa<PointerType>(FT->getParamType(0)) ||
1144 !isa<PointerType>(FT->getParamType(1)) ||
1145 !isa<IntegerType>(FT->getParamType(3)) ||
1146 FT->getParamType(2) != TD->getIntPtrType(*Context))
1149 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1152 if (SizeCI->isAllOnesValue()) {
1153 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1154 return CI->getOperand(1);
1161 //===---------------------------------------===//
1162 // 'memset_chk' Optimizations
1164 struct MemSetChkOpt : public LibCallOptimization {
1165 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1166 // These optimizations require TargetData.
1169 const FunctionType *FT = Callee->getFunctionType();
1170 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1171 !isa<PointerType>(FT->getParamType(0)) ||
1172 !isa<IntegerType>(FT->getParamType(1)) ||
1173 !isa<IntegerType>(FT->getParamType(3)) ||
1174 FT->getParamType(2) != TD->getIntPtrType(*Context))
1177 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1180 if (SizeCI->isAllOnesValue()) {
1181 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1183 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1184 return CI->getOperand(1);
1191 //===---------------------------------------===//
1192 // 'memmove_chk' Optimizations
1194 struct MemMoveChkOpt : public LibCallOptimization {
1195 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1196 // These optimizations require TargetData.
1199 const FunctionType *FT = Callee->getFunctionType();
1200 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1201 !isa<PointerType>(FT->getParamType(0)) ||
1202 !isa<PointerType>(FT->getParamType(1)) ||
1203 !isa<IntegerType>(FT->getParamType(3)) ||
1204 FT->getParamType(2) != TD->getIntPtrType(*Context))
1207 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1210 if (SizeCI->isAllOnesValue()) {
1211 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1213 return CI->getOperand(1);
1220 //===----------------------------------------------------------------------===//
1221 // Math Library Optimizations
1222 //===----------------------------------------------------------------------===//
1224 //===---------------------------------------===//
1225 // 'pow*' Optimizations
1227 struct PowOpt : public LibCallOptimization {
1228 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1229 const FunctionType *FT = Callee->getFunctionType();
1230 // Just make sure this has 2 arguments of the same FP type, which match the
1232 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1233 FT->getParamType(0) != FT->getParamType(1) ||
1234 !FT->getParamType(0)->isFloatingPoint())
1237 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1238 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1239 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1241 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1242 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1245 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1246 if (Op2C == 0) return 0;
1248 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1249 return ConstantFP::get(CI->getType(), 1.0);
1251 if (Op2C->isExactlyValue(0.5)) {
1252 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1253 // This is faster than calling pow, and still handles negative zero
1254 // and negative infinite correctly.
1255 // TODO: In fast-math mode, this could be just sqrt(x).
1256 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1257 Value *Inf = ConstantFP::getInfinity(CI->getType());
1258 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1259 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1260 Callee->getAttributes());
1261 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1262 Callee->getAttributes());
1263 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1264 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1268 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1270 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1271 return B.CreateFMul(Op1, Op1, "pow2");
1272 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1273 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1279 //===---------------------------------------===//
1280 // 'exp2' Optimizations
1282 struct Exp2Opt : public LibCallOptimization {
1283 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1284 const FunctionType *FT = Callee->getFunctionType();
1285 // Just make sure this has 1 argument of FP type, which matches the
1287 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1288 !FT->getParamType(0)->isFloatingPoint())
1291 Value *Op = CI->getOperand(1);
1292 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1293 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1294 Value *LdExpArg = 0;
1295 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1296 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1297 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1298 Type::getInt32Ty(*Context), "tmp");
1299 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1300 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1301 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1302 Type::getInt32Ty(*Context), "tmp");
1307 if (Op->getType()->isFloatTy())
1309 else if (Op->getType()->isDoubleTy())
1314 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1315 if (!Op->getType()->isFloatTy())
1316 One = ConstantExpr::getFPExtend(One, Op->getType());
1318 Module *M = Caller->getParent();
1319 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1321 Type::getInt32Ty(*Context),NULL);
1322 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1323 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1324 CI->setCallingConv(F->getCallingConv());
1332 //===---------------------------------------===//
1333 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1335 struct UnaryDoubleFPOpt : public LibCallOptimization {
1336 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1337 const FunctionType *FT = Callee->getFunctionType();
1338 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1339 !FT->getParamType(0)->isDoubleTy())
1342 // If this is something like 'floor((double)floatval)', convert to floorf.
1343 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1344 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1347 // floor((double)floatval) -> (double)floorf(floatval)
1348 Value *V = Cast->getOperand(0);
1349 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1350 Callee->getAttributes());
1351 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1355 //===----------------------------------------------------------------------===//
1356 // Integer Optimizations
1357 //===----------------------------------------------------------------------===//
1359 //===---------------------------------------===//
1360 // 'ffs*' Optimizations
1362 struct FFSOpt : public LibCallOptimization {
1363 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1364 const FunctionType *FT = Callee->getFunctionType();
1365 // Just make sure this has 2 arguments of the same FP type, which match the
1367 if (FT->getNumParams() != 1 ||
1368 FT->getReturnType() != Type::getInt32Ty(*Context) ||
1369 !isa<IntegerType>(FT->getParamType(0)))
1372 Value *Op = CI->getOperand(1);
1375 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1376 if (CI->getValue() == 0) // ffs(0) -> 0.
1377 return Constant::getNullValue(CI->getType());
1378 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1379 CI->getValue().countTrailingZeros()+1);
1382 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1383 const Type *ArgType = Op->getType();
1384 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1385 Intrinsic::cttz, &ArgType, 1);
1386 Value *V = B.CreateCall(F, Op, "cttz");
1387 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1388 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1390 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1391 return B.CreateSelect(Cond, V,
1392 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1396 //===---------------------------------------===//
1397 // 'isdigit' Optimizations
1399 struct IsDigitOpt : public LibCallOptimization {
1400 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1401 const FunctionType *FT = Callee->getFunctionType();
1402 // We require integer(i32)
1403 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1404 FT->getParamType(0) != Type::getInt32Ty(*Context))
1407 // isdigit(c) -> (c-'0') <u 10
1408 Value *Op = CI->getOperand(1);
1409 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1411 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1413 return B.CreateZExt(Op, CI->getType());
1417 //===---------------------------------------===//
1418 // 'isascii' Optimizations
1420 struct IsAsciiOpt : public LibCallOptimization {
1421 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1422 const FunctionType *FT = Callee->getFunctionType();
1423 // We require integer(i32)
1424 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1425 FT->getParamType(0) != Type::getInt32Ty(*Context))
1428 // isascii(c) -> c <u 128
1429 Value *Op = CI->getOperand(1);
1430 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1432 return B.CreateZExt(Op, CI->getType());
1436 //===---------------------------------------===//
1437 // 'abs', 'labs', 'llabs' Optimizations
1439 struct AbsOpt : public LibCallOptimization {
1440 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1441 const FunctionType *FT = Callee->getFunctionType();
1442 // We require integer(integer) where the types agree.
1443 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1444 FT->getParamType(0) != FT->getReturnType())
1447 // abs(x) -> x >s -1 ? x : -x
1448 Value *Op = CI->getOperand(1);
1449 Value *Pos = B.CreateICmpSGT(Op,
1450 Constant::getAllOnesValue(Op->getType()),
1452 Value *Neg = B.CreateNeg(Op, "neg");
1453 return B.CreateSelect(Pos, Op, Neg);
1458 //===---------------------------------------===//
1459 // 'toascii' Optimizations
1461 struct ToAsciiOpt : public LibCallOptimization {
1462 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1463 const FunctionType *FT = Callee->getFunctionType();
1464 // We require i32(i32)
1465 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1466 FT->getParamType(0) != Type::getInt32Ty(*Context))
1469 // isascii(c) -> c & 0x7f
1470 return B.CreateAnd(CI->getOperand(1),
1471 ConstantInt::get(CI->getType(),0x7F));
1475 //===----------------------------------------------------------------------===//
1476 // Formatting and IO Optimizations
1477 //===----------------------------------------------------------------------===//
1479 //===---------------------------------------===//
1480 // 'printf' Optimizations
1482 struct PrintFOpt : public LibCallOptimization {
1483 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1484 // Require one fixed pointer argument and an integer/void result.
1485 const FunctionType *FT = Callee->getFunctionType();
1486 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1487 !(isa<IntegerType>(FT->getReturnType()) ||
1488 FT->getReturnType()->isVoidTy()))
1491 // Check for a fixed format string.
1492 std::string FormatStr;
1493 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1496 // Empty format string -> noop.
1497 if (FormatStr.empty()) // Tolerate printf's declared void.
1498 return CI->use_empty() ? (Value*)CI :
1499 ConstantInt::get(CI->getType(), 0);
1501 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1502 // in case there is an error writing to stdout.
1503 if (FormatStr.size() == 1) {
1504 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1506 if (CI->use_empty()) return CI;
1507 return B.CreateIntCast(Res, CI->getType(), true);
1510 // printf("foo\n") --> puts("foo")
1511 if (FormatStr[FormatStr.size()-1] == '\n' &&
1512 FormatStr.find('%') == std::string::npos) { // no format characters.
1513 // Create a string literal with no \n on it. We expect the constant merge
1514 // pass to be run after this pass, to merge duplicate strings.
1515 FormatStr.erase(FormatStr.end()-1);
1516 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1517 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1518 GlobalVariable::InternalLinkage, C, "str");
1520 return CI->use_empty() ? (Value*)CI :
1521 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1524 // Optimize specific format strings.
1525 // printf("%c", chr) --> putchar(*(i8*)dst)
1526 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1527 isa<IntegerType>(CI->getOperand(2)->getType())) {
1528 Value *Res = EmitPutChar(CI->getOperand(2), B);
1530 if (CI->use_empty()) return CI;
1531 return B.CreateIntCast(Res, CI->getType(), true);
1534 // printf("%s\n", str) --> puts(str)
1535 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1536 isa<PointerType>(CI->getOperand(2)->getType()) &&
1538 EmitPutS(CI->getOperand(2), B);
1545 //===---------------------------------------===//
1546 // 'sprintf' Optimizations
1548 struct SPrintFOpt : public LibCallOptimization {
1549 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1550 // Require two fixed pointer arguments and an integer result.
1551 const FunctionType *FT = Callee->getFunctionType();
1552 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1553 !isa<PointerType>(FT->getParamType(1)) ||
1554 !isa<IntegerType>(FT->getReturnType()))
1557 // Check for a fixed format string.
1558 std::string FormatStr;
1559 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1562 // If we just have a format string (nothing else crazy) transform it.
1563 if (CI->getNumOperands() == 3) {
1564 // Make sure there's no % in the constant array. We could try to handle
1565 // %% -> % in the future if we cared.
1566 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1567 if (FormatStr[i] == '%')
1568 return 0; // we found a format specifier, bail out.
1570 // These optimizations require TargetData.
1573 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1574 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1575 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1576 return ConstantInt::get(CI->getType(), FormatStr.size());
1579 // The remaining optimizations require the format string to be "%s" or "%c"
1580 // and have an extra operand.
1581 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1584 // Decode the second character of the format string.
1585 if (FormatStr[1] == 'c') {
1586 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1587 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1588 Value *V = B.CreateTrunc(CI->getOperand(3),
1589 Type::getInt8Ty(*Context), "char");
1590 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1591 B.CreateStore(V, Ptr);
1592 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1594 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1596 return ConstantInt::get(CI->getType(), 1);
1599 if (FormatStr[1] == 's') {
1600 // These optimizations require TargetData.
1603 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1604 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1606 Value *Len = EmitStrLen(CI->getOperand(3), B);
1607 Value *IncLen = B.CreateAdd(Len,
1608 ConstantInt::get(Len->getType(), 1),
1610 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1612 // The sprintf result is the unincremented number of bytes in the string.
1613 return B.CreateIntCast(Len, CI->getType(), false);
1619 //===---------------------------------------===//
1620 // 'fwrite' Optimizations
1622 struct FWriteOpt : public LibCallOptimization {
1623 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1624 // Require a pointer, an integer, an integer, a pointer, returning integer.
1625 const FunctionType *FT = Callee->getFunctionType();
1626 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1627 !isa<IntegerType>(FT->getParamType(1)) ||
1628 !isa<IntegerType>(FT->getParamType(2)) ||
1629 !isa<PointerType>(FT->getParamType(3)) ||
1630 !isa<IntegerType>(FT->getReturnType()))
1633 // Get the element size and count.
1634 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1635 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1636 if (!SizeC || !CountC) return 0;
1637 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1639 // If this is writing zero records, remove the call (it's a noop).
1641 return ConstantInt::get(CI->getType(), 0);
1643 // If this is writing one byte, turn it into fputc.
1644 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1645 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1646 EmitFPutC(Char, CI->getOperand(4), B);
1647 return ConstantInt::get(CI->getType(), 1);
1654 //===---------------------------------------===//
1655 // 'fputs' Optimizations
1657 struct FPutsOpt : public LibCallOptimization {
1658 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1659 // These optimizations require TargetData.
1662 // Require two pointers. Also, we can't optimize if return value is used.
1663 const FunctionType *FT = Callee->getFunctionType();
1664 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1665 !isa<PointerType>(FT->getParamType(1)) ||
1669 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1670 uint64_t Len = GetStringLength(CI->getOperand(1));
1672 EmitFWrite(CI->getOperand(1),
1673 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1674 CI->getOperand(2), B);
1675 return CI; // Known to have no uses (see above).
1679 //===---------------------------------------===//
1680 // 'fprintf' Optimizations
1682 struct FPrintFOpt : public LibCallOptimization {
1683 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1684 // Require two fixed paramters as pointers and integer result.
1685 const FunctionType *FT = Callee->getFunctionType();
1686 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1687 !isa<PointerType>(FT->getParamType(1)) ||
1688 !isa<IntegerType>(FT->getReturnType()))
1691 // All the optimizations depend on the format string.
1692 std::string FormatStr;
1693 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1696 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1697 if (CI->getNumOperands() == 3) {
1698 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1699 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1700 return 0; // We found a format specifier.
1702 // These optimizations require TargetData.
1705 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
1707 CI->getOperand(1), B);
1708 return ConstantInt::get(CI->getType(), FormatStr.size());
1711 // The remaining optimizations require the format string to be "%s" or "%c"
1712 // and have an extra operand.
1713 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1716 // Decode the second character of the format string.
1717 if (FormatStr[1] == 'c') {
1718 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1719 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1720 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1721 return ConstantInt::get(CI->getType(), 1);
1724 if (FormatStr[1] == 's') {
1725 // fprintf(F, "%s", str) -> fputs(str, F)
1726 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1728 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1735 } // end anonymous namespace.
1737 //===----------------------------------------------------------------------===//
1738 // SimplifyLibCalls Pass Implementation
1739 //===----------------------------------------------------------------------===//
1742 /// This pass optimizes well known library functions from libc and libm.
1744 class SimplifyLibCalls : public FunctionPass {
1745 StringMap<LibCallOptimization*> Optimizations;
1746 // String and Memory LibCall Optimizations
1747 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1748 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1749 StrToOpt StrTo; StrStrOpt StrStr;
1750 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1751 // Math Library Optimizations
1752 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1753 // Integer Optimizations
1754 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1756 // Formatting and IO Optimizations
1757 SPrintFOpt SPrintF; PrintFOpt PrintF;
1758 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1760 // Object Size Checking
1762 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1764 bool Modified; // This is only used by doInitialization.
1766 static char ID; // Pass identification
1767 SimplifyLibCalls() : FunctionPass(&ID) {}
1769 void InitOptimizations();
1770 bool runOnFunction(Function &F);
1772 void setDoesNotAccessMemory(Function &F);
1773 void setOnlyReadsMemory(Function &F);
1774 void setDoesNotThrow(Function &F);
1775 void setDoesNotCapture(Function &F, unsigned n);
1776 void setDoesNotAlias(Function &F, unsigned n);
1777 bool doInitialization(Module &M);
1779 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1782 char SimplifyLibCalls::ID = 0;
1783 } // end anonymous namespace.
1785 static RegisterPass<SimplifyLibCalls>
1786 X("simplify-libcalls", "Simplify well-known library calls");
1788 // Public interface to the Simplify LibCalls pass.
1789 FunctionPass *llvm::createSimplifyLibCallsPass() {
1790 return new SimplifyLibCalls();
1793 /// Optimizations - Populate the Optimizations map with all the optimizations
1795 void SimplifyLibCalls::InitOptimizations() {
1796 // String and Memory LibCall Optimizations
1797 Optimizations["strcat"] = &StrCat;
1798 Optimizations["strncat"] = &StrNCat;
1799 Optimizations["strchr"] = &StrChr;
1800 Optimizations["strcmp"] = &StrCmp;
1801 Optimizations["strncmp"] = &StrNCmp;
1802 Optimizations["strcpy"] = &StrCpy;
1803 Optimizations["strncpy"] = &StrNCpy;
1804 Optimizations["strlen"] = &StrLen;
1805 Optimizations["strtol"] = &StrTo;
1806 Optimizations["strtod"] = &StrTo;
1807 Optimizations["strtof"] = &StrTo;
1808 Optimizations["strtoul"] = &StrTo;
1809 Optimizations["strtoll"] = &StrTo;
1810 Optimizations["strtold"] = &StrTo;
1811 Optimizations["strtoull"] = &StrTo;
1812 Optimizations["strstr"] = &StrStr;
1813 Optimizations["memcmp"] = &MemCmp;
1814 Optimizations["memcpy"] = &MemCpy;
1815 Optimizations["memmove"] = &MemMove;
1816 Optimizations["memset"] = &MemSet;
1818 // Math Library Optimizations
1819 Optimizations["powf"] = &Pow;
1820 Optimizations["pow"] = &Pow;
1821 Optimizations["powl"] = &Pow;
1822 Optimizations["llvm.pow.f32"] = &Pow;
1823 Optimizations["llvm.pow.f64"] = &Pow;
1824 Optimizations["llvm.pow.f80"] = &Pow;
1825 Optimizations["llvm.pow.f128"] = &Pow;
1826 Optimizations["llvm.pow.ppcf128"] = &Pow;
1827 Optimizations["exp2l"] = &Exp2;
1828 Optimizations["exp2"] = &Exp2;
1829 Optimizations["exp2f"] = &Exp2;
1830 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1831 Optimizations["llvm.exp2.f128"] = &Exp2;
1832 Optimizations["llvm.exp2.f80"] = &Exp2;
1833 Optimizations["llvm.exp2.f64"] = &Exp2;
1834 Optimizations["llvm.exp2.f32"] = &Exp2;
1837 Optimizations["floor"] = &UnaryDoubleFP;
1840 Optimizations["ceil"] = &UnaryDoubleFP;
1843 Optimizations["round"] = &UnaryDoubleFP;
1846 Optimizations["rint"] = &UnaryDoubleFP;
1848 #ifdef HAVE_NEARBYINTF
1849 Optimizations["nearbyint"] = &UnaryDoubleFP;
1852 // Integer Optimizations
1853 Optimizations["ffs"] = &FFS;
1854 Optimizations["ffsl"] = &FFS;
1855 Optimizations["ffsll"] = &FFS;
1856 Optimizations["abs"] = &Abs;
1857 Optimizations["labs"] = &Abs;
1858 Optimizations["llabs"] = &Abs;
1859 Optimizations["isdigit"] = &IsDigit;
1860 Optimizations["isascii"] = &IsAscii;
1861 Optimizations["toascii"] = &ToAscii;
1863 // Formatting and IO Optimizations
1864 Optimizations["sprintf"] = &SPrintF;
1865 Optimizations["printf"] = &PrintF;
1866 Optimizations["fwrite"] = &FWrite;
1867 Optimizations["fputs"] = &FPuts;
1868 Optimizations["fprintf"] = &FPrintF;
1870 // Object Size Checking
1871 Optimizations["llvm.objectsize.i32"] = &ObjectSize;
1872 Optimizations["llvm.objectsize.i64"] = &ObjectSize;
1873 Optimizations["__memcpy_chk"] = &MemCpyChk;
1874 Optimizations["__memset_chk"] = &MemSetChk;
1875 Optimizations["__memmove_chk"] = &MemMoveChk;
1879 /// runOnFunction - Top level algorithm.
1881 bool SimplifyLibCalls::runOnFunction(Function &F) {
1882 if (Optimizations.empty())
1883 InitOptimizations();
1885 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1887 IRBuilder<> Builder(F.getContext());
1889 bool Changed = false;
1890 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1891 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1892 // Ignore non-calls.
1893 CallInst *CI = dyn_cast<CallInst>(I++);
1896 // Ignore indirect calls and calls to non-external functions.
1897 Function *Callee = CI->getCalledFunction();
1898 if (Callee == 0 || !Callee->isDeclaration() ||
1899 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1902 // Ignore unknown calls.
1903 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1906 // Set the builder to the instruction after the call.
1907 Builder.SetInsertPoint(BB, I);
1909 // Try to optimize this call.
1910 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1911 if (Result == 0) continue;
1913 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1914 errs() << " into: " << *Result << "\n");
1916 // Something changed!
1920 // Inspect the instruction after the call (which was potentially just
1924 if (CI != Result && !CI->use_empty()) {
1925 CI->replaceAllUsesWith(Result);
1926 if (!Result->hasName())
1927 Result->takeName(CI);
1929 CI->eraseFromParent();
1935 // Utility methods for doInitialization.
1937 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1938 if (!F.doesNotAccessMemory()) {
1939 F.setDoesNotAccessMemory();
1944 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1945 if (!F.onlyReadsMemory()) {
1946 F.setOnlyReadsMemory();
1951 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1952 if (!F.doesNotThrow()) {
1953 F.setDoesNotThrow();
1958 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1959 if (!F.doesNotCapture(n)) {
1960 F.setDoesNotCapture(n);
1965 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1966 if (!F.doesNotAlias(n)) {
1967 F.setDoesNotAlias(n);
1973 /// doInitialization - Add attributes to well-known functions.
1975 bool SimplifyLibCalls::doInitialization(Module &M) {
1977 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1979 if (!F.isDeclaration())
1985 const FunctionType *FTy = F.getFunctionType();
1987 StringRef Name = F.getName();
1990 if (Name == "strlen") {
1991 if (FTy->getNumParams() != 1 ||
1992 !isa<PointerType>(FTy->getParamType(0)))
1994 setOnlyReadsMemory(F);
1996 setDoesNotCapture(F, 1);
1997 } else if (Name == "strcpy" ||
2003 Name == "strtoul" ||
2004 Name == "strtoll" ||
2005 Name == "strtold" ||
2006 Name == "strncat" ||
2007 Name == "strncpy" ||
2008 Name == "strtoull") {
2009 if (FTy->getNumParams() < 2 ||
2010 !isa<PointerType>(FTy->getParamType(1)))
2013 setDoesNotCapture(F, 2);
2014 } else if (Name == "strxfrm") {
2015 if (FTy->getNumParams() != 3 ||
2016 !isa<PointerType>(FTy->getParamType(0)) ||
2017 !isa<PointerType>(FTy->getParamType(1)))
2020 setDoesNotCapture(F, 1);
2021 setDoesNotCapture(F, 2);
2022 } else if (Name == "strcmp" ||
2024 Name == "strncmp" ||
2025 Name ==" strcspn" ||
2026 Name == "strcoll" ||
2027 Name == "strcasecmp" ||
2028 Name == "strncasecmp") {
2029 if (FTy->getNumParams() < 2 ||
2030 !isa<PointerType>(FTy->getParamType(0)) ||
2031 !isa<PointerType>(FTy->getParamType(1)))
2033 setOnlyReadsMemory(F);
2035 setDoesNotCapture(F, 1);
2036 setDoesNotCapture(F, 2);
2037 } else if (Name == "strstr" ||
2038 Name == "strpbrk") {
2039 if (FTy->getNumParams() != 2 ||
2040 !isa<PointerType>(FTy->getParamType(1)))
2042 setOnlyReadsMemory(F);
2044 setDoesNotCapture(F, 2);
2045 } else if (Name == "strtok" ||
2046 Name == "strtok_r") {
2047 if (FTy->getNumParams() < 2 ||
2048 !isa<PointerType>(FTy->getParamType(1)))
2051 setDoesNotCapture(F, 2);
2052 } else if (Name == "scanf" ||
2054 Name == "setvbuf") {
2055 if (FTy->getNumParams() < 1 ||
2056 !isa<PointerType>(FTy->getParamType(0)))
2059 setDoesNotCapture(F, 1);
2060 } else if (Name == "strdup" ||
2061 Name == "strndup") {
2062 if (FTy->getNumParams() < 1 ||
2063 !isa<PointerType>(FTy->getReturnType()) ||
2064 !isa<PointerType>(FTy->getParamType(0)))
2067 setDoesNotAlias(F, 0);
2068 setDoesNotCapture(F, 1);
2069 } else if (Name == "stat" ||
2071 Name == "sprintf" ||
2072 Name == "statvfs") {
2073 if (FTy->getNumParams() < 2 ||
2074 !isa<PointerType>(FTy->getParamType(0)) ||
2075 !isa<PointerType>(FTy->getParamType(1)))
2078 setDoesNotCapture(F, 1);
2079 setDoesNotCapture(F, 2);
2080 } else if (Name == "snprintf") {
2081 if (FTy->getNumParams() != 3 ||
2082 !isa<PointerType>(FTy->getParamType(0)) ||
2083 !isa<PointerType>(FTy->getParamType(2)))
2086 setDoesNotCapture(F, 1);
2087 setDoesNotCapture(F, 3);
2088 } else if (Name == "setitimer") {
2089 if (FTy->getNumParams() != 3 ||
2090 !isa<PointerType>(FTy->getParamType(1)) ||
2091 !isa<PointerType>(FTy->getParamType(2)))
2094 setDoesNotCapture(F, 2);
2095 setDoesNotCapture(F, 3);
2096 } else if (Name == "system") {
2097 if (FTy->getNumParams() != 1 ||
2098 !isa<PointerType>(FTy->getParamType(0)))
2100 // May throw; "system" is a valid pthread cancellation point.
2101 setDoesNotCapture(F, 1);
2105 if (Name == "malloc") {
2106 if (FTy->getNumParams() != 1 ||
2107 !isa<PointerType>(FTy->getReturnType()))
2110 setDoesNotAlias(F, 0);
2111 } else if (Name == "memcmp") {
2112 if (FTy->getNumParams() != 3 ||
2113 !isa<PointerType>(FTy->getParamType(0)) ||
2114 !isa<PointerType>(FTy->getParamType(1)))
2116 setOnlyReadsMemory(F);
2118 setDoesNotCapture(F, 1);
2119 setDoesNotCapture(F, 2);
2120 } else if (Name == "memchr" ||
2121 Name == "memrchr") {
2122 if (FTy->getNumParams() != 3)
2124 setOnlyReadsMemory(F);
2126 } else if (Name == "modf" ||
2130 Name == "memccpy" ||
2131 Name == "memmove") {
2132 if (FTy->getNumParams() < 2 ||
2133 !isa<PointerType>(FTy->getParamType(1)))
2136 setDoesNotCapture(F, 2);
2137 } else if (Name == "memalign") {
2138 if (!isa<PointerType>(FTy->getReturnType()))
2140 setDoesNotAlias(F, 0);
2141 } else if (Name == "mkdir" ||
2143 if (FTy->getNumParams() == 0 ||
2144 !isa<PointerType>(FTy->getParamType(0)))
2147 setDoesNotCapture(F, 1);
2151 if (Name == "realloc") {
2152 if (FTy->getNumParams() != 2 ||
2153 !isa<PointerType>(FTy->getParamType(0)) ||
2154 !isa<PointerType>(FTy->getReturnType()))
2157 setDoesNotAlias(F, 0);
2158 setDoesNotCapture(F, 1);
2159 } else if (Name == "read") {
2160 if (FTy->getNumParams() != 3 ||
2161 !isa<PointerType>(FTy->getParamType(1)))
2163 // May throw; "read" is a valid pthread cancellation point.
2164 setDoesNotCapture(F, 2);
2165 } else if (Name == "rmdir" ||
2168 Name == "realpath") {
2169 if (FTy->getNumParams() < 1 ||
2170 !isa<PointerType>(FTy->getParamType(0)))
2173 setDoesNotCapture(F, 1);
2174 } else if (Name == "rename" ||
2175 Name == "readlink") {
2176 if (FTy->getNumParams() < 2 ||
2177 !isa<PointerType>(FTy->getParamType(0)) ||
2178 !isa<PointerType>(FTy->getParamType(1)))
2181 setDoesNotCapture(F, 1);
2182 setDoesNotCapture(F, 2);
2186 if (Name == "write") {
2187 if (FTy->getNumParams() != 3 ||
2188 !isa<PointerType>(FTy->getParamType(1)))
2190 // May throw; "write" is a valid pthread cancellation point.
2191 setDoesNotCapture(F, 2);
2195 if (Name == "bcopy") {
2196 if (FTy->getNumParams() != 3 ||
2197 !isa<PointerType>(FTy->getParamType(0)) ||
2198 !isa<PointerType>(FTy->getParamType(1)))
2201 setDoesNotCapture(F, 1);
2202 setDoesNotCapture(F, 2);
2203 } else if (Name == "bcmp") {
2204 if (FTy->getNumParams() != 3 ||
2205 !isa<PointerType>(FTy->getParamType(0)) ||
2206 !isa<PointerType>(FTy->getParamType(1)))
2209 setOnlyReadsMemory(F);
2210 setDoesNotCapture(F, 1);
2211 setDoesNotCapture(F, 2);
2212 } else if (Name == "bzero") {
2213 if (FTy->getNumParams() != 2 ||
2214 !isa<PointerType>(FTy->getParamType(0)))
2217 setDoesNotCapture(F, 1);
2221 if (Name == "calloc") {
2222 if (FTy->getNumParams() != 2 ||
2223 !isa<PointerType>(FTy->getReturnType()))
2226 setDoesNotAlias(F, 0);
2227 } else if (Name == "chmod" ||
2229 Name == "ctermid" ||
2230 Name == "clearerr" ||
2231 Name == "closedir") {
2232 if (FTy->getNumParams() == 0 ||
2233 !isa<PointerType>(FTy->getParamType(0)))
2236 setDoesNotCapture(F, 1);
2240 if (Name == "atoi" ||
2244 if (FTy->getNumParams() != 1 ||
2245 !isa<PointerType>(FTy->getParamType(0)))
2248 setOnlyReadsMemory(F);
2249 setDoesNotCapture(F, 1);
2250 } else if (Name == "access") {
2251 if (FTy->getNumParams() != 2 ||
2252 !isa<PointerType>(FTy->getParamType(0)))
2255 setDoesNotCapture(F, 1);
2259 if (Name == "fopen") {
2260 if (FTy->getNumParams() != 2 ||
2261 !isa<PointerType>(FTy->getReturnType()) ||
2262 !isa<PointerType>(FTy->getParamType(0)) ||
2263 !isa<PointerType>(FTy->getParamType(1)))
2266 setDoesNotAlias(F, 0);
2267 setDoesNotCapture(F, 1);
2268 setDoesNotCapture(F, 2);
2269 } else if (Name == "fdopen") {
2270 if (FTy->getNumParams() != 2 ||
2271 !isa<PointerType>(FTy->getReturnType()) ||
2272 !isa<PointerType>(FTy->getParamType(1)))
2275 setDoesNotAlias(F, 0);
2276 setDoesNotCapture(F, 2);
2277 } else if (Name == "feof" ||
2287 Name == "fsetpos" ||
2288 Name == "flockfile" ||
2289 Name == "funlockfile" ||
2290 Name == "ftrylockfile") {
2291 if (FTy->getNumParams() == 0 ||
2292 !isa<PointerType>(FTy->getParamType(0)))
2295 setDoesNotCapture(F, 1);
2296 } else if (Name == "ferror") {
2297 if (FTy->getNumParams() != 1 ||
2298 !isa<PointerType>(FTy->getParamType(0)))
2301 setDoesNotCapture(F, 1);
2302 setOnlyReadsMemory(F);
2303 } else if (Name == "fputc" ||
2308 Name == "fstatvfs") {
2309 if (FTy->getNumParams() != 2 ||
2310 !isa<PointerType>(FTy->getParamType(1)))
2313 setDoesNotCapture(F, 2);
2314 } else if (Name == "fgets") {
2315 if (FTy->getNumParams() != 3 ||
2316 !isa<PointerType>(FTy->getParamType(0)) ||
2317 !isa<PointerType>(FTy->getParamType(2)))
2320 setDoesNotCapture(F, 3);
2321 } else if (Name == "fread" ||
2323 if (FTy->getNumParams() != 4 ||
2324 !isa<PointerType>(FTy->getParamType(0)) ||
2325 !isa<PointerType>(FTy->getParamType(3)))
2328 setDoesNotCapture(F, 1);
2329 setDoesNotCapture(F, 4);
2330 } else if (Name == "fputs" ||
2332 Name == "fprintf" ||
2333 Name == "fgetpos") {
2334 if (FTy->getNumParams() < 2 ||
2335 !isa<PointerType>(FTy->getParamType(0)) ||
2336 !isa<PointerType>(FTy->getParamType(1)))
2339 setDoesNotCapture(F, 1);
2340 setDoesNotCapture(F, 2);
2344 if (Name == "getc" ||
2345 Name == "getlogin_r" ||
2346 Name == "getc_unlocked") {
2347 if (FTy->getNumParams() == 0 ||
2348 !isa<PointerType>(FTy->getParamType(0)))
2351 setDoesNotCapture(F, 1);
2352 } else if (Name == "getenv") {
2353 if (FTy->getNumParams() != 1 ||
2354 !isa<PointerType>(FTy->getParamType(0)))
2357 setOnlyReadsMemory(F);
2358 setDoesNotCapture(F, 1);
2359 } else if (Name == "gets" ||
2360 Name == "getchar") {
2362 } else if (Name == "getitimer") {
2363 if (FTy->getNumParams() != 2 ||
2364 !isa<PointerType>(FTy->getParamType(1)))
2367 setDoesNotCapture(F, 2);
2368 } else if (Name == "getpwnam") {
2369 if (FTy->getNumParams() != 1 ||
2370 !isa<PointerType>(FTy->getParamType(0)))
2373 setDoesNotCapture(F, 1);
2377 if (Name == "ungetc") {
2378 if (FTy->getNumParams() != 2 ||
2379 !isa<PointerType>(FTy->getParamType(1)))
2382 setDoesNotCapture(F, 2);
2383 } else if (Name == "uname" ||
2385 Name == "unsetenv") {
2386 if (FTy->getNumParams() != 1 ||
2387 !isa<PointerType>(FTy->getParamType(0)))
2390 setDoesNotCapture(F, 1);
2391 } else if (Name == "utime" ||
2393 if (FTy->getNumParams() != 2 ||
2394 !isa<PointerType>(FTy->getParamType(0)) ||
2395 !isa<PointerType>(FTy->getParamType(1)))
2398 setDoesNotCapture(F, 1);
2399 setDoesNotCapture(F, 2);
2403 if (Name == "putc") {
2404 if (FTy->getNumParams() != 2 ||
2405 !isa<PointerType>(FTy->getParamType(1)))
2408 setDoesNotCapture(F, 2);
2409 } else if (Name == "puts" ||
2412 if (FTy->getNumParams() != 1 ||
2413 !isa<PointerType>(FTy->getParamType(0)))
2416 setDoesNotCapture(F, 1);
2417 } else if (Name == "pread" ||
2419 if (FTy->getNumParams() != 4 ||
2420 !isa<PointerType>(FTy->getParamType(1)))
2422 // May throw; these are valid pthread cancellation points.
2423 setDoesNotCapture(F, 2);
2424 } else if (Name == "putchar") {
2426 } else if (Name == "popen") {
2427 if (FTy->getNumParams() != 2 ||
2428 !isa<PointerType>(FTy->getReturnType()) ||
2429 !isa<PointerType>(FTy->getParamType(0)) ||
2430 !isa<PointerType>(FTy->getParamType(1)))
2433 setDoesNotAlias(F, 0);
2434 setDoesNotCapture(F, 1);
2435 setDoesNotCapture(F, 2);
2436 } else if (Name == "pclose") {
2437 if (FTy->getNumParams() != 1 ||
2438 !isa<PointerType>(FTy->getParamType(0)))
2441 setDoesNotCapture(F, 1);
2445 if (Name == "vscanf") {
2446 if (FTy->getNumParams() != 2 ||
2447 !isa<PointerType>(FTy->getParamType(1)))
2450 setDoesNotCapture(F, 1);
2451 } else if (Name == "vsscanf" ||
2452 Name == "vfscanf") {
2453 if (FTy->getNumParams() != 3 ||
2454 !isa<PointerType>(FTy->getParamType(1)) ||
2455 !isa<PointerType>(FTy->getParamType(2)))
2458 setDoesNotCapture(F, 1);
2459 setDoesNotCapture(F, 2);
2460 } else if (Name == "valloc") {
2461 if (!isa<PointerType>(FTy->getReturnType()))
2464 setDoesNotAlias(F, 0);
2465 } else if (Name == "vprintf") {
2466 if (FTy->getNumParams() != 2 ||
2467 !isa<PointerType>(FTy->getParamType(0)))
2470 setDoesNotCapture(F, 1);
2471 } else if (Name == "vfprintf" ||
2472 Name == "vsprintf") {
2473 if (FTy->getNumParams() != 3 ||
2474 !isa<PointerType>(FTy->getParamType(0)) ||
2475 !isa<PointerType>(FTy->getParamType(1)))
2478 setDoesNotCapture(F, 1);
2479 setDoesNotCapture(F, 2);
2480 } else if (Name == "vsnprintf") {
2481 if (FTy->getNumParams() != 4 ||
2482 !isa<PointerType>(FTy->getParamType(0)) ||
2483 !isa<PointerType>(FTy->getParamType(2)))
2486 setDoesNotCapture(F, 1);
2487 setDoesNotCapture(F, 3);
2491 if (Name == "open") {
2492 if (FTy->getNumParams() < 2 ||
2493 !isa<PointerType>(FTy->getParamType(0)))
2495 // May throw; "open" is a valid pthread cancellation point.
2496 setDoesNotCapture(F, 1);
2497 } else if (Name == "opendir") {
2498 if (FTy->getNumParams() != 1 ||
2499 !isa<PointerType>(FTy->getReturnType()) ||
2500 !isa<PointerType>(FTy->getParamType(0)))
2503 setDoesNotAlias(F, 0);
2504 setDoesNotCapture(F, 1);
2508 if (Name == "tmpfile") {
2509 if (!isa<PointerType>(FTy->getReturnType()))
2512 setDoesNotAlias(F, 0);
2513 } else if (Name == "times") {
2514 if (FTy->getNumParams() != 1 ||
2515 !isa<PointerType>(FTy->getParamType(0)))
2518 setDoesNotCapture(F, 1);
2522 if (Name == "htonl" ||
2525 setDoesNotAccessMemory(F);
2529 if (Name == "ntohl" ||
2532 setDoesNotAccessMemory(F);
2536 if (Name == "lstat") {
2537 if (FTy->getNumParams() != 2 ||
2538 !isa<PointerType>(FTy->getParamType(0)) ||
2539 !isa<PointerType>(FTy->getParamType(1)))
2542 setDoesNotCapture(F, 1);
2543 setDoesNotCapture(F, 2);
2544 } else if (Name == "lchown") {
2545 if (FTy->getNumParams() != 3 ||
2546 !isa<PointerType>(FTy->getParamType(0)))
2549 setDoesNotCapture(F, 1);
2553 if (Name == "qsort") {
2554 if (FTy->getNumParams() != 4 ||
2555 !isa<PointerType>(FTy->getParamType(3)))
2557 // May throw; places call through function pointer.
2558 setDoesNotCapture(F, 4);
2562 if (Name == "__strdup" ||
2563 Name == "__strndup") {
2564 if (FTy->getNumParams() < 1 ||
2565 !isa<PointerType>(FTy->getReturnType()) ||
2566 !isa<PointerType>(FTy->getParamType(0)))
2569 setDoesNotAlias(F, 0);
2570 setDoesNotCapture(F, 1);
2571 } else if (Name == "__strtok_r") {
2572 if (FTy->getNumParams() != 3 ||
2573 !isa<PointerType>(FTy->getParamType(1)))
2576 setDoesNotCapture(F, 2);
2577 } else if (Name == "_IO_getc") {
2578 if (FTy->getNumParams() != 1 ||
2579 !isa<PointerType>(FTy->getParamType(0)))
2582 setDoesNotCapture(F, 1);
2583 } else if (Name == "_IO_putc") {
2584 if (FTy->getNumParams() != 2 ||
2585 !isa<PointerType>(FTy->getParamType(1)))
2588 setDoesNotCapture(F, 2);
2592 if (Name == "\1__isoc99_scanf") {
2593 if (FTy->getNumParams() < 1 ||
2594 !isa<PointerType>(FTy->getParamType(0)))
2597 setDoesNotCapture(F, 1);
2598 } else if (Name == "\1stat64" ||
2599 Name == "\1lstat64" ||
2600 Name == "\1statvfs64" ||
2601 Name == "\1__isoc99_sscanf") {
2602 if (FTy->getNumParams() < 1 ||
2603 !isa<PointerType>(FTy->getParamType(0)) ||
2604 !isa<PointerType>(FTy->getParamType(1)))
2607 setDoesNotCapture(F, 1);
2608 setDoesNotCapture(F, 2);
2609 } else if (Name == "\1fopen64") {
2610 if (FTy->getNumParams() != 2 ||
2611 !isa<PointerType>(FTy->getReturnType()) ||
2612 !isa<PointerType>(FTy->getParamType(0)) ||
2613 !isa<PointerType>(FTy->getParamType(1)))
2616 setDoesNotAlias(F, 0);
2617 setDoesNotCapture(F, 1);
2618 setDoesNotCapture(F, 2);
2619 } else if (Name == "\1fseeko64" ||
2620 Name == "\1ftello64") {
2621 if (FTy->getNumParams() == 0 ||
2622 !isa<PointerType>(FTy->getParamType(0)))
2625 setDoesNotCapture(F, 1);
2626 } else if (Name == "\1tmpfile64") {
2627 if (!isa<PointerType>(FTy->getReturnType()))
2630 setDoesNotAlias(F, 0);
2631 } else if (Name == "\1fstat64" ||
2632 Name == "\1fstatvfs64") {
2633 if (FTy->getNumParams() != 2 ||
2634 !isa<PointerType>(FTy->getParamType(1)))
2637 setDoesNotCapture(F, 2);
2638 } else if (Name == "\1open64") {
2639 if (FTy->getNumParams() < 2 ||
2640 !isa<PointerType>(FTy->getParamType(0)))
2642 // May throw; "open" is a valid pthread cancellation point.
2643 setDoesNotCapture(F, 1);
2652 // Additional cases that we need to add to this file:
2655 // * cbrt(expN(X)) -> expN(x/3)
2656 // * cbrt(sqrt(x)) -> pow(x,1/6)
2657 // * cbrt(sqrt(x)) -> pow(x,1/9)
2660 // * cos(-x) -> cos(x)
2663 // * exp(log(x)) -> x
2666 // * log(exp(x)) -> x
2667 // * log(x**y) -> y*log(x)
2668 // * log(exp(y)) -> y*log(e)
2669 // * log(exp2(y)) -> y*log(2)
2670 // * log(exp10(y)) -> y*log(10)
2671 // * log(sqrt(x)) -> 0.5*log(x)
2672 // * log(pow(x,y)) -> y*log(x)
2674 // lround, lroundf, lroundl:
2675 // * lround(cnst) -> cnst'
2678 // * pow(exp(x),y) -> exp(x*y)
2679 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2680 // * pow(pow(x,y),z)-> pow(x,y*z)
2683 // * puts("") -> putchar("\n")
2685 // round, roundf, roundl:
2686 // * round(cnst) -> cnst'
2689 // * signbit(cnst) -> cnst'
2690 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2692 // sqrt, sqrtf, sqrtl:
2693 // * sqrt(expN(x)) -> expN(x*0.5)
2694 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2695 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2698 // * stpcpy(str, "literal") ->
2699 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2701 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2702 // (if c is a constant integer and s is a constant string)
2703 // * strrchr(s1,0) -> strchr(s1,0)
2706 // * strpbrk(s,a) -> offset_in_for(s,a)
2707 // (if s and a are both constant strings)
2708 // * strpbrk(s,"") -> 0
2709 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2712 // * strspn(s,a) -> const_int (if both args are constant)
2713 // * strspn("",a) -> 0
2714 // * strspn(s,"") -> 0
2715 // * strcspn(s,a) -> const_int (if both args are constant)
2716 // * strcspn("",a) -> 0
2717 // * strcspn(s,"") -> strlen(a)
2720 // * tan(atan(x)) -> x
2722 // trunc, truncf, truncl:
2723 // * trunc(cnst) -> cnst'