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). For example, a call to the function "exit(3)" that
13 // occurs within the main() function can be transformed into a simple "return 3"
14 // instruction. Any optimization that takes this form (replace call to library
15 // function with simpler code that provides the same result) belongs in this
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "simplify-libcalls"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/IRBuilder.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Config/config.h"
38 STATISTIC(NumSimplified, "Number of library calls simplified");
39 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
41 //===----------------------------------------------------------------------===//
42 // Optimizer Base Class
43 //===----------------------------------------------------------------------===//
45 /// This class is the abstract base class for the set of optimizations that
46 /// corresponds to one library call.
48 class VISIBILITY_HIDDEN LibCallOptimization {
54 LibCallOptimization() { }
55 virtual ~LibCallOptimization() {}
57 /// CallOptimizer - This pure virtual method is implemented by base classes to
58 /// do various optimizations. If this returns null then no transformation was
59 /// performed. If it returns CI, then it transformed the call and CI is to be
60 /// deleted. If it returns something else, replace CI with the new value and
62 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
65 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
66 Caller = CI->getParent()->getParent();
68 if (CI->getCalledFunction())
69 Context = &CI->getCalledFunction()->getContext();
70 return CallOptimizer(CI->getCalledFunction(), CI, B);
73 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
74 Value *CastToCStr(Value *V, IRBuilder<> &B);
76 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
77 /// specified pointer. Ptr is required to be some pointer type, and the
78 /// return value has 'intptr_t' type.
79 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
81 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
82 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
83 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
84 unsigned Align, IRBuilder<> &B);
86 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
87 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
88 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
90 /// EmitMemCmp - Emit a call to the memcmp function.
91 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
93 /// EmitMemSet - Emit a call to the memset function
94 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
96 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
97 /// 'floor'). This function is known to take a single of type matching 'Op'
98 /// and returns one value with the same type. If 'Op' is a long double, 'l'
99 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
100 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
102 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
104 void EmitPutChar(Value *Char, IRBuilder<> &B);
106 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
108 void EmitPutS(Value *Str, IRBuilder<> &B);
110 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
111 /// an i32, and File is a pointer to FILE.
112 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
114 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
115 /// pointer and File is a pointer to FILE.
116 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
118 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
119 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
120 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
123 } // End anonymous namespace.
125 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
126 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
128 B.CreateBitCast(V, Context->getPointerTypeUnqual(Type::Int8Ty), "cstr");
131 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
132 /// specified pointer. This always returns an integer value of size intptr_t.
133 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
134 Module *M = Caller->getParent();
135 AttributeWithIndex AWI[2];
136 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
137 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
138 Attribute::NoUnwind);
140 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
142 Context->getPointerTypeUnqual(Type::Int8Ty),
144 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
145 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
146 CI->setCallingConv(F->getCallingConv());
151 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
152 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
153 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
154 unsigned Align, IRBuilder<> &B) {
155 Module *M = Caller->getParent();
156 Intrinsic::ID IID = Intrinsic::memcpy;
158 Tys[0] = Len->getType();
159 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
160 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
161 ConstantInt::get(Type::Int32Ty, Align));
164 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
165 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
166 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
167 Value *Len, IRBuilder<> &B) {
168 Module *M = Caller->getParent();
169 AttributeWithIndex AWI;
170 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
172 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
173 Context->getPointerTypeUnqual(Type::Int8Ty),
174 Context->getPointerTypeUnqual(Type::Int8Ty),
175 Type::Int32Ty, TD->getIntPtrType(),
177 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
179 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
180 CI->setCallingConv(F->getCallingConv());
185 /// EmitMemCmp - Emit a call to the memcmp function.
186 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
187 Value *Len, IRBuilder<> &B) {
188 Module *M = Caller->getParent();
189 AttributeWithIndex AWI[3];
190 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
191 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
192 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
193 Attribute::NoUnwind);
195 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
197 Context->getPointerTypeUnqual(Type::Int8Ty),
198 Context->getPointerTypeUnqual(Type::Int8Ty),
199 TD->getIntPtrType(), NULL);
200 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
203 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
204 CI->setCallingConv(F->getCallingConv());
209 /// EmitMemSet - Emit a call to the memset function
210 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
211 Value *Len, IRBuilder<> &B) {
212 Module *M = Caller->getParent();
213 Intrinsic::ID IID = Intrinsic::memset;
215 Tys[0] = Len->getType();
216 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
217 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
218 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
221 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
222 /// 'floor'). This function is known to take a single of type matching 'Op' and
223 /// returns one value with the same type. If 'Op' is a long double, 'l' is
224 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
225 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
228 if (Op->getType() != Type::DoubleTy) {
229 // If we need to add a suffix, copy into NameBuffer.
230 unsigned NameLen = strlen(Name);
231 assert(NameLen < sizeof(NameBuffer)-2);
232 memcpy(NameBuffer, Name, NameLen);
233 if (Op->getType() == Type::FloatTy)
234 NameBuffer[NameLen] = 'f'; // floorf
236 NameBuffer[NameLen] = 'l'; // floorl
237 NameBuffer[NameLen+1] = 0;
241 Module *M = Caller->getParent();
242 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
243 Op->getType(), NULL);
244 CallInst *CI = B.CreateCall(Callee, Op, Name);
246 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
247 CI->setCallingConv(F->getCallingConv());
252 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
254 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
255 Module *M = Caller->getParent();
256 Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
257 Type::Int32Ty, NULL);
258 CallInst *CI = B.CreateCall(PutChar,
259 B.CreateIntCast(Char, Type::Int32Ty, "chari"),
262 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
263 CI->setCallingConv(F->getCallingConv());
266 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
268 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
269 Module *M = Caller->getParent();
270 AttributeWithIndex AWI[2];
271 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
272 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
274 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
276 Context->getPointerTypeUnqual(Type::Int8Ty),
278 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
279 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
280 CI->setCallingConv(F->getCallingConv());
284 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
285 /// an integer and File is a pointer to FILE.
286 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
287 Module *M = Caller->getParent();
288 AttributeWithIndex AWI[2];
289 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
290 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
292 if (isa<PointerType>(File->getType()))
293 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
294 Type::Int32Ty, File->getType(), NULL);
296 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
297 File->getType(), NULL);
298 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
299 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
301 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
302 CI->setCallingConv(Fn->getCallingConv());
305 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
306 /// pointer and File is a pointer to FILE.
307 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
308 Module *M = Caller->getParent();
309 AttributeWithIndex AWI[3];
310 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
311 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
312 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
314 if (isa<PointerType>(File->getType()))
315 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
316 Context->getPointerTypeUnqual(Type::Int8Ty),
317 File->getType(), NULL);
319 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
320 Context->getPointerTypeUnqual(Type::Int8Ty),
321 File->getType(), NULL);
322 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
324 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
325 CI->setCallingConv(Fn->getCallingConv());
328 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
329 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
330 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
332 Module *M = Caller->getParent();
333 AttributeWithIndex AWI[3];
334 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
335 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
336 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
338 if (isa<PointerType>(File->getType()))
339 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
341 Context->getPointerTypeUnqual(Type::Int8Ty),
342 TD->getIntPtrType(), TD->getIntPtrType(),
343 File->getType(), NULL);
345 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
346 Context->getPointerTypeUnqual(Type::Int8Ty),
347 TD->getIntPtrType(), TD->getIntPtrType(),
348 File->getType(), NULL);
349 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
350 ConstantInt::get(TD->getIntPtrType(), 1), File);
352 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
353 CI->setCallingConv(Fn->getCallingConv());
356 //===----------------------------------------------------------------------===//
358 //===----------------------------------------------------------------------===//
360 /// GetStringLengthH - If we can compute the length of the string pointed to by
361 /// the specified pointer, return 'len+1'. If we can't, return 0.
362 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
363 // Look through noop bitcast instructions.
364 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
365 return GetStringLengthH(BCI->getOperand(0), PHIs);
367 // If this is a PHI node, there are two cases: either we have already seen it
369 if (PHINode *PN = dyn_cast<PHINode>(V)) {
370 if (!PHIs.insert(PN))
371 return ~0ULL; // already in the set.
373 // If it was new, see if all the input strings are the same length.
374 uint64_t LenSoFar = ~0ULL;
375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
376 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
377 if (Len == 0) return 0; // Unknown length -> unknown.
379 if (Len == ~0ULL) continue;
381 if (Len != LenSoFar && LenSoFar != ~0ULL)
382 return 0; // Disagree -> unknown.
386 // Success, all agree.
390 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
391 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
392 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
393 if (Len1 == 0) return 0;
394 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
395 if (Len2 == 0) return 0;
396 if (Len1 == ~0ULL) return Len2;
397 if (Len2 == ~0ULL) return Len1;
398 if (Len1 != Len2) return 0;
402 // If the value is not a GEP instruction nor a constant expression with a
403 // GEP instruction, then return unknown.
405 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
407 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
408 if (CE->getOpcode() != Instruction::GetElementPtr)
415 // Make sure the GEP has exactly three arguments.
416 if (GEP->getNumOperands() != 3)
419 // Check to make sure that the first operand of the GEP is an integer and
420 // has value 0 so that we are sure we're indexing into the initializer.
421 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
427 // If the second index isn't a ConstantInt, then this is a variable index
428 // into the array. If this occurs, we can't say anything meaningful about
430 uint64_t StartIdx = 0;
431 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
432 StartIdx = CI->getZExtValue();
436 // The GEP instruction, constant or instruction, must reference a global
437 // variable that is a constant and is initialized. The referenced constant
438 // initializer is the array that we'll use for optimization.
439 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
440 if (!GV || !GV->isConstant() || !GV->hasInitializer())
442 Constant *GlobalInit = GV->getInitializer();
444 // Handle the ConstantAggregateZero case, which is a degenerate case. The
445 // initializer is constant zero so the length of the string must be zero.
446 if (isa<ConstantAggregateZero>(GlobalInit))
447 return 1; // Len = 0 offset by 1.
449 // Must be a Constant Array
450 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
451 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
454 // Get the number of elements in the array
455 uint64_t NumElts = Array->getType()->getNumElements();
457 // Traverse the constant array from StartIdx (derived above) which is
458 // the place the GEP refers to in the array.
459 for (unsigned i = StartIdx; i != NumElts; ++i) {
460 Constant *Elt = Array->getOperand(i);
461 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
462 if (!CI) // This array isn't suitable, non-int initializer.
465 return i-StartIdx+1; // We found end of string, success!
468 return 0; // The array isn't null terminated, conservatively return 'unknown'.
471 /// GetStringLength - If we can compute the length of the string pointed to by
472 /// the specified pointer, return 'len+1'. If we can't, return 0.
473 static uint64_t GetStringLength(Value *V) {
474 if (!isa<PointerType>(V->getType())) return 0;
476 SmallPtrSet<PHINode*, 32> PHIs;
477 uint64_t Len = GetStringLengthH(V, PHIs);
478 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
479 // an empty string as a length.
480 return Len == ~0ULL ? 1 : Len;
483 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
484 /// value is equal or not-equal to zero.
485 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
486 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
488 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
489 if (IC->isEquality())
490 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
491 if (C->isNullValue())
493 // Unknown instruction.
499 //===----------------------------------------------------------------------===//
500 // Miscellaneous LibCall Optimizations
501 //===----------------------------------------------------------------------===//
504 //===---------------------------------------===//
505 // 'exit' Optimizations
507 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
508 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
509 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
510 // Verify we have a reasonable prototype for exit.
511 if (Callee->arg_size() == 0 || !CI->use_empty())
514 // Verify the caller is main, and that the result type of main matches the
515 // argument type of exit.
516 if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
517 Caller->getReturnType() != CI->getOperand(1)->getType())
520 TerminatorInst *OldTI = CI->getParent()->getTerminator();
522 // Create the return after the call.
523 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
525 // Drop all successor phi node entries.
526 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
527 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
529 // Erase all instructions from after our return instruction until the end of
531 BasicBlock::iterator FirstDead = RI; ++FirstDead;
532 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
537 //===----------------------------------------------------------------------===//
538 // String and Memory LibCall Optimizations
539 //===----------------------------------------------------------------------===//
541 //===---------------------------------------===//
542 // 'strcat' Optimizations
544 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
545 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
546 // Verify the "strcat" function prototype.
547 const FunctionType *FT = Callee->getFunctionType();
548 if (FT->getNumParams() != 2 ||
549 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
550 FT->getParamType(0) != FT->getReturnType() ||
551 FT->getParamType(1) != FT->getReturnType())
554 // Extract some information from the instruction
555 Value *Dst = CI->getOperand(1);
556 Value *Src = CI->getOperand(2);
558 // See if we can get the length of the input string.
559 uint64_t Len = GetStringLength(Src);
560 if (Len == 0) return 0;
561 --Len; // Unbias length.
563 // Handle the simple, do-nothing case: strcat(x, "") -> x
567 EmitStrLenMemCpy(Src, Dst, Len, B);
571 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
572 // We need to find the end of the destination string. That's where the
573 // memory is to be moved to. We just generate a call to strlen.
574 Value *DstLen = EmitStrLen(Dst, B);
576 // Now that we have the destination's length, we must index into the
577 // destination's pointer to get the actual memcpy destination (end of
578 // the string .. we're concatenating).
579 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
581 // We have enough information to now generate the memcpy call to do the
582 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
583 EmitMemCpy(CpyDst, Src,
584 ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
588 //===---------------------------------------===//
589 // 'strncat' Optimizations
591 struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
592 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
593 // Verify the "strncat" function prototype.
594 const FunctionType *FT = Callee->getFunctionType();
595 if (FT->getNumParams() != 3 ||
596 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
597 FT->getParamType(0) != FT->getReturnType() ||
598 FT->getParamType(1) != FT->getReturnType() ||
599 !isa<IntegerType>(FT->getParamType(2)))
602 // Extract some information from the instruction
603 Value *Dst = CI->getOperand(1);
604 Value *Src = CI->getOperand(2);
607 // We don't do anything if length is not constant
608 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
609 Len = LengthArg->getZExtValue();
613 // See if we can get the length of the input string.
614 uint64_t SrcLen = GetStringLength(Src);
615 if (SrcLen == 0) return 0;
616 --SrcLen; // Unbias length.
618 // Handle the simple, do-nothing cases:
619 // strncat(x, "", c) -> x
620 // strncat(x, c, 0) -> x
621 if (SrcLen == 0 || Len == 0) return Dst;
623 // We don't optimize this case
624 if (Len < SrcLen) return 0;
626 // strncat(x, s, c) -> strcat(x, s)
627 // s is constant so the strcat can be optimized further
628 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
633 //===---------------------------------------===//
634 // 'strchr' Optimizations
636 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
637 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
638 // Verify the "strchr" function prototype.
639 const FunctionType *FT = Callee->getFunctionType();
640 if (FT->getNumParams() != 2 ||
641 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
642 FT->getParamType(0) != FT->getReturnType())
645 Value *SrcStr = CI->getOperand(1);
647 // If the second operand is non-constant, see if we can compute the length
648 // of the input string and turn this into memchr.
649 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
651 uint64_t Len = GetStringLength(SrcStr);
652 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
655 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
656 ConstantInt::get(TD->getIntPtrType(), Len), B);
659 // Otherwise, the character is a constant, see if the first argument is
660 // a string literal. If so, we can constant fold.
662 if (!GetConstantStringInfo(SrcStr, Str))
665 // strchr can find the nul character.
667 char CharValue = CharC->getSExtValue();
669 // Compute the offset.
672 if (i == Str.size()) // Didn't find the char. strchr returns null.
673 return Context->getNullValue(CI->getType());
674 // Did we find our match?
675 if (Str[i] == CharValue)
680 // strchr(s+n,c) -> gep(s+n+i,c)
681 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
682 return B.CreateGEP(SrcStr, Idx, "strchr");
686 //===---------------------------------------===//
687 // 'strcmp' Optimizations
689 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
690 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
691 // Verify the "strcmp" function prototype.
692 const FunctionType *FT = Callee->getFunctionType();
693 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
694 FT->getParamType(0) != FT->getParamType(1) ||
695 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
698 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
699 if (Str1P == Str2P) // strcmp(x,x) -> 0
700 return ConstantInt::get(CI->getType(), 0);
702 std::string Str1, Str2;
703 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
704 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
706 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
707 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
709 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
710 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
712 // strcmp(x, y) -> cnst (if both x and y are constant strings)
713 if (HasStr1 && HasStr2)
714 return ConstantInt::get(CI->getType(),
715 strcmp(Str1.c_str(),Str2.c_str()));
717 // strcmp(P, "x") -> memcmp(P, "x", 2)
718 uint64_t Len1 = GetStringLength(Str1P);
719 uint64_t Len2 = GetStringLength(Str2P);
721 return EmitMemCmp(Str1P, Str2P,
722 ConstantInt::get(TD->getIntPtrType(),
723 std::min(Len1, Len2)), B);
730 //===---------------------------------------===//
731 // 'strncmp' Optimizations
733 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
734 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
735 // Verify the "strncmp" function prototype.
736 const FunctionType *FT = Callee->getFunctionType();
737 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
738 FT->getParamType(0) != FT->getParamType(1) ||
739 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
740 !isa<IntegerType>(FT->getParamType(2)))
743 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
744 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
745 return ConstantInt::get(CI->getType(), 0);
747 // Get the length argument if it is constant.
749 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
750 Length = LengthArg->getZExtValue();
754 if (Length == 0) // strncmp(x,y,0) -> 0
755 return ConstantInt::get(CI->getType(), 0);
757 std::string Str1, Str2;
758 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
759 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
761 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
762 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
764 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
765 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
767 // strncmp(x, y) -> cnst (if both x and y are constant strings)
768 if (HasStr1 && HasStr2)
769 return ConstantInt::get(CI->getType(),
770 strncmp(Str1.c_str(), Str2.c_str(), Length));
776 //===---------------------------------------===//
777 // 'strcpy' Optimizations
779 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
780 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
781 // Verify the "strcpy" function prototype.
782 const FunctionType *FT = Callee->getFunctionType();
783 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
784 FT->getParamType(0) != FT->getParamType(1) ||
785 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
788 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
789 if (Dst == Src) // strcpy(x,x) -> x
792 // See if we can get the length of the input string.
793 uint64_t Len = GetStringLength(Src);
794 if (Len == 0) return 0;
796 // We have enough information to now generate the memcpy call to do the
797 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
799 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
804 //===---------------------------------------===//
805 // 'strncpy' Optimizations
807 struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
808 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
809 const FunctionType *FT = Callee->getFunctionType();
810 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
811 FT->getParamType(0) != FT->getParamType(1) ||
812 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
813 !isa<IntegerType>(FT->getParamType(2)))
816 Value *Dst = CI->getOperand(1);
817 Value *Src = CI->getOperand(2);
818 Value *LenOp = CI->getOperand(3);
820 // See if we can get the length of the input string.
821 uint64_t SrcLen = GetStringLength(Src);
822 if (SrcLen == 0) return 0;
826 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
827 EmitMemSet(Dst, ConstantInt::get(Type::Int8Ty, '\0'), LenOp, B);
832 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
833 Len = LengthArg->getZExtValue();
837 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
839 // Let strncpy handle the zero padding
840 if (Len > SrcLen+1) return 0;
842 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
844 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
850 //===---------------------------------------===//
851 // 'strlen' Optimizations
853 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
854 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
855 const FunctionType *FT = Callee->getFunctionType();
856 if (FT->getNumParams() != 1 ||
857 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
858 !isa<IntegerType>(FT->getReturnType()))
861 Value *Src = CI->getOperand(1);
863 // Constant folding: strlen("xyz") -> 3
864 if (uint64_t Len = GetStringLength(Src))
865 return ConstantInt::get(CI->getType(), Len-1);
867 // Handle strlen(p) != 0.
868 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
870 // strlen(x) != 0 --> *x != 0
871 // strlen(x) == 0 --> *x == 0
872 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
876 //===---------------------------------------===//
877 // 'strto*' Optimizations
879 struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
880 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
881 const FunctionType *FT = Callee->getFunctionType();
882 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
883 !isa<PointerType>(FT->getParamType(0)) ||
884 !isa<PointerType>(FT->getParamType(1)))
887 Value *EndPtr = CI->getOperand(2);
888 if (isa<ConstantPointerNull>(EndPtr)) {
889 CI->setOnlyReadsMemory();
890 CI->addAttribute(1, Attribute::NoCapture);
898 //===---------------------------------------===//
899 // 'memcmp' Optimizations
901 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
902 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
903 const FunctionType *FT = Callee->getFunctionType();
904 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
905 !isa<PointerType>(FT->getParamType(1)) ||
906 FT->getReturnType() != Type::Int32Ty)
909 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
911 if (LHS == RHS) // memcmp(s,s,x) -> 0
912 return Context->getNullValue(CI->getType());
914 // Make sure we have a constant length.
915 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
917 uint64_t Len = LenC->getZExtValue();
919 if (Len == 0) // memcmp(s1,s2,0) -> 0
920 return Context->getNullValue(CI->getType());
922 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
923 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
924 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
925 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
928 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
929 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
930 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
931 const Type *PTy = Context->getPointerTypeUnqual(Len == 2 ?
932 Type::Int16Ty : Type::Int32Ty);
933 LHS = B.CreateBitCast(LHS, PTy, "tmp");
934 RHS = B.CreateBitCast(RHS, PTy, "tmp");
935 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
936 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
937 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
938 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
945 //===---------------------------------------===//
946 // 'memcpy' Optimizations
948 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
949 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
950 const FunctionType *FT = Callee->getFunctionType();
951 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
952 !isa<PointerType>(FT->getParamType(0)) ||
953 !isa<PointerType>(FT->getParamType(1)) ||
954 FT->getParamType(2) != TD->getIntPtrType())
957 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
958 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
959 return CI->getOperand(1);
963 //===---------------------------------------===//
964 // 'memmove' Optimizations
966 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
967 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
968 const FunctionType *FT = Callee->getFunctionType();
969 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
970 !isa<PointerType>(FT->getParamType(0)) ||
971 !isa<PointerType>(FT->getParamType(1)) ||
972 FT->getParamType(2) != TD->getIntPtrType())
975 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
976 Module *M = Caller->getParent();
977 Intrinsic::ID IID = Intrinsic::memmove;
979 Tys[0] = TD->getIntPtrType();
980 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
981 Value *Dst = CastToCStr(CI->getOperand(1), B);
982 Value *Src = CastToCStr(CI->getOperand(2), B);
983 Value *Size = CI->getOperand(3);
984 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
985 B.CreateCall4(MemMove, Dst, Src, Size, Align);
986 return CI->getOperand(1);
990 //===---------------------------------------===//
991 // 'memset' Optimizations
993 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
994 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
995 const FunctionType *FT = Callee->getFunctionType();
996 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
997 !isa<PointerType>(FT->getParamType(0)) ||
998 !isa<IntegerType>(FT->getParamType(1)) ||
999 FT->getParamType(2) != TD->getIntPtrType())
1002 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1003 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::Int8Ty, false);
1004 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1005 return CI->getOperand(1);
1009 //===----------------------------------------------------------------------===//
1010 // Math Library Optimizations
1011 //===----------------------------------------------------------------------===//
1013 //===---------------------------------------===//
1014 // 'pow*' Optimizations
1016 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
1017 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1018 const FunctionType *FT = Callee->getFunctionType();
1019 // Just make sure this has 2 arguments of the same FP type, which match the
1021 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1022 FT->getParamType(0) != FT->getParamType(1) ||
1023 !FT->getParamType(0)->isFloatingPoint())
1026 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1027 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1028 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1030 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1031 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1034 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1035 if (Op2C == 0) return 0;
1037 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1038 return Context->getConstantFP(CI->getType(), 1.0);
1040 if (Op2C->isExactlyValue(0.5)) {
1041 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1042 // 'unsafe' math optimizations are allowed.
1043 // x pow(x, 0.5) sqrt(x)
1044 // ---------------------------------------------
1048 // pow(x, 0.5) -> sqrt(x)
1049 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1053 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1055 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1056 return B.CreateFMul(Op1, Op1, "pow2");
1057 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1058 return B.CreateFDiv(Context->getConstantFP(CI->getType(), 1.0),
1064 //===---------------------------------------===//
1065 // 'exp2' Optimizations
1067 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
1068 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1069 const FunctionType *FT = Callee->getFunctionType();
1070 // Just make sure this has 1 argument of FP type, which matches the
1072 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1073 !FT->getParamType(0)->isFloatingPoint())
1076 Value *Op = CI->getOperand(1);
1077 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1078 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1079 Value *LdExpArg = 0;
1080 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1081 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1082 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1083 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1084 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1085 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1090 if (Op->getType() == Type::FloatTy)
1092 else if (Op->getType() == Type::DoubleTy)
1097 Constant *One = Context->getConstantFP(APFloat(1.0f));
1098 if (Op->getType() != Type::FloatTy)
1099 One = Context->getConstantExprFPExtend(One, Op->getType());
1101 Module *M = Caller->getParent();
1102 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1103 Op->getType(), Type::Int32Ty,NULL);
1104 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1105 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1106 CI->setCallingConv(F->getCallingConv());
1114 //===---------------------------------------===//
1115 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1117 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
1118 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1119 const FunctionType *FT = Callee->getFunctionType();
1120 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1121 FT->getParamType(0) != Type::DoubleTy)
1124 // If this is something like 'floor((double)floatval)', convert to floorf.
1125 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1126 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1129 // floor((double)floatval) -> (double)floorf(floatval)
1130 Value *V = Cast->getOperand(0);
1131 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
1132 return B.CreateFPExt(V, Type::DoubleTy);
1136 //===----------------------------------------------------------------------===//
1137 // Integer Optimizations
1138 //===----------------------------------------------------------------------===//
1140 //===---------------------------------------===//
1141 // 'ffs*' Optimizations
1143 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
1144 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1145 const FunctionType *FT = Callee->getFunctionType();
1146 // Just make sure this has 2 arguments of the same FP type, which match the
1148 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1149 !isa<IntegerType>(FT->getParamType(0)))
1152 Value *Op = CI->getOperand(1);
1155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1156 if (CI->getValue() == 0) // ffs(0) -> 0.
1157 return Context->getNullValue(CI->getType());
1158 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
1159 CI->getValue().countTrailingZeros()+1);
1162 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1163 const Type *ArgType = Op->getType();
1164 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1165 Intrinsic::cttz, &ArgType, 1);
1166 Value *V = B.CreateCall(F, Op, "cttz");
1167 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1168 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1170 Value *Cond = B.CreateICmpNE(Op, Context->getNullValue(ArgType), "tmp");
1171 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
1175 //===---------------------------------------===//
1176 // 'isdigit' Optimizations
1178 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
1179 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1180 const FunctionType *FT = Callee->getFunctionType();
1181 // We require integer(i32)
1182 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1183 FT->getParamType(0) != Type::Int32Ty)
1186 // isdigit(c) -> (c-'0') <u 10
1187 Value *Op = CI->getOperand(1);
1188 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'),
1190 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10),
1192 return B.CreateZExt(Op, CI->getType());
1196 //===---------------------------------------===//
1197 // 'isascii' Optimizations
1199 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
1200 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1201 const FunctionType *FT = Callee->getFunctionType();
1202 // We require integer(i32)
1203 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1204 FT->getParamType(0) != Type::Int32Ty)
1207 // isascii(c) -> c <u 128
1208 Value *Op = CI->getOperand(1);
1209 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128),
1211 return B.CreateZExt(Op, CI->getType());
1215 //===---------------------------------------===//
1216 // 'abs', 'labs', 'llabs' Optimizations
1218 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
1219 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1220 const FunctionType *FT = Callee->getFunctionType();
1221 // We require integer(integer) where the types agree.
1222 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1223 FT->getParamType(0) != FT->getReturnType())
1226 // abs(x) -> x >s -1 ? x : -x
1227 Value *Op = CI->getOperand(1);
1228 Value *Pos = B.CreateICmpSGT(Op,
1229 Context->getAllOnesValue(Op->getType()),
1231 Value *Neg = B.CreateNeg(Op, "neg");
1232 return B.CreateSelect(Pos, Op, Neg);
1237 //===---------------------------------------===//
1238 // 'toascii' Optimizations
1240 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
1241 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1242 const FunctionType *FT = Callee->getFunctionType();
1243 // We require i32(i32)
1244 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1245 FT->getParamType(0) != Type::Int32Ty)
1248 // isascii(c) -> c & 0x7f
1249 return B.CreateAnd(CI->getOperand(1),
1250 ConstantInt::get(CI->getType(),0x7F));
1254 //===----------------------------------------------------------------------===//
1255 // Formatting and IO Optimizations
1256 //===----------------------------------------------------------------------===//
1258 //===---------------------------------------===//
1259 // 'printf' Optimizations
1261 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1262 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1263 // Require one fixed pointer argument and an integer/void result.
1264 const FunctionType *FT = Callee->getFunctionType();
1265 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1266 !(isa<IntegerType>(FT->getReturnType()) ||
1267 FT->getReturnType() == Type::VoidTy))
1270 // Check for a fixed format string.
1271 std::string FormatStr;
1272 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1275 // Empty format string -> noop.
1276 if (FormatStr.empty()) // Tolerate printf's declared void.
1277 return CI->use_empty() ? (Value*)CI :
1278 ConstantInt::get(CI->getType(), 0);
1280 // printf("x") -> putchar('x'), even for '%'.
1281 if (FormatStr.size() == 1) {
1282 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1283 return CI->use_empty() ? (Value*)CI :
1284 ConstantInt::get(CI->getType(), 1);
1287 // printf("foo\n") --> puts("foo")
1288 if (FormatStr[FormatStr.size()-1] == '\n' &&
1289 FormatStr.find('%') == std::string::npos) { // no format characters.
1290 // Create a string literal with no \n on it. We expect the constant merge
1291 // pass to be run after this pass, to merge duplicate strings.
1292 FormatStr.erase(FormatStr.end()-1);
1293 Constant *C = Context->getConstantArray(FormatStr, true);
1294 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1295 GlobalVariable::InternalLinkage, C, "str");
1297 return CI->use_empty() ? (Value*)CI :
1298 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1301 // Optimize specific format strings.
1302 // printf("%c", chr) --> putchar(*(i8*)dst)
1303 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1304 isa<IntegerType>(CI->getOperand(2)->getType())) {
1305 EmitPutChar(CI->getOperand(2), B);
1306 return CI->use_empty() ? (Value*)CI :
1307 ConstantInt::get(CI->getType(), 1);
1310 // printf("%s\n", str) --> puts(str)
1311 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1312 isa<PointerType>(CI->getOperand(2)->getType()) &&
1314 EmitPutS(CI->getOperand(2), B);
1321 //===---------------------------------------===//
1322 // 'sprintf' Optimizations
1324 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1325 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1326 // Require two fixed pointer arguments and an integer result.
1327 const FunctionType *FT = Callee->getFunctionType();
1328 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1329 !isa<PointerType>(FT->getParamType(1)) ||
1330 !isa<IntegerType>(FT->getReturnType()))
1333 // Check for a fixed format string.
1334 std::string FormatStr;
1335 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1338 // If we just have a format string (nothing else crazy) transform it.
1339 if (CI->getNumOperands() == 3) {
1340 // Make sure there's no % in the constant array. We could try to handle
1341 // %% -> % in the future if we cared.
1342 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1343 if (FormatStr[i] == '%')
1344 return 0; // we found a format specifier, bail out.
1346 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1347 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1348 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1349 return ConstantInt::get(CI->getType(), FormatStr.size());
1352 // The remaining optimizations require the format string to be "%s" or "%c"
1353 // and have an extra operand.
1354 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1357 // Decode the second character of the format string.
1358 if (FormatStr[1] == 'c') {
1359 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1360 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1361 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1362 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1363 B.CreateStore(V, Ptr);
1364 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1365 B.CreateStore(Context->getNullValue(Type::Int8Ty), Ptr);
1367 return ConstantInt::get(CI->getType(), 1);
1370 if (FormatStr[1] == 's') {
1371 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1372 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1374 Value *Len = EmitStrLen(CI->getOperand(3), B);
1375 Value *IncLen = B.CreateAdd(Len,
1376 ConstantInt::get(Len->getType(), 1),
1378 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1380 // The sprintf result is the unincremented number of bytes in the string.
1381 return B.CreateIntCast(Len, CI->getType(), false);
1387 //===---------------------------------------===//
1388 // 'fwrite' Optimizations
1390 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1391 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1392 // Require a pointer, an integer, an integer, a pointer, returning integer.
1393 const FunctionType *FT = Callee->getFunctionType();
1394 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1395 !isa<IntegerType>(FT->getParamType(1)) ||
1396 !isa<IntegerType>(FT->getParamType(2)) ||
1397 !isa<PointerType>(FT->getParamType(3)) ||
1398 !isa<IntegerType>(FT->getReturnType()))
1401 // Get the element size and count.
1402 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1403 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1404 if (!SizeC || !CountC) return 0;
1405 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1407 // If this is writing zero records, remove the call (it's a noop).
1409 return ConstantInt::get(CI->getType(), 0);
1411 // If this is writing one byte, turn it into fputc.
1412 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1413 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1414 EmitFPutC(Char, CI->getOperand(4), B);
1415 return ConstantInt::get(CI->getType(), 1);
1422 //===---------------------------------------===//
1423 // 'fputs' Optimizations
1425 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1426 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1427 // Require two pointers. Also, we can't optimize if return value is used.
1428 const FunctionType *FT = Callee->getFunctionType();
1429 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1430 !isa<PointerType>(FT->getParamType(1)) ||
1434 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1435 uint64_t Len = GetStringLength(CI->getOperand(1));
1437 EmitFWrite(CI->getOperand(1),
1438 ConstantInt::get(TD->getIntPtrType(), Len-1),
1439 CI->getOperand(2), B);
1440 return CI; // Known to have no uses (see above).
1444 //===---------------------------------------===//
1445 // 'fprintf' Optimizations
1447 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1448 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1449 // Require two fixed paramters as pointers and integer result.
1450 const FunctionType *FT = Callee->getFunctionType();
1451 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1452 !isa<PointerType>(FT->getParamType(1)) ||
1453 !isa<IntegerType>(FT->getReturnType()))
1456 // All the optimizations depend on the format string.
1457 std::string FormatStr;
1458 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1461 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1462 if (CI->getNumOperands() == 3) {
1463 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1464 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1465 return 0; // We found a format specifier.
1467 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1469 CI->getOperand(1), B);
1470 return ConstantInt::get(CI->getType(), FormatStr.size());
1473 // The remaining optimizations require the format string to be "%s" or "%c"
1474 // and have an extra operand.
1475 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1478 // Decode the second character of the format string.
1479 if (FormatStr[1] == 'c') {
1480 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1481 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1482 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1483 return ConstantInt::get(CI->getType(), 1);
1486 if (FormatStr[1] == 's') {
1487 // fprintf(F, "%s", str) -> fputs(str, F)
1488 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1490 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1497 } // end anonymous namespace.
1499 //===----------------------------------------------------------------------===//
1500 // SimplifyLibCalls Pass Implementation
1501 //===----------------------------------------------------------------------===//
1504 /// This pass optimizes well known library functions from libc and libm.
1506 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1507 StringMap<LibCallOptimization*> Optimizations;
1508 // Miscellaneous LibCall Optimizations
1510 // String and Memory LibCall Optimizations
1511 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1512 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1513 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1515 // Math Library Optimizations
1516 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1517 // Integer Optimizations
1518 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1520 // Formatting and IO Optimizations
1521 SPrintFOpt SPrintF; PrintFOpt PrintF;
1522 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1524 bool Modified; // This is only used by doInitialization.
1526 static char ID; // Pass identification
1527 SimplifyLibCalls() : FunctionPass(&ID) {}
1529 void InitOptimizations();
1530 bool runOnFunction(Function &F);
1532 void setDoesNotAccessMemory(Function &F);
1533 void setOnlyReadsMemory(Function &F);
1534 void setDoesNotThrow(Function &F);
1535 void setDoesNotCapture(Function &F, unsigned n);
1536 void setDoesNotAlias(Function &F, unsigned n);
1537 bool doInitialization(Module &M);
1539 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1540 AU.addRequired<TargetData>();
1543 char SimplifyLibCalls::ID = 0;
1544 } // end anonymous namespace.
1546 static RegisterPass<SimplifyLibCalls>
1547 X("simplify-libcalls", "Simplify well-known library calls");
1549 // Public interface to the Simplify LibCalls pass.
1550 FunctionPass *llvm::createSimplifyLibCallsPass() {
1551 return new SimplifyLibCalls();
1554 /// Optimizations - Populate the Optimizations map with all the optimizations
1556 void SimplifyLibCalls::InitOptimizations() {
1557 // Miscellaneous LibCall Optimizations
1558 Optimizations["exit"] = &Exit;
1560 // String and Memory LibCall Optimizations
1561 Optimizations["strcat"] = &StrCat;
1562 Optimizations["strncat"] = &StrNCat;
1563 Optimizations["strchr"] = &StrChr;
1564 Optimizations["strcmp"] = &StrCmp;
1565 Optimizations["strncmp"] = &StrNCmp;
1566 Optimizations["strcpy"] = &StrCpy;
1567 Optimizations["strncpy"] = &StrNCpy;
1568 Optimizations["strlen"] = &StrLen;
1569 Optimizations["strtol"] = &StrTo;
1570 Optimizations["strtod"] = &StrTo;
1571 Optimizations["strtof"] = &StrTo;
1572 Optimizations["strtoul"] = &StrTo;
1573 Optimizations["strtoll"] = &StrTo;
1574 Optimizations["strtold"] = &StrTo;
1575 Optimizations["strtoull"] = &StrTo;
1576 Optimizations["memcmp"] = &MemCmp;
1577 Optimizations["memcpy"] = &MemCpy;
1578 Optimizations["memmove"] = &MemMove;
1579 Optimizations["memset"] = &MemSet;
1581 // Math Library Optimizations
1582 Optimizations["powf"] = &Pow;
1583 Optimizations["pow"] = &Pow;
1584 Optimizations["powl"] = &Pow;
1585 Optimizations["llvm.pow.f32"] = &Pow;
1586 Optimizations["llvm.pow.f64"] = &Pow;
1587 Optimizations["llvm.pow.f80"] = &Pow;
1588 Optimizations["llvm.pow.f128"] = &Pow;
1589 Optimizations["llvm.pow.ppcf128"] = &Pow;
1590 Optimizations["exp2l"] = &Exp2;
1591 Optimizations["exp2"] = &Exp2;
1592 Optimizations["exp2f"] = &Exp2;
1593 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1594 Optimizations["llvm.exp2.f128"] = &Exp2;
1595 Optimizations["llvm.exp2.f80"] = &Exp2;
1596 Optimizations["llvm.exp2.f64"] = &Exp2;
1597 Optimizations["llvm.exp2.f32"] = &Exp2;
1600 Optimizations["floor"] = &UnaryDoubleFP;
1603 Optimizations["ceil"] = &UnaryDoubleFP;
1606 Optimizations["round"] = &UnaryDoubleFP;
1609 Optimizations["rint"] = &UnaryDoubleFP;
1611 #ifdef HAVE_NEARBYINTF
1612 Optimizations["nearbyint"] = &UnaryDoubleFP;
1615 // Integer Optimizations
1616 Optimizations["ffs"] = &FFS;
1617 Optimizations["ffsl"] = &FFS;
1618 Optimizations["ffsll"] = &FFS;
1619 Optimizations["abs"] = &Abs;
1620 Optimizations["labs"] = &Abs;
1621 Optimizations["llabs"] = &Abs;
1622 Optimizations["isdigit"] = &IsDigit;
1623 Optimizations["isascii"] = &IsAscii;
1624 Optimizations["toascii"] = &ToAscii;
1626 // Formatting and IO Optimizations
1627 Optimizations["sprintf"] = &SPrintF;
1628 Optimizations["printf"] = &PrintF;
1629 Optimizations["fwrite"] = &FWrite;
1630 Optimizations["fputs"] = &FPuts;
1631 Optimizations["fprintf"] = &FPrintF;
1635 /// runOnFunction - Top level algorithm.
1637 bool SimplifyLibCalls::runOnFunction(Function &F) {
1638 if (Optimizations.empty())
1639 InitOptimizations();
1641 const TargetData &TD = getAnalysis<TargetData>();
1643 IRBuilder<> Builder(F.getContext());
1645 bool Changed = false;
1646 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1647 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1648 // Ignore non-calls.
1649 CallInst *CI = dyn_cast<CallInst>(I++);
1652 // Ignore indirect calls and calls to non-external functions.
1653 Function *Callee = CI->getCalledFunction();
1654 if (Callee == 0 || !Callee->isDeclaration() ||
1655 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1658 // Ignore unknown calls.
1659 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1662 // Set the builder to the instruction after the call.
1663 Builder.SetInsertPoint(BB, I);
1665 // Try to optimize this call.
1666 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1667 if (Result == 0) continue;
1669 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1670 errs() << " into: " << *Result << "\n");
1672 // Something changed!
1676 // Inspect the instruction after the call (which was potentially just
1680 if (CI != Result && !CI->use_empty()) {
1681 CI->replaceAllUsesWith(Result);
1682 if (!Result->hasName())
1683 Result->takeName(CI);
1685 CI->eraseFromParent();
1691 // Utility methods for doInitialization.
1693 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1694 if (!F.doesNotAccessMemory()) {
1695 F.setDoesNotAccessMemory();
1700 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1701 if (!F.onlyReadsMemory()) {
1702 F.setOnlyReadsMemory();
1707 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1708 if (!F.doesNotThrow()) {
1709 F.setDoesNotThrow();
1714 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1715 if (!F.doesNotCapture(n)) {
1716 F.setDoesNotCapture(n);
1721 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1722 if (!F.doesNotAlias(n)) {
1723 F.setDoesNotAlias(n);
1729 /// doInitialization - Add attributes to well-known functions.
1731 bool SimplifyLibCalls::doInitialization(Module &M) {
1733 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1735 if (!F.isDeclaration())
1741 const FunctionType *FTy = F.getFunctionType();
1743 StringRef Name = F.getName();
1746 if (Name == "strlen") {
1747 if (FTy->getNumParams() != 1 ||
1748 !isa<PointerType>(FTy->getParamType(0)))
1750 setOnlyReadsMemory(F);
1752 setDoesNotCapture(F, 1);
1753 } else if (Name == "strcpy" ||
1759 Name == "strtoul" ||
1760 Name == "strtoll" ||
1761 Name == "strtold" ||
1762 Name == "strncat" ||
1763 Name == "strncpy" ||
1764 Name == "strtoull") {
1765 if (FTy->getNumParams() < 2 ||
1766 !isa<PointerType>(FTy->getParamType(1)))
1769 setDoesNotCapture(F, 2);
1770 } else if (Name == "strxfrm") {
1771 if (FTy->getNumParams() != 3 ||
1772 !isa<PointerType>(FTy->getParamType(0)) ||
1773 !isa<PointerType>(FTy->getParamType(1)))
1776 setDoesNotCapture(F, 1);
1777 setDoesNotCapture(F, 2);
1778 } else if (Name == "strcmp" ||
1780 Name == "strncmp" ||
1781 Name ==" strcspn" ||
1782 Name == "strcoll" ||
1783 Name == "strcasecmp" ||
1784 Name == "strncasecmp") {
1785 if (FTy->getNumParams() < 2 ||
1786 !isa<PointerType>(FTy->getParamType(0)) ||
1787 !isa<PointerType>(FTy->getParamType(1)))
1789 setOnlyReadsMemory(F);
1791 setDoesNotCapture(F, 1);
1792 setDoesNotCapture(F, 2);
1793 } else if (Name == "strstr" ||
1794 Name == "strpbrk") {
1795 if (FTy->getNumParams() != 2 ||
1796 !isa<PointerType>(FTy->getParamType(1)))
1798 setOnlyReadsMemory(F);
1800 setDoesNotCapture(F, 2);
1801 } else if (Name == "strtok" ||
1802 Name == "strtok_r") {
1803 if (FTy->getNumParams() < 2 ||
1804 !isa<PointerType>(FTy->getParamType(1)))
1807 setDoesNotCapture(F, 2);
1808 } else if (Name == "scanf" ||
1810 Name == "setvbuf") {
1811 if (FTy->getNumParams() < 1 ||
1812 !isa<PointerType>(FTy->getParamType(0)))
1815 setDoesNotCapture(F, 1);
1816 } else if (Name == "strdup" ||
1817 Name == "strndup") {
1818 if (FTy->getNumParams() < 1 ||
1819 !isa<PointerType>(FTy->getReturnType()) ||
1820 !isa<PointerType>(FTy->getParamType(0)))
1823 setDoesNotAlias(F, 0);
1824 setDoesNotCapture(F, 1);
1825 } else if (Name == "stat" ||
1827 Name == "sprintf" ||
1828 Name == "statvfs") {
1829 if (FTy->getNumParams() < 2 ||
1830 !isa<PointerType>(FTy->getParamType(0)) ||
1831 !isa<PointerType>(FTy->getParamType(1)))
1834 setDoesNotCapture(F, 1);
1835 setDoesNotCapture(F, 2);
1836 } else if (Name == "snprintf") {
1837 if (FTy->getNumParams() != 3 ||
1838 !isa<PointerType>(FTy->getParamType(0)) ||
1839 !isa<PointerType>(FTy->getParamType(2)))
1842 setDoesNotCapture(F, 1);
1843 setDoesNotCapture(F, 3);
1844 } else if (Name == "setitimer") {
1845 if (FTy->getNumParams() != 3 ||
1846 !isa<PointerType>(FTy->getParamType(1)) ||
1847 !isa<PointerType>(FTy->getParamType(2)))
1850 setDoesNotCapture(F, 2);
1851 setDoesNotCapture(F, 3);
1852 } else if (Name == "system") {
1853 if (FTy->getNumParams() != 1 ||
1854 !isa<PointerType>(FTy->getParamType(0)))
1856 // May throw; "system" is a valid pthread cancellation point.
1857 setDoesNotCapture(F, 1);
1861 if (Name == "memcmp") {
1862 if (FTy->getNumParams() != 3 ||
1863 !isa<PointerType>(FTy->getParamType(0)) ||
1864 !isa<PointerType>(FTy->getParamType(1)))
1866 setOnlyReadsMemory(F);
1868 setDoesNotCapture(F, 1);
1869 setDoesNotCapture(F, 2);
1870 } else if (Name == "memchr" ||
1871 Name == "memrchr") {
1872 if (FTy->getNumParams() != 3)
1874 setOnlyReadsMemory(F);
1876 } else if (Name == "modf" ||
1880 Name == "memccpy" ||
1881 Name == "memmove") {
1882 if (FTy->getNumParams() < 2 ||
1883 !isa<PointerType>(FTy->getParamType(1)))
1886 setDoesNotCapture(F, 2);
1887 } else if (Name == "memalign") {
1888 if (!isa<PointerType>(FTy->getReturnType()))
1890 setDoesNotAlias(F, 0);
1891 } else if (Name == "mkdir" ||
1893 if (FTy->getNumParams() == 0 ||
1894 !isa<PointerType>(FTy->getParamType(0)))
1897 setDoesNotCapture(F, 1);
1901 if (Name == "realloc") {
1902 if (FTy->getNumParams() != 2 ||
1903 !isa<PointerType>(FTy->getParamType(0)) ||
1904 !isa<PointerType>(FTy->getReturnType()))
1907 setDoesNotAlias(F, 0);
1908 setDoesNotCapture(F, 1);
1909 } else if (Name == "read") {
1910 if (FTy->getNumParams() != 3 ||
1911 !isa<PointerType>(FTy->getParamType(1)))
1913 // May throw; "read" is a valid pthread cancellation point.
1914 setDoesNotCapture(F, 2);
1915 } else if (Name == "rmdir" ||
1918 Name == "realpath") {
1919 if (FTy->getNumParams() < 1 ||
1920 !isa<PointerType>(FTy->getParamType(0)))
1923 setDoesNotCapture(F, 1);
1924 } else if (Name == "rename" ||
1925 Name == "readlink") {
1926 if (FTy->getNumParams() < 2 ||
1927 !isa<PointerType>(FTy->getParamType(0)) ||
1928 !isa<PointerType>(FTy->getParamType(1)))
1931 setDoesNotCapture(F, 1);
1932 setDoesNotCapture(F, 2);
1936 if (Name == "write") {
1937 if (FTy->getNumParams() != 3 ||
1938 !isa<PointerType>(FTy->getParamType(1)))
1940 // May throw; "write" is a valid pthread cancellation point.
1941 setDoesNotCapture(F, 2);
1945 if (Name == "bcopy") {
1946 if (FTy->getNumParams() != 3 ||
1947 !isa<PointerType>(FTy->getParamType(0)) ||
1948 !isa<PointerType>(FTy->getParamType(1)))
1951 setDoesNotCapture(F, 1);
1952 setDoesNotCapture(F, 2);
1953 } else if (Name == "bcmp") {
1954 if (FTy->getNumParams() != 3 ||
1955 !isa<PointerType>(FTy->getParamType(0)) ||
1956 !isa<PointerType>(FTy->getParamType(1)))
1959 setOnlyReadsMemory(F);
1960 setDoesNotCapture(F, 1);
1961 setDoesNotCapture(F, 2);
1962 } else if (Name == "bzero") {
1963 if (FTy->getNumParams() != 2 ||
1964 !isa<PointerType>(FTy->getParamType(0)))
1967 setDoesNotCapture(F, 1);
1971 if (Name == "calloc") {
1972 if (FTy->getNumParams() != 2 ||
1973 !isa<PointerType>(FTy->getReturnType()))
1976 setDoesNotAlias(F, 0);
1977 } else if (Name == "chmod" ||
1979 Name == "ctermid" ||
1980 Name == "clearerr" ||
1981 Name == "closedir") {
1982 if (FTy->getNumParams() == 0 ||
1983 !isa<PointerType>(FTy->getParamType(0)))
1986 setDoesNotCapture(F, 1);
1990 if (Name == "atoi" ||
1994 if (FTy->getNumParams() != 1 ||
1995 !isa<PointerType>(FTy->getParamType(0)))
1998 setOnlyReadsMemory(F);
1999 setDoesNotCapture(F, 1);
2000 } else if (Name == "access") {
2001 if (FTy->getNumParams() != 2 ||
2002 !isa<PointerType>(FTy->getParamType(0)))
2005 setDoesNotCapture(F, 1);
2009 if (Name == "fopen") {
2010 if (FTy->getNumParams() != 2 ||
2011 !isa<PointerType>(FTy->getReturnType()) ||
2012 !isa<PointerType>(FTy->getParamType(0)) ||
2013 !isa<PointerType>(FTy->getParamType(1)))
2016 setDoesNotAlias(F, 0);
2017 setDoesNotCapture(F, 1);
2018 setDoesNotCapture(F, 2);
2019 } else if (Name == "fdopen") {
2020 if (FTy->getNumParams() != 2 ||
2021 !isa<PointerType>(FTy->getReturnType()) ||
2022 !isa<PointerType>(FTy->getParamType(1)))
2025 setDoesNotAlias(F, 0);
2026 setDoesNotCapture(F, 2);
2027 } else if (Name == "feof" ||
2037 Name == "fsetpos" ||
2038 Name == "flockfile" ||
2039 Name == "funlockfile" ||
2040 Name == "ftrylockfile") {
2041 if (FTy->getNumParams() == 0 ||
2042 !isa<PointerType>(FTy->getParamType(0)))
2045 setDoesNotCapture(F, 1);
2046 } else if (Name == "ferror") {
2047 if (FTy->getNumParams() != 1 ||
2048 !isa<PointerType>(FTy->getParamType(0)))
2051 setDoesNotCapture(F, 1);
2052 setOnlyReadsMemory(F);
2053 } else if (Name == "fputc" ||
2058 Name == "fstatvfs") {
2059 if (FTy->getNumParams() != 2 ||
2060 !isa<PointerType>(FTy->getParamType(1)))
2063 setDoesNotCapture(F, 2);
2064 } else if (Name == "fgets") {
2065 if (FTy->getNumParams() != 3 ||
2066 !isa<PointerType>(FTy->getParamType(0)) ||
2067 !isa<PointerType>(FTy->getParamType(2)))
2070 setDoesNotCapture(F, 3);
2071 } else if (Name == "fread" ||
2073 if (FTy->getNumParams() != 4 ||
2074 !isa<PointerType>(FTy->getParamType(0)) ||
2075 !isa<PointerType>(FTy->getParamType(3)))
2078 setDoesNotCapture(F, 1);
2079 setDoesNotCapture(F, 4);
2080 } else if (Name == "fputs" ||
2082 Name == "fprintf" ||
2083 Name == "fgetpos") {
2084 if (FTy->getNumParams() < 2 ||
2085 !isa<PointerType>(FTy->getParamType(0)) ||
2086 !isa<PointerType>(FTy->getParamType(1)))
2089 setDoesNotCapture(F, 1);
2090 setDoesNotCapture(F, 2);
2094 if (Name == "getc" ||
2095 Name == "getlogin_r" ||
2096 Name == "getc_unlocked") {
2097 if (FTy->getNumParams() == 0 ||
2098 !isa<PointerType>(FTy->getParamType(0)))
2101 setDoesNotCapture(F, 1);
2102 } else if (Name == "getenv") {
2103 if (FTy->getNumParams() != 1 ||
2104 !isa<PointerType>(FTy->getParamType(0)))
2107 setOnlyReadsMemory(F);
2108 setDoesNotCapture(F, 1);
2109 } else if (Name == "gets" ||
2110 Name == "getchar") {
2112 } else if (Name == "getitimer") {
2113 if (FTy->getNumParams() != 2 ||
2114 !isa<PointerType>(FTy->getParamType(1)))
2117 setDoesNotCapture(F, 2);
2118 } else if (Name == "getpwnam") {
2119 if (FTy->getNumParams() != 1 ||
2120 !isa<PointerType>(FTy->getParamType(0)))
2123 setDoesNotCapture(F, 1);
2127 if (Name == "ungetc") {
2128 if (FTy->getNumParams() != 2 ||
2129 !isa<PointerType>(FTy->getParamType(1)))
2132 setDoesNotCapture(F, 2);
2133 } else if (Name == "uname" ||
2135 Name == "unsetenv") {
2136 if (FTy->getNumParams() != 1 ||
2137 !isa<PointerType>(FTy->getParamType(0)))
2140 setDoesNotCapture(F, 1);
2141 } else if (Name == "utime" ||
2143 if (FTy->getNumParams() != 2 ||
2144 !isa<PointerType>(FTy->getParamType(0)) ||
2145 !isa<PointerType>(FTy->getParamType(1)))
2148 setDoesNotCapture(F, 1);
2149 setDoesNotCapture(F, 2);
2153 if (Name == "putc") {
2154 if (FTy->getNumParams() != 2 ||
2155 !isa<PointerType>(FTy->getParamType(1)))
2158 setDoesNotCapture(F, 2);
2159 } else if (Name == "puts" ||
2162 if (FTy->getNumParams() != 1 ||
2163 !isa<PointerType>(FTy->getParamType(0)))
2166 setDoesNotCapture(F, 1);
2167 } else if (Name == "pread" ||
2169 if (FTy->getNumParams() != 4 ||
2170 !isa<PointerType>(FTy->getParamType(1)))
2172 // May throw; these are valid pthread cancellation points.
2173 setDoesNotCapture(F, 2);
2174 } else if (Name == "putchar") {
2176 } else if (Name == "popen") {
2177 if (FTy->getNumParams() != 2 ||
2178 !isa<PointerType>(FTy->getReturnType()) ||
2179 !isa<PointerType>(FTy->getParamType(0)) ||
2180 !isa<PointerType>(FTy->getParamType(1)))
2183 setDoesNotAlias(F, 0);
2184 setDoesNotCapture(F, 1);
2185 setDoesNotCapture(F, 2);
2186 } else if (Name == "pclose") {
2187 if (FTy->getNumParams() != 1 ||
2188 !isa<PointerType>(FTy->getParamType(0)))
2191 setDoesNotCapture(F, 1);
2195 if (Name == "vscanf") {
2196 if (FTy->getNumParams() != 2 ||
2197 !isa<PointerType>(FTy->getParamType(1)))
2200 setDoesNotCapture(F, 1);
2201 } else if (Name == "vsscanf" ||
2202 Name == "vfscanf") {
2203 if (FTy->getNumParams() != 3 ||
2204 !isa<PointerType>(FTy->getParamType(1)) ||
2205 !isa<PointerType>(FTy->getParamType(2)))
2208 setDoesNotCapture(F, 1);
2209 setDoesNotCapture(F, 2);
2210 } else if (Name == "valloc") {
2211 if (!isa<PointerType>(FTy->getReturnType()))
2214 setDoesNotAlias(F, 0);
2215 } else if (Name == "vprintf") {
2216 if (FTy->getNumParams() != 2 ||
2217 !isa<PointerType>(FTy->getParamType(0)))
2220 setDoesNotCapture(F, 1);
2221 } else if (Name == "vfprintf" ||
2222 Name == "vsprintf") {
2223 if (FTy->getNumParams() != 3 ||
2224 !isa<PointerType>(FTy->getParamType(0)) ||
2225 !isa<PointerType>(FTy->getParamType(1)))
2228 setDoesNotCapture(F, 1);
2229 setDoesNotCapture(F, 2);
2230 } else if (Name == "vsnprintf") {
2231 if (FTy->getNumParams() != 4 ||
2232 !isa<PointerType>(FTy->getParamType(0)) ||
2233 !isa<PointerType>(FTy->getParamType(2)))
2236 setDoesNotCapture(F, 1);
2237 setDoesNotCapture(F, 3);
2241 if (Name == "open") {
2242 if (FTy->getNumParams() < 2 ||
2243 !isa<PointerType>(FTy->getParamType(0)))
2245 // May throw; "open" is a valid pthread cancellation point.
2246 setDoesNotCapture(F, 1);
2247 } else if (Name == "opendir") {
2248 if (FTy->getNumParams() != 1 ||
2249 !isa<PointerType>(FTy->getReturnType()) ||
2250 !isa<PointerType>(FTy->getParamType(0)))
2253 setDoesNotAlias(F, 0);
2254 setDoesNotCapture(F, 1);
2258 if (Name == "tmpfile") {
2259 if (!isa<PointerType>(FTy->getReturnType()))
2262 setDoesNotAlias(F, 0);
2263 } else if (Name == "times") {
2264 if (FTy->getNumParams() != 1 ||
2265 !isa<PointerType>(FTy->getParamType(0)))
2268 setDoesNotCapture(F, 1);
2272 if (Name == "htonl" ||
2275 setDoesNotAccessMemory(F);
2279 if (Name == "ntohl" ||
2282 setDoesNotAccessMemory(F);
2286 if (Name == "lstat") {
2287 if (FTy->getNumParams() != 2 ||
2288 !isa<PointerType>(FTy->getParamType(0)) ||
2289 !isa<PointerType>(FTy->getParamType(1)))
2292 setDoesNotCapture(F, 1);
2293 setDoesNotCapture(F, 2);
2294 } else if (Name == "lchown") {
2295 if (FTy->getNumParams() != 3 ||
2296 !isa<PointerType>(FTy->getParamType(0)))
2299 setDoesNotCapture(F, 1);
2303 if (Name == "qsort") {
2304 if (FTy->getNumParams() != 4 ||
2305 !isa<PointerType>(FTy->getParamType(3)))
2307 // May throw; places call through function pointer.
2308 setDoesNotCapture(F, 4);
2312 if (Name == "__strdup" ||
2313 Name == "__strndup") {
2314 if (FTy->getNumParams() < 1 ||
2315 !isa<PointerType>(FTy->getReturnType()) ||
2316 !isa<PointerType>(FTy->getParamType(0)))
2319 setDoesNotAlias(F, 0);
2320 setDoesNotCapture(F, 1);
2321 } else if (Name == "__strtok_r") {
2322 if (FTy->getNumParams() != 3 ||
2323 !isa<PointerType>(FTy->getParamType(1)))
2326 setDoesNotCapture(F, 2);
2327 } else if (Name == "_IO_getc") {
2328 if (FTy->getNumParams() != 1 ||
2329 !isa<PointerType>(FTy->getParamType(0)))
2332 setDoesNotCapture(F, 1);
2333 } else if (Name == "_IO_putc") {
2334 if (FTy->getNumParams() != 2 ||
2335 !isa<PointerType>(FTy->getParamType(1)))
2338 setDoesNotCapture(F, 2);
2342 if (Name == "\1__isoc99_scanf") {
2343 if (FTy->getNumParams() < 1 ||
2344 !isa<PointerType>(FTy->getParamType(0)))
2347 setDoesNotCapture(F, 1);
2348 } else if (Name == "\1stat64" ||
2349 Name == "\1lstat64" ||
2350 Name == "\1statvfs64" ||
2351 Name == "\1__isoc99_sscanf") {
2352 if (FTy->getNumParams() < 1 ||
2353 !isa<PointerType>(FTy->getParamType(0)) ||
2354 !isa<PointerType>(FTy->getParamType(1)))
2357 setDoesNotCapture(F, 1);
2358 setDoesNotCapture(F, 2);
2359 } else if (Name == "\1fopen64") {
2360 if (FTy->getNumParams() != 2 ||
2361 !isa<PointerType>(FTy->getReturnType()) ||
2362 !isa<PointerType>(FTy->getParamType(0)) ||
2363 !isa<PointerType>(FTy->getParamType(1)))
2366 setDoesNotAlias(F, 0);
2367 setDoesNotCapture(F, 1);
2368 setDoesNotCapture(F, 2);
2369 } else if (Name == "\1fseeko64" ||
2370 Name == "\1ftello64") {
2371 if (FTy->getNumParams() == 0 ||
2372 !isa<PointerType>(FTy->getParamType(0)))
2375 setDoesNotCapture(F, 1);
2376 } else if (Name == "\1tmpfile64") {
2377 if (!isa<PointerType>(FTy->getReturnType()))
2380 setDoesNotAlias(F, 0);
2381 } else if (Name == "\1fstat64" ||
2382 Name == "\1fstatvfs64") {
2383 if (FTy->getNumParams() != 2 ||
2384 !isa<PointerType>(FTy->getParamType(1)))
2387 setDoesNotCapture(F, 2);
2388 } else if (Name == "\1open64") {
2389 if (FTy->getNumParams() < 2 ||
2390 !isa<PointerType>(FTy->getParamType(0)))
2392 // May throw; "open" is a valid pthread cancellation point.
2393 setDoesNotCapture(F, 1);
2402 // Additional cases that we need to add to this file:
2405 // * cbrt(expN(X)) -> expN(x/3)
2406 // * cbrt(sqrt(x)) -> pow(x,1/6)
2407 // * cbrt(sqrt(x)) -> pow(x,1/9)
2410 // * cos(-x) -> cos(x)
2413 // * exp(log(x)) -> x
2416 // * log(exp(x)) -> x
2417 // * log(x**y) -> y*log(x)
2418 // * log(exp(y)) -> y*log(e)
2419 // * log(exp2(y)) -> y*log(2)
2420 // * log(exp10(y)) -> y*log(10)
2421 // * log(sqrt(x)) -> 0.5*log(x)
2422 // * log(pow(x,y)) -> y*log(x)
2424 // lround, lroundf, lroundl:
2425 // * lround(cnst) -> cnst'
2428 // * memcmp(x,y,l) -> cnst
2429 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2432 // * pow(exp(x),y) -> exp(x*y)
2433 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2434 // * pow(pow(x,y),z)-> pow(x,y*z)
2437 // * puts("") -> putchar("\n")
2439 // round, roundf, roundl:
2440 // * round(cnst) -> cnst'
2443 // * signbit(cnst) -> cnst'
2444 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2446 // sqrt, sqrtf, sqrtl:
2447 // * sqrt(expN(x)) -> expN(x*0.5)
2448 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2449 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2452 // * stpcpy(str, "literal") ->
2453 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2455 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2456 // (if c is a constant integer and s is a constant string)
2457 // * strrchr(s1,0) -> strchr(s1,0)
2460 // * strpbrk(s,a) -> offset_in_for(s,a)
2461 // (if s and a are both constant strings)
2462 // * strpbrk(s,"") -> 0
2463 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2466 // * strspn(s,a) -> const_int (if both args are constant)
2467 // * strspn("",a) -> 0
2468 // * strspn(s,"") -> 0
2469 // * strcspn(s,a) -> const_int (if both args are constant)
2470 // * strcspn("",a) -> 0
2471 // * strcspn(s,"") -> strlen(a)
2474 // * strstr(x,x) -> x
2475 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2476 // (if s1 and s2 are constant strings)
2479 // * tan(atan(x)) -> x
2481 // trunc, truncf, truncl:
2482 // * trunc(cnst) -> cnst'