1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
15 //
16 //===----------------------------------------------------------------------===//
17
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/Target/TargetLibraryInfo.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/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
36 using namespace llvm;
37
38 STATISTIC(NumSimplified, "Number of library calls simplified");
39 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
40
41 //===----------------------------------------------------------------------===//
42 // Optimizer Base Class
43 //===----------------------------------------------------------------------===//
44
45 /// This class is the abstract base class for the set of optimizations that
46 /// corresponds to one library call.
47 namespace {
48 class LibCallOptimization {
49 protected:
50 Function *Caller;
51 const TargetData *TD;
52 const TargetLibraryInfo *TLI;
53 LLVMContext* Context;
54 public:
LibCallOptimization()55 LibCallOptimization() { }
~LibCallOptimization()56 virtual ~LibCallOptimization() {}
57
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
62 /// delete CI.
63 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
64 =0;
65
OptimizeCall(CallInst * CI,const TargetData * TD,const TargetLibraryInfo * TLI,IRBuilder<> & B)66 Value *OptimizeCall(CallInst *CI, const TargetData *TD,
67 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
68 Caller = CI->getParent()->getParent();
69 this->TD = TD;
70 this->TLI = TLI;
71 if (CI->getCalledFunction())
72 Context = &CI->getCalledFunction()->getContext();
73
74 // We never change the calling convention.
75 if (CI->getCallingConv() != llvm::CallingConv::C)
76 return NULL;
77
78 return CallOptimizer(CI->getCalledFunction(), CI, B);
79 }
80 };
81 } // End anonymous namespace.
82
83
84 //===----------------------------------------------------------------------===//
85 // Helper Functions
86 //===----------------------------------------------------------------------===//
87
88 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
89 /// value is equal or not-equal to zero.
IsOnlyUsedInZeroEqualityComparison(Value * V)90 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
92 UI != E; ++UI) {
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
94 if (IC->isEquality())
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
96 if (C->isNullValue())
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102 }
103
CallHasFloatingPointArgument(const CallInst * CI)104 static bool CallHasFloatingPointArgument(const CallInst *CI) {
105 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
106 it != e; ++it) {
107 if ((*it)->getType()->isFloatingPointTy())
108 return true;
109 }
110 return false;
111 }
112
113 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
114 /// comparisons with With.
IsOnlyUsedInEqualityComparison(Value * V,Value * With)115 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
116 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
117 UI != E; ++UI) {
118 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
119 if (IC->isEquality() && IC->getOperand(1) == With)
120 continue;
121 // Unknown instruction.
122 return false;
123 }
124 return true;
125 }
126
127 //===----------------------------------------------------------------------===//
128 // String and Memory LibCall Optimizations
129 //===----------------------------------------------------------------------===//
130
131 //===---------------------------------------===//
132 // 'strcat' Optimizations
133 namespace {
134 struct StrCatOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrCatOpt135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
136 // Verify the "strcat" function prototype.
137 FunctionType *FT = Callee->getFunctionType();
138 if (FT->getNumParams() != 2 ||
139 FT->getReturnType() != B.getInt8PtrTy() ||
140 FT->getParamType(0) != FT->getReturnType() ||
141 FT->getParamType(1) != FT->getReturnType())
142 return 0;
143
144 // Extract some information from the instruction
145 Value *Dst = CI->getArgOperand(0);
146 Value *Src = CI->getArgOperand(1);
147
148 // See if we can get the length of the input string.
149 uint64_t Len = GetStringLength(Src);
150 if (Len == 0) return 0;
151 --Len; // Unbias length.
152
153 // Handle the simple, do-nothing case: strcat(x, "") -> x
154 if (Len == 0)
155 return Dst;
156
157 // These optimizations require TargetData.
158 if (!TD) return 0;
159
160 EmitStrLenMemCpy(Src, Dst, Len, B);
161 return Dst;
162 }
163
EmitStrLenMemCpy__anon0f7d73dd0211::StrCatOpt164 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
165 // We need to find the end of the destination string. That's where the
166 // memory is to be moved to. We just generate a call to strlen.
167 Value *DstLen = EmitStrLen(Dst, B, TD);
168
169 // Now that we have the destination's length, we must index into the
170 // destination's pointer to get the actual memcpy destination (end of
171 // the string .. we're concatenating).
172 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
173
174 // We have enough information to now generate the memcpy call to do the
175 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
176 B.CreateMemCpy(CpyDst, Src,
177 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
178 }
179 };
180
181 //===---------------------------------------===//
182 // 'strncat' Optimizations
183
184 struct StrNCatOpt : public StrCatOpt {
CallOptimizer__anon0f7d73dd0211::StrNCatOpt185 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
186 // Verify the "strncat" function prototype.
187 FunctionType *FT = Callee->getFunctionType();
188 if (FT->getNumParams() != 3 ||
189 FT->getReturnType() != B.getInt8PtrTy() ||
190 FT->getParamType(0) != FT->getReturnType() ||
191 FT->getParamType(1) != FT->getReturnType() ||
192 !FT->getParamType(2)->isIntegerTy())
193 return 0;
194
195 // Extract some information from the instruction
196 Value *Dst = CI->getArgOperand(0);
197 Value *Src = CI->getArgOperand(1);
198 uint64_t Len;
199
200 // We don't do anything if length is not constant
201 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
202 Len = LengthArg->getZExtValue();
203 else
204 return 0;
205
206 // See if we can get the length of the input string.
207 uint64_t SrcLen = GetStringLength(Src);
208 if (SrcLen == 0) return 0;
209 --SrcLen; // Unbias length.
210
211 // Handle the simple, do-nothing cases:
212 // strncat(x, "", c) -> x
213 // strncat(x, c, 0) -> x
214 if (SrcLen == 0 || Len == 0) return Dst;
215
216 // These optimizations require TargetData.
217 if (!TD) return 0;
218
219 // We don't optimize this case
220 if (Len < SrcLen) return 0;
221
222 // strncat(x, s, c) -> strcat(x, s)
223 // s is constant so the strcat can be optimized further
224 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
225 return Dst;
226 }
227 };
228
229 //===---------------------------------------===//
230 // 'strchr' Optimizations
231
232 struct StrChrOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrChrOpt233 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
234 // Verify the "strchr" function prototype.
235 FunctionType *FT = Callee->getFunctionType();
236 if (FT->getNumParams() != 2 ||
237 FT->getReturnType() != B.getInt8PtrTy() ||
238 FT->getParamType(0) != FT->getReturnType() ||
239 !FT->getParamType(1)->isIntegerTy(32))
240 return 0;
241
242 Value *SrcStr = CI->getArgOperand(0);
243
244 // If the second operand is non-constant, see if we can compute the length
245 // of the input string and turn this into memchr.
246 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
247 if (CharC == 0) {
248 // These optimizations require TargetData.
249 if (!TD) return 0;
250
251 uint64_t Len = GetStringLength(SrcStr);
252 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
253 return 0;
254
255 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
256 ConstantInt::get(TD->getIntPtrType(*Context), Len),
257 B, TD);
258 }
259
260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
262 std::string Str;
263 if (!GetConstantStringInfo(SrcStr, Str))
264 return 0;
265
266 // strchr can find the nul character.
267 Str += '\0';
268
269 // Compute the offset.
270 size_t I = Str.find(CharC->getSExtValue());
271 if (I == std::string::npos) // Didn't find the char. strchr returns null.
272 return Constant::getNullValue(CI->getType());
273
274 // strchr(s+n,c) -> gep(s+n+i,c)
275 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
276 }
277 };
278
279 //===---------------------------------------===//
280 // 'strrchr' Optimizations
281
282 struct StrRChrOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrRChrOpt283 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
284 // Verify the "strrchr" function prototype.
285 FunctionType *FT = Callee->getFunctionType();
286 if (FT->getNumParams() != 2 ||
287 FT->getReturnType() != B.getInt8PtrTy() ||
288 FT->getParamType(0) != FT->getReturnType() ||
289 !FT->getParamType(1)->isIntegerTy(32))
290 return 0;
291
292 Value *SrcStr = CI->getArgOperand(0);
293 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
294
295 // Cannot fold anything if we're not looking for a constant.
296 if (!CharC)
297 return 0;
298
299 std::string Str;
300 if (!GetConstantStringInfo(SrcStr, Str)) {
301 // strrchr(s, 0) -> strchr(s, 0)
302 if (TD && CharC->isZero())
303 return EmitStrChr(SrcStr, '\0', B, TD);
304 return 0;
305 }
306
307 // strrchr can find the nul character.
308 Str += '\0';
309
310 // Compute the offset.
311 size_t I = Str.rfind(CharC->getSExtValue());
312 if (I == std::string::npos) // Didn't find the char. Return null.
313 return Constant::getNullValue(CI->getType());
314
315 // strrchr(s+n,c) -> gep(s+n+i,c)
316 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
317 }
318 };
319
320 //===---------------------------------------===//
321 // 'strcmp' Optimizations
322
323 struct StrCmpOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrCmpOpt324 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
325 // Verify the "strcmp" function prototype.
326 FunctionType *FT = Callee->getFunctionType();
327 if (FT->getNumParams() != 2 ||
328 !FT->getReturnType()->isIntegerTy(32) ||
329 FT->getParamType(0) != FT->getParamType(1) ||
330 FT->getParamType(0) != B.getInt8PtrTy())
331 return 0;
332
333 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
334 if (Str1P == Str2P) // strcmp(x,x) -> 0
335 return ConstantInt::get(CI->getType(), 0);
336
337 std::string Str1, Str2;
338 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
339 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
340
341 // strcmp(x, y) -> cnst (if both x and y are constant strings)
342 if (HasStr1 && HasStr2)
343 return ConstantInt::get(CI->getType(),
344 StringRef(Str1).compare(Str2));
345
346 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
347 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
348 CI->getType()));
349
350 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
351 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
352
353 // strcmp(P, "x") -> memcmp(P, "x", 2)
354 uint64_t Len1 = GetStringLength(Str1P);
355 uint64_t Len2 = GetStringLength(Str2P);
356 if (Len1 && Len2) {
357 // These optimizations require TargetData.
358 if (!TD) return 0;
359
360 return EmitMemCmp(Str1P, Str2P,
361 ConstantInt::get(TD->getIntPtrType(*Context),
362 std::min(Len1, Len2)), B, TD);
363 }
364
365 return 0;
366 }
367 };
368
369 //===---------------------------------------===//
370 // 'strncmp' Optimizations
371
372 struct StrNCmpOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrNCmpOpt373 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
374 // Verify the "strncmp" function prototype.
375 FunctionType *FT = Callee->getFunctionType();
376 if (FT->getNumParams() != 3 ||
377 !FT->getReturnType()->isIntegerTy(32) ||
378 FT->getParamType(0) != FT->getParamType(1) ||
379 FT->getParamType(0) != B.getInt8PtrTy() ||
380 !FT->getParamType(2)->isIntegerTy())
381 return 0;
382
383 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
384 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
385 return ConstantInt::get(CI->getType(), 0);
386
387 // Get the length argument if it is constant.
388 uint64_t Length;
389 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
390 Length = LengthArg->getZExtValue();
391 else
392 return 0;
393
394 if (Length == 0) // strncmp(x,y,0) -> 0
395 return ConstantInt::get(CI->getType(), 0);
396
397 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
398 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
399
400 std::string Str1, Str2;
401 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
402 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
403
404 // strncmp(x, y) -> cnst (if both x and y are constant strings)
405 if (HasStr1 && HasStr2) {
406 StringRef SubStr1 = StringRef(Str1).substr(0, Length);
407 StringRef SubStr2 = StringRef(Str2).substr(0, Length);
408 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
409 }
410
411 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
412 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
413 CI->getType()));
414
415 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
416 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
417
418 return 0;
419 }
420 };
421
422
423 //===---------------------------------------===//
424 // 'strcpy' Optimizations
425
426 struct StrCpyOpt : public LibCallOptimization {
427 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
428
StrCpyOpt__anon0f7d73dd0211::StrCpyOpt429 StrCpyOpt(bool c) : OptChkCall(c) {}
430
CallOptimizer__anon0f7d73dd0211::StrCpyOpt431 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
432 // Verify the "strcpy" function prototype.
433 unsigned NumParams = OptChkCall ? 3 : 2;
434 FunctionType *FT = Callee->getFunctionType();
435 if (FT->getNumParams() != NumParams ||
436 FT->getReturnType() != FT->getParamType(0) ||
437 FT->getParamType(0) != FT->getParamType(1) ||
438 FT->getParamType(0) != B.getInt8PtrTy())
439 return 0;
440
441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
442 if (Dst == Src) // strcpy(x,x) -> x
443 return Src;
444
445 // These optimizations require TargetData.
446 if (!TD) return 0;
447
448 // See if we can get the length of the input string.
449 uint64_t Len = GetStringLength(Src);
450 if (Len == 0) return 0;
451
452 // We have enough information to now generate the memcpy call to do the
453 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
454 if (OptChkCall)
455 EmitMemCpyChk(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len),
457 CI->getArgOperand(2), B, TD);
458 else
459 B.CreateMemCpy(Dst, Src,
460 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
461 return Dst;
462 }
463 };
464
465 //===---------------------------------------===//
466 // 'strncpy' Optimizations
467
468 struct StrNCpyOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrNCpyOpt469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
470 FunctionType *FT = Callee->getFunctionType();
471 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
472 FT->getParamType(0) != FT->getParamType(1) ||
473 FT->getParamType(0) != B.getInt8PtrTy() ||
474 !FT->getParamType(2)->isIntegerTy())
475 return 0;
476
477 Value *Dst = CI->getArgOperand(0);
478 Value *Src = CI->getArgOperand(1);
479 Value *LenOp = CI->getArgOperand(2);
480
481 // See if we can get the length of the input string.
482 uint64_t SrcLen = GetStringLength(Src);
483 if (SrcLen == 0) return 0;
484 --SrcLen;
485
486 if (SrcLen == 0) {
487 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
488 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
489 return Dst;
490 }
491
492 uint64_t Len;
493 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
494 Len = LengthArg->getZExtValue();
495 else
496 return 0;
497
498 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
499
500 // These optimizations require TargetData.
501 if (!TD) return 0;
502
503 // Let strncpy handle the zero padding
504 if (Len > SrcLen+1) return 0;
505
506 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
507 B.CreateMemCpy(Dst, Src,
508 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
509
510 return Dst;
511 }
512 };
513
514 //===---------------------------------------===//
515 // 'strlen' Optimizations
516
517 struct StrLenOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrLenOpt518 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
519 FunctionType *FT = Callee->getFunctionType();
520 if (FT->getNumParams() != 1 ||
521 FT->getParamType(0) != B.getInt8PtrTy() ||
522 !FT->getReturnType()->isIntegerTy())
523 return 0;
524
525 Value *Src = CI->getArgOperand(0);
526
527 // Constant folding: strlen("xyz") -> 3
528 if (uint64_t Len = GetStringLength(Src))
529 return ConstantInt::get(CI->getType(), Len-1);
530
531 // strlen(x) != 0 --> *x != 0
532 // strlen(x) == 0 --> *x == 0
533 if (IsOnlyUsedInZeroEqualityComparison(CI))
534 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
535 return 0;
536 }
537 };
538
539
540 //===---------------------------------------===//
541 // 'strpbrk' Optimizations
542
543 struct StrPBrkOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrPBrkOpt544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
545 FunctionType *FT = Callee->getFunctionType();
546 if (FT->getNumParams() != 2 ||
547 FT->getParamType(0) != B.getInt8PtrTy() ||
548 FT->getParamType(1) != FT->getParamType(0) ||
549 FT->getReturnType() != FT->getParamType(0))
550 return 0;
551
552 std::string S1, S2;
553 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
554 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
555
556 // strpbrk(s, "") -> NULL
557 // strpbrk("", s) -> NULL
558 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
559 return Constant::getNullValue(CI->getType());
560
561 // Constant folding.
562 if (HasS1 && HasS2) {
563 size_t I = S1.find_first_of(S2);
564 if (I == std::string::npos) // No match.
565 return Constant::getNullValue(CI->getType());
566
567 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
568 }
569
570 // strpbrk(s, "a") -> strchr(s, 'a')
571 if (TD && HasS2 && S2.size() == 1)
572 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
573
574 return 0;
575 }
576 };
577
578 //===---------------------------------------===//
579 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
580
581 struct StrToOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrToOpt582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
583 FunctionType *FT = Callee->getFunctionType();
584 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
585 !FT->getParamType(0)->isPointerTy() ||
586 !FT->getParamType(1)->isPointerTy())
587 return 0;
588
589 Value *EndPtr = CI->getArgOperand(1);
590 if (isa<ConstantPointerNull>(EndPtr)) {
591 // With a null EndPtr, this function won't capture the main argument.
592 // It would be readonly too, except that it still may write to errno.
593 CI->addAttribute(1, Attribute::NoCapture);
594 }
595
596 return 0;
597 }
598 };
599
600 //===---------------------------------------===//
601 // 'strspn' Optimizations
602
603 struct StrSpnOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrSpnOpt604 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
605 FunctionType *FT = Callee->getFunctionType();
606 if (FT->getNumParams() != 2 ||
607 FT->getParamType(0) != B.getInt8PtrTy() ||
608 FT->getParamType(1) != FT->getParamType(0) ||
609 !FT->getReturnType()->isIntegerTy())
610 return 0;
611
612 std::string S1, S2;
613 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
614 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
615
616 // strspn(s, "") -> 0
617 // strspn("", s) -> 0
618 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
619 return Constant::getNullValue(CI->getType());
620
621 // Constant folding.
622 if (HasS1 && HasS2)
623 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
624
625 return 0;
626 }
627 };
628
629 //===---------------------------------------===//
630 // 'strcspn' Optimizations
631
632 struct StrCSpnOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrCSpnOpt633 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
634 FunctionType *FT = Callee->getFunctionType();
635 if (FT->getNumParams() != 2 ||
636 FT->getParamType(0) != B.getInt8PtrTy() ||
637 FT->getParamType(1) != FT->getParamType(0) ||
638 !FT->getReturnType()->isIntegerTy())
639 return 0;
640
641 std::string S1, S2;
642 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
643 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
644
645 // strcspn("", s) -> 0
646 if (HasS1 && S1.empty())
647 return Constant::getNullValue(CI->getType());
648
649 // Constant folding.
650 if (HasS1 && HasS2)
651 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
652
653 // strcspn(s, "") -> strlen(s)
654 if (TD && HasS2 && S2.empty())
655 return EmitStrLen(CI->getArgOperand(0), B, TD);
656
657 return 0;
658 }
659 };
660
661 //===---------------------------------------===//
662 // 'strstr' Optimizations
663
664 struct StrStrOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::StrStrOpt665 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
666 FunctionType *FT = Callee->getFunctionType();
667 if (FT->getNumParams() != 2 ||
668 !FT->getParamType(0)->isPointerTy() ||
669 !FT->getParamType(1)->isPointerTy() ||
670 !FT->getReturnType()->isPointerTy())
671 return 0;
672
673 // fold strstr(x, x) -> x.
674 if (CI->getArgOperand(0) == CI->getArgOperand(1))
675 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
676
677 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
678 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
679 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
680 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
681 StrLen, B, TD);
682 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
683 UI != UE; ) {
684 ICmpInst *Old = cast<ICmpInst>(*UI++);
685 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
686 ConstantInt::getNullValue(StrNCmp->getType()),
687 "cmp");
688 Old->replaceAllUsesWith(Cmp);
689 Old->eraseFromParent();
690 }
691 return CI;
692 }
693
694 // See if either input string is a constant string.
695 std::string SearchStr, ToFindStr;
696 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
697 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
698
699 // fold strstr(x, "") -> x.
700 if (HasStr2 && ToFindStr.empty())
701 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
702
703 // If both strings are known, constant fold it.
704 if (HasStr1 && HasStr2) {
705 std::string::size_type Offset = SearchStr.find(ToFindStr);
706
707 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
708 return Constant::getNullValue(CI->getType());
709
710 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
711 Value *Result = CastToCStr(CI->getArgOperand(0), B);
712 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
713 return B.CreateBitCast(Result, CI->getType());
714 }
715
716 // fold strstr(x, "y") -> strchr(x, 'y').
717 if (HasStr2 && ToFindStr.size() == 1)
718 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
719 ToFindStr[0], B, TD), CI->getType());
720 return 0;
721 }
722 };
723
724
725 //===---------------------------------------===//
726 // 'memcmp' Optimizations
727
728 struct MemCmpOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::MemCmpOpt729 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
730 FunctionType *FT = Callee->getFunctionType();
731 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
732 !FT->getParamType(1)->isPointerTy() ||
733 !FT->getReturnType()->isIntegerTy(32))
734 return 0;
735
736 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
737
738 if (LHS == RHS) // memcmp(s,s,x) -> 0
739 return Constant::getNullValue(CI->getType());
740
741 // Make sure we have a constant length.
742 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
743 if (!LenC) return 0;
744 uint64_t Len = LenC->getZExtValue();
745
746 if (Len == 0) // memcmp(s1,s2,0) -> 0
747 return Constant::getNullValue(CI->getType());
748
749 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
750 if (Len == 1) {
751 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
752 CI->getType(), "lhsv");
753 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
754 CI->getType(), "rhsv");
755 return B.CreateSub(LHSV, RHSV, "chardiff");
756 }
757
758 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
759 std::string LHSStr, RHSStr;
760 if (GetConstantStringInfo(LHS, LHSStr) &&
761 GetConstantStringInfo(RHS, RHSStr)) {
762 // Make sure we're not reading out-of-bounds memory.
763 if (Len > LHSStr.length() || Len > RHSStr.length())
764 return 0;
765 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
766 return ConstantInt::get(CI->getType(), Ret);
767 }
768
769 return 0;
770 }
771 };
772
773 //===---------------------------------------===//
774 // 'memcpy' Optimizations
775
776 struct MemCpyOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::MemCpyOpt777 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
778 // These optimizations require TargetData.
779 if (!TD) return 0;
780
781 FunctionType *FT = Callee->getFunctionType();
782 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
783 !FT->getParamType(0)->isPointerTy() ||
784 !FT->getParamType(1)->isPointerTy() ||
785 FT->getParamType(2) != TD->getIntPtrType(*Context))
786 return 0;
787
788 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
789 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
790 CI->getArgOperand(2), 1);
791 return CI->getArgOperand(0);
792 }
793 };
794
795 //===---------------------------------------===//
796 // 'memmove' Optimizations
797
798 struct MemMoveOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::MemMoveOpt799 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
800 // These optimizations require TargetData.
801 if (!TD) return 0;
802
803 FunctionType *FT = Callee->getFunctionType();
804 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
805 !FT->getParamType(0)->isPointerTy() ||
806 !FT->getParamType(1)->isPointerTy() ||
807 FT->getParamType(2) != TD->getIntPtrType(*Context))
808 return 0;
809
810 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
811 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
812 CI->getArgOperand(2), 1);
813 return CI->getArgOperand(0);
814 }
815 };
816
817 //===---------------------------------------===//
818 // 'memset' Optimizations
819
820 struct MemSetOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::MemSetOpt821 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
822 // These optimizations require TargetData.
823 if (!TD) return 0;
824
825 FunctionType *FT = Callee->getFunctionType();
826 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
827 !FT->getParamType(0)->isPointerTy() ||
828 !FT->getParamType(1)->isIntegerTy() ||
829 FT->getParamType(2) != TD->getIntPtrType(*Context))
830 return 0;
831
832 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
833 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
834 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
835 return CI->getArgOperand(0);
836 }
837 };
838
839 //===----------------------------------------------------------------------===//
840 // Math Library Optimizations
841 //===----------------------------------------------------------------------===//
842
843 //===---------------------------------------===//
844 // 'pow*' Optimizations
845
846 struct PowOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::PowOpt847 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
848 FunctionType *FT = Callee->getFunctionType();
849 // Just make sure this has 2 arguments of the same FP type, which match the
850 // result type.
851 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
852 FT->getParamType(0) != FT->getParamType(1) ||
853 !FT->getParamType(0)->isFloatingPointTy())
854 return 0;
855
856 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
857 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
858 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
859 return Op1C;
860 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
861 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
862 }
863
864 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
865 if (Op2C == 0) return 0;
866
867 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
868 return ConstantFP::get(CI->getType(), 1.0);
869
870 if (Op2C->isExactlyValue(0.5)) {
871 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
872 // This is faster than calling pow, and still handles negative zero
873 // and negative infinite correctly.
874 // TODO: In fast-math mode, this could be just sqrt(x).
875 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
876 Value *Inf = ConstantFP::getInfinity(CI->getType());
877 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
878 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
879 Callee->getAttributes());
880 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
881 Callee->getAttributes());
882 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
883 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
884 return Sel;
885 }
886
887 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
888 return Op1;
889 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
890 return B.CreateFMul(Op1, Op1, "pow2");
891 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
892 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
893 Op1, "powrecip");
894 return 0;
895 }
896 };
897
898 //===---------------------------------------===//
899 // 'exp2' Optimizations
900
901 struct Exp2Opt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::Exp2Opt902 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
903 FunctionType *FT = Callee->getFunctionType();
904 // Just make sure this has 1 argument of FP type, which matches the
905 // result type.
906 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
907 !FT->getParamType(0)->isFloatingPointTy())
908 return 0;
909
910 Value *Op = CI->getArgOperand(0);
911 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
912 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
913 Value *LdExpArg = 0;
914 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
915 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
916 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
917 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
918 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
919 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
920 }
921
922 if (LdExpArg) {
923 const char *Name;
924 if (Op->getType()->isFloatTy())
925 Name = "ldexpf";
926 else if (Op->getType()->isDoubleTy())
927 Name = "ldexp";
928 else
929 Name = "ldexpl";
930
931 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
932 if (!Op->getType()->isFloatTy())
933 One = ConstantExpr::getFPExtend(One, Op->getType());
934
935 Module *M = Caller->getParent();
936 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
937 Op->getType(),
938 B.getInt32Ty(), NULL);
939 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
940 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
941 CI->setCallingConv(F->getCallingConv());
942
943 return CI;
944 }
945 return 0;
946 }
947 };
948
949 //===---------------------------------------===//
950 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
951
952 struct UnaryDoubleFPOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::UnaryDoubleFPOpt953 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
954 FunctionType *FT = Callee->getFunctionType();
955 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
956 !FT->getParamType(0)->isDoubleTy())
957 return 0;
958
959 // If this is something like 'floor((double)floatval)', convert to floorf.
960 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
961 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
962 return 0;
963
964 // floor((double)floatval) -> (double)floorf(floatval)
965 Value *V = Cast->getOperand(0);
966 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
967 Callee->getAttributes());
968 return B.CreateFPExt(V, B.getDoubleTy());
969 }
970 };
971
972 //===----------------------------------------------------------------------===//
973 // Integer Optimizations
974 //===----------------------------------------------------------------------===//
975
976 //===---------------------------------------===//
977 // 'ffs*' Optimizations
978
979 struct FFSOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::FFSOpt980 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
981 FunctionType *FT = Callee->getFunctionType();
982 // Just make sure this has 2 arguments of the same FP type, which match the
983 // result type.
984 if (FT->getNumParams() != 1 ||
985 !FT->getReturnType()->isIntegerTy(32) ||
986 !FT->getParamType(0)->isIntegerTy())
987 return 0;
988
989 Value *Op = CI->getArgOperand(0);
990
991 // Constant fold.
992 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
993 if (CI->getValue() == 0) // ffs(0) -> 0.
994 return Constant::getNullValue(CI->getType());
995 // ffs(c) -> cttz(c)+1
996 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
997 }
998
999 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1000 Type *ArgType = Op->getType();
1001 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1002 Intrinsic::cttz, ArgType);
1003 Value *V = B.CreateCall(F, Op, "cttz");
1004 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1005 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1006
1007 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1008 return B.CreateSelect(Cond, V, B.getInt32(0));
1009 }
1010 };
1011
1012 //===---------------------------------------===//
1013 // 'isdigit' Optimizations
1014
1015 struct IsDigitOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::IsDigitOpt1016 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1017 FunctionType *FT = Callee->getFunctionType();
1018 // We require integer(i32)
1019 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1020 !FT->getParamType(0)->isIntegerTy(32))
1021 return 0;
1022
1023 // isdigit(c) -> (c-'0') <u 10
1024 Value *Op = CI->getArgOperand(0);
1025 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1026 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1027 return B.CreateZExt(Op, CI->getType());
1028 }
1029 };
1030
1031 //===---------------------------------------===//
1032 // 'isascii' Optimizations
1033
1034 struct IsAsciiOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::IsAsciiOpt1035 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1036 FunctionType *FT = Callee->getFunctionType();
1037 // We require integer(i32)
1038 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1039 !FT->getParamType(0)->isIntegerTy(32))
1040 return 0;
1041
1042 // isascii(c) -> c <u 128
1043 Value *Op = CI->getArgOperand(0);
1044 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1045 return B.CreateZExt(Op, CI->getType());
1046 }
1047 };
1048
1049 //===---------------------------------------===//
1050 // 'abs', 'labs', 'llabs' Optimizations
1051
1052 struct AbsOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::AbsOpt1053 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1054 FunctionType *FT = Callee->getFunctionType();
1055 // We require integer(integer) where the types agree.
1056 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1057 FT->getParamType(0) != FT->getReturnType())
1058 return 0;
1059
1060 // abs(x) -> x >s -1 ? x : -x
1061 Value *Op = CI->getArgOperand(0);
1062 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1063 "ispos");
1064 Value *Neg = B.CreateNeg(Op, "neg");
1065 return B.CreateSelect(Pos, Op, Neg);
1066 }
1067 };
1068
1069
1070 //===---------------------------------------===//
1071 // 'toascii' Optimizations
1072
1073 struct ToAsciiOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::ToAsciiOpt1074 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1075 FunctionType *FT = Callee->getFunctionType();
1076 // We require i32(i32)
1077 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1078 !FT->getParamType(0)->isIntegerTy(32))
1079 return 0;
1080
1081 // isascii(c) -> c & 0x7f
1082 return B.CreateAnd(CI->getArgOperand(0),
1083 ConstantInt::get(CI->getType(),0x7F));
1084 }
1085 };
1086
1087 //===----------------------------------------------------------------------===//
1088 // Formatting and IO Optimizations
1089 //===----------------------------------------------------------------------===//
1090
1091 //===---------------------------------------===//
1092 // 'printf' Optimizations
1093
1094 struct PrintFOpt : public LibCallOptimization {
OptimizeFixedFormatString__anon0f7d73dd0211::PrintFOpt1095 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1096 IRBuilder<> &B) {
1097 // Check for a fixed format string.
1098 std::string FormatStr;
1099 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
1100 return 0;
1101
1102 // Empty format string -> noop.
1103 if (FormatStr.empty()) // Tolerate printf's declared void.
1104 return CI->use_empty() ? (Value*)CI :
1105 ConstantInt::get(CI->getType(), 0);
1106
1107 // Do not do any of the following transformations if the printf return value
1108 // is used, in general the printf return value is not compatible with either
1109 // putchar() or puts().
1110 if (!CI->use_empty())
1111 return 0;
1112
1113 // printf("x") -> putchar('x'), even for '%'.
1114 if (FormatStr.size() == 1) {
1115 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
1116 if (CI->use_empty()) return CI;
1117 return B.CreateIntCast(Res, CI->getType(), true);
1118 }
1119
1120 // printf("foo\n") --> puts("foo")
1121 if (FormatStr[FormatStr.size()-1] == '\n' &&
1122 FormatStr.find('%') == std::string::npos) { // no format characters.
1123 // Create a string literal with no \n on it. We expect the constant merge
1124 // pass to be run after this pass, to merge duplicate strings.
1125 FormatStr.erase(FormatStr.end()-1);
1126 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1127 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1128 GlobalVariable::InternalLinkage, C, "str");
1129 EmitPutS(C, B, TD);
1130 return CI->use_empty() ? (Value*)CI :
1131 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1132 }
1133
1134 // Optimize specific format strings.
1135 // printf("%c", chr) --> putchar(chr)
1136 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1137 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1138 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
1139
1140 if (CI->use_empty()) return CI;
1141 return B.CreateIntCast(Res, CI->getType(), true);
1142 }
1143
1144 // printf("%s\n", str) --> puts(str)
1145 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1146 CI->getArgOperand(1)->getType()->isPointerTy()) {
1147 EmitPutS(CI->getArgOperand(1), B, TD);
1148 return CI;
1149 }
1150 return 0;
1151 }
1152
CallOptimizer__anon0f7d73dd0211::PrintFOpt1153 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1154 // Require one fixed pointer argument and an integer/void result.
1155 FunctionType *FT = Callee->getFunctionType();
1156 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1157 !(FT->getReturnType()->isIntegerTy() ||
1158 FT->getReturnType()->isVoidTy()))
1159 return 0;
1160
1161 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1162 return V;
1163 }
1164
1165 // printf(format, ...) -> iprintf(format, ...) if no floating point
1166 // arguments.
1167 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1168 Module *M = B.GetInsertBlock()->getParent()->getParent();
1169 Constant *IPrintFFn =
1170 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1171 CallInst *New = cast<CallInst>(CI->clone());
1172 New->setCalledFunction(IPrintFFn);
1173 B.Insert(New);
1174 return New;
1175 }
1176 return 0;
1177 }
1178 };
1179
1180 //===---------------------------------------===//
1181 // 'sprintf' Optimizations
1182
1183 struct SPrintFOpt : public LibCallOptimization {
OptimizeFixedFormatString__anon0f7d73dd0211::SPrintFOpt1184 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1185 IRBuilder<> &B) {
1186 // Check for a fixed format string.
1187 std::string FormatStr;
1188 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1189 return 0;
1190
1191 // If we just have a format string (nothing else crazy) transform it.
1192 if (CI->getNumArgOperands() == 2) {
1193 // Make sure there's no % in the constant array. We could try to handle
1194 // %% -> % in the future if we cared.
1195 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1196 if (FormatStr[i] == '%')
1197 return 0; // we found a format specifier, bail out.
1198
1199 // These optimizations require TargetData.
1200 if (!TD) return 0;
1201
1202 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1203 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1204 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1205 FormatStr.size() + 1), 1); // nul byte.
1206 return ConstantInt::get(CI->getType(), FormatStr.size());
1207 }
1208
1209 // The remaining optimizations require the format string to be "%s" or "%c"
1210 // and have an extra operand.
1211 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1212 CI->getNumArgOperands() < 3)
1213 return 0;
1214
1215 // Decode the second character of the format string.
1216 if (FormatStr[1] == 'c') {
1217 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1218 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1219 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1220 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1221 B.CreateStore(V, Ptr);
1222 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1223 B.CreateStore(B.getInt8(0), Ptr);
1224
1225 return ConstantInt::get(CI->getType(), 1);
1226 }
1227
1228 if (FormatStr[1] == 's') {
1229 // These optimizations require TargetData.
1230 if (!TD) return 0;
1231
1232 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1233 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1234
1235 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
1236 Value *IncLen = B.CreateAdd(Len,
1237 ConstantInt::get(Len->getType(), 1),
1238 "leninc");
1239 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1240
1241 // The sprintf result is the unincremented number of bytes in the string.
1242 return B.CreateIntCast(Len, CI->getType(), false);
1243 }
1244 return 0;
1245 }
1246
CallOptimizer__anon0f7d73dd0211::SPrintFOpt1247 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1248 // Require two fixed pointer arguments and an integer result.
1249 FunctionType *FT = Callee->getFunctionType();
1250 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1251 !FT->getParamType(1)->isPointerTy() ||
1252 !FT->getReturnType()->isIntegerTy())
1253 return 0;
1254
1255 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1256 return V;
1257 }
1258
1259 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1260 // point arguments.
1261 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1262 Module *M = B.GetInsertBlock()->getParent()->getParent();
1263 Constant *SIPrintFFn =
1264 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1265 CallInst *New = cast<CallInst>(CI->clone());
1266 New->setCalledFunction(SIPrintFFn);
1267 B.Insert(New);
1268 return New;
1269 }
1270 return 0;
1271 }
1272 };
1273
1274 //===---------------------------------------===//
1275 // 'fwrite' Optimizations
1276
1277 struct FWriteOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::FWriteOpt1278 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1279 // Require a pointer, an integer, an integer, a pointer, returning integer.
1280 FunctionType *FT = Callee->getFunctionType();
1281 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1282 !FT->getParamType(1)->isIntegerTy() ||
1283 !FT->getParamType(2)->isIntegerTy() ||
1284 !FT->getParamType(3)->isPointerTy() ||
1285 !FT->getReturnType()->isIntegerTy())
1286 return 0;
1287
1288 // Get the element size and count.
1289 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1290 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1291 if (!SizeC || !CountC) return 0;
1292 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1293
1294 // If this is writing zero records, remove the call (it's a noop).
1295 if (Bytes == 0)
1296 return ConstantInt::get(CI->getType(), 0);
1297
1298 // If this is writing one byte, turn it into fputc.
1299 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1300 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1301 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
1302 return ConstantInt::get(CI->getType(), 1);
1303 }
1304
1305 return 0;
1306 }
1307 };
1308
1309 //===---------------------------------------===//
1310 // 'fputs' Optimizations
1311
1312 struct FPutsOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::FPutsOpt1313 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1314 // These optimizations require TargetData.
1315 if (!TD) return 0;
1316
1317 // Require two pointers. Also, we can't optimize if return value is used.
1318 FunctionType *FT = Callee->getFunctionType();
1319 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1320 !FT->getParamType(1)->isPointerTy() ||
1321 !CI->use_empty())
1322 return 0;
1323
1324 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1325 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1326 if (!Len) return 0;
1327 EmitFWrite(CI->getArgOperand(0),
1328 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1329 CI->getArgOperand(1), B, TD);
1330 return CI; // Known to have no uses (see above).
1331 }
1332 };
1333
1334 //===---------------------------------------===//
1335 // 'fprintf' Optimizations
1336
1337 struct FPrintFOpt : public LibCallOptimization {
OptimizeFixedFormatString__anon0f7d73dd0211::FPrintFOpt1338 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1339 IRBuilder<> &B) {
1340 // All the optimizations depend on the format string.
1341 std::string FormatStr;
1342 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1343 return 0;
1344
1345 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1346 if (CI->getNumArgOperands() == 2) {
1347 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1348 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1349 return 0; // We found a format specifier.
1350
1351 // These optimizations require TargetData.
1352 if (!TD) return 0;
1353
1354 EmitFWrite(CI->getArgOperand(1),
1355 ConstantInt::get(TD->getIntPtrType(*Context),
1356 FormatStr.size()),
1357 CI->getArgOperand(0), B, TD);
1358 return ConstantInt::get(CI->getType(), FormatStr.size());
1359 }
1360
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] != '%' ||
1364 CI->getNumArgOperands() < 3)
1365 return 0;
1366
1367 // Decode the second character of the format string.
1368 if (FormatStr[1] == 'c') {
1369 // fprintf(F, "%c", chr) --> fputc(chr, F)
1370 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1371 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1372 return ConstantInt::get(CI->getType(), 1);
1373 }
1374
1375 if (FormatStr[1] == 's') {
1376 // fprintf(F, "%s", str) --> fputs(str, F)
1377 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1378 return 0;
1379 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1380 return CI;
1381 }
1382 return 0;
1383 }
1384
CallOptimizer__anon0f7d73dd0211::FPrintFOpt1385 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1386 // Require two fixed paramters as pointers and integer result.
1387 FunctionType *FT = Callee->getFunctionType();
1388 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1389 !FT->getParamType(1)->isPointerTy() ||
1390 !FT->getReturnType()->isIntegerTy())
1391 return 0;
1392
1393 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1394 return V;
1395 }
1396
1397 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1398 // floating point arguments.
1399 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1400 Module *M = B.GetInsertBlock()->getParent()->getParent();
1401 Constant *FIPrintFFn =
1402 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1403 CallInst *New = cast<CallInst>(CI->clone());
1404 New->setCalledFunction(FIPrintFFn);
1405 B.Insert(New);
1406 return New;
1407 }
1408 return 0;
1409 }
1410 };
1411
1412 //===---------------------------------------===//
1413 // 'puts' Optimizations
1414
1415 struct PutsOpt : public LibCallOptimization {
CallOptimizer__anon0f7d73dd0211::PutsOpt1416 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1417 // Require one fixed pointer argument and an integer/void result.
1418 FunctionType *FT = Callee->getFunctionType();
1419 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1420 !(FT->getReturnType()->isIntegerTy() ||
1421 FT->getReturnType()->isVoidTy()))
1422 return 0;
1423
1424 // Check for a constant string.
1425 std::string Str;
1426 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
1427 return 0;
1428
1429 if (Str.empty() && CI->use_empty()) {
1430 // puts("") -> putchar('\n')
1431 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1432 if (CI->use_empty()) return CI;
1433 return B.CreateIntCast(Res, CI->getType(), true);
1434 }
1435
1436 return 0;
1437 }
1438 };
1439
1440 } // end anonymous namespace.
1441
1442 //===----------------------------------------------------------------------===//
1443 // SimplifyLibCalls Pass Implementation
1444 //===----------------------------------------------------------------------===//
1445
1446 namespace {
1447 /// This pass optimizes well known library functions from libc and libm.
1448 ///
1449 class SimplifyLibCalls : public FunctionPass {
1450 TargetLibraryInfo *TLI;
1451
1452 StringMap<LibCallOptimization*> Optimizations;
1453 // String and Memory LibCall Optimizations
1454 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1455 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1456 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1457 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1458 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1459 // Math Library Optimizations
1460 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1461 // Integer Optimizations
1462 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1463 ToAsciiOpt ToAscii;
1464 // Formatting and IO Optimizations
1465 SPrintFOpt SPrintF; PrintFOpt PrintF;
1466 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1467 PutsOpt Puts;
1468
1469 bool Modified; // This is only used by doInitialization.
1470 public:
1471 static char ID; // Pass identification
SimplifyLibCalls()1472 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1473 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1474 }
1475 void InitOptimizations();
1476 bool runOnFunction(Function &F);
1477
1478 void setDoesNotAccessMemory(Function &F);
1479 void setOnlyReadsMemory(Function &F);
1480 void setDoesNotThrow(Function &F);
1481 void setDoesNotCapture(Function &F, unsigned n);
1482 void setDoesNotAlias(Function &F, unsigned n);
1483 bool doInitialization(Module &M);
1484
1485 void inferPrototypeAttributes(Function &F);
getAnalysisUsage(AnalysisUsage & AU) const1486 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1487 AU.addRequired<TargetLibraryInfo>();
1488 }
1489 };
1490 } // end anonymous namespace.
1491
1492 char SimplifyLibCalls::ID = 0;
1493
1494 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1495 "Simplify well-known library calls", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)1496 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1497 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1498 "Simplify well-known library calls", false, false)
1499
1500 // Public interface to the Simplify LibCalls pass.
1501 FunctionPass *llvm::createSimplifyLibCallsPass() {
1502 return new SimplifyLibCalls();
1503 }
1504
1505 /// Optimizations - Populate the Optimizations map with all the optimizations
1506 /// we know.
InitOptimizations()1507 void SimplifyLibCalls::InitOptimizations() {
1508 // String and Memory LibCall Optimizations
1509 Optimizations["strcat"] = &StrCat;
1510 Optimizations["strncat"] = &StrNCat;
1511 Optimizations["strchr"] = &StrChr;
1512 Optimizations["strrchr"] = &StrRChr;
1513 Optimizations["strcmp"] = &StrCmp;
1514 Optimizations["strncmp"] = &StrNCmp;
1515 Optimizations["strcpy"] = &StrCpy;
1516 Optimizations["strncpy"] = &StrNCpy;
1517 Optimizations["strlen"] = &StrLen;
1518 Optimizations["strpbrk"] = &StrPBrk;
1519 Optimizations["strtol"] = &StrTo;
1520 Optimizations["strtod"] = &StrTo;
1521 Optimizations["strtof"] = &StrTo;
1522 Optimizations["strtoul"] = &StrTo;
1523 Optimizations["strtoll"] = &StrTo;
1524 Optimizations["strtold"] = &StrTo;
1525 Optimizations["strtoull"] = &StrTo;
1526 Optimizations["strspn"] = &StrSpn;
1527 Optimizations["strcspn"] = &StrCSpn;
1528 Optimizations["strstr"] = &StrStr;
1529 Optimizations["memcmp"] = &MemCmp;
1530 if (TLI->has(LibFunc::memcpy)) Optimizations["memcpy"] = &MemCpy;
1531 Optimizations["memmove"] = &MemMove;
1532 if (TLI->has(LibFunc::memset)) Optimizations["memset"] = &MemSet;
1533
1534 // _chk variants of String and Memory LibCall Optimizations.
1535 Optimizations["__strcpy_chk"] = &StrCpyChk;
1536
1537 // Math Library Optimizations
1538 Optimizations["powf"] = &Pow;
1539 Optimizations["pow"] = &Pow;
1540 Optimizations["powl"] = &Pow;
1541 Optimizations["llvm.pow.f32"] = &Pow;
1542 Optimizations["llvm.pow.f64"] = &Pow;
1543 Optimizations["llvm.pow.f80"] = &Pow;
1544 Optimizations["llvm.pow.f128"] = &Pow;
1545 Optimizations["llvm.pow.ppcf128"] = &Pow;
1546 Optimizations["exp2l"] = &Exp2;
1547 Optimizations["exp2"] = &Exp2;
1548 Optimizations["exp2f"] = &Exp2;
1549 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1550 Optimizations["llvm.exp2.f128"] = &Exp2;
1551 Optimizations["llvm.exp2.f80"] = &Exp2;
1552 Optimizations["llvm.exp2.f64"] = &Exp2;
1553 Optimizations["llvm.exp2.f32"] = &Exp2;
1554
1555 #ifdef HAVE_FLOORF
1556 Optimizations["floor"] = &UnaryDoubleFP;
1557 #endif
1558 #ifdef HAVE_CEILF
1559 Optimizations["ceil"] = &UnaryDoubleFP;
1560 #endif
1561 #ifdef HAVE_ROUNDF
1562 Optimizations["round"] = &UnaryDoubleFP;
1563 #endif
1564 #ifdef HAVE_RINTF
1565 Optimizations["rint"] = &UnaryDoubleFP;
1566 #endif
1567 #ifdef HAVE_NEARBYINTF
1568 Optimizations["nearbyint"] = &UnaryDoubleFP;
1569 #endif
1570
1571 // Integer Optimizations
1572 Optimizations["ffs"] = &FFS;
1573 Optimizations["ffsl"] = &FFS;
1574 Optimizations["ffsll"] = &FFS;
1575 Optimizations["abs"] = &Abs;
1576 Optimizations["labs"] = &Abs;
1577 Optimizations["llabs"] = &Abs;
1578 Optimizations["isdigit"] = &IsDigit;
1579 Optimizations["isascii"] = &IsAscii;
1580 Optimizations["toascii"] = &ToAscii;
1581
1582 // Formatting and IO Optimizations
1583 Optimizations["sprintf"] = &SPrintF;
1584 Optimizations["printf"] = &PrintF;
1585 Optimizations["fwrite"] = &FWrite;
1586 Optimizations["fputs"] = &FPuts;
1587 Optimizations["fprintf"] = &FPrintF;
1588 Optimizations["puts"] = &Puts;
1589 }
1590
1591
1592 /// runOnFunction - Top level algorithm.
1593 ///
runOnFunction(Function & F)1594 bool SimplifyLibCalls::runOnFunction(Function &F) {
1595 TLI = &getAnalysis<TargetLibraryInfo>();
1596
1597 if (Optimizations.empty())
1598 InitOptimizations();
1599
1600 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1601
1602 IRBuilder<> Builder(F.getContext());
1603
1604 bool Changed = false;
1605 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1606 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1607 // Ignore non-calls.
1608 CallInst *CI = dyn_cast<CallInst>(I++);
1609 if (!CI) continue;
1610
1611 // Ignore indirect calls and calls to non-external functions.
1612 Function *Callee = CI->getCalledFunction();
1613 if (Callee == 0 || !Callee->isDeclaration() ||
1614 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1615 continue;
1616
1617 // Ignore unknown calls.
1618 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1619 if (!LCO) continue;
1620
1621 // Set the builder to the instruction after the call.
1622 Builder.SetInsertPoint(BB, I);
1623
1624 // Use debug location of CI for all new instructions.
1625 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1626
1627 // Try to optimize this call.
1628 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1629 if (Result == 0) continue;
1630
1631 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1632 dbgs() << " into: " << *Result << "\n");
1633
1634 // Something changed!
1635 Changed = true;
1636 ++NumSimplified;
1637
1638 // Inspect the instruction after the call (which was potentially just
1639 // added) next.
1640 I = CI; ++I;
1641
1642 if (CI != Result && !CI->use_empty()) {
1643 CI->replaceAllUsesWith(Result);
1644 if (!Result->hasName())
1645 Result->takeName(CI);
1646 }
1647 CI->eraseFromParent();
1648 }
1649 }
1650 return Changed;
1651 }
1652
1653 // Utility methods for doInitialization.
1654
setDoesNotAccessMemory(Function & F)1655 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1656 if (!F.doesNotAccessMemory()) {
1657 F.setDoesNotAccessMemory();
1658 ++NumAnnotated;
1659 Modified = true;
1660 }
1661 }
setOnlyReadsMemory(Function & F)1662 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1663 if (!F.onlyReadsMemory()) {
1664 F.setOnlyReadsMemory();
1665 ++NumAnnotated;
1666 Modified = true;
1667 }
1668 }
setDoesNotThrow(Function & F)1669 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1670 if (!F.doesNotThrow()) {
1671 F.setDoesNotThrow();
1672 ++NumAnnotated;
1673 Modified = true;
1674 }
1675 }
setDoesNotCapture(Function & F,unsigned n)1676 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1677 if (!F.doesNotCapture(n)) {
1678 F.setDoesNotCapture(n);
1679 ++NumAnnotated;
1680 Modified = true;
1681 }
1682 }
setDoesNotAlias(Function & F,unsigned n)1683 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1684 if (!F.doesNotAlias(n)) {
1685 F.setDoesNotAlias(n);
1686 ++NumAnnotated;
1687 Modified = true;
1688 }
1689 }
1690
1691
inferPrototypeAttributes(Function & F)1692 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1693 FunctionType *FTy = F.getFunctionType();
1694
1695 StringRef Name = F.getName();
1696 switch (Name[0]) {
1697 case 's':
1698 if (Name == "strlen") {
1699 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1700 return;
1701 setOnlyReadsMemory(F);
1702 setDoesNotThrow(F);
1703 setDoesNotCapture(F, 1);
1704 } else if (Name == "strchr" ||
1705 Name == "strrchr") {
1706 if (FTy->getNumParams() != 2 ||
1707 !FTy->getParamType(0)->isPointerTy() ||
1708 !FTy->getParamType(1)->isIntegerTy())
1709 return;
1710 setOnlyReadsMemory(F);
1711 setDoesNotThrow(F);
1712 } else if (Name == "strcpy" ||
1713 Name == "stpcpy" ||
1714 Name == "strcat" ||
1715 Name == "strtol" ||
1716 Name == "strtod" ||
1717 Name == "strtof" ||
1718 Name == "strtoul" ||
1719 Name == "strtoll" ||
1720 Name == "strtold" ||
1721 Name == "strncat" ||
1722 Name == "strncpy" ||
1723 Name == "strtoull") {
1724 if (FTy->getNumParams() < 2 ||
1725 !FTy->getParamType(1)->isPointerTy())
1726 return;
1727 setDoesNotThrow(F);
1728 setDoesNotCapture(F, 2);
1729 } else if (Name == "strxfrm") {
1730 if (FTy->getNumParams() != 3 ||
1731 !FTy->getParamType(0)->isPointerTy() ||
1732 !FTy->getParamType(1)->isPointerTy())
1733 return;
1734 setDoesNotThrow(F);
1735 setDoesNotCapture(F, 1);
1736 setDoesNotCapture(F, 2);
1737 } else if (Name == "strcmp" ||
1738 Name == "strspn" ||
1739 Name == "strncmp" ||
1740 Name == "strcspn" ||
1741 Name == "strcoll" ||
1742 Name == "strcasecmp" ||
1743 Name == "strncasecmp") {
1744 if (FTy->getNumParams() < 2 ||
1745 !FTy->getParamType(0)->isPointerTy() ||
1746 !FTy->getParamType(1)->isPointerTy())
1747 return;
1748 setOnlyReadsMemory(F);
1749 setDoesNotThrow(F);
1750 setDoesNotCapture(F, 1);
1751 setDoesNotCapture(F, 2);
1752 } else if (Name == "strstr" ||
1753 Name == "strpbrk") {
1754 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1755 return;
1756 setOnlyReadsMemory(F);
1757 setDoesNotThrow(F);
1758 setDoesNotCapture(F, 2);
1759 } else if (Name == "strtok" ||
1760 Name == "strtok_r") {
1761 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1762 return;
1763 setDoesNotThrow(F);
1764 setDoesNotCapture(F, 2);
1765 } else if (Name == "scanf" ||
1766 Name == "setbuf" ||
1767 Name == "setvbuf") {
1768 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1769 return;
1770 setDoesNotThrow(F);
1771 setDoesNotCapture(F, 1);
1772 } else if (Name == "strdup" ||
1773 Name == "strndup") {
1774 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1775 !FTy->getParamType(0)->isPointerTy())
1776 return;
1777 setDoesNotThrow(F);
1778 setDoesNotAlias(F, 0);
1779 setDoesNotCapture(F, 1);
1780 } else if (Name == "stat" ||
1781 Name == "sscanf" ||
1782 Name == "sprintf" ||
1783 Name == "statvfs") {
1784 if (FTy->getNumParams() < 2 ||
1785 !FTy->getParamType(0)->isPointerTy() ||
1786 !FTy->getParamType(1)->isPointerTy())
1787 return;
1788 setDoesNotThrow(F);
1789 setDoesNotCapture(F, 1);
1790 setDoesNotCapture(F, 2);
1791 } else if (Name == "snprintf") {
1792 if (FTy->getNumParams() != 3 ||
1793 !FTy->getParamType(0)->isPointerTy() ||
1794 !FTy->getParamType(2)->isPointerTy())
1795 return;
1796 setDoesNotThrow(F);
1797 setDoesNotCapture(F, 1);
1798 setDoesNotCapture(F, 3);
1799 } else if (Name == "setitimer") {
1800 if (FTy->getNumParams() != 3 ||
1801 !FTy->getParamType(1)->isPointerTy() ||
1802 !FTy->getParamType(2)->isPointerTy())
1803 return;
1804 setDoesNotThrow(F);
1805 setDoesNotCapture(F, 2);
1806 setDoesNotCapture(F, 3);
1807 } else if (Name == "system") {
1808 if (FTy->getNumParams() != 1 ||
1809 !FTy->getParamType(0)->isPointerTy())
1810 return;
1811 // May throw; "system" is a valid pthread cancellation point.
1812 setDoesNotCapture(F, 1);
1813 }
1814 break;
1815 case 'm':
1816 if (Name == "malloc") {
1817 if (FTy->getNumParams() != 1 ||
1818 !FTy->getReturnType()->isPointerTy())
1819 return;
1820 setDoesNotThrow(F);
1821 setDoesNotAlias(F, 0);
1822 } else if (Name == "memcmp") {
1823 if (FTy->getNumParams() != 3 ||
1824 !FTy->getParamType(0)->isPointerTy() ||
1825 !FTy->getParamType(1)->isPointerTy())
1826 return;
1827 setOnlyReadsMemory(F);
1828 setDoesNotThrow(F);
1829 setDoesNotCapture(F, 1);
1830 setDoesNotCapture(F, 2);
1831 } else if (Name == "memchr" ||
1832 Name == "memrchr") {
1833 if (FTy->getNumParams() != 3)
1834 return;
1835 setOnlyReadsMemory(F);
1836 setDoesNotThrow(F);
1837 } else if (Name == "modf" ||
1838 Name == "modff" ||
1839 Name == "modfl" ||
1840 Name == "memcpy" ||
1841 Name == "memccpy" ||
1842 Name == "memmove") {
1843 if (FTy->getNumParams() < 2 ||
1844 !FTy->getParamType(1)->isPointerTy())
1845 return;
1846 setDoesNotThrow(F);
1847 setDoesNotCapture(F, 2);
1848 } else if (Name == "memalign") {
1849 if (!FTy->getReturnType()->isPointerTy())
1850 return;
1851 setDoesNotAlias(F, 0);
1852 } else if (Name == "mkdir" ||
1853 Name == "mktime") {
1854 if (FTy->getNumParams() == 0 ||
1855 !FTy->getParamType(0)->isPointerTy())
1856 return;
1857 setDoesNotThrow(F);
1858 setDoesNotCapture(F, 1);
1859 }
1860 break;
1861 case 'r':
1862 if (Name == "realloc") {
1863 if (FTy->getNumParams() != 2 ||
1864 !FTy->getParamType(0)->isPointerTy() ||
1865 !FTy->getReturnType()->isPointerTy())
1866 return;
1867 setDoesNotThrow(F);
1868 setDoesNotAlias(F, 0);
1869 setDoesNotCapture(F, 1);
1870 } else if (Name == "read") {
1871 if (FTy->getNumParams() != 3 ||
1872 !FTy->getParamType(1)->isPointerTy())
1873 return;
1874 // May throw; "read" is a valid pthread cancellation point.
1875 setDoesNotCapture(F, 2);
1876 } else if (Name == "rmdir" ||
1877 Name == "rewind" ||
1878 Name == "remove" ||
1879 Name == "realpath") {
1880 if (FTy->getNumParams() < 1 ||
1881 !FTy->getParamType(0)->isPointerTy())
1882 return;
1883 setDoesNotThrow(F);
1884 setDoesNotCapture(F, 1);
1885 } else if (Name == "rename" ||
1886 Name == "readlink") {
1887 if (FTy->getNumParams() < 2 ||
1888 !FTy->getParamType(0)->isPointerTy() ||
1889 !FTy->getParamType(1)->isPointerTy())
1890 return;
1891 setDoesNotThrow(F);
1892 setDoesNotCapture(F, 1);
1893 setDoesNotCapture(F, 2);
1894 }
1895 break;
1896 case 'w':
1897 if (Name == "write") {
1898 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1899 return;
1900 // May throw; "write" is a valid pthread cancellation point.
1901 setDoesNotCapture(F, 2);
1902 }
1903 break;
1904 case 'b':
1905 if (Name == "bcopy") {
1906 if (FTy->getNumParams() != 3 ||
1907 !FTy->getParamType(0)->isPointerTy() ||
1908 !FTy->getParamType(1)->isPointerTy())
1909 return;
1910 setDoesNotThrow(F);
1911 setDoesNotCapture(F, 1);
1912 setDoesNotCapture(F, 2);
1913 } else if (Name == "bcmp") {
1914 if (FTy->getNumParams() != 3 ||
1915 !FTy->getParamType(0)->isPointerTy() ||
1916 !FTy->getParamType(1)->isPointerTy())
1917 return;
1918 setDoesNotThrow(F);
1919 setOnlyReadsMemory(F);
1920 setDoesNotCapture(F, 1);
1921 setDoesNotCapture(F, 2);
1922 } else if (Name == "bzero") {
1923 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1924 return;
1925 setDoesNotThrow(F);
1926 setDoesNotCapture(F, 1);
1927 }
1928 break;
1929 case 'c':
1930 if (Name == "calloc") {
1931 if (FTy->getNumParams() != 2 ||
1932 !FTy->getReturnType()->isPointerTy())
1933 return;
1934 setDoesNotThrow(F);
1935 setDoesNotAlias(F, 0);
1936 } else if (Name == "chmod" ||
1937 Name == "chown" ||
1938 Name == "ctermid" ||
1939 Name == "clearerr" ||
1940 Name == "closedir") {
1941 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1942 return;
1943 setDoesNotThrow(F);
1944 setDoesNotCapture(F, 1);
1945 }
1946 break;
1947 case 'a':
1948 if (Name == "atoi" ||
1949 Name == "atol" ||
1950 Name == "atof" ||
1951 Name == "atoll") {
1952 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1953 return;
1954 setDoesNotThrow(F);
1955 setOnlyReadsMemory(F);
1956 setDoesNotCapture(F, 1);
1957 } else if (Name == "access") {
1958 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1959 return;
1960 setDoesNotThrow(F);
1961 setDoesNotCapture(F, 1);
1962 }
1963 break;
1964 case 'f':
1965 if (Name == "fopen") {
1966 if (FTy->getNumParams() != 2 ||
1967 !FTy->getReturnType()->isPointerTy() ||
1968 !FTy->getParamType(0)->isPointerTy() ||
1969 !FTy->getParamType(1)->isPointerTy())
1970 return;
1971 setDoesNotThrow(F);
1972 setDoesNotAlias(F, 0);
1973 setDoesNotCapture(F, 1);
1974 setDoesNotCapture(F, 2);
1975 } else if (Name == "fdopen") {
1976 if (FTy->getNumParams() != 2 ||
1977 !FTy->getReturnType()->isPointerTy() ||
1978 !FTy->getParamType(1)->isPointerTy())
1979 return;
1980 setDoesNotThrow(F);
1981 setDoesNotAlias(F, 0);
1982 setDoesNotCapture(F, 2);
1983 } else if (Name == "feof" ||
1984 Name == "free" ||
1985 Name == "fseek" ||
1986 Name == "ftell" ||
1987 Name == "fgetc" ||
1988 Name == "fseeko" ||
1989 Name == "ftello" ||
1990 Name == "fileno" ||
1991 Name == "fflush" ||
1992 Name == "fclose" ||
1993 Name == "fsetpos" ||
1994 Name == "flockfile" ||
1995 Name == "funlockfile" ||
1996 Name == "ftrylockfile") {
1997 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1998 return;
1999 setDoesNotThrow(F);
2000 setDoesNotCapture(F, 1);
2001 } else if (Name == "ferror") {
2002 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2003 return;
2004 setDoesNotThrow(F);
2005 setDoesNotCapture(F, 1);
2006 setOnlyReadsMemory(F);
2007 } else if (Name == "fputc" ||
2008 Name == "fstat" ||
2009 Name == "frexp" ||
2010 Name == "frexpf" ||
2011 Name == "frexpl" ||
2012 Name == "fstatvfs") {
2013 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2014 return;
2015 setDoesNotThrow(F);
2016 setDoesNotCapture(F, 2);
2017 } else if (Name == "fgets") {
2018 if (FTy->getNumParams() != 3 ||
2019 !FTy->getParamType(0)->isPointerTy() ||
2020 !FTy->getParamType(2)->isPointerTy())
2021 return;
2022 setDoesNotThrow(F);
2023 setDoesNotCapture(F, 3);
2024 } else if (Name == "fread" ||
2025 Name == "fwrite") {
2026 if (FTy->getNumParams() != 4 ||
2027 !FTy->getParamType(0)->isPointerTy() ||
2028 !FTy->getParamType(3)->isPointerTy())
2029 return;
2030 setDoesNotThrow(F);
2031 setDoesNotCapture(F, 1);
2032 setDoesNotCapture(F, 4);
2033 } else if (Name == "fputs" ||
2034 Name == "fscanf" ||
2035 Name == "fprintf" ||
2036 Name == "fgetpos") {
2037 if (FTy->getNumParams() < 2 ||
2038 !FTy->getParamType(0)->isPointerTy() ||
2039 !FTy->getParamType(1)->isPointerTy())
2040 return;
2041 setDoesNotThrow(F);
2042 setDoesNotCapture(F, 1);
2043 setDoesNotCapture(F, 2);
2044 }
2045 break;
2046 case 'g':
2047 if (Name == "getc" ||
2048 Name == "getlogin_r" ||
2049 Name == "getc_unlocked") {
2050 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2051 return;
2052 setDoesNotThrow(F);
2053 setDoesNotCapture(F, 1);
2054 } else if (Name == "getenv") {
2055 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2056 return;
2057 setDoesNotThrow(F);
2058 setOnlyReadsMemory(F);
2059 setDoesNotCapture(F, 1);
2060 } else if (Name == "gets" ||
2061 Name == "getchar") {
2062 setDoesNotThrow(F);
2063 } else if (Name == "getitimer") {
2064 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2065 return;
2066 setDoesNotThrow(F);
2067 setDoesNotCapture(F, 2);
2068 } else if (Name == "getpwnam") {
2069 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2070 return;
2071 setDoesNotThrow(F);
2072 setDoesNotCapture(F, 1);
2073 }
2074 break;
2075 case 'u':
2076 if (Name == "ungetc") {
2077 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2078 return;
2079 setDoesNotThrow(F);
2080 setDoesNotCapture(F, 2);
2081 } else if (Name == "uname" ||
2082 Name == "unlink" ||
2083 Name == "unsetenv") {
2084 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2085 return;
2086 setDoesNotThrow(F);
2087 setDoesNotCapture(F, 1);
2088 } else if (Name == "utime" ||
2089 Name == "utimes") {
2090 if (FTy->getNumParams() != 2 ||
2091 !FTy->getParamType(0)->isPointerTy() ||
2092 !FTy->getParamType(1)->isPointerTy())
2093 return;
2094 setDoesNotThrow(F);
2095 setDoesNotCapture(F, 1);
2096 setDoesNotCapture(F, 2);
2097 }
2098 break;
2099 case 'p':
2100 if (Name == "putc") {
2101 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2102 return;
2103 setDoesNotThrow(F);
2104 setDoesNotCapture(F, 2);
2105 } else if (Name == "puts" ||
2106 Name == "printf" ||
2107 Name == "perror") {
2108 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2109 return;
2110 setDoesNotThrow(F);
2111 setDoesNotCapture(F, 1);
2112 } else if (Name == "pread" ||
2113 Name == "pwrite") {
2114 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2115 return;
2116 // May throw; these are valid pthread cancellation points.
2117 setDoesNotCapture(F, 2);
2118 } else if (Name == "putchar") {
2119 setDoesNotThrow(F);
2120 } else if (Name == "popen") {
2121 if (FTy->getNumParams() != 2 ||
2122 !FTy->getReturnType()->isPointerTy() ||
2123 !FTy->getParamType(0)->isPointerTy() ||
2124 !FTy->getParamType(1)->isPointerTy())
2125 return;
2126 setDoesNotThrow(F);
2127 setDoesNotAlias(F, 0);
2128 setDoesNotCapture(F, 1);
2129 setDoesNotCapture(F, 2);
2130 } else if (Name == "pclose") {
2131 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2132 return;
2133 setDoesNotThrow(F);
2134 setDoesNotCapture(F, 1);
2135 }
2136 break;
2137 case 'v':
2138 if (Name == "vscanf") {
2139 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2140 return;
2141 setDoesNotThrow(F);
2142 setDoesNotCapture(F, 1);
2143 } else if (Name == "vsscanf" ||
2144 Name == "vfscanf") {
2145 if (FTy->getNumParams() != 3 ||
2146 !FTy->getParamType(1)->isPointerTy() ||
2147 !FTy->getParamType(2)->isPointerTy())
2148 return;
2149 setDoesNotThrow(F);
2150 setDoesNotCapture(F, 1);
2151 setDoesNotCapture(F, 2);
2152 } else if (Name == "valloc") {
2153 if (!FTy->getReturnType()->isPointerTy())
2154 return;
2155 setDoesNotThrow(F);
2156 setDoesNotAlias(F, 0);
2157 } else if (Name == "vprintf") {
2158 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2159 return;
2160 setDoesNotThrow(F);
2161 setDoesNotCapture(F, 1);
2162 } else if (Name == "vfprintf" ||
2163 Name == "vsprintf") {
2164 if (FTy->getNumParams() != 3 ||
2165 !FTy->getParamType(0)->isPointerTy() ||
2166 !FTy->getParamType(1)->isPointerTy())
2167 return;
2168 setDoesNotThrow(F);
2169 setDoesNotCapture(F, 1);
2170 setDoesNotCapture(F, 2);
2171 } else if (Name == "vsnprintf") {
2172 if (FTy->getNumParams() != 4 ||
2173 !FTy->getParamType(0)->isPointerTy() ||
2174 !FTy->getParamType(2)->isPointerTy())
2175 return;
2176 setDoesNotThrow(F);
2177 setDoesNotCapture(F, 1);
2178 setDoesNotCapture(F, 3);
2179 }
2180 break;
2181 case 'o':
2182 if (Name == "open") {
2183 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2184 return;
2185 // May throw; "open" is a valid pthread cancellation point.
2186 setDoesNotCapture(F, 1);
2187 } else if (Name == "opendir") {
2188 if (FTy->getNumParams() != 1 ||
2189 !FTy->getReturnType()->isPointerTy() ||
2190 !FTy->getParamType(0)->isPointerTy())
2191 return;
2192 setDoesNotThrow(F);
2193 setDoesNotAlias(F, 0);
2194 setDoesNotCapture(F, 1);
2195 }
2196 break;
2197 case 't':
2198 if (Name == "tmpfile") {
2199 if (!FTy->getReturnType()->isPointerTy())
2200 return;
2201 setDoesNotThrow(F);
2202 setDoesNotAlias(F, 0);
2203 } else if (Name == "times") {
2204 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2205 return;
2206 setDoesNotThrow(F);
2207 setDoesNotCapture(F, 1);
2208 }
2209 break;
2210 case 'h':
2211 if (Name == "htonl" ||
2212 Name == "htons") {
2213 setDoesNotThrow(F);
2214 setDoesNotAccessMemory(F);
2215 }
2216 break;
2217 case 'n':
2218 if (Name == "ntohl" ||
2219 Name == "ntohs") {
2220 setDoesNotThrow(F);
2221 setDoesNotAccessMemory(F);
2222 }
2223 break;
2224 case 'l':
2225 if (Name == "lstat") {
2226 if (FTy->getNumParams() != 2 ||
2227 !FTy->getParamType(0)->isPointerTy() ||
2228 !FTy->getParamType(1)->isPointerTy())
2229 return;
2230 setDoesNotThrow(F);
2231 setDoesNotCapture(F, 1);
2232 setDoesNotCapture(F, 2);
2233 } else if (Name == "lchown") {
2234 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2235 return;
2236 setDoesNotThrow(F);
2237 setDoesNotCapture(F, 1);
2238 }
2239 break;
2240 case 'q':
2241 if (Name == "qsort") {
2242 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2243 return;
2244 // May throw; places call through function pointer.
2245 setDoesNotCapture(F, 4);
2246 }
2247 break;
2248 case '_':
2249 if (Name == "__strdup" ||
2250 Name == "__strndup") {
2251 if (FTy->getNumParams() < 1 ||
2252 !FTy->getReturnType()->isPointerTy() ||
2253 !FTy->getParamType(0)->isPointerTy())
2254 return;
2255 setDoesNotThrow(F);
2256 setDoesNotAlias(F, 0);
2257 setDoesNotCapture(F, 1);
2258 } else if (Name == "__strtok_r") {
2259 if (FTy->getNumParams() != 3 ||
2260 !FTy->getParamType(1)->isPointerTy())
2261 return;
2262 setDoesNotThrow(F);
2263 setDoesNotCapture(F, 2);
2264 } else if (Name == "_IO_getc") {
2265 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2266 return;
2267 setDoesNotThrow(F);
2268 setDoesNotCapture(F, 1);
2269 } else if (Name == "_IO_putc") {
2270 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2271 return;
2272 setDoesNotThrow(F);
2273 setDoesNotCapture(F, 2);
2274 }
2275 break;
2276 case 1:
2277 if (Name == "\1__isoc99_scanf") {
2278 if (FTy->getNumParams() < 1 ||
2279 !FTy->getParamType(0)->isPointerTy())
2280 return;
2281 setDoesNotThrow(F);
2282 setDoesNotCapture(F, 1);
2283 } else if (Name == "\1stat64" ||
2284 Name == "\1lstat64" ||
2285 Name == "\1statvfs64" ||
2286 Name == "\1__isoc99_sscanf") {
2287 if (FTy->getNumParams() < 1 ||
2288 !FTy->getParamType(0)->isPointerTy() ||
2289 !FTy->getParamType(1)->isPointerTy())
2290 return;
2291 setDoesNotThrow(F);
2292 setDoesNotCapture(F, 1);
2293 setDoesNotCapture(F, 2);
2294 } else if (Name == "\1fopen64") {
2295 if (FTy->getNumParams() != 2 ||
2296 !FTy->getReturnType()->isPointerTy() ||
2297 !FTy->getParamType(0)->isPointerTy() ||
2298 !FTy->getParamType(1)->isPointerTy())
2299 return;
2300 setDoesNotThrow(F);
2301 setDoesNotAlias(F, 0);
2302 setDoesNotCapture(F, 1);
2303 setDoesNotCapture(F, 2);
2304 } else if (Name == "\1fseeko64" ||
2305 Name == "\1ftello64") {
2306 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2307 return;
2308 setDoesNotThrow(F);
2309 setDoesNotCapture(F, 1);
2310 } else if (Name == "\1tmpfile64") {
2311 if (!FTy->getReturnType()->isPointerTy())
2312 return;
2313 setDoesNotThrow(F);
2314 setDoesNotAlias(F, 0);
2315 } else if (Name == "\1fstat64" ||
2316 Name == "\1fstatvfs64") {
2317 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2318 return;
2319 setDoesNotThrow(F);
2320 setDoesNotCapture(F, 2);
2321 } else if (Name == "\1open64") {
2322 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2323 return;
2324 // May throw; "open" is a valid pthread cancellation point.
2325 setDoesNotCapture(F, 1);
2326 }
2327 break;
2328 }
2329 }
2330
2331 /// doInitialization - Add attributes to well-known functions.
2332 ///
doInitialization(Module & M)2333 bool SimplifyLibCalls::doInitialization(Module &M) {
2334 Modified = false;
2335 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2336 Function &F = *I;
2337 if (F.isDeclaration() && F.hasName())
2338 inferPrototypeAttributes(F);
2339 }
2340 return Modified;
2341 }
2342
2343 // TODO:
2344 // Additional cases that we need to add to this file:
2345 //
2346 // cbrt:
2347 // * cbrt(expN(X)) -> expN(x/3)
2348 // * cbrt(sqrt(x)) -> pow(x,1/6)
2349 // * cbrt(sqrt(x)) -> pow(x,1/9)
2350 //
2351 // cos, cosf, cosl:
2352 // * cos(-x) -> cos(x)
2353 //
2354 // exp, expf, expl:
2355 // * exp(log(x)) -> x
2356 //
2357 // log, logf, logl:
2358 // * log(exp(x)) -> x
2359 // * log(x**y) -> y*log(x)
2360 // * log(exp(y)) -> y*log(e)
2361 // * log(exp2(y)) -> y*log(2)
2362 // * log(exp10(y)) -> y*log(10)
2363 // * log(sqrt(x)) -> 0.5*log(x)
2364 // * log(pow(x,y)) -> y*log(x)
2365 //
2366 // lround, lroundf, lroundl:
2367 // * lround(cnst) -> cnst'
2368 //
2369 // pow, powf, powl:
2370 // * pow(exp(x),y) -> exp(x*y)
2371 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2372 // * pow(pow(x,y),z)-> pow(x,y*z)
2373 //
2374 // round, roundf, roundl:
2375 // * round(cnst) -> cnst'
2376 //
2377 // signbit:
2378 // * signbit(cnst) -> cnst'
2379 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2380 //
2381 // sqrt, sqrtf, sqrtl:
2382 // * sqrt(expN(x)) -> expN(x*0.5)
2383 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2384 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2385 //
2386 // stpcpy:
2387 // * stpcpy(str, "literal") ->
2388 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2389 //
2390 // tan, tanf, tanl:
2391 // * tan(atan(x)) -> x
2392 //
2393 // trunc, truncf, truncl:
2394 // * trunc(cnst) -> cnst'
2395 //
2396 //
2397