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/ADT/STLExtras.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Config/config.h"
39 STATISTIC(NumSimplified, "Number of library calls simplified");
40 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
42 //===----------------------------------------------------------------------===//
43 // Optimizer Base Class
44 //===----------------------------------------------------------------------===//
46 /// This class is the abstract base class for the set of optimizations that
47 /// corresponds to one library call.
49 class VISIBILITY_HIDDEN LibCallOptimization {
55 LibCallOptimization() { }
56 virtual ~LibCallOptimization() {}
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
63 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
66 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
67 Caller = CI->getParent()->getParent();
69 if (CI->getCalledFunction())
70 Context = &CI->getCalledFunction()->getContext();
71 return CallOptimizer(CI->getCalledFunction(), CI, B);
74 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
75 Value *CastToCStr(Value *V, IRBuilder<> &B);
77 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
78 /// specified pointer. Ptr is required to be some pointer type, and the
79 /// return value has 'intptr_t' type.
80 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
82 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
83 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
84 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
85 unsigned Align, IRBuilder<> &B);
87 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
88 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
89 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
91 /// EmitMemCmp - Emit a call to the memcmp function.
92 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
94 /// EmitMemSet - Emit a call to the memset function
95 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
97 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
98 /// 'floor'). This function is known to take a single of type matching 'Op'
99 /// and returns one value with the same type. If 'Op' is a long double, 'l'
100 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
101 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
103 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
105 void EmitPutChar(Value *Char, IRBuilder<> &B);
107 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
109 void EmitPutS(Value *Str, IRBuilder<> &B);
111 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
112 /// an i32, and File is a pointer to FILE.
113 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
115 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
116 /// pointer and File is a pointer to FILE.
117 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
119 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
120 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
121 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
124 } // End anonymous namespace.
126 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
127 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
129 B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
132 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
133 /// specified pointer. This always returns an integer value of size intptr_t.
134 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
135 Module *M = Caller->getParent();
136 AttributeWithIndex AWI[2];
137 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
138 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
139 Attribute::NoUnwind);
141 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
143 PointerType::getUnqual(Type::Int8Ty),
145 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
146 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
147 CI->setCallingConv(F->getCallingConv());
152 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
153 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
154 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
155 unsigned Align, IRBuilder<> &B) {
156 Module *M = Caller->getParent();
157 Intrinsic::ID IID = Intrinsic::memcpy;
159 Tys[0] = Len->getType();
160 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
161 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
162 ConstantInt::get(Type::Int32Ty, Align));
165 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
166 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
167 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
168 Value *Len, IRBuilder<> &B) {
169 Module *M = Caller->getParent();
170 AttributeWithIndex AWI;
171 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
173 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
174 PointerType::getUnqual(Type::Int8Ty),
175 PointerType::getUnqual(Type::Int8Ty),
176 Type::Int32Ty, TD->getIntPtrType(),
178 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
180 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
181 CI->setCallingConv(F->getCallingConv());
186 /// EmitMemCmp - Emit a call to the memcmp function.
187 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
188 Value *Len, IRBuilder<> &B) {
189 Module *M = Caller->getParent();
190 AttributeWithIndex AWI[3];
191 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
192 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
193 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
194 Attribute::NoUnwind);
196 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
198 PointerType::getUnqual(Type::Int8Ty),
199 PointerType::getUnqual(Type::Int8Ty),
200 TD->getIntPtrType(), NULL);
201 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
204 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
205 CI->setCallingConv(F->getCallingConv());
210 /// EmitMemSet - Emit a call to the memset function
211 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
212 Value *Len, IRBuilder<> &B) {
213 Module *M = Caller->getParent();
214 Intrinsic::ID IID = Intrinsic::memset;
216 Tys[0] = Len->getType();
217 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
218 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
219 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
222 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
223 /// 'floor'). This function is known to take a single of type matching 'Op' and
224 /// returns one value with the same type. If 'Op' is a long double, 'l' is
225 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
226 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
229 if (Op->getType() != Type::DoubleTy) {
230 // If we need to add a suffix, copy into NameBuffer.
231 unsigned NameLen = strlen(Name);
232 assert(NameLen < sizeof(NameBuffer)-2);
233 memcpy(NameBuffer, Name, NameLen);
234 if (Op->getType() == Type::FloatTy)
235 NameBuffer[NameLen] = 'f'; // floorf
237 NameBuffer[NameLen] = 'l'; // floorl
238 NameBuffer[NameLen+1] = 0;
242 Module *M = Caller->getParent();
243 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
244 Op->getType(), NULL);
245 CallInst *CI = B.CreateCall(Callee, Op, Name);
247 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
248 CI->setCallingConv(F->getCallingConv());
253 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
255 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
256 Module *M = Caller->getParent();
257 Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
258 Type::Int32Ty, NULL);
259 CallInst *CI = B.CreateCall(PutChar,
260 B.CreateIntCast(Char, Type::Int32Ty, "chari"),
263 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
264 CI->setCallingConv(F->getCallingConv());
267 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
269 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
270 Module *M = Caller->getParent();
271 AttributeWithIndex AWI[2];
272 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
273 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
275 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
277 PointerType::getUnqual(Type::Int8Ty),
279 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
280 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
281 CI->setCallingConv(F->getCallingConv());
285 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
286 /// an integer and File is a pointer to FILE.
287 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
288 Module *M = Caller->getParent();
289 AttributeWithIndex AWI[2];
290 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
291 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
293 if (isa<PointerType>(File->getType()))
294 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
295 Type::Int32Ty, File->getType(), NULL);
297 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
298 File->getType(), NULL);
299 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
300 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
302 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
303 CI->setCallingConv(Fn->getCallingConv());
306 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
307 /// pointer and File is a pointer to FILE.
308 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
309 Module *M = Caller->getParent();
310 AttributeWithIndex AWI[3];
311 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
312 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
313 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
315 if (isa<PointerType>(File->getType()))
316 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
317 PointerType::getUnqual(Type::Int8Ty),
318 File->getType(), NULL);
320 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
321 PointerType::getUnqual(Type::Int8Ty),
322 File->getType(), NULL);
323 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
325 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
326 CI->setCallingConv(Fn->getCallingConv());
329 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
330 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
331 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
333 Module *M = Caller->getParent();
334 AttributeWithIndex AWI[3];
335 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
336 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
337 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
339 if (isa<PointerType>(File->getType()))
340 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
342 PointerType::getUnqual(Type::Int8Ty),
343 TD->getIntPtrType(), TD->getIntPtrType(),
344 File->getType(), NULL);
346 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
347 PointerType::getUnqual(Type::Int8Ty),
348 TD->getIntPtrType(), TD->getIntPtrType(),
349 File->getType(), NULL);
350 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
351 ConstantInt::get(TD->getIntPtrType(), 1), File);
353 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
354 CI->setCallingConv(Fn->getCallingConv());
357 //===----------------------------------------------------------------------===//
359 //===----------------------------------------------------------------------===//
361 /// GetStringLengthH - If we can compute the length of the string pointed to by
362 /// the specified pointer, return 'len+1'. If we can't, return 0.
363 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
364 // Look through noop bitcast instructions.
365 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
366 return GetStringLengthH(BCI->getOperand(0), PHIs);
368 // If this is a PHI node, there are two cases: either we have already seen it
370 if (PHINode *PN = dyn_cast<PHINode>(V)) {
371 if (!PHIs.insert(PN))
372 return ~0ULL; // already in the set.
374 // If it was new, see if all the input strings are the same length.
375 uint64_t LenSoFar = ~0ULL;
376 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
377 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
378 if (Len == 0) return 0; // Unknown length -> unknown.
380 if (Len == ~0ULL) continue;
382 if (Len != LenSoFar && LenSoFar != ~0ULL)
383 return 0; // Disagree -> unknown.
387 // Success, all agree.
391 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
392 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
393 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
394 if (Len1 == 0) return 0;
395 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
396 if (Len2 == 0) return 0;
397 if (Len1 == ~0ULL) return Len2;
398 if (Len2 == ~0ULL) return Len1;
399 if (Len1 != Len2) return 0;
403 // If the value is not a GEP instruction nor a constant expression with a
404 // GEP instruction, then return unknown.
406 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
408 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
409 if (CE->getOpcode() != Instruction::GetElementPtr)
416 // Make sure the GEP has exactly three arguments.
417 if (GEP->getNumOperands() != 3)
420 // Check to make sure that the first operand of the GEP is an integer and
421 // has value 0 so that we are sure we're indexing into the initializer.
422 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
428 // If the second index isn't a ConstantInt, then this is a variable index
429 // into the array. If this occurs, we can't say anything meaningful about
431 uint64_t StartIdx = 0;
432 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
433 StartIdx = CI->getZExtValue();
437 // The GEP instruction, constant or instruction, must reference a global
438 // variable that is a constant and is initialized. The referenced constant
439 // initializer is the array that we'll use for optimization.
440 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
441 if (!GV || !GV->isConstant() || !GV->hasInitializer())
443 Constant *GlobalInit = GV->getInitializer();
445 // Handle the ConstantAggregateZero case, which is a degenerate case. The
446 // initializer is constant zero so the length of the string must be zero.
447 if (isa<ConstantAggregateZero>(GlobalInit))
448 return 1; // Len = 0 offset by 1.
450 // Must be a Constant Array
451 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
452 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
455 // Get the number of elements in the array
456 uint64_t NumElts = Array->getType()->getNumElements();
458 // Traverse the constant array from StartIdx (derived above) which is
459 // the place the GEP refers to in the array.
460 for (unsigned i = StartIdx; i != NumElts; ++i) {
461 Constant *Elt = Array->getOperand(i);
462 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
463 if (!CI) // This array isn't suitable, non-int initializer.
466 return i-StartIdx+1; // We found end of string, success!
469 return 0; // The array isn't null terminated, conservatively return 'unknown'.
472 /// GetStringLength - If we can compute the length of the string pointed to by
473 /// the specified pointer, return 'len+1'. If we can't, return 0.
474 static uint64_t GetStringLength(Value *V) {
475 if (!isa<PointerType>(V->getType())) return 0;
477 SmallPtrSet<PHINode*, 32> PHIs;
478 uint64_t Len = GetStringLengthH(V, PHIs);
479 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
480 // an empty string as a length.
481 return Len == ~0ULL ? 1 : Len;
484 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
485 /// value is equal or not-equal to zero.
486 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
487 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
489 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
490 if (IC->isEquality())
491 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
492 if (C->isNullValue())
494 // Unknown instruction.
500 //===----------------------------------------------------------------------===//
501 // Miscellaneous LibCall Optimizations
502 //===----------------------------------------------------------------------===//
505 //===---------------------------------------===//
506 // 'exit' Optimizations
508 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
509 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
510 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
511 // Verify we have a reasonable prototype for exit.
512 if (Callee->arg_size() == 0 || !CI->use_empty())
515 // Verify the caller is main, and that the result type of main matches the
516 // argument type of exit.
517 if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
518 Caller->getReturnType() != CI->getOperand(1)->getType())
521 TerminatorInst *OldTI = CI->getParent()->getTerminator();
523 // Drop all successor phi node entries.
524 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
525 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
527 // Remove all instructions after the exit.
528 BasicBlock::iterator Dead = CI, E = OldTI; ++Dead;
530 BasicBlock::iterator Next = next(Dead);
531 if (Dead->getType() != Type::VoidTy)
532 Dead->replaceAllUsesWith(UndefValue::get(Dead->getType()));
533 Dead->eraseFromParent();
537 // Insert a return instruction.
538 OldTI->eraseFromParent();
539 B.SetInsertPoint(B.GetInsertBlock());
540 B.CreateRet(CI->getOperand(1));
546 //===----------------------------------------------------------------------===//
547 // String and Memory LibCall Optimizations
548 //===----------------------------------------------------------------------===//
550 //===---------------------------------------===//
551 // 'strcat' Optimizations
553 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
554 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
555 // Verify the "strcat" function prototype.
556 const FunctionType *FT = Callee->getFunctionType();
557 if (FT->getNumParams() != 2 ||
558 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
559 FT->getParamType(0) != FT->getReturnType() ||
560 FT->getParamType(1) != FT->getReturnType())
563 // Extract some information from the instruction
564 Value *Dst = CI->getOperand(1);
565 Value *Src = CI->getOperand(2);
567 // See if we can get the length of the input string.
568 uint64_t Len = GetStringLength(Src);
569 if (Len == 0) return 0;
570 --Len; // Unbias length.
572 // Handle the simple, do-nothing case: strcat(x, "") -> x
576 EmitStrLenMemCpy(Src, Dst, Len, B);
580 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
581 // We need to find the end of the destination string. That's where the
582 // memory is to be moved to. We just generate a call to strlen.
583 Value *DstLen = EmitStrLen(Dst, B);
585 // Now that we have the destination's length, we must index into the
586 // destination's pointer to get the actual memcpy destination (end of
587 // the string .. we're concatenating).
588 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
590 // We have enough information to now generate the memcpy call to do the
591 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
592 EmitMemCpy(CpyDst, Src,
593 ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
597 //===---------------------------------------===//
598 // 'strncat' Optimizations
600 struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
601 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
602 // Verify the "strncat" function prototype.
603 const FunctionType *FT = Callee->getFunctionType();
604 if (FT->getNumParams() != 3 ||
605 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
606 FT->getParamType(0) != FT->getReturnType() ||
607 FT->getParamType(1) != FT->getReturnType() ||
608 !isa<IntegerType>(FT->getParamType(2)))
611 // Extract some information from the instruction
612 Value *Dst = CI->getOperand(1);
613 Value *Src = CI->getOperand(2);
616 // We don't do anything if length is not constant
617 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
618 Len = LengthArg->getZExtValue();
622 // See if we can get the length of the input string.
623 uint64_t SrcLen = GetStringLength(Src);
624 if (SrcLen == 0) return 0;
625 --SrcLen; // Unbias length.
627 // Handle the simple, do-nothing cases:
628 // strncat(x, "", c) -> x
629 // strncat(x, c, 0) -> x
630 if (SrcLen == 0 || Len == 0) return Dst;
632 // We don't optimize this case
633 if (Len < SrcLen) return 0;
635 // strncat(x, s, c) -> strcat(x, s)
636 // s is constant so the strcat can be optimized further
637 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
642 //===---------------------------------------===//
643 // 'strchr' Optimizations
645 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
646 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
647 // Verify the "strchr" function prototype.
648 const FunctionType *FT = Callee->getFunctionType();
649 if (FT->getNumParams() != 2 ||
650 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
651 FT->getParamType(0) != FT->getReturnType())
654 Value *SrcStr = CI->getOperand(1);
656 // If the second operand is non-constant, see if we can compute the length
657 // of the input string and turn this into memchr.
658 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
660 uint64_t Len = GetStringLength(SrcStr);
661 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
664 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
665 ConstantInt::get(TD->getIntPtrType(), Len), B);
668 // Otherwise, the character is a constant, see if the first argument is
669 // a string literal. If so, we can constant fold.
671 if (!GetConstantStringInfo(SrcStr, Str))
674 // strchr can find the nul character.
676 char CharValue = CharC->getSExtValue();
678 // Compute the offset.
681 if (i == Str.size()) // Didn't find the char. strchr returns null.
682 return Context->getNullValue(CI->getType());
683 // Did we find our match?
684 if (Str[i] == CharValue)
689 // strchr(s+n,c) -> gep(s+n+i,c)
690 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
691 return B.CreateGEP(SrcStr, Idx, "strchr");
695 //===---------------------------------------===//
696 // 'strcmp' Optimizations
698 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
699 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
700 // Verify the "strcmp" function prototype.
701 const FunctionType *FT = Callee->getFunctionType();
702 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
703 FT->getParamType(0) != FT->getParamType(1) ||
704 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
707 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
708 if (Str1P == Str2P) // strcmp(x,x) -> 0
709 return ConstantInt::get(CI->getType(), 0);
711 std::string Str1, Str2;
712 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
713 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
715 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
716 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
718 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
719 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
721 // strcmp(x, y) -> cnst (if both x and y are constant strings)
722 if (HasStr1 && HasStr2)
723 return ConstantInt::get(CI->getType(),
724 strcmp(Str1.c_str(),Str2.c_str()));
726 // strcmp(P, "x") -> memcmp(P, "x", 2)
727 uint64_t Len1 = GetStringLength(Str1P);
728 uint64_t Len2 = GetStringLength(Str2P);
730 return EmitMemCmp(Str1P, Str2P,
731 ConstantInt::get(TD->getIntPtrType(),
732 std::min(Len1, Len2)), B);
739 //===---------------------------------------===//
740 // 'strncmp' Optimizations
742 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
743 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
744 // Verify the "strncmp" function prototype.
745 const FunctionType *FT = Callee->getFunctionType();
746 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
747 FT->getParamType(0) != FT->getParamType(1) ||
748 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
749 !isa<IntegerType>(FT->getParamType(2)))
752 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
753 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
754 return ConstantInt::get(CI->getType(), 0);
756 // Get the length argument if it is constant.
758 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
759 Length = LengthArg->getZExtValue();
763 if (Length == 0) // strncmp(x,y,0) -> 0
764 return ConstantInt::get(CI->getType(), 0);
766 std::string Str1, Str2;
767 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
768 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
770 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
771 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
773 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
774 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
776 // strncmp(x, y) -> cnst (if both x and y are constant strings)
777 if (HasStr1 && HasStr2)
778 return ConstantInt::get(CI->getType(),
779 strncmp(Str1.c_str(), Str2.c_str(), Length));
785 //===---------------------------------------===//
786 // 'strcpy' Optimizations
788 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
789 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
790 // Verify the "strcpy" function prototype.
791 const FunctionType *FT = Callee->getFunctionType();
792 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
793 FT->getParamType(0) != FT->getParamType(1) ||
794 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
797 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
798 if (Dst == Src) // strcpy(x,x) -> x
801 // See if we can get the length of the input string.
802 uint64_t Len = GetStringLength(Src);
803 if (Len == 0) return 0;
805 // We have enough information to now generate the memcpy call to do the
806 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
808 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
813 //===---------------------------------------===//
814 // 'strncpy' Optimizations
816 struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
817 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
818 const FunctionType *FT = Callee->getFunctionType();
819 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
820 FT->getParamType(0) != FT->getParamType(1) ||
821 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
822 !isa<IntegerType>(FT->getParamType(2)))
825 Value *Dst = CI->getOperand(1);
826 Value *Src = CI->getOperand(2);
827 Value *LenOp = CI->getOperand(3);
829 // See if we can get the length of the input string.
830 uint64_t SrcLen = GetStringLength(Src);
831 if (SrcLen == 0) return 0;
835 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
836 EmitMemSet(Dst, ConstantInt::get(Type::Int8Ty, '\0'), LenOp, B);
841 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
842 Len = LengthArg->getZExtValue();
846 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
848 // Let strncpy handle the zero padding
849 if (Len > SrcLen+1) return 0;
851 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
853 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
859 //===---------------------------------------===//
860 // 'strlen' Optimizations
862 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
863 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
864 const FunctionType *FT = Callee->getFunctionType();
865 if (FT->getNumParams() != 1 ||
866 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
867 !isa<IntegerType>(FT->getReturnType()))
870 Value *Src = CI->getOperand(1);
872 // Constant folding: strlen("xyz") -> 3
873 if (uint64_t Len = GetStringLength(Src))
874 return ConstantInt::get(CI->getType(), Len-1);
876 // Handle strlen(p) != 0.
877 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
879 // strlen(x) != 0 --> *x != 0
880 // strlen(x) == 0 --> *x == 0
881 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
885 //===---------------------------------------===//
886 // 'strto*' Optimizations
888 struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
889 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
890 const FunctionType *FT = Callee->getFunctionType();
891 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
892 !isa<PointerType>(FT->getParamType(0)) ||
893 !isa<PointerType>(FT->getParamType(1)))
896 Value *EndPtr = CI->getOperand(2);
897 if (isa<ConstantPointerNull>(EndPtr)) {
898 CI->setOnlyReadsMemory();
899 CI->addAttribute(1, Attribute::NoCapture);
907 //===---------------------------------------===//
908 // 'memcmp' Optimizations
910 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
911 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
912 const FunctionType *FT = Callee->getFunctionType();
913 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
914 !isa<PointerType>(FT->getParamType(1)) ||
915 FT->getReturnType() != Type::Int32Ty)
918 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
920 if (LHS == RHS) // memcmp(s,s,x) -> 0
921 return Context->getNullValue(CI->getType());
923 // Make sure we have a constant length.
924 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
926 uint64_t Len = LenC->getZExtValue();
928 if (Len == 0) // memcmp(s1,s2,0) -> 0
929 return Context->getNullValue(CI->getType());
931 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
932 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
933 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
934 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
937 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
938 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
939 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
940 const Type *PTy = PointerType::getUnqual(Len == 2 ?
941 Type::Int16Ty : Type::Int32Ty);
942 LHS = B.CreateBitCast(LHS, PTy, "tmp");
943 RHS = B.CreateBitCast(RHS, PTy, "tmp");
944 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
945 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
946 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
947 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
954 //===---------------------------------------===//
955 // 'memcpy' Optimizations
957 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
958 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
959 const FunctionType *FT = Callee->getFunctionType();
960 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
961 !isa<PointerType>(FT->getParamType(0)) ||
962 !isa<PointerType>(FT->getParamType(1)) ||
963 FT->getParamType(2) != TD->getIntPtrType())
966 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
967 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
968 return CI->getOperand(1);
972 //===---------------------------------------===//
973 // 'memmove' Optimizations
975 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
976 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
977 const FunctionType *FT = Callee->getFunctionType();
978 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
979 !isa<PointerType>(FT->getParamType(0)) ||
980 !isa<PointerType>(FT->getParamType(1)) ||
981 FT->getParamType(2) != TD->getIntPtrType())
984 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
985 Module *M = Caller->getParent();
986 Intrinsic::ID IID = Intrinsic::memmove;
988 Tys[0] = TD->getIntPtrType();
989 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
990 Value *Dst = CastToCStr(CI->getOperand(1), B);
991 Value *Src = CastToCStr(CI->getOperand(2), B);
992 Value *Size = CI->getOperand(3);
993 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
994 B.CreateCall4(MemMove, Dst, Src, Size, Align);
995 return CI->getOperand(1);
999 //===---------------------------------------===//
1000 // 'memset' Optimizations
1002 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
1003 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1004 const FunctionType *FT = Callee->getFunctionType();
1005 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1006 !isa<PointerType>(FT->getParamType(0)) ||
1007 !isa<IntegerType>(FT->getParamType(1)) ||
1008 FT->getParamType(2) != TD->getIntPtrType())
1011 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1012 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::Int8Ty, false);
1013 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1014 return CI->getOperand(1);
1018 //===----------------------------------------------------------------------===//
1019 // Math Library Optimizations
1020 //===----------------------------------------------------------------------===//
1022 //===---------------------------------------===//
1023 // 'pow*' Optimizations
1025 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
1026 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1027 const FunctionType *FT = Callee->getFunctionType();
1028 // Just make sure this has 2 arguments of the same FP type, which match the
1030 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1031 FT->getParamType(0) != FT->getParamType(1) ||
1032 !FT->getParamType(0)->isFloatingPoint())
1035 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1036 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1037 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1039 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1040 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1043 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1044 if (Op2C == 0) return 0;
1046 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1047 return ConstantFP::get(CI->getType(), 1.0);
1049 if (Op2C->isExactlyValue(0.5)) {
1050 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1051 // 'unsafe' math optimizations are allowed.
1052 // x pow(x, 0.5) sqrt(x)
1053 // ---------------------------------------------
1057 // pow(x, 0.5) -> sqrt(x)
1058 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1062 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1064 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1065 return B.CreateFMul(Op1, Op1, "pow2");
1066 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1067 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1073 //===---------------------------------------===//
1074 // 'exp2' Optimizations
1076 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
1077 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1078 const FunctionType *FT = Callee->getFunctionType();
1079 // Just make sure this has 1 argument of FP type, which matches the
1081 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1082 !FT->getParamType(0)->isFloatingPoint())
1085 Value *Op = CI->getOperand(1);
1086 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1087 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1088 Value *LdExpArg = 0;
1089 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1090 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1091 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1092 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1093 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1094 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1099 if (Op->getType() == Type::FloatTy)
1101 else if (Op->getType() == Type::DoubleTy)
1106 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1107 if (Op->getType() != Type::FloatTy)
1108 One = ConstantExpr::getFPExtend(One, Op->getType());
1110 Module *M = Caller->getParent();
1111 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1112 Op->getType(), Type::Int32Ty,NULL);
1113 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1114 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1115 CI->setCallingConv(F->getCallingConv());
1123 //===---------------------------------------===//
1124 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1126 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
1127 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1128 const FunctionType *FT = Callee->getFunctionType();
1129 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1130 FT->getParamType(0) != Type::DoubleTy)
1133 // If this is something like 'floor((double)floatval)', convert to floorf.
1134 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1135 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1138 // floor((double)floatval) -> (double)floorf(floatval)
1139 Value *V = Cast->getOperand(0);
1140 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
1141 return B.CreateFPExt(V, Type::DoubleTy);
1145 //===----------------------------------------------------------------------===//
1146 // Integer Optimizations
1147 //===----------------------------------------------------------------------===//
1149 //===---------------------------------------===//
1150 // 'ffs*' Optimizations
1152 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
1153 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1154 const FunctionType *FT = Callee->getFunctionType();
1155 // Just make sure this has 2 arguments of the same FP type, which match the
1157 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1158 !isa<IntegerType>(FT->getParamType(0)))
1161 Value *Op = CI->getOperand(1);
1164 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1165 if (CI->getValue() == 0) // ffs(0) -> 0.
1166 return Context->getNullValue(CI->getType());
1167 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
1168 CI->getValue().countTrailingZeros()+1);
1171 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1172 const Type *ArgType = Op->getType();
1173 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1174 Intrinsic::cttz, &ArgType, 1);
1175 Value *V = B.CreateCall(F, Op, "cttz");
1176 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1177 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1179 Value *Cond = B.CreateICmpNE(Op, Context->getNullValue(ArgType), "tmp");
1180 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
1184 //===---------------------------------------===//
1185 // 'isdigit' Optimizations
1187 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
1188 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1189 const FunctionType *FT = Callee->getFunctionType();
1190 // We require integer(i32)
1191 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1192 FT->getParamType(0) != Type::Int32Ty)
1195 // isdigit(c) -> (c-'0') <u 10
1196 Value *Op = CI->getOperand(1);
1197 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'),
1199 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10),
1201 return B.CreateZExt(Op, CI->getType());
1205 //===---------------------------------------===//
1206 // 'isascii' Optimizations
1208 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
1209 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1210 const FunctionType *FT = Callee->getFunctionType();
1211 // We require integer(i32)
1212 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1213 FT->getParamType(0) != Type::Int32Ty)
1216 // isascii(c) -> c <u 128
1217 Value *Op = CI->getOperand(1);
1218 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128),
1220 return B.CreateZExt(Op, CI->getType());
1224 //===---------------------------------------===//
1225 // 'abs', 'labs', 'llabs' Optimizations
1227 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
1228 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1229 const FunctionType *FT = Callee->getFunctionType();
1230 // We require integer(integer) where the types agree.
1231 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1232 FT->getParamType(0) != FT->getReturnType())
1235 // abs(x) -> x >s -1 ? x : -x
1236 Value *Op = CI->getOperand(1);
1237 Value *Pos = B.CreateICmpSGT(Op,
1238 Context->getAllOnesValue(Op->getType()),
1240 Value *Neg = B.CreateNeg(Op, "neg");
1241 return B.CreateSelect(Pos, Op, Neg);
1246 //===---------------------------------------===//
1247 // 'toascii' Optimizations
1249 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
1250 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1251 const FunctionType *FT = Callee->getFunctionType();
1252 // We require i32(i32)
1253 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1254 FT->getParamType(0) != Type::Int32Ty)
1257 // isascii(c) -> c & 0x7f
1258 return B.CreateAnd(CI->getOperand(1),
1259 ConstantInt::get(CI->getType(),0x7F));
1263 //===----------------------------------------------------------------------===//
1264 // Formatting and IO Optimizations
1265 //===----------------------------------------------------------------------===//
1267 //===---------------------------------------===//
1268 // 'printf' Optimizations
1270 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1271 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1272 // Require one fixed pointer argument and an integer/void result.
1273 const FunctionType *FT = Callee->getFunctionType();
1274 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1275 !(isa<IntegerType>(FT->getReturnType()) ||
1276 FT->getReturnType() == Type::VoidTy))
1279 // Check for a fixed format string.
1280 std::string FormatStr;
1281 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1284 // Empty format string -> noop.
1285 if (FormatStr.empty()) // Tolerate printf's declared void.
1286 return CI->use_empty() ? (Value*)CI :
1287 ConstantInt::get(CI->getType(), 0);
1289 // printf("x") -> putchar('x'), even for '%'.
1290 if (FormatStr.size() == 1) {
1291 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1292 return CI->use_empty() ? (Value*)CI :
1293 ConstantInt::get(CI->getType(), 1);
1296 // printf("foo\n") --> puts("foo")
1297 if (FormatStr[FormatStr.size()-1] == '\n' &&
1298 FormatStr.find('%') == std::string::npos) { // no format characters.
1299 // Create a string literal with no \n on it. We expect the constant merge
1300 // pass to be run after this pass, to merge duplicate strings.
1301 FormatStr.erase(FormatStr.end()-1);
1302 Constant *C = ConstantArray::get(FormatStr, true);
1303 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1304 GlobalVariable::InternalLinkage, C, "str");
1306 return CI->use_empty() ? (Value*)CI :
1307 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1310 // Optimize specific format strings.
1311 // printf("%c", chr) --> putchar(*(i8*)dst)
1312 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1313 isa<IntegerType>(CI->getOperand(2)->getType())) {
1314 EmitPutChar(CI->getOperand(2), B);
1315 return CI->use_empty() ? (Value*)CI :
1316 ConstantInt::get(CI->getType(), 1);
1319 // printf("%s\n", str) --> puts(str)
1320 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1321 isa<PointerType>(CI->getOperand(2)->getType()) &&
1323 EmitPutS(CI->getOperand(2), B);
1330 //===---------------------------------------===//
1331 // 'sprintf' Optimizations
1333 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1334 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1335 // Require two fixed pointer arguments and an integer result.
1336 const FunctionType *FT = Callee->getFunctionType();
1337 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1338 !isa<PointerType>(FT->getParamType(1)) ||
1339 !isa<IntegerType>(FT->getReturnType()))
1342 // Check for a fixed format string.
1343 std::string FormatStr;
1344 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1347 // If we just have a format string (nothing else crazy) transform it.
1348 if (CI->getNumOperands() == 3) {
1349 // Make sure there's no % in the constant array. We could try to handle
1350 // %% -> % in the future if we cared.
1351 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1352 if (FormatStr[i] == '%')
1353 return 0; // we found a format specifier, bail out.
1355 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1356 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1357 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1358 return ConstantInt::get(CI->getType(), FormatStr.size());
1361 // The remaining optimizations require the format string to be "%s" or "%c"
1362 // and have an extra operand.
1363 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1366 // Decode the second character of the format string.
1367 if (FormatStr[1] == 'c') {
1368 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1369 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1370 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1371 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1372 B.CreateStore(V, Ptr);
1373 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1374 B.CreateStore(Context->getNullValue(Type::Int8Ty), Ptr);
1376 return ConstantInt::get(CI->getType(), 1);
1379 if (FormatStr[1] == 's') {
1380 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1381 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1383 Value *Len = EmitStrLen(CI->getOperand(3), B);
1384 Value *IncLen = B.CreateAdd(Len,
1385 ConstantInt::get(Len->getType(), 1),
1387 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1389 // The sprintf result is the unincremented number of bytes in the string.
1390 return B.CreateIntCast(Len, CI->getType(), false);
1396 //===---------------------------------------===//
1397 // 'fwrite' Optimizations
1399 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1400 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1401 // Require a pointer, an integer, an integer, a pointer, returning integer.
1402 const FunctionType *FT = Callee->getFunctionType();
1403 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1404 !isa<IntegerType>(FT->getParamType(1)) ||
1405 !isa<IntegerType>(FT->getParamType(2)) ||
1406 !isa<PointerType>(FT->getParamType(3)) ||
1407 !isa<IntegerType>(FT->getReturnType()))
1410 // Get the element size and count.
1411 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1412 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1413 if (!SizeC || !CountC) return 0;
1414 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1416 // If this is writing zero records, remove the call (it's a noop).
1418 return ConstantInt::get(CI->getType(), 0);
1420 // If this is writing one byte, turn it into fputc.
1421 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1422 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1423 EmitFPutC(Char, CI->getOperand(4), B);
1424 return ConstantInt::get(CI->getType(), 1);
1431 //===---------------------------------------===//
1432 // 'fputs' Optimizations
1434 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1435 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1436 // Require two pointers. Also, we can't optimize if return value is used.
1437 const FunctionType *FT = Callee->getFunctionType();
1438 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1439 !isa<PointerType>(FT->getParamType(1)) ||
1443 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1444 uint64_t Len = GetStringLength(CI->getOperand(1));
1446 EmitFWrite(CI->getOperand(1),
1447 ConstantInt::get(TD->getIntPtrType(), Len-1),
1448 CI->getOperand(2), B);
1449 return CI; // Known to have no uses (see above).
1453 //===---------------------------------------===//
1454 // 'fprintf' Optimizations
1456 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1457 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1458 // Require two fixed paramters as pointers and integer result.
1459 const FunctionType *FT = Callee->getFunctionType();
1460 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1461 !isa<PointerType>(FT->getParamType(1)) ||
1462 !isa<IntegerType>(FT->getReturnType()))
1465 // All the optimizations depend on the format string.
1466 std::string FormatStr;
1467 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1470 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1471 if (CI->getNumOperands() == 3) {
1472 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1473 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1474 return 0; // We found a format specifier.
1476 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1478 CI->getOperand(1), B);
1479 return ConstantInt::get(CI->getType(), FormatStr.size());
1482 // The remaining optimizations require the format string to be "%s" or "%c"
1483 // and have an extra operand.
1484 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1487 // Decode the second character of the format string.
1488 if (FormatStr[1] == 'c') {
1489 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1490 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1491 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1492 return ConstantInt::get(CI->getType(), 1);
1495 if (FormatStr[1] == 's') {
1496 // fprintf(F, "%s", str) -> fputs(str, F)
1497 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1499 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1506 } // end anonymous namespace.
1508 //===----------------------------------------------------------------------===//
1509 // SimplifyLibCalls Pass Implementation
1510 //===----------------------------------------------------------------------===//
1513 /// This pass optimizes well known library functions from libc and libm.
1515 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1516 StringMap<LibCallOptimization*> Optimizations;
1517 // Miscellaneous LibCall Optimizations
1519 // String and Memory LibCall Optimizations
1520 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1521 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1522 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1524 // Math Library Optimizations
1525 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1526 // Integer Optimizations
1527 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1529 // Formatting and IO Optimizations
1530 SPrintFOpt SPrintF; PrintFOpt PrintF;
1531 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1533 bool Modified; // This is only used by doInitialization.
1535 static char ID; // Pass identification
1536 SimplifyLibCalls() : FunctionPass(&ID) {}
1538 void InitOptimizations();
1539 bool runOnFunction(Function &F);
1541 void setDoesNotAccessMemory(Function &F);
1542 void setOnlyReadsMemory(Function &F);
1543 void setDoesNotThrow(Function &F);
1544 void setDoesNotCapture(Function &F, unsigned n);
1545 void setDoesNotAlias(Function &F, unsigned n);
1546 bool doInitialization(Module &M);
1548 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1549 AU.addRequired<TargetData>();
1552 char SimplifyLibCalls::ID = 0;
1553 } // end anonymous namespace.
1555 static RegisterPass<SimplifyLibCalls>
1556 X("simplify-libcalls", "Simplify well-known library calls");
1558 // Public interface to the Simplify LibCalls pass.
1559 FunctionPass *llvm::createSimplifyLibCallsPass() {
1560 return new SimplifyLibCalls();
1563 /// Optimizations - Populate the Optimizations map with all the optimizations
1565 void SimplifyLibCalls::InitOptimizations() {
1566 // Miscellaneous LibCall Optimizations
1567 Optimizations["exit"] = &Exit;
1569 // String and Memory LibCall Optimizations
1570 Optimizations["strcat"] = &StrCat;
1571 Optimizations["strncat"] = &StrNCat;
1572 Optimizations["strchr"] = &StrChr;
1573 Optimizations["strcmp"] = &StrCmp;
1574 Optimizations["strncmp"] = &StrNCmp;
1575 Optimizations["strcpy"] = &StrCpy;
1576 Optimizations["strncpy"] = &StrNCpy;
1577 Optimizations["strlen"] = &StrLen;
1578 Optimizations["strtol"] = &StrTo;
1579 Optimizations["strtod"] = &StrTo;
1580 Optimizations["strtof"] = &StrTo;
1581 Optimizations["strtoul"] = &StrTo;
1582 Optimizations["strtoll"] = &StrTo;
1583 Optimizations["strtold"] = &StrTo;
1584 Optimizations["strtoull"] = &StrTo;
1585 Optimizations["memcmp"] = &MemCmp;
1586 Optimizations["memcpy"] = &MemCpy;
1587 Optimizations["memmove"] = &MemMove;
1588 Optimizations["memset"] = &MemSet;
1590 // Math Library Optimizations
1591 Optimizations["powf"] = &Pow;
1592 Optimizations["pow"] = &Pow;
1593 Optimizations["powl"] = &Pow;
1594 Optimizations["llvm.pow.f32"] = &Pow;
1595 Optimizations["llvm.pow.f64"] = &Pow;
1596 Optimizations["llvm.pow.f80"] = &Pow;
1597 Optimizations["llvm.pow.f128"] = &Pow;
1598 Optimizations["llvm.pow.ppcf128"] = &Pow;
1599 Optimizations["exp2l"] = &Exp2;
1600 Optimizations["exp2"] = &Exp2;
1601 Optimizations["exp2f"] = &Exp2;
1602 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1603 Optimizations["llvm.exp2.f128"] = &Exp2;
1604 Optimizations["llvm.exp2.f80"] = &Exp2;
1605 Optimizations["llvm.exp2.f64"] = &Exp2;
1606 Optimizations["llvm.exp2.f32"] = &Exp2;
1609 Optimizations["floor"] = &UnaryDoubleFP;
1612 Optimizations["ceil"] = &UnaryDoubleFP;
1615 Optimizations["round"] = &UnaryDoubleFP;
1618 Optimizations["rint"] = &UnaryDoubleFP;
1620 #ifdef HAVE_NEARBYINTF
1621 Optimizations["nearbyint"] = &UnaryDoubleFP;
1624 // Integer Optimizations
1625 Optimizations["ffs"] = &FFS;
1626 Optimizations["ffsl"] = &FFS;
1627 Optimizations["ffsll"] = &FFS;
1628 Optimizations["abs"] = &Abs;
1629 Optimizations["labs"] = &Abs;
1630 Optimizations["llabs"] = &Abs;
1631 Optimizations["isdigit"] = &IsDigit;
1632 Optimizations["isascii"] = &IsAscii;
1633 Optimizations["toascii"] = &ToAscii;
1635 // Formatting and IO Optimizations
1636 Optimizations["sprintf"] = &SPrintF;
1637 Optimizations["printf"] = &PrintF;
1638 Optimizations["fwrite"] = &FWrite;
1639 Optimizations["fputs"] = &FPuts;
1640 Optimizations["fprintf"] = &FPrintF;
1644 /// runOnFunction - Top level algorithm.
1646 bool SimplifyLibCalls::runOnFunction(Function &F) {
1647 if (Optimizations.empty())
1648 InitOptimizations();
1650 const TargetData &TD = getAnalysis<TargetData>();
1652 IRBuilder<> Builder(F.getContext());
1654 bool Changed = false;
1655 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1656 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1657 // Ignore non-calls.
1658 CallInst *CI = dyn_cast<CallInst>(I++);
1661 // Ignore indirect calls and calls to non-external functions.
1662 Function *Callee = CI->getCalledFunction();
1663 if (Callee == 0 || !Callee->isDeclaration() ||
1664 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1667 // Ignore unknown calls.
1668 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1671 // Set the builder to the instruction after the call.
1672 Builder.SetInsertPoint(BB, I);
1674 // Try to optimize this call.
1675 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1676 if (Result == 0) continue;
1678 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1679 errs() << " into: " << *Result << "\n");
1681 // Something changed!
1685 // Inspect the instruction after the call (which was potentially just
1689 if (CI != Result && !CI->use_empty()) {
1690 CI->replaceAllUsesWith(Result);
1691 if (!Result->hasName())
1692 Result->takeName(CI);
1694 CI->eraseFromParent();
1700 // Utility methods for doInitialization.
1702 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1703 if (!F.doesNotAccessMemory()) {
1704 F.setDoesNotAccessMemory();
1709 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1710 if (!F.onlyReadsMemory()) {
1711 F.setOnlyReadsMemory();
1716 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1717 if (!F.doesNotThrow()) {
1718 F.setDoesNotThrow();
1723 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1724 if (!F.doesNotCapture(n)) {
1725 F.setDoesNotCapture(n);
1730 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1731 if (!F.doesNotAlias(n)) {
1732 F.setDoesNotAlias(n);
1738 /// doInitialization - Add attributes to well-known functions.
1740 bool SimplifyLibCalls::doInitialization(Module &M) {
1742 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1744 if (!F.isDeclaration())
1750 const FunctionType *FTy = F.getFunctionType();
1752 StringRef Name = F.getName();
1755 if (Name == "strlen") {
1756 if (FTy->getNumParams() != 1 ||
1757 !isa<PointerType>(FTy->getParamType(0)))
1759 setOnlyReadsMemory(F);
1761 setDoesNotCapture(F, 1);
1762 } else if (Name == "strcpy" ||
1768 Name == "strtoul" ||
1769 Name == "strtoll" ||
1770 Name == "strtold" ||
1771 Name == "strncat" ||
1772 Name == "strncpy" ||
1773 Name == "strtoull") {
1774 if (FTy->getNumParams() < 2 ||
1775 !isa<PointerType>(FTy->getParamType(1)))
1778 setDoesNotCapture(F, 2);
1779 } else if (Name == "strxfrm") {
1780 if (FTy->getNumParams() != 3 ||
1781 !isa<PointerType>(FTy->getParamType(0)) ||
1782 !isa<PointerType>(FTy->getParamType(1)))
1785 setDoesNotCapture(F, 1);
1786 setDoesNotCapture(F, 2);
1787 } else if (Name == "strcmp" ||
1789 Name == "strncmp" ||
1790 Name ==" strcspn" ||
1791 Name == "strcoll" ||
1792 Name == "strcasecmp" ||
1793 Name == "strncasecmp") {
1794 if (FTy->getNumParams() < 2 ||
1795 !isa<PointerType>(FTy->getParamType(0)) ||
1796 !isa<PointerType>(FTy->getParamType(1)))
1798 setOnlyReadsMemory(F);
1800 setDoesNotCapture(F, 1);
1801 setDoesNotCapture(F, 2);
1802 } else if (Name == "strstr" ||
1803 Name == "strpbrk") {
1804 if (FTy->getNumParams() != 2 ||
1805 !isa<PointerType>(FTy->getParamType(1)))
1807 setOnlyReadsMemory(F);
1809 setDoesNotCapture(F, 2);
1810 } else if (Name == "strtok" ||
1811 Name == "strtok_r") {
1812 if (FTy->getNumParams() < 2 ||
1813 !isa<PointerType>(FTy->getParamType(1)))
1816 setDoesNotCapture(F, 2);
1817 } else if (Name == "scanf" ||
1819 Name == "setvbuf") {
1820 if (FTy->getNumParams() < 1 ||
1821 !isa<PointerType>(FTy->getParamType(0)))
1824 setDoesNotCapture(F, 1);
1825 } else if (Name == "strdup" ||
1826 Name == "strndup") {
1827 if (FTy->getNumParams() < 1 ||
1828 !isa<PointerType>(FTy->getReturnType()) ||
1829 !isa<PointerType>(FTy->getParamType(0)))
1832 setDoesNotAlias(F, 0);
1833 setDoesNotCapture(F, 1);
1834 } else if (Name == "stat" ||
1836 Name == "sprintf" ||
1837 Name == "statvfs") {
1838 if (FTy->getNumParams() < 2 ||
1839 !isa<PointerType>(FTy->getParamType(0)) ||
1840 !isa<PointerType>(FTy->getParamType(1)))
1843 setDoesNotCapture(F, 1);
1844 setDoesNotCapture(F, 2);
1845 } else if (Name == "snprintf") {
1846 if (FTy->getNumParams() != 3 ||
1847 !isa<PointerType>(FTy->getParamType(0)) ||
1848 !isa<PointerType>(FTy->getParamType(2)))
1851 setDoesNotCapture(F, 1);
1852 setDoesNotCapture(F, 3);
1853 } else if (Name == "setitimer") {
1854 if (FTy->getNumParams() != 3 ||
1855 !isa<PointerType>(FTy->getParamType(1)) ||
1856 !isa<PointerType>(FTy->getParamType(2)))
1859 setDoesNotCapture(F, 2);
1860 setDoesNotCapture(F, 3);
1861 } else if (Name == "system") {
1862 if (FTy->getNumParams() != 1 ||
1863 !isa<PointerType>(FTy->getParamType(0)))
1865 // May throw; "system" is a valid pthread cancellation point.
1866 setDoesNotCapture(F, 1);
1870 if (Name == "memcmp") {
1871 if (FTy->getNumParams() != 3 ||
1872 !isa<PointerType>(FTy->getParamType(0)) ||
1873 !isa<PointerType>(FTy->getParamType(1)))
1875 setOnlyReadsMemory(F);
1877 setDoesNotCapture(F, 1);
1878 setDoesNotCapture(F, 2);
1879 } else if (Name == "memchr" ||
1880 Name == "memrchr") {
1881 if (FTy->getNumParams() != 3)
1883 setOnlyReadsMemory(F);
1885 } else if (Name == "modf" ||
1889 Name == "memccpy" ||
1890 Name == "memmove") {
1891 if (FTy->getNumParams() < 2 ||
1892 !isa<PointerType>(FTy->getParamType(1)))
1895 setDoesNotCapture(F, 2);
1896 } else if (Name == "memalign") {
1897 if (!isa<PointerType>(FTy->getReturnType()))
1899 setDoesNotAlias(F, 0);
1900 } else if (Name == "mkdir" ||
1902 if (FTy->getNumParams() == 0 ||
1903 !isa<PointerType>(FTy->getParamType(0)))
1906 setDoesNotCapture(F, 1);
1910 if (Name == "realloc") {
1911 if (FTy->getNumParams() != 2 ||
1912 !isa<PointerType>(FTy->getParamType(0)) ||
1913 !isa<PointerType>(FTy->getReturnType()))
1916 setDoesNotAlias(F, 0);
1917 setDoesNotCapture(F, 1);
1918 } else if (Name == "read") {
1919 if (FTy->getNumParams() != 3 ||
1920 !isa<PointerType>(FTy->getParamType(1)))
1922 // May throw; "read" is a valid pthread cancellation point.
1923 setDoesNotCapture(F, 2);
1924 } else if (Name == "rmdir" ||
1927 Name == "realpath") {
1928 if (FTy->getNumParams() < 1 ||
1929 !isa<PointerType>(FTy->getParamType(0)))
1932 setDoesNotCapture(F, 1);
1933 } else if (Name == "rename" ||
1934 Name == "readlink") {
1935 if (FTy->getNumParams() < 2 ||
1936 !isa<PointerType>(FTy->getParamType(0)) ||
1937 !isa<PointerType>(FTy->getParamType(1)))
1940 setDoesNotCapture(F, 1);
1941 setDoesNotCapture(F, 2);
1945 if (Name == "write") {
1946 if (FTy->getNumParams() != 3 ||
1947 !isa<PointerType>(FTy->getParamType(1)))
1949 // May throw; "write" is a valid pthread cancellation point.
1950 setDoesNotCapture(F, 2);
1954 if (Name == "bcopy") {
1955 if (FTy->getNumParams() != 3 ||
1956 !isa<PointerType>(FTy->getParamType(0)) ||
1957 !isa<PointerType>(FTy->getParamType(1)))
1960 setDoesNotCapture(F, 1);
1961 setDoesNotCapture(F, 2);
1962 } else if (Name == "bcmp") {
1963 if (FTy->getNumParams() != 3 ||
1964 !isa<PointerType>(FTy->getParamType(0)) ||
1965 !isa<PointerType>(FTy->getParamType(1)))
1968 setOnlyReadsMemory(F);
1969 setDoesNotCapture(F, 1);
1970 setDoesNotCapture(F, 2);
1971 } else if (Name == "bzero") {
1972 if (FTy->getNumParams() != 2 ||
1973 !isa<PointerType>(FTy->getParamType(0)))
1976 setDoesNotCapture(F, 1);
1980 if (Name == "calloc") {
1981 if (FTy->getNumParams() != 2 ||
1982 !isa<PointerType>(FTy->getReturnType()))
1985 setDoesNotAlias(F, 0);
1986 } else if (Name == "chmod" ||
1988 Name == "ctermid" ||
1989 Name == "clearerr" ||
1990 Name == "closedir") {
1991 if (FTy->getNumParams() == 0 ||
1992 !isa<PointerType>(FTy->getParamType(0)))
1995 setDoesNotCapture(F, 1);
1999 if (Name == "atoi" ||
2003 if (FTy->getNumParams() != 1 ||
2004 !isa<PointerType>(FTy->getParamType(0)))
2007 setOnlyReadsMemory(F);
2008 setDoesNotCapture(F, 1);
2009 } else if (Name == "access") {
2010 if (FTy->getNumParams() != 2 ||
2011 !isa<PointerType>(FTy->getParamType(0)))
2014 setDoesNotCapture(F, 1);
2018 if (Name == "fopen") {
2019 if (FTy->getNumParams() != 2 ||
2020 !isa<PointerType>(FTy->getReturnType()) ||
2021 !isa<PointerType>(FTy->getParamType(0)) ||
2022 !isa<PointerType>(FTy->getParamType(1)))
2025 setDoesNotAlias(F, 0);
2026 setDoesNotCapture(F, 1);
2027 setDoesNotCapture(F, 2);
2028 } else if (Name == "fdopen") {
2029 if (FTy->getNumParams() != 2 ||
2030 !isa<PointerType>(FTy->getReturnType()) ||
2031 !isa<PointerType>(FTy->getParamType(1)))
2034 setDoesNotAlias(F, 0);
2035 setDoesNotCapture(F, 2);
2036 } else if (Name == "feof" ||
2046 Name == "fsetpos" ||
2047 Name == "flockfile" ||
2048 Name == "funlockfile" ||
2049 Name == "ftrylockfile") {
2050 if (FTy->getNumParams() == 0 ||
2051 !isa<PointerType>(FTy->getParamType(0)))
2054 setDoesNotCapture(F, 1);
2055 } else if (Name == "ferror") {
2056 if (FTy->getNumParams() != 1 ||
2057 !isa<PointerType>(FTy->getParamType(0)))
2060 setDoesNotCapture(F, 1);
2061 setOnlyReadsMemory(F);
2062 } else if (Name == "fputc" ||
2067 Name == "fstatvfs") {
2068 if (FTy->getNumParams() != 2 ||
2069 !isa<PointerType>(FTy->getParamType(1)))
2072 setDoesNotCapture(F, 2);
2073 } else if (Name == "fgets") {
2074 if (FTy->getNumParams() != 3 ||
2075 !isa<PointerType>(FTy->getParamType(0)) ||
2076 !isa<PointerType>(FTy->getParamType(2)))
2079 setDoesNotCapture(F, 3);
2080 } else if (Name == "fread" ||
2082 if (FTy->getNumParams() != 4 ||
2083 !isa<PointerType>(FTy->getParamType(0)) ||
2084 !isa<PointerType>(FTy->getParamType(3)))
2087 setDoesNotCapture(F, 1);
2088 setDoesNotCapture(F, 4);
2089 } else if (Name == "fputs" ||
2091 Name == "fprintf" ||
2092 Name == "fgetpos") {
2093 if (FTy->getNumParams() < 2 ||
2094 !isa<PointerType>(FTy->getParamType(0)) ||
2095 !isa<PointerType>(FTy->getParamType(1)))
2098 setDoesNotCapture(F, 1);
2099 setDoesNotCapture(F, 2);
2103 if (Name == "getc" ||
2104 Name == "getlogin_r" ||
2105 Name == "getc_unlocked") {
2106 if (FTy->getNumParams() == 0 ||
2107 !isa<PointerType>(FTy->getParamType(0)))
2110 setDoesNotCapture(F, 1);
2111 } else if (Name == "getenv") {
2112 if (FTy->getNumParams() != 1 ||
2113 !isa<PointerType>(FTy->getParamType(0)))
2116 setOnlyReadsMemory(F);
2117 setDoesNotCapture(F, 1);
2118 } else if (Name == "gets" ||
2119 Name == "getchar") {
2121 } else if (Name == "getitimer") {
2122 if (FTy->getNumParams() != 2 ||
2123 !isa<PointerType>(FTy->getParamType(1)))
2126 setDoesNotCapture(F, 2);
2127 } else if (Name == "getpwnam") {
2128 if (FTy->getNumParams() != 1 ||
2129 !isa<PointerType>(FTy->getParamType(0)))
2132 setDoesNotCapture(F, 1);
2136 if (Name == "ungetc") {
2137 if (FTy->getNumParams() != 2 ||
2138 !isa<PointerType>(FTy->getParamType(1)))
2141 setDoesNotCapture(F, 2);
2142 } else if (Name == "uname" ||
2144 Name == "unsetenv") {
2145 if (FTy->getNumParams() != 1 ||
2146 !isa<PointerType>(FTy->getParamType(0)))
2149 setDoesNotCapture(F, 1);
2150 } else if (Name == "utime" ||
2152 if (FTy->getNumParams() != 2 ||
2153 !isa<PointerType>(FTy->getParamType(0)) ||
2154 !isa<PointerType>(FTy->getParamType(1)))
2157 setDoesNotCapture(F, 1);
2158 setDoesNotCapture(F, 2);
2162 if (Name == "putc") {
2163 if (FTy->getNumParams() != 2 ||
2164 !isa<PointerType>(FTy->getParamType(1)))
2167 setDoesNotCapture(F, 2);
2168 } else if (Name == "puts" ||
2171 if (FTy->getNumParams() != 1 ||
2172 !isa<PointerType>(FTy->getParamType(0)))
2175 setDoesNotCapture(F, 1);
2176 } else if (Name == "pread" ||
2178 if (FTy->getNumParams() != 4 ||
2179 !isa<PointerType>(FTy->getParamType(1)))
2181 // May throw; these are valid pthread cancellation points.
2182 setDoesNotCapture(F, 2);
2183 } else if (Name == "putchar") {
2185 } else if (Name == "popen") {
2186 if (FTy->getNumParams() != 2 ||
2187 !isa<PointerType>(FTy->getReturnType()) ||
2188 !isa<PointerType>(FTy->getParamType(0)) ||
2189 !isa<PointerType>(FTy->getParamType(1)))
2192 setDoesNotAlias(F, 0);
2193 setDoesNotCapture(F, 1);
2194 setDoesNotCapture(F, 2);
2195 } else if (Name == "pclose") {
2196 if (FTy->getNumParams() != 1 ||
2197 !isa<PointerType>(FTy->getParamType(0)))
2200 setDoesNotCapture(F, 1);
2204 if (Name == "vscanf") {
2205 if (FTy->getNumParams() != 2 ||
2206 !isa<PointerType>(FTy->getParamType(1)))
2209 setDoesNotCapture(F, 1);
2210 } else if (Name == "vsscanf" ||
2211 Name == "vfscanf") {
2212 if (FTy->getNumParams() != 3 ||
2213 !isa<PointerType>(FTy->getParamType(1)) ||
2214 !isa<PointerType>(FTy->getParamType(2)))
2217 setDoesNotCapture(F, 1);
2218 setDoesNotCapture(F, 2);
2219 } else if (Name == "valloc") {
2220 if (!isa<PointerType>(FTy->getReturnType()))
2223 setDoesNotAlias(F, 0);
2224 } else if (Name == "vprintf") {
2225 if (FTy->getNumParams() != 2 ||
2226 !isa<PointerType>(FTy->getParamType(0)))
2229 setDoesNotCapture(F, 1);
2230 } else if (Name == "vfprintf" ||
2231 Name == "vsprintf") {
2232 if (FTy->getNumParams() != 3 ||
2233 !isa<PointerType>(FTy->getParamType(0)) ||
2234 !isa<PointerType>(FTy->getParamType(1)))
2237 setDoesNotCapture(F, 1);
2238 setDoesNotCapture(F, 2);
2239 } else if (Name == "vsnprintf") {
2240 if (FTy->getNumParams() != 4 ||
2241 !isa<PointerType>(FTy->getParamType(0)) ||
2242 !isa<PointerType>(FTy->getParamType(2)))
2245 setDoesNotCapture(F, 1);
2246 setDoesNotCapture(F, 3);
2250 if (Name == "open") {
2251 if (FTy->getNumParams() < 2 ||
2252 !isa<PointerType>(FTy->getParamType(0)))
2254 // May throw; "open" is a valid pthread cancellation point.
2255 setDoesNotCapture(F, 1);
2256 } else if (Name == "opendir") {
2257 if (FTy->getNumParams() != 1 ||
2258 !isa<PointerType>(FTy->getReturnType()) ||
2259 !isa<PointerType>(FTy->getParamType(0)))
2262 setDoesNotAlias(F, 0);
2263 setDoesNotCapture(F, 1);
2267 if (Name == "tmpfile") {
2268 if (!isa<PointerType>(FTy->getReturnType()))
2271 setDoesNotAlias(F, 0);
2272 } else if (Name == "times") {
2273 if (FTy->getNumParams() != 1 ||
2274 !isa<PointerType>(FTy->getParamType(0)))
2277 setDoesNotCapture(F, 1);
2281 if (Name == "htonl" ||
2284 setDoesNotAccessMemory(F);
2288 if (Name == "ntohl" ||
2291 setDoesNotAccessMemory(F);
2295 if (Name == "lstat") {
2296 if (FTy->getNumParams() != 2 ||
2297 !isa<PointerType>(FTy->getParamType(0)) ||
2298 !isa<PointerType>(FTy->getParamType(1)))
2301 setDoesNotCapture(F, 1);
2302 setDoesNotCapture(F, 2);
2303 } else if (Name == "lchown") {
2304 if (FTy->getNumParams() != 3 ||
2305 !isa<PointerType>(FTy->getParamType(0)))
2308 setDoesNotCapture(F, 1);
2312 if (Name == "qsort") {
2313 if (FTy->getNumParams() != 4 ||
2314 !isa<PointerType>(FTy->getParamType(3)))
2316 // May throw; places call through function pointer.
2317 setDoesNotCapture(F, 4);
2321 if (Name == "__strdup" ||
2322 Name == "__strndup") {
2323 if (FTy->getNumParams() < 1 ||
2324 !isa<PointerType>(FTy->getReturnType()) ||
2325 !isa<PointerType>(FTy->getParamType(0)))
2328 setDoesNotAlias(F, 0);
2329 setDoesNotCapture(F, 1);
2330 } else if (Name == "__strtok_r") {
2331 if (FTy->getNumParams() != 3 ||
2332 !isa<PointerType>(FTy->getParamType(1)))
2335 setDoesNotCapture(F, 2);
2336 } else if (Name == "_IO_getc") {
2337 if (FTy->getNumParams() != 1 ||
2338 !isa<PointerType>(FTy->getParamType(0)))
2341 setDoesNotCapture(F, 1);
2342 } else if (Name == "_IO_putc") {
2343 if (FTy->getNumParams() != 2 ||
2344 !isa<PointerType>(FTy->getParamType(1)))
2347 setDoesNotCapture(F, 2);
2351 if (Name == "\1__isoc99_scanf") {
2352 if (FTy->getNumParams() < 1 ||
2353 !isa<PointerType>(FTy->getParamType(0)))
2356 setDoesNotCapture(F, 1);
2357 } else if (Name == "\1stat64" ||
2358 Name == "\1lstat64" ||
2359 Name == "\1statvfs64" ||
2360 Name == "\1__isoc99_sscanf") {
2361 if (FTy->getNumParams() < 1 ||
2362 !isa<PointerType>(FTy->getParamType(0)) ||
2363 !isa<PointerType>(FTy->getParamType(1)))
2366 setDoesNotCapture(F, 1);
2367 setDoesNotCapture(F, 2);
2368 } else if (Name == "\1fopen64") {
2369 if (FTy->getNumParams() != 2 ||
2370 !isa<PointerType>(FTy->getReturnType()) ||
2371 !isa<PointerType>(FTy->getParamType(0)) ||
2372 !isa<PointerType>(FTy->getParamType(1)))
2375 setDoesNotAlias(F, 0);
2376 setDoesNotCapture(F, 1);
2377 setDoesNotCapture(F, 2);
2378 } else if (Name == "\1fseeko64" ||
2379 Name == "\1ftello64") {
2380 if (FTy->getNumParams() == 0 ||
2381 !isa<PointerType>(FTy->getParamType(0)))
2384 setDoesNotCapture(F, 1);
2385 } else if (Name == "\1tmpfile64") {
2386 if (!isa<PointerType>(FTy->getReturnType()))
2389 setDoesNotAlias(F, 0);
2390 } else if (Name == "\1fstat64" ||
2391 Name == "\1fstatvfs64") {
2392 if (FTy->getNumParams() != 2 ||
2393 !isa<PointerType>(FTy->getParamType(1)))
2396 setDoesNotCapture(F, 2);
2397 } else if (Name == "\1open64") {
2398 if (FTy->getNumParams() < 2 ||
2399 !isa<PointerType>(FTy->getParamType(0)))
2401 // May throw; "open" is a valid pthread cancellation point.
2402 setDoesNotCapture(F, 1);
2411 // Additional cases that we need to add to this file:
2414 // * cbrt(expN(X)) -> expN(x/3)
2415 // * cbrt(sqrt(x)) -> pow(x,1/6)
2416 // * cbrt(sqrt(x)) -> pow(x,1/9)
2419 // * cos(-x) -> cos(x)
2422 // * exp(log(x)) -> x
2425 // * log(exp(x)) -> x
2426 // * log(x**y) -> y*log(x)
2427 // * log(exp(y)) -> y*log(e)
2428 // * log(exp2(y)) -> y*log(2)
2429 // * log(exp10(y)) -> y*log(10)
2430 // * log(sqrt(x)) -> 0.5*log(x)
2431 // * log(pow(x,y)) -> y*log(x)
2433 // lround, lroundf, lroundl:
2434 // * lround(cnst) -> cnst'
2437 // * memcmp(x,y,l) -> cnst
2438 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2441 // * pow(exp(x),y) -> exp(x*y)
2442 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2443 // * pow(pow(x,y),z)-> pow(x,y*z)
2446 // * puts("") -> putchar("\n")
2448 // round, roundf, roundl:
2449 // * round(cnst) -> cnst'
2452 // * signbit(cnst) -> cnst'
2453 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2455 // sqrt, sqrtf, sqrtl:
2456 // * sqrt(expN(x)) -> expN(x*0.5)
2457 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2458 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2461 // * stpcpy(str, "literal") ->
2462 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2464 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2465 // (if c is a constant integer and s is a constant string)
2466 // * strrchr(s1,0) -> strchr(s1,0)
2469 // * strpbrk(s,a) -> offset_in_for(s,a)
2470 // (if s and a are both constant strings)
2471 // * strpbrk(s,"") -> 0
2472 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2475 // * strspn(s,a) -> const_int (if both args are constant)
2476 // * strspn("",a) -> 0
2477 // * strspn(s,"") -> 0
2478 // * strcspn(s,a) -> const_int (if both args are constant)
2479 // * strcspn("",a) -> 0
2480 // * strcspn(s,"") -> strlen(a)
2483 // * strstr(x,x) -> x
2484 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2485 // (if s1 and s2 are constant strings)
2488 // * tan(atan(x)) -> x
2490 // trunc, truncf, truncl:
2491 // * trunc(cnst) -> cnst'