1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/BuildLibCalls.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Config/config.h"
37 STATISTIC(NumSimplified
, "Number of library calls simplified");
38 STATISTIC(NumAnnotated
, "Number of attributes added to library functions");
40 //===----------------------------------------------------------------------===//
41 // Optimizer Base Class
42 //===----------------------------------------------------------------------===//
44 /// This class is the abstract base class for the set of optimizations that
45 /// corresponds to one library call.
47 class LibCallOptimization
{
53 LibCallOptimization() { }
54 virtual ~LibCallOptimization() {}
56 /// CallOptimizer - This pure virtual method is implemented by base classes to
57 /// do various optimizations. If this returns null then no transformation was
58 /// performed. If it returns CI, then it transformed the call and CI is to be
59 /// deleted. If it returns something else, replace CI with the new value and
61 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
)
64 Value
*OptimizeCall(CallInst
*CI
, const TargetData
*TD
, IRBuilder
<> &B
) {
65 Caller
= CI
->getParent()->getParent();
67 if (CI
->getCalledFunction())
68 Context
= &CI
->getCalledFunction()->getContext();
70 // We never change the calling convention.
71 if (CI
->getCallingConv() != llvm::CallingConv::C
)
74 return CallOptimizer(CI
->getCalledFunction(), CI
, B
);
77 } // End anonymous namespace.
80 //===----------------------------------------------------------------------===//
82 //===----------------------------------------------------------------------===//
84 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
85 /// value is equal or not-equal to zero.
86 static bool IsOnlyUsedInZeroEqualityComparison(Value
*V
) {
87 for (Value::use_iterator UI
= V
->use_begin(), E
= V
->use_end();
89 if (ICmpInst
*IC
= dyn_cast
<ICmpInst
>(*UI
))
91 if (Constant
*C
= dyn_cast
<Constant
>(IC
->getOperand(1)))
94 // Unknown instruction.
100 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
101 /// comparisons with With.
102 static bool IsOnlyUsedInEqualityComparison(Value
*V
, Value
*With
) {
103 for (Value::use_iterator UI
= V
->use_begin(), E
= V
->use_end();
105 if (ICmpInst
*IC
= dyn_cast
<ICmpInst
>(*UI
))
106 if (IC
->isEquality() && IC
->getOperand(1) == With
)
108 // Unknown instruction.
114 //===----------------------------------------------------------------------===//
115 // String and Memory LibCall Optimizations
116 //===----------------------------------------------------------------------===//
118 //===---------------------------------------===//
119 // 'strcat' Optimizations
121 struct StrCatOpt
: public LibCallOptimization
{
122 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
123 // Verify the "strcat" function prototype.
124 const FunctionType
*FT
= Callee
->getFunctionType();
125 if (FT
->getNumParams() != 2 ||
126 FT
->getReturnType() != Type::getInt8PtrTy(*Context
) ||
127 FT
->getParamType(0) != FT
->getReturnType() ||
128 FT
->getParamType(1) != FT
->getReturnType())
131 // Extract some information from the instruction
132 Value
*Dst
= CI
->getArgOperand(0);
133 Value
*Src
= CI
->getArgOperand(1);
135 // See if we can get the length of the input string.
136 uint64_t Len
= GetStringLength(Src
);
137 if (Len
== 0) return 0;
138 --Len
; // Unbias length.
140 // Handle the simple, do-nothing case: strcat(x, "") -> x
144 // These optimizations require TargetData.
147 EmitStrLenMemCpy(Src
, Dst
, Len
, B
);
151 void EmitStrLenMemCpy(Value
*Src
, Value
*Dst
, uint64_t Len
, IRBuilder
<> &B
) {
152 // We need to find the end of the destination string. That's where the
153 // memory is to be moved to. We just generate a call to strlen.
154 Value
*DstLen
= EmitStrLen(Dst
, B
, TD
);
156 // Now that we have the destination's length, we must index into the
157 // destination's pointer to get the actual memcpy destination (end of
158 // the string .. we're concatenating).
159 Value
*CpyDst
= B
.CreateGEP(Dst
, DstLen
, "endptr");
161 // We have enough information to now generate the memcpy call to do the
162 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
163 EmitMemCpy(CpyDst
, Src
,
164 ConstantInt::get(TD
->getIntPtrType(*Context
), Len
+1),
169 //===---------------------------------------===//
170 // 'strncat' Optimizations
172 struct StrNCatOpt
: public StrCatOpt
{
173 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
174 // Verify the "strncat" function prototype.
175 const FunctionType
*FT
= Callee
->getFunctionType();
176 if (FT
->getNumParams() != 3 ||
177 FT
->getReturnType() != Type::getInt8PtrTy(*Context
) ||
178 FT
->getParamType(0) != FT
->getReturnType() ||
179 FT
->getParamType(1) != FT
->getReturnType() ||
180 !FT
->getParamType(2)->isIntegerTy())
183 // Extract some information from the instruction
184 Value
*Dst
= CI
->getArgOperand(0);
185 Value
*Src
= CI
->getArgOperand(1);
188 // We don't do anything if length is not constant
189 if (ConstantInt
*LengthArg
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(2)))
190 Len
= LengthArg
->getZExtValue();
194 // See if we can get the length of the input string.
195 uint64_t SrcLen
= GetStringLength(Src
);
196 if (SrcLen
== 0) return 0;
197 --SrcLen
; // Unbias length.
199 // Handle the simple, do-nothing cases:
200 // strncat(x, "", c) -> x
201 // strncat(x, c, 0) -> x
202 if (SrcLen
== 0 || Len
== 0) return Dst
;
204 // These optimizations require TargetData.
207 // We don't optimize this case
208 if (Len
< SrcLen
) return 0;
210 // strncat(x, s, c) -> strcat(x, s)
211 // s is constant so the strcat can be optimized further
212 EmitStrLenMemCpy(Src
, Dst
, SrcLen
, B
);
217 //===---------------------------------------===//
218 // 'strchr' Optimizations
220 struct StrChrOpt
: public LibCallOptimization
{
221 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
222 // Verify the "strchr" function prototype.
223 const FunctionType
*FT
= Callee
->getFunctionType();
224 if (FT
->getNumParams() != 2 ||
225 FT
->getReturnType() != Type::getInt8PtrTy(*Context
) ||
226 FT
->getParamType(0) != FT
->getReturnType() ||
227 !FT
->getParamType(1)->isIntegerTy(32))
230 Value
*SrcStr
= CI
->getArgOperand(0);
232 // If the second operand is non-constant, see if we can compute the length
233 // of the input string and turn this into memchr.
234 ConstantInt
*CharC
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(1));
236 // These optimizations require TargetData.
239 uint64_t Len
= GetStringLength(SrcStr
);
240 if (Len
== 0 || !FT
->getParamType(1)->isIntegerTy(32))// memchr needs i32.
243 return EmitMemChr(SrcStr
, CI
->getArgOperand(1), // include nul.
244 ConstantInt::get(TD
->getIntPtrType(*Context
), Len
),
248 // Otherwise, the character is a constant, see if the first argument is
249 // a string literal. If so, we can constant fold.
251 if (!GetConstantStringInfo(SrcStr
, Str
))
254 // strchr can find the nul character.
257 // Compute the offset.
258 size_t I
= Str
.find(CharC
->getSExtValue());
259 if (I
== std::string::npos
) // Didn't find the char. strchr returns null.
260 return Constant::getNullValue(CI
->getType());
262 // strchr(s+n,c) -> gep(s+n+i,c)
263 Value
*Idx
= ConstantInt::get(Type::getInt64Ty(*Context
), I
);
264 return B
.CreateGEP(SrcStr
, Idx
, "strchr");
268 //===---------------------------------------===//
269 // 'strrchr' Optimizations
271 struct StrRChrOpt
: public LibCallOptimization
{
272 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
273 // Verify the "strrchr" function prototype.
274 const FunctionType
*FT
= Callee
->getFunctionType();
275 if (FT
->getNumParams() != 2 ||
276 FT
->getReturnType() != Type::getInt8PtrTy(*Context
) ||
277 FT
->getParamType(0) != FT
->getReturnType() ||
278 !FT
->getParamType(1)->isIntegerTy(32))
281 Value
*SrcStr
= CI
->getArgOperand(0);
282 ConstantInt
*CharC
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(1));
284 // Cannot fold anything if we're not looking for a constant.
289 if (!GetConstantStringInfo(SrcStr
, Str
)) {
290 // strrchr(s, 0) -> strchr(s, 0)
291 if (TD
&& CharC
->isZero())
292 return EmitStrChr(SrcStr
, '\0', B
, TD
);
296 // strrchr can find the nul character.
299 // Compute the offset.
300 size_t I
= Str
.rfind(CharC
->getSExtValue());
301 if (I
== std::string::npos
) // Didn't find the char. Return null.
302 return Constant::getNullValue(CI
->getType());
304 // strrchr(s+n,c) -> gep(s+n+i,c)
305 Value
*Idx
= ConstantInt::get(Type::getInt64Ty(*Context
), I
);
306 return B
.CreateGEP(SrcStr
, Idx
, "strrchr");
310 //===---------------------------------------===//
311 // 'strcmp' Optimizations
313 struct StrCmpOpt
: public LibCallOptimization
{
314 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
315 // Verify the "strcmp" function prototype.
316 const FunctionType
*FT
= Callee
->getFunctionType();
317 if (FT
->getNumParams() != 2 ||
318 !FT
->getReturnType()->isIntegerTy(32) ||
319 FT
->getParamType(0) != FT
->getParamType(1) ||
320 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
))
323 Value
*Str1P
= CI
->getArgOperand(0), *Str2P
= CI
->getArgOperand(1);
324 if (Str1P
== Str2P
) // strcmp(x,x) -> 0
325 return ConstantInt::get(CI
->getType(), 0);
327 std::string Str1
, Str2
;
328 bool HasStr1
= GetConstantStringInfo(Str1P
, Str1
);
329 bool HasStr2
= GetConstantStringInfo(Str2P
, Str2
);
331 if (HasStr1
&& Str1
.empty()) // strcmp("", x) -> *x
332 return B
.CreateZExt(B
.CreateLoad(Str2P
, "strcmpload"), CI
->getType());
334 if (HasStr2
&& Str2
.empty()) // strcmp(x,"") -> *x
335 return B
.CreateZExt(B
.CreateLoad(Str1P
, "strcmpload"), CI
->getType());
337 // strcmp(x, y) -> cnst (if both x and y are constant strings)
338 if (HasStr1
&& HasStr2
)
339 return ConstantInt::get(CI
->getType(),
340 strcmp(Str1
.c_str(),Str2
.c_str()));
342 // strcmp(P, "x") -> memcmp(P, "x", 2)
343 uint64_t Len1
= GetStringLength(Str1P
);
344 uint64_t Len2
= GetStringLength(Str2P
);
346 // These optimizations require TargetData.
349 return EmitMemCmp(Str1P
, Str2P
,
350 ConstantInt::get(TD
->getIntPtrType(*Context
),
351 std::min(Len1
, Len2
)), B
, TD
);
358 //===---------------------------------------===//
359 // 'strncmp' Optimizations
361 struct StrNCmpOpt
: public LibCallOptimization
{
362 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
363 // Verify the "strncmp" function prototype.
364 const FunctionType
*FT
= Callee
->getFunctionType();
365 if (FT
->getNumParams() != 3 ||
366 !FT
->getReturnType()->isIntegerTy(32) ||
367 FT
->getParamType(0) != FT
->getParamType(1) ||
368 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
) ||
369 !FT
->getParamType(2)->isIntegerTy())
372 Value
*Str1P
= CI
->getArgOperand(0), *Str2P
= CI
->getArgOperand(1);
373 if (Str1P
== Str2P
) // strncmp(x,x,n) -> 0
374 return ConstantInt::get(CI
->getType(), 0);
376 // Get the length argument if it is constant.
378 if (ConstantInt
*LengthArg
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(2)))
379 Length
= LengthArg
->getZExtValue();
383 if (Length
== 0) // strncmp(x,y,0) -> 0
384 return ConstantInt::get(CI
->getType(), 0);
386 if (TD
&& Length
== 1) // strncmp(x,y,1) -> memcmp(x,y,1)
387 return EmitMemCmp(Str1P
, Str2P
, CI
->getArgOperand(2), B
, TD
);
389 std::string Str1
, Str2
;
390 bool HasStr1
= GetConstantStringInfo(Str1P
, Str1
);
391 bool HasStr2
= GetConstantStringInfo(Str2P
, Str2
);
393 if (HasStr1
&& Str1
.empty()) // strncmp("", x, n) -> *x
394 return B
.CreateZExt(B
.CreateLoad(Str2P
, "strcmpload"), CI
->getType());
396 if (HasStr2
&& Str2
.empty()) // strncmp(x, "", n) -> *x
397 return B
.CreateZExt(B
.CreateLoad(Str1P
, "strcmpload"), CI
->getType());
399 // strncmp(x, y) -> cnst (if both x and y are constant strings)
400 if (HasStr1
&& HasStr2
)
401 return ConstantInt::get(CI
->getType(),
402 strncmp(Str1
.c_str(), Str2
.c_str(), Length
));
408 //===---------------------------------------===//
409 // 'strcpy' Optimizations
411 struct StrCpyOpt
: public LibCallOptimization
{
412 bool OptChkCall
; // True if it's optimizing a __strcpy_chk libcall.
414 StrCpyOpt(bool c
) : OptChkCall(c
) {}
416 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
417 // Verify the "strcpy" function prototype.
418 unsigned NumParams
= OptChkCall
? 3 : 2;
419 const FunctionType
*FT
= Callee
->getFunctionType();
420 if (FT
->getNumParams() != NumParams
||
421 FT
->getReturnType() != FT
->getParamType(0) ||
422 FT
->getParamType(0) != FT
->getParamType(1) ||
423 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
))
426 Value
*Dst
= CI
->getArgOperand(0), *Src
= CI
->getArgOperand(1);
427 if (Dst
== Src
) // strcpy(x,x) -> x
430 // These optimizations require TargetData.
433 // See if we can get the length of the input string.
434 uint64_t Len
= GetStringLength(Src
);
435 if (Len
== 0) return 0;
437 // We have enough information to now generate the memcpy call to do the
438 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
440 EmitMemCpyChk(Dst
, Src
,
441 ConstantInt::get(TD
->getIntPtrType(*Context
), Len
),
442 CI
->getArgOperand(2), B
, TD
);
445 ConstantInt::get(TD
->getIntPtrType(*Context
), Len
),
451 //===---------------------------------------===//
452 // 'strncpy' Optimizations
454 struct StrNCpyOpt
: public LibCallOptimization
{
455 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
456 const FunctionType
*FT
= Callee
->getFunctionType();
457 if (FT
->getNumParams() != 3 || FT
->getReturnType() != FT
->getParamType(0) ||
458 FT
->getParamType(0) != FT
->getParamType(1) ||
459 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
) ||
460 !FT
->getParamType(2)->isIntegerTy())
463 Value
*Dst
= CI
->getArgOperand(0);
464 Value
*Src
= CI
->getArgOperand(1);
465 Value
*LenOp
= CI
->getArgOperand(2);
467 // See if we can get the length of the input string.
468 uint64_t SrcLen
= GetStringLength(Src
);
469 if (SrcLen
== 0) return 0;
473 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
474 EmitMemSet(Dst
, ConstantInt::get(Type::getInt8Ty(*Context
), '\0'),
475 LenOp
, false, B
, TD
);
480 if (ConstantInt
*LengthArg
= dyn_cast
<ConstantInt
>(LenOp
))
481 Len
= LengthArg
->getZExtValue();
485 if (Len
== 0) return Dst
; // strncpy(x, y, 0) -> x
487 // These optimizations require TargetData.
490 // Let strncpy handle the zero padding
491 if (Len
> SrcLen
+1) return 0;
493 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
495 ConstantInt::get(TD
->getIntPtrType(*Context
), Len
),
502 //===---------------------------------------===//
503 // 'strlen' Optimizations
505 struct StrLenOpt
: public LibCallOptimization
{
506 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
507 const FunctionType
*FT
= Callee
->getFunctionType();
508 if (FT
->getNumParams() != 1 ||
509 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
) ||
510 !FT
->getReturnType()->isIntegerTy())
513 Value
*Src
= CI
->getArgOperand(0);
515 // Constant folding: strlen("xyz") -> 3
516 if (uint64_t Len
= GetStringLength(Src
))
517 return ConstantInt::get(CI
->getType(), Len
-1);
519 // strlen(x) != 0 --> *x != 0
520 // strlen(x) == 0 --> *x == 0
521 if (IsOnlyUsedInZeroEqualityComparison(CI
))
522 return B
.CreateZExt(B
.CreateLoad(Src
, "strlenfirst"), CI
->getType());
528 //===---------------------------------------===//
529 // 'strpbrk' Optimizations
531 struct StrPBrkOpt
: public LibCallOptimization
{
532 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
533 const FunctionType
*FT
= Callee
->getFunctionType();
534 if (FT
->getNumParams() != 2 ||
535 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
) ||
536 FT
->getParamType(1) != FT
->getParamType(0) ||
537 FT
->getReturnType() != FT
->getParamType(0))
541 bool HasS1
= GetConstantStringInfo(CI
->getArgOperand(0), S1
);
542 bool HasS2
= GetConstantStringInfo(CI
->getArgOperand(1), S2
);
544 // strpbrk(s, "") -> NULL
545 // strpbrk("", s) -> NULL
546 if ((HasS1
&& S1
.empty()) || (HasS2
&& S2
.empty()))
547 return Constant::getNullValue(CI
->getType());
550 if (HasS1
&& HasS2
) {
551 size_t I
= S1
.find_first_of(S2
);
552 if (I
== std::string::npos
) // No match.
553 return Constant::getNullValue(CI
->getType());
555 Value
*Idx
= ConstantInt::get(Type::getInt64Ty(*Context
), I
);
556 return B
.CreateGEP(CI
->getArgOperand(0), Idx
, "strpbrk");
559 // strpbrk(s, "a") -> strchr(s, 'a')
560 if (TD
&& HasS2
&& S2
.size() == 1)
561 return EmitStrChr(CI
->getArgOperand(0), S2
[0], B
, TD
);
567 //===---------------------------------------===//
568 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
570 struct StrToOpt
: public LibCallOptimization
{
571 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
572 const FunctionType
*FT
= Callee
->getFunctionType();
573 if ((FT
->getNumParams() != 2 && FT
->getNumParams() != 3) ||
574 !FT
->getParamType(0)->isPointerTy() ||
575 !FT
->getParamType(1)->isPointerTy())
578 Value
*EndPtr
= CI
->getArgOperand(1);
579 if (isa
<ConstantPointerNull
>(EndPtr
)) {
580 CI
->setOnlyReadsMemory();
581 CI
->addAttribute(1, Attribute::NoCapture
);
588 //===---------------------------------------===//
589 // 'strspn' Optimizations
591 struct StrSpnOpt
: public LibCallOptimization
{
592 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
593 const FunctionType
*FT
= Callee
->getFunctionType();
594 if (FT
->getNumParams() != 2 ||
595 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
) ||
596 FT
->getParamType(1) != FT
->getParamType(0) ||
597 !FT
->getReturnType()->isIntegerTy())
601 bool HasS1
= GetConstantStringInfo(CI
->getArgOperand(0), S1
);
602 bool HasS2
= GetConstantStringInfo(CI
->getArgOperand(1), S2
);
604 // strspn(s, "") -> 0
605 // strspn("", s) -> 0
606 if ((HasS1
&& S1
.empty()) || (HasS2
&& S2
.empty()))
607 return Constant::getNullValue(CI
->getType());
611 return ConstantInt::get(CI
->getType(), strspn(S1
.c_str(), S2
.c_str()));
617 //===---------------------------------------===//
618 // 'strcspn' Optimizations
620 struct StrCSpnOpt
: public LibCallOptimization
{
621 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
622 const FunctionType
*FT
= Callee
->getFunctionType();
623 if (FT
->getNumParams() != 2 ||
624 FT
->getParamType(0) != Type::getInt8PtrTy(*Context
) ||
625 FT
->getParamType(1) != FT
->getParamType(0) ||
626 !FT
->getReturnType()->isIntegerTy())
630 bool HasS1
= GetConstantStringInfo(CI
->getArgOperand(0), S1
);
631 bool HasS2
= GetConstantStringInfo(CI
->getArgOperand(1), S2
);
633 // strcspn("", s) -> 0
634 if (HasS1
&& S1
.empty())
635 return Constant::getNullValue(CI
->getType());
639 return ConstantInt::get(CI
->getType(), strcspn(S1
.c_str(), S2
.c_str()));
641 // strcspn(s, "") -> strlen(s)
642 if (TD
&& HasS2
&& S2
.empty())
643 return EmitStrLen(CI
->getArgOperand(0), B
, TD
);
649 //===---------------------------------------===//
650 // 'strstr' Optimizations
652 struct StrStrOpt
: public LibCallOptimization
{
653 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
654 const FunctionType
*FT
= Callee
->getFunctionType();
655 if (FT
->getNumParams() != 2 ||
656 !FT
->getParamType(0)->isPointerTy() ||
657 !FT
->getParamType(1)->isPointerTy() ||
658 !FT
->getReturnType()->isPointerTy())
661 // fold strstr(x, x) -> x.
662 if (CI
->getArgOperand(0) == CI
->getArgOperand(1))
663 return B
.CreateBitCast(CI
->getArgOperand(0), CI
->getType());
665 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
666 if (TD
&& IsOnlyUsedInEqualityComparison(CI
, CI
->getArgOperand(0))) {
667 Value
*StrLen
= EmitStrLen(CI
->getArgOperand(1), B
, TD
);
668 Value
*StrNCmp
= EmitStrNCmp(CI
->getArgOperand(0), CI
->getArgOperand(1),
670 for (Value::use_iterator UI
= CI
->use_begin(), UE
= CI
->use_end();
672 ICmpInst
*Old
= cast
<ICmpInst
>(*UI
++);
673 Value
*Cmp
= B
.CreateICmp(Old
->getPredicate(), StrNCmp
,
674 ConstantInt::getNullValue(StrNCmp
->getType()),
676 Old
->replaceAllUsesWith(Cmp
);
677 Old
->eraseFromParent();
682 // See if either input string is a constant string.
683 std::string SearchStr
, ToFindStr
;
684 bool HasStr1
= GetConstantStringInfo(CI
->getArgOperand(0), SearchStr
);
685 bool HasStr2
= GetConstantStringInfo(CI
->getArgOperand(1), ToFindStr
);
687 // fold strstr(x, "") -> x.
688 if (HasStr2
&& ToFindStr
.empty())
689 return B
.CreateBitCast(CI
->getArgOperand(0), CI
->getType());
691 // If both strings are known, constant fold it.
692 if (HasStr1
&& HasStr2
) {
693 std::string::size_type Offset
= SearchStr
.find(ToFindStr
);
695 if (Offset
== std::string::npos
) // strstr("foo", "bar") -> null
696 return Constant::getNullValue(CI
->getType());
698 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
699 Value
*Result
= CastToCStr(CI
->getArgOperand(0), B
);
700 Result
= B
.CreateConstInBoundsGEP1_64(Result
, Offset
, "strstr");
701 return B
.CreateBitCast(Result
, CI
->getType());
704 // fold strstr(x, "y") -> strchr(x, 'y').
705 if (HasStr2
&& ToFindStr
.size() == 1)
706 return B
.CreateBitCast(EmitStrChr(CI
->getArgOperand(0),
707 ToFindStr
[0], B
, TD
), CI
->getType());
713 //===---------------------------------------===//
714 // 'memcmp' Optimizations
716 struct MemCmpOpt
: public LibCallOptimization
{
717 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
718 const FunctionType
*FT
= Callee
->getFunctionType();
719 if (FT
->getNumParams() != 3 || !FT
->getParamType(0)->isPointerTy() ||
720 !FT
->getParamType(1)->isPointerTy() ||
721 !FT
->getReturnType()->isIntegerTy(32))
724 Value
*LHS
= CI
->getArgOperand(0), *RHS
= CI
->getArgOperand(1);
726 if (LHS
== RHS
) // memcmp(s,s,x) -> 0
727 return Constant::getNullValue(CI
->getType());
729 // Make sure we have a constant length.
730 ConstantInt
*LenC
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(2));
732 uint64_t Len
= LenC
->getZExtValue();
734 if (Len
== 0) // memcmp(s1,s2,0) -> 0
735 return Constant::getNullValue(CI
->getType());
737 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
739 Value
*LHSV
= B
.CreateZExt(B
.CreateLoad(CastToCStr(LHS
, B
), "lhsc"),
740 CI
->getType(), "lhsv");
741 Value
*RHSV
= B
.CreateZExt(B
.CreateLoad(CastToCStr(RHS
, B
), "rhsc"),
742 CI
->getType(), "rhsv");
743 return B
.CreateSub(LHSV
, RHSV
, "chardiff");
746 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
747 std::string LHSStr
, RHSStr
;
748 if (GetConstantStringInfo(LHS
, LHSStr
) &&
749 GetConstantStringInfo(RHS
, RHSStr
)) {
750 // Make sure we're not reading out-of-bounds memory.
751 if (Len
> LHSStr
.length() || Len
> RHSStr
.length())
753 uint64_t Ret
= memcmp(LHSStr
.data(), RHSStr
.data(), Len
);
754 return ConstantInt::get(CI
->getType(), Ret
);
761 //===---------------------------------------===//
762 // 'memcpy' Optimizations
764 struct MemCpyOpt
: public LibCallOptimization
{
765 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
766 // These optimizations require TargetData.
769 const FunctionType
*FT
= Callee
->getFunctionType();
770 if (FT
->getNumParams() != 3 || FT
->getReturnType() != FT
->getParamType(0) ||
771 !FT
->getParamType(0)->isPointerTy() ||
772 !FT
->getParamType(1)->isPointerTy() ||
773 FT
->getParamType(2) != TD
->getIntPtrType(*Context
))
776 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
777 EmitMemCpy(CI
->getArgOperand(0), CI
->getArgOperand(1),
778 CI
->getArgOperand(2), 1, false, B
, TD
);
779 return CI
->getArgOperand(0);
783 //===---------------------------------------===//
784 // 'memmove' Optimizations
786 struct MemMoveOpt
: public LibCallOptimization
{
787 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
788 // These optimizations require TargetData.
791 const FunctionType
*FT
= Callee
->getFunctionType();
792 if (FT
->getNumParams() != 3 || FT
->getReturnType() != FT
->getParamType(0) ||
793 !FT
->getParamType(0)->isPointerTy() ||
794 !FT
->getParamType(1)->isPointerTy() ||
795 FT
->getParamType(2) != TD
->getIntPtrType(*Context
))
798 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
799 EmitMemMove(CI
->getArgOperand(0), CI
->getArgOperand(1),
800 CI
->getArgOperand(2), 1, false, B
, TD
);
801 return CI
->getArgOperand(0);
805 //===---------------------------------------===//
806 // 'memset' Optimizations
808 struct MemSetOpt
: public LibCallOptimization
{
809 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
810 // These optimizations require TargetData.
813 const FunctionType
*FT
= Callee
->getFunctionType();
814 if (FT
->getNumParams() != 3 || FT
->getReturnType() != FT
->getParamType(0) ||
815 !FT
->getParamType(0)->isPointerTy() ||
816 !FT
->getParamType(1)->isIntegerTy() ||
817 FT
->getParamType(2) != TD
->getIntPtrType(*Context
))
820 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
821 Value
*Val
= B
.CreateIntCast(CI
->getArgOperand(1),
822 Type::getInt8Ty(*Context
), false);
823 EmitMemSet(CI
->getArgOperand(0), Val
, CI
->getArgOperand(2), false, B
, TD
);
824 return CI
->getArgOperand(0);
828 //===----------------------------------------------------------------------===//
829 // Math Library Optimizations
830 //===----------------------------------------------------------------------===//
832 //===---------------------------------------===//
833 // 'pow*' Optimizations
835 struct PowOpt
: public LibCallOptimization
{
836 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
837 const FunctionType
*FT
= Callee
->getFunctionType();
838 // Just make sure this has 2 arguments of the same FP type, which match the
840 if (FT
->getNumParams() != 2 || FT
->getReturnType() != FT
->getParamType(0) ||
841 FT
->getParamType(0) != FT
->getParamType(1) ||
842 !FT
->getParamType(0)->isFloatingPointTy())
845 Value
*Op1
= CI
->getArgOperand(0), *Op2
= CI
->getArgOperand(1);
846 if (ConstantFP
*Op1C
= dyn_cast
<ConstantFP
>(Op1
)) {
847 if (Op1C
->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
849 if (Op1C
->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
850 return EmitUnaryFloatFnCall(Op2
, "exp2", B
, Callee
->getAttributes());
853 ConstantFP
*Op2C
= dyn_cast
<ConstantFP
>(Op2
);
854 if (Op2C
== 0) return 0;
856 if (Op2C
->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
857 return ConstantFP::get(CI
->getType(), 1.0);
859 if (Op2C
->isExactlyValue(0.5)) {
860 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
861 // This is faster than calling pow, and still handles negative zero
862 // and negative infinite correctly.
863 // TODO: In fast-math mode, this could be just sqrt(x).
864 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
865 Value
*Inf
= ConstantFP::getInfinity(CI
->getType());
866 Value
*NegInf
= ConstantFP::getInfinity(CI
->getType(), true);
867 Value
*Sqrt
= EmitUnaryFloatFnCall(Op1
, "sqrt", B
,
868 Callee
->getAttributes());
869 Value
*FAbs
= EmitUnaryFloatFnCall(Sqrt
, "fabs", B
,
870 Callee
->getAttributes());
871 Value
*FCmp
= B
.CreateFCmpOEQ(Op1
, NegInf
, "tmp");
872 Value
*Sel
= B
.CreateSelect(FCmp
, Inf
, FAbs
, "tmp");
876 if (Op2C
->isExactlyValue(1.0)) // pow(x, 1.0) -> x
878 if (Op2C
->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
879 return B
.CreateFMul(Op1
, Op1
, "pow2");
880 if (Op2C
->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
881 return B
.CreateFDiv(ConstantFP::get(CI
->getType(), 1.0),
887 //===---------------------------------------===//
888 // 'exp2' Optimizations
890 struct Exp2Opt
: public LibCallOptimization
{
891 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
892 const FunctionType
*FT
= Callee
->getFunctionType();
893 // Just make sure this has 1 argument of FP type, which matches the
895 if (FT
->getNumParams() != 1 || FT
->getReturnType() != FT
->getParamType(0) ||
896 !FT
->getParamType(0)->isFloatingPointTy())
899 Value
*Op
= CI
->getArgOperand(0);
900 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
901 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
903 if (SIToFPInst
*OpC
= dyn_cast
<SIToFPInst
>(Op
)) {
904 if (OpC
->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
905 LdExpArg
= B
.CreateSExt(OpC
->getOperand(0),
906 Type::getInt32Ty(*Context
), "tmp");
907 } else if (UIToFPInst
*OpC
= dyn_cast
<UIToFPInst
>(Op
)) {
908 if (OpC
->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
909 LdExpArg
= B
.CreateZExt(OpC
->getOperand(0),
910 Type::getInt32Ty(*Context
), "tmp");
915 if (Op
->getType()->isFloatTy())
917 else if (Op
->getType()->isDoubleTy())
922 Constant
*One
= ConstantFP::get(*Context
, APFloat(1.0f
));
923 if (!Op
->getType()->isFloatTy())
924 One
= ConstantExpr::getFPExtend(One
, Op
->getType());
926 Module
*M
= Caller
->getParent();
927 Value
*Callee
= M
->getOrInsertFunction(Name
, Op
->getType(),
929 Type::getInt32Ty(*Context
),NULL
);
930 CallInst
*CI
= B
.CreateCall2(Callee
, One
, LdExpArg
);
931 if (const Function
*F
= dyn_cast
<Function
>(Callee
->stripPointerCasts()))
932 CI
->setCallingConv(F
->getCallingConv());
940 //===---------------------------------------===//
941 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
943 struct UnaryDoubleFPOpt
: public LibCallOptimization
{
944 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
945 const FunctionType
*FT
= Callee
->getFunctionType();
946 if (FT
->getNumParams() != 1 || !FT
->getReturnType()->isDoubleTy() ||
947 !FT
->getParamType(0)->isDoubleTy())
950 // If this is something like 'floor((double)floatval)', convert to floorf.
951 FPExtInst
*Cast
= dyn_cast
<FPExtInst
>(CI
->getArgOperand(0));
952 if (Cast
== 0 || !Cast
->getOperand(0)->getType()->isFloatTy())
955 // floor((double)floatval) -> (double)floorf(floatval)
956 Value
*V
= Cast
->getOperand(0);
957 V
= EmitUnaryFloatFnCall(V
, Callee
->getName().data(), B
,
958 Callee
->getAttributes());
959 return B
.CreateFPExt(V
, Type::getDoubleTy(*Context
));
963 //===----------------------------------------------------------------------===//
964 // Integer Optimizations
965 //===----------------------------------------------------------------------===//
967 //===---------------------------------------===//
968 // 'ffs*' Optimizations
970 struct FFSOpt
: public LibCallOptimization
{
971 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
972 const FunctionType
*FT
= Callee
->getFunctionType();
973 // Just make sure this has 2 arguments of the same FP type, which match the
975 if (FT
->getNumParams() != 1 ||
976 !FT
->getReturnType()->isIntegerTy(32) ||
977 !FT
->getParamType(0)->isIntegerTy())
980 Value
*Op
= CI
->getArgOperand(0);
983 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Op
)) {
984 if (CI
->getValue() == 0) // ffs(0) -> 0.
985 return Constant::getNullValue(CI
->getType());
986 return ConstantInt::get(Type::getInt32Ty(*Context
), // ffs(c) -> cttz(c)+1
987 CI
->getValue().countTrailingZeros()+1);
990 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
991 const Type
*ArgType
= Op
->getType();
992 Value
*F
= Intrinsic::getDeclaration(Callee
->getParent(),
993 Intrinsic::cttz
, &ArgType
, 1);
994 Value
*V
= B
.CreateCall(F
, Op
, "cttz");
995 V
= B
.CreateAdd(V
, ConstantInt::get(V
->getType(), 1), "tmp");
996 V
= B
.CreateIntCast(V
, Type::getInt32Ty(*Context
), false, "tmp");
998 Value
*Cond
= B
.CreateICmpNE(Op
, Constant::getNullValue(ArgType
), "tmp");
999 return B
.CreateSelect(Cond
, V
,
1000 ConstantInt::get(Type::getInt32Ty(*Context
), 0));
1004 //===---------------------------------------===//
1005 // 'isdigit' Optimizations
1007 struct IsDigitOpt
: public LibCallOptimization
{
1008 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1009 const FunctionType
*FT
= Callee
->getFunctionType();
1010 // We require integer(i32)
1011 if (FT
->getNumParams() != 1 || !FT
->getReturnType()->isIntegerTy() ||
1012 !FT
->getParamType(0)->isIntegerTy(32))
1015 // isdigit(c) -> (c-'0') <u 10
1016 Value
*Op
= CI
->getArgOperand(0);
1017 Op
= B
.CreateSub(Op
, ConstantInt::get(Type::getInt32Ty(*Context
), '0'),
1019 Op
= B
.CreateICmpULT(Op
, ConstantInt::get(Type::getInt32Ty(*Context
), 10),
1021 return B
.CreateZExt(Op
, CI
->getType());
1025 //===---------------------------------------===//
1026 // 'isascii' Optimizations
1028 struct IsAsciiOpt
: public LibCallOptimization
{
1029 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1030 const FunctionType
*FT
= Callee
->getFunctionType();
1031 // We require integer(i32)
1032 if (FT
->getNumParams() != 1 || !FT
->getReturnType()->isIntegerTy() ||
1033 !FT
->getParamType(0)->isIntegerTy(32))
1036 // isascii(c) -> c <u 128
1037 Value
*Op
= CI
->getArgOperand(0);
1038 Op
= B
.CreateICmpULT(Op
, ConstantInt::get(Type::getInt32Ty(*Context
), 128),
1040 return B
.CreateZExt(Op
, CI
->getType());
1044 //===---------------------------------------===//
1045 // 'abs', 'labs', 'llabs' Optimizations
1047 struct AbsOpt
: public LibCallOptimization
{
1048 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1049 const FunctionType
*FT
= Callee
->getFunctionType();
1050 // We require integer(integer) where the types agree.
1051 if (FT
->getNumParams() != 1 || !FT
->getReturnType()->isIntegerTy() ||
1052 FT
->getParamType(0) != FT
->getReturnType())
1055 // abs(x) -> x >s -1 ? x : -x
1056 Value
*Op
= CI
->getArgOperand(0);
1057 Value
*Pos
= B
.CreateICmpSGT(Op
,
1058 Constant::getAllOnesValue(Op
->getType()),
1060 Value
*Neg
= B
.CreateNeg(Op
, "neg");
1061 return B
.CreateSelect(Pos
, Op
, Neg
);
1066 //===---------------------------------------===//
1067 // 'toascii' Optimizations
1069 struct ToAsciiOpt
: public LibCallOptimization
{
1070 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1071 const FunctionType
*FT
= Callee
->getFunctionType();
1072 // We require i32(i32)
1073 if (FT
->getNumParams() != 1 || FT
->getReturnType() != FT
->getParamType(0) ||
1074 !FT
->getParamType(0)->isIntegerTy(32))
1077 // isascii(c) -> c & 0x7f
1078 return B
.CreateAnd(CI
->getArgOperand(0),
1079 ConstantInt::get(CI
->getType(),0x7F));
1083 //===----------------------------------------------------------------------===//
1084 // Formatting and IO Optimizations
1085 //===----------------------------------------------------------------------===//
1087 //===---------------------------------------===//
1088 // 'printf' Optimizations
1090 struct PrintFOpt
: public LibCallOptimization
{
1091 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1092 // Require one fixed pointer argument and an integer/void result.
1093 const FunctionType
*FT
= Callee
->getFunctionType();
1094 if (FT
->getNumParams() < 1 || !FT
->getParamType(0)->isPointerTy() ||
1095 !(FT
->getReturnType()->isIntegerTy() ||
1096 FT
->getReturnType()->isVoidTy()))
1099 // Check for a fixed format string.
1100 std::string FormatStr
;
1101 if (!GetConstantStringInfo(CI
->getArgOperand(0), FormatStr
))
1104 // Empty format string -> noop.
1105 if (FormatStr
.empty()) // Tolerate printf's declared void.
1106 return CI
->use_empty() ? (Value
*)CI
:
1107 ConstantInt::get(CI
->getType(), 0);
1109 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1110 // in case there is an error writing to stdout.
1111 if (FormatStr
.size() == 1) {
1112 Value
*Res
= EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context
),
1113 FormatStr
[0]), B
, TD
);
1114 if (CI
->use_empty()) return CI
;
1115 return B
.CreateIntCast(Res
, CI
->getType(), true);
1118 // printf("foo\n") --> puts("foo")
1119 if (FormatStr
[FormatStr
.size()-1] == '\n' &&
1120 FormatStr
.find('%') == std::string::npos
) { // no format characters.
1121 // Create a string literal with no \n on it. We expect the constant merge
1122 // pass to be run after this pass, to merge duplicate strings.
1123 FormatStr
.erase(FormatStr
.end()-1);
1124 Constant
*C
= ConstantArray::get(*Context
, FormatStr
, true);
1125 C
= new GlobalVariable(*Callee
->getParent(), C
->getType(), true,
1126 GlobalVariable::InternalLinkage
, C
, "str");
1128 return CI
->use_empty() ? (Value
*)CI
:
1129 ConstantInt::get(CI
->getType(), FormatStr
.size()+1);
1132 // Optimize specific format strings.
1133 // printf("%c", chr) --> putchar(chr)
1134 if (FormatStr
== "%c" && CI
->getNumArgOperands() > 1 &&
1135 CI
->getArgOperand(1)->getType()->isIntegerTy()) {
1136 Value
*Res
= EmitPutChar(CI
->getArgOperand(1), B
, TD
);
1138 if (CI
->use_empty()) return CI
;
1139 return B
.CreateIntCast(Res
, CI
->getType(), true);
1142 // printf("%s\n", str) --> puts(str)
1143 if (FormatStr
== "%s\n" && CI
->getNumArgOperands() > 1 &&
1144 CI
->getArgOperand(1)->getType()->isPointerTy() &&
1146 EmitPutS(CI
->getArgOperand(1), B
, TD
);
1153 //===---------------------------------------===//
1154 // 'sprintf' Optimizations
1156 struct SPrintFOpt
: public LibCallOptimization
{
1157 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1158 // Require two fixed pointer arguments and an integer result.
1159 const FunctionType
*FT
= Callee
->getFunctionType();
1160 if (FT
->getNumParams() != 2 || !FT
->getParamType(0)->isPointerTy() ||
1161 !FT
->getParamType(1)->isPointerTy() ||
1162 !FT
->getReturnType()->isIntegerTy())
1165 // Check for a fixed format string.
1166 std::string FormatStr
;
1167 if (!GetConstantStringInfo(CI
->getArgOperand(1), FormatStr
))
1170 // If we just have a format string (nothing else crazy) transform it.
1171 if (CI
->getNumArgOperands() == 2) {
1172 // Make sure there's no % in the constant array. We could try to handle
1173 // %% -> % in the future if we cared.
1174 for (unsigned i
= 0, e
= FormatStr
.size(); i
!= e
; ++i
)
1175 if (FormatStr
[i
] == '%')
1176 return 0; // we found a format specifier, bail out.
1178 // These optimizations require TargetData.
1181 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1182 EmitMemCpy(CI
->getArgOperand(0), CI
->getArgOperand(1), // Copy the
1183 ConstantInt::get(TD
->getIntPtrType(*Context
), // nul byte.
1184 FormatStr
.size() + 1), 1, false, B
, TD
);
1185 return ConstantInt::get(CI
->getType(), FormatStr
.size());
1188 // The remaining optimizations require the format string to be "%s" or "%c"
1189 // and have an extra operand.
1190 if (FormatStr
.size() != 2 || FormatStr
[0] != '%' ||
1191 CI
->getNumArgOperands() < 3)
1194 // Decode the second character of the format string.
1195 if (FormatStr
[1] == 'c') {
1196 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1197 if (!CI
->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1198 Value
*V
= B
.CreateTrunc(CI
->getArgOperand(2),
1199 Type::getInt8Ty(*Context
), "char");
1200 Value
*Ptr
= CastToCStr(CI
->getArgOperand(0), B
);
1201 B
.CreateStore(V
, Ptr
);
1202 Ptr
= B
.CreateGEP(Ptr
, ConstantInt::get(Type::getInt32Ty(*Context
), 1),
1204 B
.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context
)), Ptr
);
1206 return ConstantInt::get(CI
->getType(), 1);
1209 if (FormatStr
[1] == 's') {
1210 // These optimizations require TargetData.
1213 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1214 if (!CI
->getArgOperand(2)->getType()->isPointerTy()) return 0;
1216 Value
*Len
= EmitStrLen(CI
->getArgOperand(2), B
, TD
);
1217 Value
*IncLen
= B
.CreateAdd(Len
,
1218 ConstantInt::get(Len
->getType(), 1),
1220 EmitMemCpy(CI
->getArgOperand(0), CI
->getArgOperand(2),
1221 IncLen
, 1, false, B
, TD
);
1223 // The sprintf result is the unincremented number of bytes in the string.
1224 return B
.CreateIntCast(Len
, CI
->getType(), false);
1230 //===---------------------------------------===//
1231 // 'fwrite' Optimizations
1233 struct FWriteOpt
: public LibCallOptimization
{
1234 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1235 // Require a pointer, an integer, an integer, a pointer, returning integer.
1236 const FunctionType
*FT
= Callee
->getFunctionType();
1237 if (FT
->getNumParams() != 4 || !FT
->getParamType(0)->isPointerTy() ||
1238 !FT
->getParamType(1)->isIntegerTy() ||
1239 !FT
->getParamType(2)->isIntegerTy() ||
1240 !FT
->getParamType(3)->isPointerTy() ||
1241 !FT
->getReturnType()->isIntegerTy())
1244 // Get the element size and count.
1245 ConstantInt
*SizeC
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(1));
1246 ConstantInt
*CountC
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(2));
1247 if (!SizeC
|| !CountC
) return 0;
1248 uint64_t Bytes
= SizeC
->getZExtValue()*CountC
->getZExtValue();
1250 // If this is writing zero records, remove the call (it's a noop).
1252 return ConstantInt::get(CI
->getType(), 0);
1254 // If this is writing one byte, turn it into fputc.
1255 if (Bytes
== 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1256 Value
*Char
= B
.CreateLoad(CastToCStr(CI
->getArgOperand(0), B
), "char");
1257 EmitFPutC(Char
, CI
->getArgOperand(3), B
, TD
);
1258 return ConstantInt::get(CI
->getType(), 1);
1265 //===---------------------------------------===//
1266 // 'fputs' Optimizations
1268 struct FPutsOpt
: public LibCallOptimization
{
1269 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1270 // These optimizations require TargetData.
1273 // Require two pointers. Also, we can't optimize if return value is used.
1274 const FunctionType
*FT
= Callee
->getFunctionType();
1275 if (FT
->getNumParams() != 2 || !FT
->getParamType(0)->isPointerTy() ||
1276 !FT
->getParamType(1)->isPointerTy() ||
1280 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1281 uint64_t Len
= GetStringLength(CI
->getArgOperand(0));
1283 EmitFWrite(CI
->getArgOperand(0),
1284 ConstantInt::get(TD
->getIntPtrType(*Context
), Len
-1),
1285 CI
->getArgOperand(1), B
, TD
);
1286 return CI
; // Known to have no uses (see above).
1290 //===---------------------------------------===//
1291 // 'fprintf' Optimizations
1293 struct FPrintFOpt
: public LibCallOptimization
{
1294 virtual Value
*CallOptimizer(Function
*Callee
, CallInst
*CI
, IRBuilder
<> &B
) {
1295 // Require two fixed paramters as pointers and integer result.
1296 const FunctionType
*FT
= Callee
->getFunctionType();
1297 if (FT
->getNumParams() != 2 || !FT
->getParamType(0)->isPointerTy() ||
1298 !FT
->getParamType(1)->isPointerTy() ||
1299 !FT
->getReturnType()->isIntegerTy())
1302 // All the optimizations depend on the format string.
1303 std::string FormatStr
;
1304 if (!GetConstantStringInfo(CI
->getArgOperand(1), FormatStr
))
1307 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1308 if (CI
->getNumArgOperands() == 2) {
1309 for (unsigned i
= 0, e
= FormatStr
.size(); i
!= e
; ++i
)
1310 if (FormatStr
[i
] == '%') // Could handle %% -> % if we cared.
1311 return 0; // We found a format specifier.
1313 // These optimizations require TargetData.
1316 EmitFWrite(CI
->getArgOperand(1),
1317 ConstantInt::get(TD
->getIntPtrType(*Context
),
1319 CI
->getArgOperand(0), B
, TD
);
1320 return ConstantInt::get(CI
->getType(), FormatStr
.size());
1323 // The remaining optimizations require the format string to be "%s" or "%c"
1324 // and have an extra operand.
1325 if (FormatStr
.size() != 2 || FormatStr
[0] != '%' ||
1326 CI
->getNumArgOperands() < 3)
1329 // Decode the second character of the format string.
1330 if (FormatStr
[1] == 'c') {
1331 // fprintf(F, "%c", chr) --> fputc(chr, F)
1332 if (!CI
->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1333 EmitFPutC(CI
->getArgOperand(2), CI
->getArgOperand(0), B
, TD
);
1334 return ConstantInt::get(CI
->getType(), 1);
1337 if (FormatStr
[1] == 's') {
1338 // fprintf(F, "%s", str) --> fputs(str, F)
1339 if (!CI
->getArgOperand(2)->getType()->isPointerTy() || !CI
->use_empty())
1341 EmitFPutS(CI
->getArgOperand(2), CI
->getArgOperand(0), B
, TD
);
1348 } // end anonymous namespace.
1350 //===----------------------------------------------------------------------===//
1351 // SimplifyLibCalls Pass Implementation
1352 //===----------------------------------------------------------------------===//
1355 /// This pass optimizes well known library functions from libc and libm.
1357 class SimplifyLibCalls
: public FunctionPass
{
1358 StringMap
<LibCallOptimization
*> Optimizations
;
1359 // String and Memory LibCall Optimizations
1360 StrCatOpt StrCat
; StrNCatOpt StrNCat
; StrChrOpt StrChr
; StrRChrOpt StrRChr
;
1361 StrCmpOpt StrCmp
; StrNCmpOpt StrNCmp
; StrCpyOpt StrCpy
; StrCpyOpt StrCpyChk
;
1362 StrNCpyOpt StrNCpy
; StrLenOpt StrLen
; StrPBrkOpt StrPBrk
;
1363 StrToOpt StrTo
; StrSpnOpt StrSpn
; StrCSpnOpt StrCSpn
; StrStrOpt StrStr
;
1364 MemCmpOpt MemCmp
; MemCpyOpt MemCpy
; MemMoveOpt MemMove
; MemSetOpt MemSet
;
1365 // Math Library Optimizations
1366 PowOpt Pow
; Exp2Opt Exp2
; UnaryDoubleFPOpt UnaryDoubleFP
;
1367 // Integer Optimizations
1368 FFSOpt FFS
; AbsOpt Abs
; IsDigitOpt IsDigit
; IsAsciiOpt IsAscii
;
1370 // Formatting and IO Optimizations
1371 SPrintFOpt SPrintF
; PrintFOpt PrintF
;
1372 FWriteOpt FWrite
; FPutsOpt FPuts
; FPrintFOpt FPrintF
;
1374 bool Modified
; // This is only used by doInitialization.
1376 static char ID
; // Pass identification
1377 SimplifyLibCalls() : FunctionPass(ID
), StrCpy(false), StrCpyChk(true) {
1378 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1380 void InitOptimizations();
1381 bool runOnFunction(Function
&F
);
1383 void setDoesNotAccessMemory(Function
&F
);
1384 void setOnlyReadsMemory(Function
&F
);
1385 void setDoesNotThrow(Function
&F
);
1386 void setDoesNotCapture(Function
&F
, unsigned n
);
1387 void setDoesNotAlias(Function
&F
, unsigned n
);
1388 bool doInitialization(Module
&M
);
1390 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
1393 char SimplifyLibCalls::ID
= 0;
1394 } // end anonymous namespace.
1396 INITIALIZE_PASS(SimplifyLibCalls
, "simplify-libcalls",
1397 "Simplify well-known library calls", false, false)
1399 // Public interface to the Simplify LibCalls pass.
1400 FunctionPass
*llvm::createSimplifyLibCallsPass() {
1401 return new SimplifyLibCalls();
1404 /// Optimizations - Populate the Optimizations map with all the optimizations
1406 void SimplifyLibCalls::InitOptimizations() {
1407 // String and Memory LibCall Optimizations
1408 Optimizations
["strcat"] = &StrCat
;
1409 Optimizations
["strncat"] = &StrNCat
;
1410 Optimizations
["strchr"] = &StrChr
;
1411 Optimizations
["strrchr"] = &StrRChr
;
1412 Optimizations
["strcmp"] = &StrCmp
;
1413 Optimizations
["strncmp"] = &StrNCmp
;
1414 Optimizations
["strcpy"] = &StrCpy
;
1415 Optimizations
["strncpy"] = &StrNCpy
;
1416 Optimizations
["strlen"] = &StrLen
;
1417 Optimizations
["strpbrk"] = &StrPBrk
;
1418 Optimizations
["strtol"] = &StrTo
;
1419 Optimizations
["strtod"] = &StrTo
;
1420 Optimizations
["strtof"] = &StrTo
;
1421 Optimizations
["strtoul"] = &StrTo
;
1422 Optimizations
["strtoll"] = &StrTo
;
1423 Optimizations
["strtold"] = &StrTo
;
1424 Optimizations
["strtoull"] = &StrTo
;
1425 Optimizations
["strspn"] = &StrSpn
;
1426 Optimizations
["strcspn"] = &StrCSpn
;
1427 Optimizations
["strstr"] = &StrStr
;
1428 Optimizations
["memcmp"] = &MemCmp
;
1429 Optimizations
["memcpy"] = &MemCpy
;
1430 Optimizations
["memmove"] = &MemMove
;
1431 Optimizations
["memset"] = &MemSet
;
1433 // _chk variants of String and Memory LibCall Optimizations.
1434 Optimizations
["__strcpy_chk"] = &StrCpyChk
;
1436 // Math Library Optimizations
1437 Optimizations
["powf"] = &Pow
;
1438 Optimizations
["pow"] = &Pow
;
1439 Optimizations
["powl"] = &Pow
;
1440 Optimizations
["llvm.pow.f32"] = &Pow
;
1441 Optimizations
["llvm.pow.f64"] = &Pow
;
1442 Optimizations
["llvm.pow.f80"] = &Pow
;
1443 Optimizations
["llvm.pow.f128"] = &Pow
;
1444 Optimizations
["llvm.pow.ppcf128"] = &Pow
;
1445 Optimizations
["exp2l"] = &Exp2
;
1446 Optimizations
["exp2"] = &Exp2
;
1447 Optimizations
["exp2f"] = &Exp2
;
1448 Optimizations
["llvm.exp2.ppcf128"] = &Exp2
;
1449 Optimizations
["llvm.exp2.f128"] = &Exp2
;
1450 Optimizations
["llvm.exp2.f80"] = &Exp2
;
1451 Optimizations
["llvm.exp2.f64"] = &Exp2
;
1452 Optimizations
["llvm.exp2.f32"] = &Exp2
;
1455 Optimizations
["floor"] = &UnaryDoubleFP
;
1458 Optimizations
["ceil"] = &UnaryDoubleFP
;
1461 Optimizations
["round"] = &UnaryDoubleFP
;
1464 Optimizations
["rint"] = &UnaryDoubleFP
;
1466 #ifdef HAVE_NEARBYINTF
1467 Optimizations
["nearbyint"] = &UnaryDoubleFP
;
1470 // Integer Optimizations
1471 Optimizations
["ffs"] = &FFS
;
1472 Optimizations
["ffsl"] = &FFS
;
1473 Optimizations
["ffsll"] = &FFS
;
1474 Optimizations
["abs"] = &Abs
;
1475 Optimizations
["labs"] = &Abs
;
1476 Optimizations
["llabs"] = &Abs
;
1477 Optimizations
["isdigit"] = &IsDigit
;
1478 Optimizations
["isascii"] = &IsAscii
;
1479 Optimizations
["toascii"] = &ToAscii
;
1481 // Formatting and IO Optimizations
1482 Optimizations
["sprintf"] = &SPrintF
;
1483 Optimizations
["printf"] = &PrintF
;
1484 Optimizations
["fwrite"] = &FWrite
;
1485 Optimizations
["fputs"] = &FPuts
;
1486 Optimizations
["fprintf"] = &FPrintF
;
1490 /// runOnFunction - Top level algorithm.
1492 bool SimplifyLibCalls::runOnFunction(Function
&F
) {
1493 if (Optimizations
.empty())
1494 InitOptimizations();
1496 const TargetData
*TD
= getAnalysisIfAvailable
<TargetData
>();
1498 IRBuilder
<> Builder(F
.getContext());
1500 bool Changed
= false;
1501 for (Function::iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
) {
1502 for (BasicBlock::iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
; ) {
1503 // Ignore non-calls.
1504 CallInst
*CI
= dyn_cast
<CallInst
>(I
++);
1507 // Ignore indirect calls and calls to non-external functions.
1508 Function
*Callee
= CI
->getCalledFunction();
1509 if (Callee
== 0 || !Callee
->isDeclaration() ||
1510 !(Callee
->hasExternalLinkage() || Callee
->hasDLLImportLinkage()))
1513 // Ignore unknown calls.
1514 LibCallOptimization
*LCO
= Optimizations
.lookup(Callee
->getName());
1517 // Set the builder to the instruction after the call.
1518 Builder
.SetInsertPoint(BB
, I
);
1520 // Try to optimize this call.
1521 Value
*Result
= LCO
->OptimizeCall(CI
, TD
, Builder
);
1522 if (Result
== 0) continue;
1524 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI
;
1525 dbgs() << " into: " << *Result
<< "\n");
1527 // Something changed!
1531 // Inspect the instruction after the call (which was potentially just
1535 if (CI
!= Result
&& !CI
->use_empty()) {
1536 CI
->replaceAllUsesWith(Result
);
1537 if (!Result
->hasName())
1538 Result
->takeName(CI
);
1540 CI
->eraseFromParent();
1546 // Utility methods for doInitialization.
1548 void SimplifyLibCalls::setDoesNotAccessMemory(Function
&F
) {
1549 if (!F
.doesNotAccessMemory()) {
1550 F
.setDoesNotAccessMemory();
1555 void SimplifyLibCalls::setOnlyReadsMemory(Function
&F
) {
1556 if (!F
.onlyReadsMemory()) {
1557 F
.setOnlyReadsMemory();
1562 void SimplifyLibCalls::setDoesNotThrow(Function
&F
) {
1563 if (!F
.doesNotThrow()) {
1564 F
.setDoesNotThrow();
1569 void SimplifyLibCalls::setDoesNotCapture(Function
&F
, unsigned n
) {
1570 if (!F
.doesNotCapture(n
)) {
1571 F
.setDoesNotCapture(n
);
1576 void SimplifyLibCalls::setDoesNotAlias(Function
&F
, unsigned n
) {
1577 if (!F
.doesNotAlias(n
)) {
1578 F
.setDoesNotAlias(n
);
1584 /// doInitialization - Add attributes to well-known functions.
1586 bool SimplifyLibCalls::doInitialization(Module
&M
) {
1588 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
) {
1590 if (!F
.isDeclaration())
1596 const FunctionType
*FTy
= F
.getFunctionType();
1598 StringRef Name
= F
.getName();
1601 if (Name
== "strlen") {
1602 if (FTy
->getNumParams() != 1 ||
1603 !FTy
->getParamType(0)->isPointerTy())
1605 setOnlyReadsMemory(F
);
1607 setDoesNotCapture(F
, 1);
1608 } else if (Name
== "strchr" ||
1609 Name
== "strrchr") {
1610 if (FTy
->getNumParams() != 2 ||
1611 !FTy
->getParamType(0)->isPointerTy() ||
1612 !FTy
->getParamType(1)->isIntegerTy())
1614 setOnlyReadsMemory(F
);
1616 } else if (Name
== "strcpy" ||
1622 Name
== "strtoul" ||
1623 Name
== "strtoll" ||
1624 Name
== "strtold" ||
1625 Name
== "strncat" ||
1626 Name
== "strncpy" ||
1627 Name
== "strtoull") {
1628 if (FTy
->getNumParams() < 2 ||
1629 !FTy
->getParamType(1)->isPointerTy())
1632 setDoesNotCapture(F
, 2);
1633 } else if (Name
== "strxfrm") {
1634 if (FTy
->getNumParams() != 3 ||
1635 !FTy
->getParamType(0)->isPointerTy() ||
1636 !FTy
->getParamType(1)->isPointerTy())
1639 setDoesNotCapture(F
, 1);
1640 setDoesNotCapture(F
, 2);
1641 } else if (Name
== "strcmp" ||
1643 Name
== "strncmp" ||
1644 Name
== "strcspn" ||
1645 Name
== "strcoll" ||
1646 Name
== "strcasecmp" ||
1647 Name
== "strncasecmp") {
1648 if (FTy
->getNumParams() < 2 ||
1649 !FTy
->getParamType(0)->isPointerTy() ||
1650 !FTy
->getParamType(1)->isPointerTy())
1652 setOnlyReadsMemory(F
);
1654 setDoesNotCapture(F
, 1);
1655 setDoesNotCapture(F
, 2);
1656 } else if (Name
== "strstr" ||
1657 Name
== "strpbrk") {
1658 if (FTy
->getNumParams() != 2 ||
1659 !FTy
->getParamType(1)->isPointerTy())
1661 setOnlyReadsMemory(F
);
1663 setDoesNotCapture(F
, 2);
1664 } else if (Name
== "strtok" ||
1665 Name
== "strtok_r") {
1666 if (FTy
->getNumParams() < 2 ||
1667 !FTy
->getParamType(1)->isPointerTy())
1670 setDoesNotCapture(F
, 2);
1671 } else if (Name
== "scanf" ||
1673 Name
== "setvbuf") {
1674 if (FTy
->getNumParams() < 1 ||
1675 !FTy
->getParamType(0)->isPointerTy())
1678 setDoesNotCapture(F
, 1);
1679 } else if (Name
== "strdup" ||
1680 Name
== "strndup") {
1681 if (FTy
->getNumParams() < 1 ||
1682 !FTy
->getReturnType()->isPointerTy() ||
1683 !FTy
->getParamType(0)->isPointerTy())
1686 setDoesNotAlias(F
, 0);
1687 setDoesNotCapture(F
, 1);
1688 } else if (Name
== "stat" ||
1690 Name
== "sprintf" ||
1691 Name
== "statvfs") {
1692 if (FTy
->getNumParams() < 2 ||
1693 !FTy
->getParamType(0)->isPointerTy() ||
1694 !FTy
->getParamType(1)->isPointerTy())
1697 setDoesNotCapture(F
, 1);
1698 setDoesNotCapture(F
, 2);
1699 } else if (Name
== "snprintf") {
1700 if (FTy
->getNumParams() != 3 ||
1701 !FTy
->getParamType(0)->isPointerTy() ||
1702 !FTy
->getParamType(2)->isPointerTy())
1705 setDoesNotCapture(F
, 1);
1706 setDoesNotCapture(F
, 3);
1707 } else if (Name
== "setitimer") {
1708 if (FTy
->getNumParams() != 3 ||
1709 !FTy
->getParamType(1)->isPointerTy() ||
1710 !FTy
->getParamType(2)->isPointerTy())
1713 setDoesNotCapture(F
, 2);
1714 setDoesNotCapture(F
, 3);
1715 } else if (Name
== "system") {
1716 if (FTy
->getNumParams() != 1 ||
1717 !FTy
->getParamType(0)->isPointerTy())
1719 // May throw; "system" is a valid pthread cancellation point.
1720 setDoesNotCapture(F
, 1);
1724 if (Name
== "malloc") {
1725 if (FTy
->getNumParams() != 1 ||
1726 !FTy
->getReturnType()->isPointerTy())
1729 setDoesNotAlias(F
, 0);
1730 } else if (Name
== "memcmp") {
1731 if (FTy
->getNumParams() != 3 ||
1732 !FTy
->getParamType(0)->isPointerTy() ||
1733 !FTy
->getParamType(1)->isPointerTy())
1735 setOnlyReadsMemory(F
);
1737 setDoesNotCapture(F
, 1);
1738 setDoesNotCapture(F
, 2);
1739 } else if (Name
== "memchr" ||
1740 Name
== "memrchr") {
1741 if (FTy
->getNumParams() != 3)
1743 setOnlyReadsMemory(F
);
1745 } else if (Name
== "modf" ||
1749 Name
== "memccpy" ||
1750 Name
== "memmove") {
1751 if (FTy
->getNumParams() < 2 ||
1752 !FTy
->getParamType(1)->isPointerTy())
1755 setDoesNotCapture(F
, 2);
1756 } else if (Name
== "memalign") {
1757 if (!FTy
->getReturnType()->isPointerTy())
1759 setDoesNotAlias(F
, 0);
1760 } else if (Name
== "mkdir" ||
1762 if (FTy
->getNumParams() == 0 ||
1763 !FTy
->getParamType(0)->isPointerTy())
1766 setDoesNotCapture(F
, 1);
1770 if (Name
== "realloc") {
1771 if (FTy
->getNumParams() != 2 ||
1772 !FTy
->getParamType(0)->isPointerTy() ||
1773 !FTy
->getReturnType()->isPointerTy())
1776 setDoesNotAlias(F
, 0);
1777 setDoesNotCapture(F
, 1);
1778 } else if (Name
== "read") {
1779 if (FTy
->getNumParams() != 3 ||
1780 !FTy
->getParamType(1)->isPointerTy())
1782 // May throw; "read" is a valid pthread cancellation point.
1783 setDoesNotCapture(F
, 2);
1784 } else if (Name
== "rmdir" ||
1787 Name
== "realpath") {
1788 if (FTy
->getNumParams() < 1 ||
1789 !FTy
->getParamType(0)->isPointerTy())
1792 setDoesNotCapture(F
, 1);
1793 } else if (Name
== "rename" ||
1794 Name
== "readlink") {
1795 if (FTy
->getNumParams() < 2 ||
1796 !FTy
->getParamType(0)->isPointerTy() ||
1797 !FTy
->getParamType(1)->isPointerTy())
1800 setDoesNotCapture(F
, 1);
1801 setDoesNotCapture(F
, 2);
1805 if (Name
== "write") {
1806 if (FTy
->getNumParams() != 3 ||
1807 !FTy
->getParamType(1)->isPointerTy())
1809 // May throw; "write" is a valid pthread cancellation point.
1810 setDoesNotCapture(F
, 2);
1814 if (Name
== "bcopy") {
1815 if (FTy
->getNumParams() != 3 ||
1816 !FTy
->getParamType(0)->isPointerTy() ||
1817 !FTy
->getParamType(1)->isPointerTy())
1820 setDoesNotCapture(F
, 1);
1821 setDoesNotCapture(F
, 2);
1822 } else if (Name
== "bcmp") {
1823 if (FTy
->getNumParams() != 3 ||
1824 !FTy
->getParamType(0)->isPointerTy() ||
1825 !FTy
->getParamType(1)->isPointerTy())
1828 setOnlyReadsMemory(F
);
1829 setDoesNotCapture(F
, 1);
1830 setDoesNotCapture(F
, 2);
1831 } else if (Name
== "bzero") {
1832 if (FTy
->getNumParams() != 2 ||
1833 !FTy
->getParamType(0)->isPointerTy())
1836 setDoesNotCapture(F
, 1);
1840 if (Name
== "calloc") {
1841 if (FTy
->getNumParams() != 2 ||
1842 !FTy
->getReturnType()->isPointerTy())
1845 setDoesNotAlias(F
, 0);
1846 } else if (Name
== "chmod" ||
1848 Name
== "ctermid" ||
1849 Name
== "clearerr" ||
1850 Name
== "closedir") {
1851 if (FTy
->getNumParams() == 0 ||
1852 !FTy
->getParamType(0)->isPointerTy())
1855 setDoesNotCapture(F
, 1);
1859 if (Name
== "atoi" ||
1863 if (FTy
->getNumParams() != 1 ||
1864 !FTy
->getParamType(0)->isPointerTy())
1867 setOnlyReadsMemory(F
);
1868 setDoesNotCapture(F
, 1);
1869 } else if (Name
== "access") {
1870 if (FTy
->getNumParams() != 2 ||
1871 !FTy
->getParamType(0)->isPointerTy())
1874 setDoesNotCapture(F
, 1);
1878 if (Name
== "fopen") {
1879 if (FTy
->getNumParams() != 2 ||
1880 !FTy
->getReturnType()->isPointerTy() ||
1881 !FTy
->getParamType(0)->isPointerTy() ||
1882 !FTy
->getParamType(1)->isPointerTy())
1885 setDoesNotAlias(F
, 0);
1886 setDoesNotCapture(F
, 1);
1887 setDoesNotCapture(F
, 2);
1888 } else if (Name
== "fdopen") {
1889 if (FTy
->getNumParams() != 2 ||
1890 !FTy
->getReturnType()->isPointerTy() ||
1891 !FTy
->getParamType(1)->isPointerTy())
1894 setDoesNotAlias(F
, 0);
1895 setDoesNotCapture(F
, 2);
1896 } else if (Name
== "feof" ||
1906 Name
== "fsetpos" ||
1907 Name
== "flockfile" ||
1908 Name
== "funlockfile" ||
1909 Name
== "ftrylockfile") {
1910 if (FTy
->getNumParams() == 0 ||
1911 !FTy
->getParamType(0)->isPointerTy())
1914 setDoesNotCapture(F
, 1);
1915 } else if (Name
== "ferror") {
1916 if (FTy
->getNumParams() != 1 ||
1917 !FTy
->getParamType(0)->isPointerTy())
1920 setDoesNotCapture(F
, 1);
1921 setOnlyReadsMemory(F
);
1922 } else if (Name
== "fputc" ||
1927 Name
== "fstatvfs") {
1928 if (FTy
->getNumParams() != 2 ||
1929 !FTy
->getParamType(1)->isPointerTy())
1932 setDoesNotCapture(F
, 2);
1933 } else if (Name
== "fgets") {
1934 if (FTy
->getNumParams() != 3 ||
1935 !FTy
->getParamType(0)->isPointerTy() ||
1936 !FTy
->getParamType(2)->isPointerTy())
1939 setDoesNotCapture(F
, 3);
1940 } else if (Name
== "fread" ||
1942 if (FTy
->getNumParams() != 4 ||
1943 !FTy
->getParamType(0)->isPointerTy() ||
1944 !FTy
->getParamType(3)->isPointerTy())
1947 setDoesNotCapture(F
, 1);
1948 setDoesNotCapture(F
, 4);
1949 } else if (Name
== "fputs" ||
1951 Name
== "fprintf" ||
1952 Name
== "fgetpos") {
1953 if (FTy
->getNumParams() < 2 ||
1954 !FTy
->getParamType(0)->isPointerTy() ||
1955 !FTy
->getParamType(1)->isPointerTy())
1958 setDoesNotCapture(F
, 1);
1959 setDoesNotCapture(F
, 2);
1963 if (Name
== "getc" ||
1964 Name
== "getlogin_r" ||
1965 Name
== "getc_unlocked") {
1966 if (FTy
->getNumParams() == 0 ||
1967 !FTy
->getParamType(0)->isPointerTy())
1970 setDoesNotCapture(F
, 1);
1971 } else if (Name
== "getenv") {
1972 if (FTy
->getNumParams() != 1 ||
1973 !FTy
->getParamType(0)->isPointerTy())
1976 setOnlyReadsMemory(F
);
1977 setDoesNotCapture(F
, 1);
1978 } else if (Name
== "gets" ||
1979 Name
== "getchar") {
1981 } else if (Name
== "getitimer") {
1982 if (FTy
->getNumParams() != 2 ||
1983 !FTy
->getParamType(1)->isPointerTy())
1986 setDoesNotCapture(F
, 2);
1987 } else if (Name
== "getpwnam") {
1988 if (FTy
->getNumParams() != 1 ||
1989 !FTy
->getParamType(0)->isPointerTy())
1992 setDoesNotCapture(F
, 1);
1996 if (Name
== "ungetc") {
1997 if (FTy
->getNumParams() != 2 ||
1998 !FTy
->getParamType(1)->isPointerTy())
2001 setDoesNotCapture(F
, 2);
2002 } else if (Name
== "uname" ||
2004 Name
== "unsetenv") {
2005 if (FTy
->getNumParams() != 1 ||
2006 !FTy
->getParamType(0)->isPointerTy())
2009 setDoesNotCapture(F
, 1);
2010 } else if (Name
== "utime" ||
2012 if (FTy
->getNumParams() != 2 ||
2013 !FTy
->getParamType(0)->isPointerTy() ||
2014 !FTy
->getParamType(1)->isPointerTy())
2017 setDoesNotCapture(F
, 1);
2018 setDoesNotCapture(F
, 2);
2022 if (Name
== "putc") {
2023 if (FTy
->getNumParams() != 2 ||
2024 !FTy
->getParamType(1)->isPointerTy())
2027 setDoesNotCapture(F
, 2);
2028 } else if (Name
== "puts" ||
2031 if (FTy
->getNumParams() != 1 ||
2032 !FTy
->getParamType(0)->isPointerTy())
2035 setDoesNotCapture(F
, 1);
2036 } else if (Name
== "pread" ||
2038 if (FTy
->getNumParams() != 4 ||
2039 !FTy
->getParamType(1)->isPointerTy())
2041 // May throw; these are valid pthread cancellation points.
2042 setDoesNotCapture(F
, 2);
2043 } else if (Name
== "putchar") {
2045 } else if (Name
== "popen") {
2046 if (FTy
->getNumParams() != 2 ||
2047 !FTy
->getReturnType()->isPointerTy() ||
2048 !FTy
->getParamType(0)->isPointerTy() ||
2049 !FTy
->getParamType(1)->isPointerTy())
2052 setDoesNotAlias(F
, 0);
2053 setDoesNotCapture(F
, 1);
2054 setDoesNotCapture(F
, 2);
2055 } else if (Name
== "pclose") {
2056 if (FTy
->getNumParams() != 1 ||
2057 !FTy
->getParamType(0)->isPointerTy())
2060 setDoesNotCapture(F
, 1);
2064 if (Name
== "vscanf") {
2065 if (FTy
->getNumParams() != 2 ||
2066 !FTy
->getParamType(1)->isPointerTy())
2069 setDoesNotCapture(F
, 1);
2070 } else if (Name
== "vsscanf" ||
2071 Name
== "vfscanf") {
2072 if (FTy
->getNumParams() != 3 ||
2073 !FTy
->getParamType(1)->isPointerTy() ||
2074 !FTy
->getParamType(2)->isPointerTy())
2077 setDoesNotCapture(F
, 1);
2078 setDoesNotCapture(F
, 2);
2079 } else if (Name
== "valloc") {
2080 if (!FTy
->getReturnType()->isPointerTy())
2083 setDoesNotAlias(F
, 0);
2084 } else if (Name
== "vprintf") {
2085 if (FTy
->getNumParams() != 2 ||
2086 !FTy
->getParamType(0)->isPointerTy())
2089 setDoesNotCapture(F
, 1);
2090 } else if (Name
== "vfprintf" ||
2091 Name
== "vsprintf") {
2092 if (FTy
->getNumParams() != 3 ||
2093 !FTy
->getParamType(0)->isPointerTy() ||
2094 !FTy
->getParamType(1)->isPointerTy())
2097 setDoesNotCapture(F
, 1);
2098 setDoesNotCapture(F
, 2);
2099 } else if (Name
== "vsnprintf") {
2100 if (FTy
->getNumParams() != 4 ||
2101 !FTy
->getParamType(0)->isPointerTy() ||
2102 !FTy
->getParamType(2)->isPointerTy())
2105 setDoesNotCapture(F
, 1);
2106 setDoesNotCapture(F
, 3);
2110 if (Name
== "open") {
2111 if (FTy
->getNumParams() < 2 ||
2112 !FTy
->getParamType(0)->isPointerTy())
2114 // May throw; "open" is a valid pthread cancellation point.
2115 setDoesNotCapture(F
, 1);
2116 } else if (Name
== "opendir") {
2117 if (FTy
->getNumParams() != 1 ||
2118 !FTy
->getReturnType()->isPointerTy() ||
2119 !FTy
->getParamType(0)->isPointerTy())
2122 setDoesNotAlias(F
, 0);
2123 setDoesNotCapture(F
, 1);
2127 if (Name
== "tmpfile") {
2128 if (!FTy
->getReturnType()->isPointerTy())
2131 setDoesNotAlias(F
, 0);
2132 } else if (Name
== "times") {
2133 if (FTy
->getNumParams() != 1 ||
2134 !FTy
->getParamType(0)->isPointerTy())
2137 setDoesNotCapture(F
, 1);
2141 if (Name
== "htonl" ||
2144 setDoesNotAccessMemory(F
);
2148 if (Name
== "ntohl" ||
2151 setDoesNotAccessMemory(F
);
2155 if (Name
== "lstat") {
2156 if (FTy
->getNumParams() != 2 ||
2157 !FTy
->getParamType(0)->isPointerTy() ||
2158 !FTy
->getParamType(1)->isPointerTy())
2161 setDoesNotCapture(F
, 1);
2162 setDoesNotCapture(F
, 2);
2163 } else if (Name
== "lchown") {
2164 if (FTy
->getNumParams() != 3 ||
2165 !FTy
->getParamType(0)->isPointerTy())
2168 setDoesNotCapture(F
, 1);
2172 if (Name
== "qsort") {
2173 if (FTy
->getNumParams() != 4 ||
2174 !FTy
->getParamType(3)->isPointerTy())
2176 // May throw; places call through function pointer.
2177 setDoesNotCapture(F
, 4);
2181 if (Name
== "__strdup" ||
2182 Name
== "__strndup") {
2183 if (FTy
->getNumParams() < 1 ||
2184 !FTy
->getReturnType()->isPointerTy() ||
2185 !FTy
->getParamType(0)->isPointerTy())
2188 setDoesNotAlias(F
, 0);
2189 setDoesNotCapture(F
, 1);
2190 } else if (Name
== "__strtok_r") {
2191 if (FTy
->getNumParams() != 3 ||
2192 !FTy
->getParamType(1)->isPointerTy())
2195 setDoesNotCapture(F
, 2);
2196 } else if (Name
== "_IO_getc") {
2197 if (FTy
->getNumParams() != 1 ||
2198 !FTy
->getParamType(0)->isPointerTy())
2201 setDoesNotCapture(F
, 1);
2202 } else if (Name
== "_IO_putc") {
2203 if (FTy
->getNumParams() != 2 ||
2204 !FTy
->getParamType(1)->isPointerTy())
2207 setDoesNotCapture(F
, 2);
2211 if (Name
== "\1__isoc99_scanf") {
2212 if (FTy
->getNumParams() < 1 ||
2213 !FTy
->getParamType(0)->isPointerTy())
2216 setDoesNotCapture(F
, 1);
2217 } else if (Name
== "\1stat64" ||
2218 Name
== "\1lstat64" ||
2219 Name
== "\1statvfs64" ||
2220 Name
== "\1__isoc99_sscanf") {
2221 if (FTy
->getNumParams() < 1 ||
2222 !FTy
->getParamType(0)->isPointerTy() ||
2223 !FTy
->getParamType(1)->isPointerTy())
2226 setDoesNotCapture(F
, 1);
2227 setDoesNotCapture(F
, 2);
2228 } else if (Name
== "\1fopen64") {
2229 if (FTy
->getNumParams() != 2 ||
2230 !FTy
->getReturnType()->isPointerTy() ||
2231 !FTy
->getParamType(0)->isPointerTy() ||
2232 !FTy
->getParamType(1)->isPointerTy())
2235 setDoesNotAlias(F
, 0);
2236 setDoesNotCapture(F
, 1);
2237 setDoesNotCapture(F
, 2);
2238 } else if (Name
== "\1fseeko64" ||
2239 Name
== "\1ftello64") {
2240 if (FTy
->getNumParams() == 0 ||
2241 !FTy
->getParamType(0)->isPointerTy())
2244 setDoesNotCapture(F
, 1);
2245 } else if (Name
== "\1tmpfile64") {
2246 if (!FTy
->getReturnType()->isPointerTy())
2249 setDoesNotAlias(F
, 0);
2250 } else if (Name
== "\1fstat64" ||
2251 Name
== "\1fstatvfs64") {
2252 if (FTy
->getNumParams() != 2 ||
2253 !FTy
->getParamType(1)->isPointerTy())
2256 setDoesNotCapture(F
, 2);
2257 } else if (Name
== "\1open64") {
2258 if (FTy
->getNumParams() < 2 ||
2259 !FTy
->getParamType(0)->isPointerTy())
2261 // May throw; "open" is a valid pthread cancellation point.
2262 setDoesNotCapture(F
, 1);
2271 // Additional cases that we need to add to this file:
2274 // * cbrt(expN(X)) -> expN(x/3)
2275 // * cbrt(sqrt(x)) -> pow(x,1/6)
2276 // * cbrt(sqrt(x)) -> pow(x,1/9)
2279 // * cos(-x) -> cos(x)
2282 // * exp(log(x)) -> x
2285 // * log(exp(x)) -> x
2286 // * log(x**y) -> y*log(x)
2287 // * log(exp(y)) -> y*log(e)
2288 // * log(exp2(y)) -> y*log(2)
2289 // * log(exp10(y)) -> y*log(10)
2290 // * log(sqrt(x)) -> 0.5*log(x)
2291 // * log(pow(x,y)) -> y*log(x)
2293 // lround, lroundf, lroundl:
2294 // * lround(cnst) -> cnst'
2297 // * pow(exp(x),y) -> exp(x*y)
2298 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2299 // * pow(pow(x,y),z)-> pow(x,y*z)
2302 // * puts("") -> putchar('\n')
2304 // round, roundf, roundl:
2305 // * round(cnst) -> cnst'
2308 // * signbit(cnst) -> cnst'
2309 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2311 // sqrt, sqrtf, sqrtl:
2312 // * sqrt(expN(x)) -> expN(x*0.5)
2313 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2314 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2317 // * stpcpy(str, "literal") ->
2318 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2321 // * tan(atan(x)) -> x
2323 // trunc, truncf, truncl:
2324 // * trunc(cnst) -> cnst'