1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). For example, a call to the function "exit(3)" that
13 // occurs within the main() function can be transformed into a simple "return 3"
14 // instruction. Any optimization that takes this form (replace call to library
15 // function with simpler code that provides the same result) belongs in this
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "simplify-libcalls"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/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/Support/Compiler.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Config/config.h"
36 STATISTIC(NumSimplified, "Number of library calls simplified");
38 //===----------------------------------------------------------------------===//
39 // Optimizer Base Class
40 //===----------------------------------------------------------------------===//
42 /// This class is the abstract base class for the set of optimizations that
43 /// corresponds to one library call.
45 class VISIBILITY_HIDDEN LibCallOptimization {
50 LibCallOptimization() { }
51 virtual ~LibCallOptimization() {}
53 /// CallOptimizer - This pure virtual method is implemented by base classes to
54 /// do various optimizations. If this returns null then no transformation was
55 /// performed. If it returns CI, then it transformed the call and CI is to be
56 /// deleted. If it returns something else, replace CI with the new value and
58 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
61 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
62 Caller = CI->getParent()->getParent();
64 return CallOptimizer(CI->getCalledFunction(), CI, B);
67 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
68 Value *CastToCStr(Value *V, IRBuilder<> &B);
70 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
71 /// specified pointer. Ptr is required to be some pointer type, and the
72 /// return value has 'intptr_t' type.
73 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
75 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
76 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
77 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
78 unsigned Align, IRBuilder<> &B);
80 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
81 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
82 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
84 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
85 /// 'floor'). This function is known to take a single of type matching 'Op'
86 /// and returns one value with the same type. If 'Op' is a long double, 'l'
87 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
88 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
90 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
92 void EmitPutChar(Value *Char, IRBuilder<> &B);
94 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
96 void EmitPutS(Value *Str, IRBuilder<> &B);
98 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
99 /// an i32, and File is a pointer to FILE.
100 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
102 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
103 /// pointer and File is a pointer to FILE.
104 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
106 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
107 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
108 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
111 } // End anonymous namespace.
113 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
114 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
115 return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
118 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
119 /// specified pointer. This always returns an integer value of size intptr_t.
120 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
121 Module *M = Caller->getParent();
122 Constant *StrLen =M->getOrInsertFunction("strlen", TD->getIntPtrType(),
123 PointerType::getUnqual(Type::Int8Ty),
125 return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
128 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
129 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
130 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
131 unsigned Align, IRBuilder<> &B) {
132 Module *M = Caller->getParent();
133 Intrinsic::ID IID = Intrinsic::memcpy;
135 Tys[0] = Len->getType();
136 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
137 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
138 ConstantInt::get(Type::Int32Ty, Align));
141 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
142 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
143 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
144 Value *Len, IRBuilder<> &B) {
145 Module *M = Caller->getParent();
146 Value *MemChr = M->getOrInsertFunction("memchr",
147 PointerType::getUnqual(Type::Int8Ty),
148 PointerType::getUnqual(Type::Int8Ty),
149 Type::Int32Ty, TD->getIntPtrType(),
151 return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
154 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
155 /// 'floor'). This function is known to take a single of type matching 'Op' and
156 /// returns one value with the same type. If 'Op' is a long double, 'l' is
157 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
158 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
161 if (Op->getType() != Type::DoubleTy) {
162 // If we need to add a suffix, copy into NameBuffer.
163 unsigned NameLen = strlen(Name);
164 assert(NameLen < sizeof(NameBuffer)-2);
165 memcpy(NameBuffer, Name, NameLen);
166 if (Op->getType() == Type::FloatTy)
167 NameBuffer[NameLen] = 'f'; // floorf
169 NameBuffer[NameLen] = 'l'; // floorl
170 NameBuffer[NameLen+1] = 0;
174 Module *M = Caller->getParent();
175 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
176 Op->getType(), NULL);
177 return B.CreateCall(Callee, Op, Name);
180 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
182 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
183 Module *M = Caller->getParent();
184 Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
185 Type::Int32Ty, NULL);
186 B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
189 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
191 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
192 Module *M = Caller->getParent();
193 Value *F = M->getOrInsertFunction("puts", Type::Int32Ty,
194 PointerType::getUnqual(Type::Int8Ty), NULL);
195 B.CreateCall(F, CastToCStr(Str, B), "puts");
198 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
199 /// an integer and File is a pointer to FILE.
200 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
201 Module *M = Caller->getParent();
202 Constant *F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
203 File->getType(), NULL);
204 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
205 B.CreateCall2(F, Char, File, "fputc");
208 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
209 /// pointer and File is a pointer to FILE.
210 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
211 Module *M = Caller->getParent();
212 Constant *F = M->getOrInsertFunction("fputs", Type::Int32Ty,
213 PointerType::getUnqual(Type::Int8Ty),
214 File->getType(), NULL);
215 B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
218 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
219 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
220 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
222 Module *M = Caller->getParent();
223 Constant *F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
224 PointerType::getUnqual(Type::Int8Ty),
225 TD->getIntPtrType(), TD->getIntPtrType(),
226 File->getType(), NULL);
227 B.CreateCall4(F, CastToCStr(Ptr, B), Size,
228 ConstantInt::get(TD->getIntPtrType(), 1), File);
231 //===----------------------------------------------------------------------===//
233 //===----------------------------------------------------------------------===//
235 /// GetStringLengthH - If we can compute the length of the string pointed to by
236 /// the specified pointer, return 'len+1'. If we can't, return 0.
237 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
238 // Look through noop bitcast instructions.
239 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
240 return GetStringLengthH(BCI->getOperand(0), PHIs);
242 // If this is a PHI node, there are two cases: either we have already seen it
244 if (PHINode *PN = dyn_cast<PHINode>(V)) {
245 if (!PHIs.insert(PN))
246 return ~0ULL; // already in the set.
248 // If it was new, see if all the input strings are the same length.
249 uint64_t LenSoFar = ~0ULL;
250 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
251 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
252 if (Len == 0) return 0; // Unknown length -> unknown.
254 if (Len == ~0ULL) continue;
256 if (Len != LenSoFar && LenSoFar != ~0ULL)
257 return 0; // Disagree -> unknown.
261 // Success, all agree.
265 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
266 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
267 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
268 if (Len1 == 0) return 0;
269 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
270 if (Len2 == 0) return 0;
271 if (Len1 == ~0ULL) return Len2;
272 if (Len2 == ~0ULL) return Len1;
273 if (Len1 != Len2) return 0;
277 // If the value is not a GEP instruction nor a constant expression with a
278 // GEP instruction, then return unknown.
280 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
282 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
283 if (CE->getOpcode() != Instruction::GetElementPtr)
290 // Make sure the GEP has exactly three arguments.
291 if (GEP->getNumOperands() != 3)
294 // Check to make sure that the first operand of the GEP is an integer and
295 // has value 0 so that we are sure we're indexing into the initializer.
296 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
302 // If the second index isn't a ConstantInt, then this is a variable index
303 // into the array. If this occurs, we can't say anything meaningful about
305 uint64_t StartIdx = 0;
306 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
307 StartIdx = CI->getZExtValue();
311 // The GEP instruction, constant or instruction, must reference a global
312 // variable that is a constant and is initialized. The referenced constant
313 // initializer is the array that we'll use for optimization.
314 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
315 if (!GV || !GV->isConstant() || !GV->hasInitializer())
317 Constant *GlobalInit = GV->getInitializer();
319 // Handle the ConstantAggregateZero case, which is a degenerate case. The
320 // initializer is constant zero so the length of the string must be zero.
321 if (isa<ConstantAggregateZero>(GlobalInit))
322 return 1; // Len = 0 offset by 1.
324 // Must be a Constant Array
325 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
326 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
329 // Get the number of elements in the array
330 uint64_t NumElts = Array->getType()->getNumElements();
332 // Traverse the constant array from StartIdx (derived above) which is
333 // the place the GEP refers to in the array.
334 for (unsigned i = StartIdx; i != NumElts; ++i) {
335 Constant *Elt = Array->getOperand(i);
336 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
337 if (!CI) // This array isn't suitable, non-int initializer.
340 return i-StartIdx+1; // We found end of string, success!
343 return 0; // The array isn't null terminated, conservatively return 'unknown'.
346 /// GetStringLength - If we can compute the length of the string pointed to by
347 /// the specified pointer, return 'len+1'. If we can't, return 0.
348 static uint64_t GetStringLength(Value *V) {
349 if (!isa<PointerType>(V->getType())) return 0;
351 SmallPtrSet<PHINode*, 32> PHIs;
352 uint64_t Len = GetStringLengthH(V, PHIs);
353 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
354 // an empty string as a length.
355 return Len == ~0ULL ? 1 : Len;
358 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
359 /// value is equal or not-equal to zero.
360 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
361 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
363 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
364 if (IC->isEquality())
365 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
366 if (C->isNullValue())
368 // Unknown instruction.
374 //===----------------------------------------------------------------------===//
375 // Miscellaneous LibCall Optimizations
376 //===----------------------------------------------------------------------===//
379 //===---------------------------------------===//
380 // 'exit' Optimizations
382 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
383 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
384 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
385 // Verify we have a reasonable prototype for exit.
386 if (Callee->arg_size() == 0 || !CI->use_empty())
389 // Verify the caller is main, and that the result type of main matches the
390 // argument type of exit.
391 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
392 Caller->getReturnType() != CI->getOperand(1)->getType())
395 TerminatorInst *OldTI = CI->getParent()->getTerminator();
397 // Create the return after the call.
398 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
400 // Drop all successor phi node entries.
401 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
402 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
404 // Erase all instructions from after our return instruction until the end of
406 BasicBlock::iterator FirstDead = RI; ++FirstDead;
407 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
412 //===----------------------------------------------------------------------===//
413 // String and Memory LibCall Optimizations
414 //===----------------------------------------------------------------------===//
416 //===---------------------------------------===//
417 // 'strcat' Optimizations
419 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
420 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
421 // Verify the "strcat" function prototype.
422 const FunctionType *FT = Callee->getFunctionType();
423 if (FT->getNumParams() != 2 ||
424 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
425 FT->getParamType(0) != FT->getReturnType() ||
426 FT->getParamType(1) != FT->getReturnType())
429 // Extract some information from the instruction
430 Value *Dst = CI->getOperand(1);
431 Value *Src = CI->getOperand(2);
433 // See if we can get the length of the input string.
434 uint64_t Len = GetStringLength(Src);
435 if (Len == 0) return 0;
436 --Len; // Unbias length.
438 // Handle the simple, do-nothing case: strcat(x, "") -> x
442 // We need to find the end of the destination string. That's where the
443 // memory is to be moved to. We just generate a call to strlen.
444 Value *DstLen = EmitStrLen(Dst, B);
446 // Now that we have the destination's length, we must index into the
447 // destination's pointer to get the actual memcpy destination (end of
448 // the string .. we're concatenating).
449 Dst = B.CreateGEP(Dst, DstLen, "endptr");
451 // We have enough information to now generate the memcpy call to do the
452 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
453 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
458 //===---------------------------------------===//
459 // 'strchr' Optimizations
461 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
462 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
463 // Verify the "strchr" function prototype.
464 const FunctionType *FT = Callee->getFunctionType();
465 if (FT->getNumParams() != 2 ||
466 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
467 FT->getParamType(0) != FT->getReturnType())
470 Value *SrcStr = CI->getOperand(1);
472 // If the second operand is non-constant, see if we can compute the length
473 // of the input string and turn this into memchr.
474 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
476 uint64_t Len = GetStringLength(SrcStr);
477 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
480 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
481 ConstantInt::get(TD->getIntPtrType(), Len), B);
484 // Otherwise, the character is a constant, see if the first argument is
485 // a string literal. If so, we can constant fold.
487 if (!GetConstantStringInfo(SrcStr, Str))
490 // strchr can find the nul character.
492 char CharValue = CharC->getSExtValue();
494 // Compute the offset.
497 if (i == Str.size()) // Didn't find the char. strchr returns null.
498 return Constant::getNullValue(CI->getType());
499 // Did we find our match?
500 if (Str[i] == CharValue)
505 // strchr(s+n,c) -> gep(s+n+i,c)
506 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
507 return B.CreateGEP(SrcStr, Idx, "strchr");
511 //===---------------------------------------===//
512 // 'strcmp' Optimizations
514 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
515 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
516 // Verify the "strcmp" function prototype.
517 const FunctionType *FT = Callee->getFunctionType();
518 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
519 FT->getParamType(0) != FT->getParamType(1) ||
520 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
523 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
524 if (Str1P == Str2P) // strcmp(x,x) -> 0
525 return ConstantInt::get(CI->getType(), 0);
527 std::string Str1, Str2;
528 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
529 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
531 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
532 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
534 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
535 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
537 // strcmp(x, y) -> cnst (if both x and y are constant strings)
538 if (HasStr1 && HasStr2)
539 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
544 //===---------------------------------------===//
545 // 'strncmp' Optimizations
547 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
548 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
549 // Verify the "strncmp" function prototype.
550 const FunctionType *FT = Callee->getFunctionType();
551 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
552 FT->getParamType(0) != FT->getParamType(1) ||
553 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
554 !isa<IntegerType>(FT->getParamType(2)))
557 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
558 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
559 return ConstantInt::get(CI->getType(), 0);
561 // Get the length argument if it is constant.
563 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
564 Length = LengthArg->getZExtValue();
568 if (Length == 0) // strncmp(x,y,0) -> 0
569 return ConstantInt::get(CI->getType(), 0);
571 std::string Str1, Str2;
572 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
573 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
575 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
576 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
578 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
579 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
581 // strncmp(x, y) -> cnst (if both x and y are constant strings)
582 if (HasStr1 && HasStr2)
583 return ConstantInt::get(CI->getType(),
584 strncmp(Str1.c_str(), Str2.c_str(), Length));
590 //===---------------------------------------===//
591 // 'strcpy' Optimizations
593 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
594 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
595 // Verify the "strcpy" function prototype.
596 const FunctionType *FT = Callee->getFunctionType();
597 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
598 FT->getParamType(0) != FT->getParamType(1) ||
599 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
602 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
603 if (Dst == Src) // strcpy(x,x) -> x
606 // See if we can get the length of the input string.
607 uint64_t Len = GetStringLength(Src);
608 if (Len == 0) return 0;
610 // We have enough information to now generate the memcpy call to do the
611 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
612 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
619 //===---------------------------------------===//
620 // 'strlen' Optimizations
622 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
623 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
624 const FunctionType *FT = Callee->getFunctionType();
625 if (FT->getNumParams() != 1 ||
626 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
627 !isa<IntegerType>(FT->getReturnType()))
630 Value *Src = CI->getOperand(1);
632 // Constant folding: strlen("xyz") -> 3
633 if (uint64_t Len = GetStringLength(Src))
634 return ConstantInt::get(CI->getType(), Len-1);
636 // Handle strlen(p) != 0.
637 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
639 // strlen(x) != 0 --> *x != 0
640 // strlen(x) == 0 --> *x == 0
641 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
645 //===---------------------------------------===//
646 // 'memcmp' Optimizations
648 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
649 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
650 const FunctionType *FT = Callee->getFunctionType();
651 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
652 !isa<PointerType>(FT->getParamType(1)) ||
653 FT->getReturnType() != Type::Int32Ty)
656 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
658 if (LHS == RHS) // memcmp(s,s,x) -> 0
659 return Constant::getNullValue(CI->getType());
661 // Make sure we have a constant length.
662 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
664 uint64_t Len = LenC->getZExtValue();
666 if (Len == 0) // memcmp(s1,s2,0) -> 0
667 return Constant::getNullValue(CI->getType());
669 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
670 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
671 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
672 return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
675 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
676 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
677 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
678 const Type *PTy = PointerType::getUnqual(Len == 2 ?
679 Type::Int16Ty : Type::Int32Ty);
680 LHS = B.CreateBitCast(LHS, PTy, "tmp");
681 RHS = B.CreateBitCast(RHS, PTy, "tmp");
682 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
683 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
684 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
685 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
692 //===---------------------------------------===//
693 // 'memcpy' Optimizations
695 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
696 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
697 const FunctionType *FT = Callee->getFunctionType();
698 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
699 !isa<PointerType>(FT->getParamType(0)) ||
700 !isa<PointerType>(FT->getParamType(1)) ||
701 FT->getParamType(2) != TD->getIntPtrType())
704 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
705 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
706 return CI->getOperand(1);
710 //===----------------------------------------------------------------------===//
711 // Math Library Optimizations
712 //===----------------------------------------------------------------------===//
714 //===---------------------------------------===//
715 // 'pow*' Optimizations
717 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
718 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
719 const FunctionType *FT = Callee->getFunctionType();
720 // Just make sure this has 2 arguments of the same FP type, which match the
722 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
723 FT->getParamType(0) != FT->getParamType(1) ||
724 !FT->getParamType(0)->isFloatingPoint())
727 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
728 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
729 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
731 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
732 return EmitUnaryFloatFnCall(Op2, "exp2", B);
735 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
736 if (Op2C == 0) return 0;
738 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
739 return ConstantFP::get(CI->getType(), 1.0);
741 if (Op2C->isExactlyValue(0.5)) {
742 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
743 // 'unsafe' math optimizations are allowed.
744 // x pow(x, 0.5) sqrt(x)
745 // ---------------------------------------------
749 // pow(x, 0.5) -> sqrt(x)
750 return B.CreateCall(get_sqrt(), Op1, "sqrt");
754 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
756 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
757 return B.CreateMul(Op1, Op1, "pow2");
758 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
759 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
764 //===---------------------------------------===//
765 // 'exp2' Optimizations
767 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
768 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
769 const FunctionType *FT = Callee->getFunctionType();
770 // Just make sure this has 1 argument of FP type, which matches the
772 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
773 !FT->getParamType(0)->isFloatingPoint())
776 Value *Op = CI->getOperand(1);
777 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
778 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
780 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
781 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
782 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
783 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
784 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
785 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
790 if (Op->getType() == Type::FloatTy)
792 else if (Op->getType() == Type::DoubleTy)
797 Constant *One = ConstantFP::get(APFloat(1.0f));
798 if (Op->getType() != Type::FloatTy)
799 One = ConstantExpr::getFPExtend(One, Op->getType());
801 Module *M = Caller->getParent();
802 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
803 Op->getType(), Type::Int32Ty,NULL);
804 return B.CreateCall2(Callee, One, LdExpArg);
811 //===---------------------------------------===//
812 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
814 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
815 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
816 const FunctionType *FT = Callee->getFunctionType();
817 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
818 FT->getParamType(0) != Type::DoubleTy)
821 // If this is something like 'floor((double)floatval)', convert to floorf.
822 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
823 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
826 // floor((double)floatval) -> (double)floorf(floatval)
827 Value *V = Cast->getOperand(0);
828 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
829 return B.CreateFPExt(V, Type::DoubleTy);
833 //===----------------------------------------------------------------------===//
834 // Integer Optimizations
835 //===----------------------------------------------------------------------===//
837 //===---------------------------------------===//
838 // 'ffs*' Optimizations
840 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
841 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
842 const FunctionType *FT = Callee->getFunctionType();
843 // Just make sure this has 2 arguments of the same FP type, which match the
845 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
846 !isa<IntegerType>(FT->getParamType(0)))
849 Value *Op = CI->getOperand(1);
852 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
853 if (CI->getValue() == 0) // ffs(0) -> 0.
854 return Constant::getNullValue(CI->getType());
855 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
856 CI->getValue().countTrailingZeros()+1);
859 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
860 const Type *ArgType = Op->getType();
861 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
862 Intrinsic::cttz, &ArgType, 1);
863 Value *V = B.CreateCall(F, Op, "cttz");
864 V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
865 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
867 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
868 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
872 //===---------------------------------------===//
873 // 'isdigit' Optimizations
875 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
876 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
877 const FunctionType *FT = Callee->getFunctionType();
878 // We require integer(i32)
879 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
880 FT->getParamType(0) != Type::Int32Ty)
883 // isdigit(c) -> (c-'0') <u 10
884 Value *Op = CI->getOperand(1);
885 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
886 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
887 return B.CreateZExt(Op, CI->getType());
891 //===---------------------------------------===//
892 // 'isascii' Optimizations
894 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
895 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
896 const FunctionType *FT = Callee->getFunctionType();
897 // We require integer(i32)
898 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
899 FT->getParamType(0) != Type::Int32Ty)
902 // isascii(c) -> c <u 128
903 Value *Op = CI->getOperand(1);
904 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
905 return B.CreateZExt(Op, CI->getType());
909 //===---------------------------------------===//
910 // 'abs', 'labs', 'llabs' Optimizations
912 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
913 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
914 const FunctionType *FT = Callee->getFunctionType();
915 // We require integer(integer) where the types agree.
916 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
917 FT->getParamType(0) != FT->getReturnType())
920 // abs(x) -> x >s -1 ? x : -x
921 Value *Op = CI->getOperand(1);
922 Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
924 Value *Neg = B.CreateNeg(Op, "neg");
925 return B.CreateSelect(Pos, Op, Neg);
930 //===---------------------------------------===//
931 // 'toascii' Optimizations
933 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
934 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
935 const FunctionType *FT = Callee->getFunctionType();
936 // We require i32(i32)
937 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
938 FT->getParamType(0) != Type::Int32Ty)
941 // isascii(c) -> c & 0x7f
942 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
946 //===----------------------------------------------------------------------===//
947 // Formatting and IO Optimizations
948 //===----------------------------------------------------------------------===//
950 //===---------------------------------------===//
951 // 'printf' Optimizations
953 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
954 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
955 // Require one fixed pointer argument and an integer/void result.
956 const FunctionType *FT = Callee->getFunctionType();
957 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
958 !(isa<IntegerType>(FT->getReturnType()) ||
959 FT->getReturnType() == Type::VoidTy))
962 // Check for a fixed format string.
963 std::string FormatStr;
964 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
967 // Empty format string -> noop.
968 if (FormatStr.empty()) // Tolerate printf's declared void.
969 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
971 // printf("x") -> putchar('x'), even for '%'.
972 if (FormatStr.size() == 1) {
973 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
974 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
977 // printf("foo\n") --> puts("foo")
978 if (FormatStr[FormatStr.size()-1] == '\n' &&
979 FormatStr.find('%') == std::string::npos) { // no format characters.
980 // Create a string literal with no \n on it. We expect the constant merge
981 // pass to be run after this pass, to merge duplicate strings.
982 FormatStr.erase(FormatStr.end()-1);
983 Constant *C = ConstantArray::get(FormatStr, true);
984 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
985 C, "str", Callee->getParent());
987 return CI->use_empty() ? (Value*)CI :
988 ConstantInt::get(CI->getType(), FormatStr.size()+1);
991 // Optimize specific format strings.
992 // printf("%c", chr) --> putchar(*(i8*)dst)
993 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
994 isa<IntegerType>(CI->getOperand(2)->getType())) {
995 EmitPutChar(CI->getOperand(2), B);
996 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
999 // printf("%s\n", str) --> puts(str)
1000 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1001 isa<PointerType>(CI->getOperand(2)->getType()) &&
1003 EmitPutS(CI->getOperand(2), B);
1010 //===---------------------------------------===//
1011 // 'sprintf' Optimizations
1013 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1014 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1015 // Require two fixed pointer arguments and an integer result.
1016 const FunctionType *FT = Callee->getFunctionType();
1017 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1018 !isa<PointerType>(FT->getParamType(1)) ||
1019 !isa<IntegerType>(FT->getReturnType()))
1022 // Check for a fixed format string.
1023 std::string FormatStr;
1024 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1027 // If we just have a format string (nothing else crazy) transform it.
1028 if (CI->getNumOperands() == 3) {
1029 // Make sure there's no % in the constant array. We could try to handle
1030 // %% -> % in the future if we cared.
1031 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1032 if (FormatStr[i] == '%')
1033 return 0; // we found a format specifier, bail out.
1035 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1036 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1037 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1038 return ConstantInt::get(CI->getType(), FormatStr.size());
1041 // The remaining optimizations require the format string to be "%s" or "%c"
1042 // and have an extra operand.
1043 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1046 // Decode the second character of the format string.
1047 if (FormatStr[1] == 'c') {
1048 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1049 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1050 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1051 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1052 B.CreateStore(V, Ptr);
1053 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1054 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1056 return ConstantInt::get(CI->getType(), 1);
1059 if (FormatStr[1] == 's') {
1060 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1061 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1063 Value *Len = EmitStrLen(CI->getOperand(3), B);
1064 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1066 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1068 // The sprintf result is the unincremented number of bytes in the string.
1069 return B.CreateIntCast(Len, CI->getType(), false);
1075 //===---------------------------------------===//
1076 // 'fwrite' Optimizations
1078 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1079 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1080 // Require a pointer, an integer, an integer, a pointer, returning integer.
1081 const FunctionType *FT = Callee->getFunctionType();
1082 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1083 !isa<IntegerType>(FT->getParamType(1)) ||
1084 !isa<IntegerType>(FT->getParamType(2)) ||
1085 !isa<PointerType>(FT->getParamType(3)) ||
1086 !isa<IntegerType>(FT->getReturnType()))
1089 // Get the element size and count.
1090 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1091 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1092 if (!SizeC || !CountC) return 0;
1093 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1095 // If this is writing zero records, remove the call (it's a noop).
1097 return ConstantInt::get(CI->getType(), 0);
1099 // If this is writing one byte, turn it into fputc.
1100 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1101 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1102 EmitFPutC(Char, CI->getOperand(4), B);
1103 return ConstantInt::get(CI->getType(), 1);
1110 //===---------------------------------------===//
1111 // 'fputs' Optimizations
1113 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1114 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1115 // Require two pointers. Also, we can't optimize if return value is used.
1116 const FunctionType *FT = Callee->getFunctionType();
1117 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1118 !isa<PointerType>(FT->getParamType(1)) ||
1122 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1123 uint64_t Len = GetStringLength(CI->getOperand(1));
1125 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1126 CI->getOperand(2), B);
1127 return CI; // Known to have no uses (see above).
1131 //===---------------------------------------===//
1132 // 'fprintf' Optimizations
1134 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1136 // Require two fixed paramters as pointers and integer result.
1137 const FunctionType *FT = Callee->getFunctionType();
1138 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1139 !isa<PointerType>(FT->getParamType(1)) ||
1140 !isa<IntegerType>(FT->getReturnType()))
1143 // All the optimizations depend on the format string.
1144 std::string FormatStr;
1145 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1148 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1149 if (CI->getNumOperands() == 3) {
1150 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1151 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1152 return 0; // We found a format specifier.
1154 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1156 CI->getOperand(1), B);
1157 return ConstantInt::get(CI->getType(), FormatStr.size());
1160 // The remaining optimizations require the format string to be "%s" or "%c"
1161 // and have an extra operand.
1162 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1165 // Decode the second character of the format string.
1166 if (FormatStr[1] == 'c') {
1167 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1168 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1169 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1170 return ConstantInt::get(CI->getType(), 1);
1173 if (FormatStr[1] == 's') {
1174 // fprintf(F, "%s", str) -> fputs(str, F)
1175 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1177 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1184 } // end anonymous namespace.
1186 //===----------------------------------------------------------------------===//
1187 // SimplifyLibCalls Pass Implementation
1188 //===----------------------------------------------------------------------===//
1191 /// This pass optimizes well known library functions from libc and libm.
1193 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1194 StringMap<LibCallOptimization*> Optimizations;
1195 // Miscellaneous LibCall Optimizations
1197 // String and Memory LibCall Optimizations
1198 StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1199 StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt MemCpy;
1200 // Math Library Optimizations
1201 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1202 // Integer Optimizations
1203 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1205 // Formatting and IO Optimizations
1206 SPrintFOpt SPrintF; PrintFOpt PrintF;
1207 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1209 static char ID; // Pass identification
1210 SimplifyLibCalls() : FunctionPass(&ID) {}
1212 void InitOptimizations();
1213 bool runOnFunction(Function &F);
1215 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1216 AU.addRequired<TargetData>();
1219 char SimplifyLibCalls::ID = 0;
1220 } // end anonymous namespace.
1222 static RegisterPass<SimplifyLibCalls>
1223 X("simplify-libcalls", "Simplify well-known library calls");
1225 // Public interface to the Simplify LibCalls pass.
1226 FunctionPass *llvm::createSimplifyLibCallsPass() {
1227 return new SimplifyLibCalls();
1230 /// Optimizations - Populate the Optimizations map with all the optimizations
1232 void SimplifyLibCalls::InitOptimizations() {
1233 // Miscellaneous LibCall Optimizations
1234 Optimizations["exit"] = &Exit;
1236 // String and Memory LibCall Optimizations
1237 Optimizations["strcat"] = &StrCat;
1238 Optimizations["strchr"] = &StrChr;
1239 Optimizations["strcmp"] = &StrCmp;
1240 Optimizations["strncmp"] = &StrNCmp;
1241 Optimizations["strcpy"] = &StrCpy;
1242 Optimizations["strlen"] = &StrLen;
1243 Optimizations["memcmp"] = &MemCmp;
1244 Optimizations["memcpy"] = &MemCpy;
1246 // Math Library Optimizations
1247 Optimizations["powf"] = &Pow;
1248 Optimizations["pow"] = &Pow;
1249 Optimizations["powl"] = &Pow;
1250 Optimizations["llvm.pow.f32"] = &Pow;
1251 Optimizations["llvm.pow.f64"] = &Pow;
1252 Optimizations["llvm.pow.f80"] = &Pow;
1253 Optimizations["llvm.pow.f128"] = &Pow;
1254 Optimizations["llvm.pow.ppcf128"] = &Pow;
1255 Optimizations["exp2l"] = &Exp2;
1256 Optimizations["exp2"] = &Exp2;
1257 Optimizations["exp2f"] = &Exp2;
1258 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1259 Optimizations["llvm.exp2.f128"] = &Exp2;
1260 Optimizations["llvm.exp2.f80"] = &Exp2;
1261 Optimizations["llvm.exp2.f64"] = &Exp2;
1262 Optimizations["llvm.exp2.f32"] = &Exp2;
1265 Optimizations["floor"] = &UnaryDoubleFP;
1268 Optimizations["ceil"] = &UnaryDoubleFP;
1271 Optimizations["round"] = &UnaryDoubleFP;
1274 Optimizations["rint"] = &UnaryDoubleFP;
1276 #ifdef HAVE_NEARBYINTF
1277 Optimizations["nearbyint"] = &UnaryDoubleFP;
1280 // Integer Optimizations
1281 Optimizations["ffs"] = &FFS;
1282 Optimizations["ffsl"] = &FFS;
1283 Optimizations["ffsll"] = &FFS;
1284 Optimizations["abs"] = &Abs;
1285 Optimizations["labs"] = &Abs;
1286 Optimizations["llabs"] = &Abs;
1287 Optimizations["isdigit"] = &IsDigit;
1288 Optimizations["isascii"] = &IsAscii;
1289 Optimizations["toascii"] = &ToAscii;
1291 // Formatting and IO Optimizations
1292 Optimizations["sprintf"] = &SPrintF;
1293 Optimizations["printf"] = &PrintF;
1294 Optimizations["fwrite"] = &FWrite;
1295 Optimizations["fputs"] = &FPuts;
1296 Optimizations["fprintf"] = &FPrintF;
1300 /// runOnFunction - Top level algorithm.
1302 bool SimplifyLibCalls::runOnFunction(Function &F) {
1303 if (Optimizations.empty())
1304 InitOptimizations();
1306 const TargetData &TD = getAnalysis<TargetData>();
1308 IRBuilder<> Builder;
1310 bool Changed = false;
1311 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1312 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1313 // Ignore non-calls.
1314 CallInst *CI = dyn_cast<CallInst>(I++);
1317 // Ignore indirect calls and calls to non-external functions.
1318 Function *Callee = CI->getCalledFunction();
1319 if (Callee == 0 || !Callee->isDeclaration() ||
1320 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1323 // Ignore unknown calls.
1324 const char *CalleeName = Callee->getNameStart();
1325 StringMap<LibCallOptimization*>::iterator OMI =
1326 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1327 if (OMI == Optimizations.end()) continue;
1329 // Set the builder to the instruction after the call.
1330 Builder.SetInsertPoint(BB, I);
1332 // Try to optimize this call.
1333 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1334 if (Result == 0) continue;
1336 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1337 DOUT << " into: " << *Result << "\n");
1339 // Something changed!
1343 // Inspect the instruction after the call (which was potentially just
1347 if (CI != Result && !CI->use_empty()) {
1348 CI->replaceAllUsesWith(Result);
1349 if (!Result->hasName())
1350 Result->takeName(CI);
1352 CI->eraseFromParent();
1360 // Additional cases that we need to add to this file:
1363 // * cbrt(expN(X)) -> expN(x/3)
1364 // * cbrt(sqrt(x)) -> pow(x,1/6)
1365 // * cbrt(sqrt(x)) -> pow(x,1/9)
1368 // * cos(-x) -> cos(x)
1371 // * exp(log(x)) -> x
1374 // * log(exp(x)) -> x
1375 // * log(x**y) -> y*log(x)
1376 // * log(exp(y)) -> y*log(e)
1377 // * log(exp2(y)) -> y*log(2)
1378 // * log(exp10(y)) -> y*log(10)
1379 // * log(sqrt(x)) -> 0.5*log(x)
1380 // * log(pow(x,y)) -> y*log(x)
1382 // lround, lroundf, lroundl:
1383 // * lround(cnst) -> cnst'
1386 // * memcmp(x,y,l) -> cnst
1387 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1390 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1391 // (if s is a global constant array)
1394 // * pow(exp(x),y) -> exp(x*y)
1395 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1396 // * pow(pow(x,y),z)-> pow(x,y*z)
1399 // * puts("") -> putchar("\n")
1401 // round, roundf, roundl:
1402 // * round(cnst) -> cnst'
1405 // * signbit(cnst) -> cnst'
1406 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1408 // sqrt, sqrtf, sqrtl:
1409 // * sqrt(expN(x)) -> expN(x*0.5)
1410 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1411 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1414 // * stpcpy(str, "literal") ->
1415 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
1417 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1418 // (if c is a constant integer and s is a constant string)
1419 // * strrchr(s1,0) -> strchr(s1,0)
1422 // * strncat(x,y,0) -> x
1423 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1424 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1427 // * strncpy(d,s,0) -> d
1428 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1429 // (if s and l are constants)
1432 // * strpbrk(s,a) -> offset_in_for(s,a)
1433 // (if s and a are both constant strings)
1434 // * strpbrk(s,"") -> 0
1435 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1438 // * strspn(s,a) -> const_int (if both args are constant)
1439 // * strspn("",a) -> 0
1440 // * strspn(s,"") -> 0
1441 // * strcspn(s,a) -> const_int (if both args are constant)
1442 // * strcspn("",a) -> 0
1443 // * strcspn(s,"") -> strlen(a)
1446 // * strstr(x,x) -> x
1447 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1448 // (if s1 and s2 are constant strings)
1451 // * tan(atan(x)) -> x
1453 // trunc, truncf, truncl:
1454 // * trunc(cnst) -> cnst'