LLVM API Documentation
00001 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements a simple pass that applies a variety of small 00011 // optimizations for calls to specific well-known function calls (e.g. runtime 00012 // library functions). For example, a call to the function "exit(3)" that 00013 // occurs within the main() function can be transformed into a simple "return 3" 00014 // instruction. Any optimization that takes this form (replace call to library 00015 // function with simpler code that provides the same result) belongs in this 00016 // file. 00017 // 00018 //===----------------------------------------------------------------------===// 00019 00020 #define DEBUG_TYPE "simplify-libcalls" 00021 #include "llvm/Transforms/Scalar.h" 00022 #include "llvm/Intrinsics.h" 00023 #include "llvm/Module.h" 00024 #include "llvm/Pass.h" 00025 #include "llvm/Support/IRBuilder.h" 00026 #include "llvm/Analysis/ValueTracking.h" 00027 #include "llvm/Target/TargetData.h" 00028 #include "llvm/ADT/SmallPtrSet.h" 00029 #include "llvm/ADT/StringMap.h" 00030 #include "llvm/ADT/Statistic.h" 00031 #include "llvm/Support/Compiler.h" 00032 #include "llvm/Support/Debug.h" 00033 #include "llvm/Config/config.h" 00034 using namespace llvm; 00035 00036 STATISTIC(NumSimplified, "Number of library calls simplified"); 00037 STATISTIC(NumAnnotated, "Number of attributes added to library functions"); 00038 00039 //===----------------------------------------------------------------------===// 00040 // Optimizer Base Class 00041 //===----------------------------------------------------------------------===// 00042 00043 /// This class is the abstract base class for the set of optimizations that 00044 /// corresponds to one library call. 00045 namespace { 00046 class VISIBILITY_HIDDEN LibCallOptimization { 00047 protected: 00048 Function *Caller; 00049 const TargetData *TD; 00050 public: 00051 LibCallOptimization() { } 00052 virtual ~LibCallOptimization() {} 00053 00054 /// CallOptimizer - This pure virtual method is implemented by base classes to 00055 /// do various optimizations. If this returns null then no transformation was 00056 /// performed. If it returns CI, then it transformed the call and CI is to be 00057 /// deleted. If it returns something else, replace CI with the new value and 00058 /// delete CI. 00059 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) 00060 =0; 00061 00062 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) { 00063 Caller = CI->getParent()->getParent(); 00064 this->TD = &TD; 00065 return CallOptimizer(CI->getCalledFunction(), CI, B); 00066 } 00067 00068 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*. 00069 Value *CastToCStr(Value *V, IRBuilder<> &B); 00070 00071 /// EmitStrLen - Emit a call to the strlen function to the builder, for the 00072 /// specified pointer. Ptr is required to be some pointer type, and the 00073 /// return value has 'intptr_t' type. 00074 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B); 00075 00076 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This 00077 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers. 00078 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len, 00079 unsigned Align, IRBuilder<> &B); 00080 00081 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is 00082 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value. 00083 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B); 00084 00085 /// EmitMemCmp - Emit a call to the memcmp function. 00086 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B); 00087 00088 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g. 00089 /// 'floor'). This function is known to take a single of type matching 'Op' 00090 /// and returns one value with the same type. If 'Op' is a long double, 'l' 00091 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix. 00092 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B); 00093 00094 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char 00095 /// is an integer. 00096 void EmitPutChar(Value *Char, IRBuilder<> &B); 00097 00098 /// EmitPutS - Emit a call to the puts function. This assumes that Str is 00099 /// some pointer. 00100 void EmitPutS(Value *Str, IRBuilder<> &B); 00101 00102 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is 00103 /// an i32, and File is a pointer to FILE. 00104 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B); 00105 00106 /// EmitFPutS - Emit a call to the puts function. Str is required to be a 00107 /// pointer and File is a pointer to FILE. 00108 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B); 00109 00110 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is 00111 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE. 00112 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B); 00113 00114 }; 00115 } // End anonymous namespace. 00116 00117 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*. 00118 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) { 00119 return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr"); 00120 } 00121 00122 /// EmitStrLen - Emit a call to the strlen function to the builder, for the 00123 /// specified pointer. This always returns an integer value of size intptr_t. 00124 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) { 00125 Module *M = Caller->getParent(); 00126 AttributeWithIndex AWI[2]; 00127 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture); 00128 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly | 00129 Attribute::NoUnwind); 00130 00131 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2), 00132 TD->getIntPtrType(), 00133 PointerType::getUnqual(Type::Int8Ty), 00134 NULL); 00135 return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen"); 00136 } 00137 00138 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always 00139 /// expects that the size has type 'intptr_t' and Dst/Src are pointers. 00140 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len, 00141 unsigned Align, IRBuilder<> &B) { 00142 Module *M = Caller->getParent(); 00143 Intrinsic::ID IID = Intrinsic::memcpy; 00144 const Type *Tys[1]; 00145 Tys[0] = Len->getType(); 00146 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1); 00147 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len, 00148 ConstantInt::get(Type::Int32Ty, Align)); 00149 } 00150 00151 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is 00152 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value. 00153 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val, 00154 Value *Len, IRBuilder<> &B) { 00155 Module *M = Caller->getParent(); 00156 AttributeWithIndex AWI; 00157 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind); 00158 00159 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1), 00160 PointerType::getUnqual(Type::Int8Ty), 00161 PointerType::getUnqual(Type::Int8Ty), 00162 Type::Int32Ty, TD->getIntPtrType(), 00163 NULL); 00164 return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr"); 00165 } 00166 00167 /// EmitMemCmp - Emit a call to the memcmp function. 00168 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2, 00169 Value *Len, IRBuilder<> &B) { 00170 Module *M = Caller->getParent(); 00171 AttributeWithIndex AWI[3]; 00172 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture); 00173 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture); 00174 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly | 00175 Attribute::NoUnwind); 00176 00177 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3), 00178 Type::Int32Ty, 00179 PointerType::getUnqual(Type::Int8Ty), 00180 PointerType::getUnqual(Type::Int8Ty), 00181 TD->getIntPtrType(), NULL); 00182 return B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B), 00183 Len, "memcmp"); 00184 } 00185 00186 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g. 00187 /// 'floor'). This function is known to take a single of type matching 'Op' and 00188 /// returns one value with the same type. If 'Op' is a long double, 'l' is 00189 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix. 00190 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name, 00191 IRBuilder<> &B) { 00192 char NameBuffer[20]; 00193 if (Op->getType() != Type::DoubleTy) { 00194 // If we need to add a suffix, copy into NameBuffer. 00195 unsigned NameLen = strlen(Name); 00196 assert(NameLen < sizeof(NameBuffer)-2); 00197 memcpy(NameBuffer, Name, NameLen); 00198 if (Op->getType() == Type::FloatTy) 00199 NameBuffer[NameLen] = 'f'; // floorf 00200 else 00201 NameBuffer[NameLen] = 'l'; // floorl 00202 NameBuffer[NameLen+1] = 0; 00203 Name = NameBuffer; 00204 } 00205 00206 Module *M = Caller->getParent(); 00207 Value *Callee = M->getOrInsertFunction(Name, Op->getType(), 00208 Op->getType(), NULL); 00209 return B.CreateCall(Callee, Op, Name); 00210 } 00211 00212 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char 00213 /// is an integer. 00214 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) { 00215 Module *M = Caller->getParent(); 00216 Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty, 00217 Type::Int32Ty, NULL); 00218 B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar"); 00219 } 00220 00221 /// EmitPutS - Emit a call to the puts function. This assumes that Str is 00222 /// some pointer. 00223 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) { 00224 Module *M = Caller->getParent(); 00225 AttributeWithIndex AWI[2]; 00226 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture); 00227 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind); 00228 00229 Value *F = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2), 00230 Type::Int32Ty, 00231 PointerType::getUnqual(Type::Int8Ty), NULL); 00232 B.CreateCall(F, CastToCStr(Str, B), "puts"); 00233 } 00234 00235 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is 00236 /// an integer and File is a pointer to FILE. 00237 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) { 00238 Module *M = Caller->getParent(); 00239 AttributeWithIndex AWI[2]; 00240 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture); 00241 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind); 00242 Constant *F; 00243 if (isa<PointerType>(File->getType())) 00244 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty, 00245 Type::Int32Ty, File->getType(), NULL); 00246 00247 else 00248 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty, 00249 File->getType(), NULL); 00250 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari"); 00251 B.CreateCall2(F, Char, File, "fputc"); 00252 } 00253 00254 /// EmitFPutS - Emit a call to the puts function. Str is required to be a 00255 /// pointer and File is a pointer to FILE. 00256 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) { 00257 Module *M = Caller->getParent(); 00258 AttributeWithIndex AWI[2]; 00259 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture); 00260 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind); 00261 Constant *F; 00262 if (isa<PointerType>(File->getType())) 00263 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 2), Type::Int32Ty, 00264 PointerType::getUnqual(Type::Int8Ty), 00265 File->getType(), NULL); 00266 else 00267 F = M->getOrInsertFunction("fputs", Type::Int32Ty, 00268 PointerType::getUnqual(Type::Int8Ty), 00269 File->getType(), NULL); 00270 B.CreateCall2(F, CastToCStr(Str, B), File, "fputs"); 00271 } 00272 00273 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is 00274 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE. 00275 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File, 00276 IRBuilder<> &B) { 00277 Module *M = Caller->getParent(); 00278 AttributeWithIndex AWI[3]; 00279 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture); 00280 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture); 00281 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind); 00282 Constant *F; 00283 if (isa<PointerType>(File->getType())) 00284 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3), 00285 TD->getIntPtrType(), 00286 PointerType::getUnqual(Type::Int8Ty), 00287 TD->getIntPtrType(), TD->getIntPtrType(), 00288 File->getType(), NULL); 00289 else 00290 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(), 00291 PointerType::getUnqual(Type::Int8Ty), 00292 TD->getIntPtrType(), TD->getIntPtrType(), 00293 File->getType(), NULL); 00294 B.CreateCall4(F, CastToCStr(Ptr, B), Size, 00295 ConstantInt::get(TD->getIntPtrType(), 1), File); 00296 } 00297 00298 //===----------------------------------------------------------------------===// 00299 // Helper Functions 00300 //===----------------------------------------------------------------------===// 00301 00302 /// GetStringLengthH - If we can compute the length of the string pointed to by 00303 /// the specified pointer, return 'len+1'. If we can't, return 0. 00304 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) { 00305 // Look through noop bitcast instructions. 00306 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 00307 return GetStringLengthH(BCI->getOperand(0), PHIs); 00308 00309 // If this is a PHI node, there are two cases: either we have already seen it 00310 // or we haven't. 00311 if (PHINode *PN = dyn_cast<PHINode>(V)) { 00312 if (!PHIs.insert(PN)) 00313 return ~0ULL; // already in the set. 00314 00315 // If it was new, see if all the input strings are the same length. 00316 uint64_t LenSoFar = ~0ULL; 00317 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 00318 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs); 00319 if (Len == 0) return 0; // Unknown length -> unknown. 00320 00321 if (Len == ~0ULL) continue; 00322 00323 if (Len != LenSoFar && LenSoFar != ~0ULL) 00324 return 0; // Disagree -> unknown. 00325 LenSoFar = Len; 00326 } 00327 00328 // Success, all agree. 00329 return LenSoFar; 00330 } 00331 00332 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y) 00333 if (SelectInst *SI = dyn_cast<SelectInst>(V)) { 00334 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs); 00335 if (Len1 == 0) return 0; 00336 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs); 00337 if (Len2 == 0) return 0; 00338 if (Len1 == ~0ULL) return Len2; 00339 if (Len2 == ~0ULL) return Len1; 00340 if (Len1 != Len2) return 0; 00341 return Len1; 00342 } 00343 00344 // If the value is not a GEP instruction nor a constant expression with a 00345 // GEP instruction, then return unknown. 00346 User *GEP = 0; 00347 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) { 00348 GEP = GEPI; 00349 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 00350 if (CE->getOpcode() != Instruction::GetElementPtr) 00351 return 0; 00352 GEP = CE; 00353 } else { 00354 return 0; 00355 } 00356 00357 // Make sure the GEP has exactly three arguments. 00358 if (GEP->getNumOperands() != 3) 00359 return 0; 00360 00361 // Check to make sure that the first operand of the GEP is an integer and 00362 // has value 0 so that we are sure we're indexing into the initializer. 00363 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) { 00364 if (!Idx->isZero()) 00365 return 0; 00366 } else 00367 return 0; 00368 00369 // If the second index isn't a ConstantInt, then this is a variable index 00370 // into the array. If this occurs, we can't say anything meaningful about 00371 // the string. 00372 uint64_t StartIdx = 0; 00373 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2))) 00374 StartIdx = CI->getZExtValue(); 00375 else 00376 return 0; 00377 00378 // The GEP instruction, constant or instruction, must reference a global 00379 // variable that is a constant and is initialized. The referenced constant 00380 // initializer is the array that we'll use for optimization. 00381 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 00382 if (!GV || !GV->isConstant() || !GV->hasInitializer()) 00383 return 0; 00384 Constant *GlobalInit = GV->getInitializer(); 00385 00386 // Handle the ConstantAggregateZero case, which is a degenerate case. The 00387 // initializer is constant zero so the length of the string must be zero. 00388 if (isa<ConstantAggregateZero>(GlobalInit)) 00389 return 1; // Len = 0 offset by 1. 00390 00391 // Must be a Constant Array 00392 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit); 00393 if (!Array || Array->getType()->getElementType() != Type::Int8Ty) 00394 return false; 00395 00396 // Get the number of elements in the array 00397 uint64_t NumElts = Array->getType()->getNumElements(); 00398 00399 // Traverse the constant array from StartIdx (derived above) which is 00400 // the place the GEP refers to in the array. 00401 for (unsigned i = StartIdx; i != NumElts; ++i) { 00402 Constant *Elt = Array->getOperand(i); 00403 ConstantInt *CI = dyn_cast<ConstantInt>(Elt); 00404 if (!CI) // This array isn't suitable, non-int initializer. 00405 return 0; 00406 if (CI->isZero()) 00407 return i-StartIdx+1; // We found end of string, success! 00408 } 00409 00410 return 0; // The array isn't null terminated, conservatively return 'unknown'. 00411 } 00412 00413 /// GetStringLength - If we can compute the length of the string pointed to by 00414 /// the specified pointer, return 'len+1'. If we can't, return 0. 00415 static uint64_t GetStringLength(Value *V) { 00416 if (!isa<PointerType>(V->getType())) return 0; 00417 00418 SmallPtrSet<PHINode*, 32> PHIs; 00419 uint64_t Len = GetStringLengthH(V, PHIs); 00420 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return 00421 // an empty string as a length. 00422 return Len == ~0ULL ? 1 : Len; 00423 } 00424 00425 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 00426 /// value is equal or not-equal to zero. 00427 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) { 00428 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); 00429 UI != E; ++UI) { 00430 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 00431 if (IC->isEquality()) 00432 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 00433 if (C->isNullValue()) 00434 continue; 00435 // Unknown instruction. 00436 return false; 00437 } 00438 return true; 00439 } 00440 00441 //===----------------------------------------------------------------------===// 00442 // Miscellaneous LibCall Optimizations 00443 //===----------------------------------------------------------------------===// 00444 00445 namespace { 00446 //===---------------------------------------===// 00447 // 'exit' Optimizations 00448 00449 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; } 00450 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization { 00451 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00452 // Verify we have a reasonable prototype for exit. 00453 if (Callee->arg_size() == 0 || !CI->use_empty()) 00454 return 0; 00455 00456 // Verify the caller is main, and that the result type of main matches the 00457 // argument type of exit. 00458 if (!Caller->isName("main") || !Caller->hasExternalLinkage() || 00459 Caller->getReturnType() != CI->getOperand(1)->getType()) 00460 return 0; 00461 00462 TerminatorInst *OldTI = CI->getParent()->getTerminator(); 00463 00464 // Create the return after the call. 00465 ReturnInst *RI = B.CreateRet(CI->getOperand(1)); 00466 00467 // Drop all successor phi node entries. 00468 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i) 00469 OldTI->getSuccessor(i)->removePredecessor(CI->getParent()); 00470 00471 // Erase all instructions from after our return instruction until the end of 00472 // the block. 00473 BasicBlock::iterator FirstDead = RI; ++FirstDead; 00474 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end()); 00475 return CI; 00476 } 00477 }; 00478 00479 //===----------------------------------------------------------------------===// 00480 // String and Memory LibCall Optimizations 00481 //===----------------------------------------------------------------------===// 00482 00483 //===---------------------------------------===// 00484 // 'strcat' Optimizations 00485 00486 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization { 00487 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00488 // Verify the "strcat" function prototype. 00489 const FunctionType *FT = Callee->getFunctionType(); 00490 if (FT->getNumParams() != 2 || 00491 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) || 00492 FT->getParamType(0) != FT->getReturnType() || 00493 FT->getParamType(1) != FT->getReturnType()) 00494 return 0; 00495 00496 // Extract some information from the instruction 00497 Value *Dst = CI->getOperand(1); 00498 Value *Src = CI->getOperand(2); 00499 00500 // See if we can get the length of the input string. 00501 uint64_t Len = GetStringLength(Src); 00502 if (Len == 0) return 0; 00503 --Len; // Unbias length. 00504 00505 // Handle the simple, do-nothing case: strcat(x, "") -> x 00506 if (Len == 0) 00507 return Dst; 00508 00509 // We need to find the end of the destination string. That's where the 00510 // memory is to be moved to. We just generate a call to strlen. 00511 Value *DstLen = EmitStrLen(Dst, B); 00512 00513 // Now that we have the destination's length, we must index into the 00514 // destination's pointer to get the actual memcpy destination (end of 00515 // the string .. we're concatenating). 00516 Dst = B.CreateGEP(Dst, DstLen, "endptr"); 00517 00518 // We have enough information to now generate the memcpy call to do the 00519 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 00520 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B); 00521 return Dst; 00522 } 00523 }; 00524 00525 //===---------------------------------------===// 00526 // 'strchr' Optimizations 00527 00528 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization { 00529 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00530 // Verify the "strchr" function prototype. 00531 const FunctionType *FT = Callee->getFunctionType(); 00532 if (FT->getNumParams() != 2 || 00533 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) || 00534 FT->getParamType(0) != FT->getReturnType()) 00535 return 0; 00536 00537 Value *SrcStr = CI->getOperand(1); 00538 00539 // If the second operand is non-constant, see if we can compute the length 00540 // of the input string and turn this into memchr. 00541 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2)); 00542 if (CharC == 0) { 00543 uint64_t Len = GetStringLength(SrcStr); 00544 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32. 00545 return 0; 00546 00547 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul. 00548 ConstantInt::get(TD->getIntPtrType(), Len), B); 00549 } 00550 00551 // Otherwise, the character is a constant, see if the first argument is 00552 // a string literal. If so, we can constant fold. 00553 std::string Str; 00554 if (!GetConstantStringInfo(SrcStr, Str)) 00555 return 0; 00556 00557 // strchr can find the nul character. 00558 Str += '\0'; 00559 char CharValue = CharC->getSExtValue(); 00560 00561 // Compute the offset. 00562 uint64_t i = 0; 00563 while (1) { 00564 if (i == Str.size()) // Didn't find the char. strchr returns null. 00565 return Constant::getNullValue(CI->getType()); 00566 // Did we find our match? 00567 if (Str[i] == CharValue) 00568 break; 00569 ++i; 00570 } 00571 00572 // strchr(s+n,c) -> gep(s+n+i,c) 00573 Value *Idx = ConstantInt::get(Type::Int64Ty, i); 00574 return B.CreateGEP(SrcStr, Idx, "strchr"); 00575 } 00576 }; 00577 00578 //===---------------------------------------===// 00579 // 'strcmp' Optimizations 00580 00581 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization { 00582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00583 // Verify the "strcmp" function prototype. 00584 const FunctionType *FT = Callee->getFunctionType(); 00585 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty || 00586 FT->getParamType(0) != FT->getParamType(1) || 00587 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty)) 00588 return 0; 00589 00590 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2); 00591 if (Str1P == Str2P) // strcmp(x,x) -> 0 00592 return ConstantInt::get(CI->getType(), 0); 00593 00594 std::string Str1, Str2; 00595 bool HasStr1 = GetConstantStringInfo(Str1P, Str1); 00596 bool HasStr2 = GetConstantStringInfo(Str2P, Str2); 00597 00598 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x 00599 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()); 00600 00601 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 00602 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 00603 00604 // strcmp(x, y) -> cnst (if both x and y are constant strings) 00605 if (HasStr1 && HasStr2) 00606 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str())); 00607 00608 // strcmp(P, "x") -> memcmp(P, "x", 2) 00609 uint64_t Len1 = GetStringLength(Str1P); 00610 uint64_t Len2 = GetStringLength(Str2P); 00611 if (Len1 || Len2) { 00612 // Choose the smallest Len excluding 0 which means 'unknown'. 00613 if (!Len1 || (Len2 && Len2 < Len1)) 00614 Len1 = Len2; 00615 return EmitMemCmp(Str1P, Str2P, 00616 ConstantInt::get(TD->getIntPtrType(), Len1), B); 00617 } 00618 00619 return 0; 00620 } 00621 }; 00622 00623 //===---------------------------------------===// 00624 // 'strncmp' Optimizations 00625 00626 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization { 00627 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00628 // Verify the "strncmp" function prototype. 00629 const FunctionType *FT = Callee->getFunctionType(); 00630 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty || 00631 FT->getParamType(0) != FT->getParamType(1) || 00632 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) || 00633 !isa<IntegerType>(FT->getParamType(2))) 00634 return 0; 00635 00636 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2); 00637 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 00638 return ConstantInt::get(CI->getType(), 0); 00639 00640 // Get the length argument if it is constant. 00641 uint64_t Length; 00642 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3))) 00643 Length = LengthArg->getZExtValue(); 00644 else 00645 return 0; 00646 00647 if (Length == 0) // strncmp(x,y,0) -> 0 00648 return ConstantInt::get(CI->getType(), 0); 00649 00650 std::string Str1, Str2; 00651 bool HasStr1 = GetConstantStringInfo(Str1P, Str1); 00652 bool HasStr2 = GetConstantStringInfo(Str2P, Str2); 00653 00654 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x 00655 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()); 00656 00657 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 00658 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 00659 00660 // strncmp(x, y) -> cnst (if both x and y are constant strings) 00661 if (HasStr1 && HasStr2) 00662 return ConstantInt::get(CI->getType(), 00663 strncmp(Str1.c_str(), Str2.c_str(), Length)); 00664 return 0; 00665 } 00666 }; 00667 00668 00669 //===---------------------------------------===// 00670 // 'strcpy' Optimizations 00671 00672 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization { 00673 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00674 // Verify the "strcpy" function prototype. 00675 const FunctionType *FT = Callee->getFunctionType(); 00676 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) || 00677 FT->getParamType(0) != FT->getParamType(1) || 00678 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty)) 00679 return 0; 00680 00681 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2); 00682 if (Dst == Src) // strcpy(x,x) -> x 00683 return Src; 00684 00685 // See if we can get the length of the input string. 00686 uint64_t Len = GetStringLength(Src); 00687 if (Len == 0) return 0; 00688 00689 // We have enough information to now generate the memcpy call to do the 00690 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 00691 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B); 00692 return Dst; 00693 } 00694 }; 00695 00696 00697 00698 //===---------------------------------------===// 00699 // 'strlen' Optimizations 00700 00701 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization { 00702 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00703 const FunctionType *FT = Callee->getFunctionType(); 00704 if (FT->getNumParams() != 1 || 00705 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) || 00706 !isa<IntegerType>(FT->getReturnType())) 00707 return 0; 00708 00709 Value *Src = CI->getOperand(1); 00710 00711 // Constant folding: strlen("xyz") -> 3 00712 if (uint64_t Len = GetStringLength(Src)) 00713 return ConstantInt::get(CI->getType(), Len-1); 00714 00715 // Handle strlen(p) != 0. 00716 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0; 00717 00718 // strlen(x) != 0 --> *x != 0 00719 // strlen(x) == 0 --> *x == 0 00720 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType()); 00721 } 00722 }; 00723 00724 //===---------------------------------------===// 00725 // 'memcmp' Optimizations 00726 00727 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization { 00728 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00729 const FunctionType *FT = Callee->getFunctionType(); 00730 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) || 00731 !isa<PointerType>(FT->getParamType(1)) || 00732 FT->getReturnType() != Type::Int32Ty) 00733 return 0; 00734 00735 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2); 00736 00737 if (LHS == RHS) // memcmp(s,s,x) -> 0 00738 return Constant::getNullValue(CI->getType()); 00739 00740 // Make sure we have a constant length. 00741 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3)); 00742 if (!LenC) return 0; 00743 uint64_t Len = LenC->getZExtValue(); 00744 00745 if (Len == 0) // memcmp(s1,s2,0) -> 0 00746 return Constant::getNullValue(CI->getType()); 00747 00748 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS 00749 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv"); 00750 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv"); 00751 return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType()); 00752 } 00753 00754 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0 00755 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0 00756 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) { 00757 const Type *PTy = PointerType::getUnqual(Len == 2 ? 00758 Type::Int16Ty : Type::Int32Ty); 00759 LHS = B.CreateBitCast(LHS, PTy, "tmp"); 00760 RHS = B.CreateBitCast(RHS, PTy, "tmp"); 00761 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv"); 00762 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv"); 00763 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads. 00764 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType()); 00765 } 00766 00767 return 0; 00768 } 00769 }; 00770 00771 //===---------------------------------------===// 00772 // 'memcpy' Optimizations 00773 00774 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization { 00775 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00776 const FunctionType *FT = Callee->getFunctionType(); 00777 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) || 00778 !isa<PointerType>(FT->getParamType(0)) || 00779 !isa<PointerType>(FT->getParamType(1)) || 00780 FT->getParamType(2) != TD->getIntPtrType()) 00781 return 0; 00782 00783 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1) 00784 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B); 00785 return CI->getOperand(1); 00786 } 00787 }; 00788 00789 //===---------------------------------------===// 00790 // 'memmove' Optimizations 00791 00792 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization { 00793 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00794 const FunctionType *FT = Callee->getFunctionType(); 00795 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) || 00796 !isa<PointerType>(FT->getParamType(0)) || 00797 !isa<PointerType>(FT->getParamType(1)) || 00798 FT->getParamType(2) != TD->getIntPtrType()) 00799 return 0; 00800 00801 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1) 00802 Module *M = Caller->getParent(); 00803 Intrinsic::ID IID = Intrinsic::memmove; 00804 const Type *Tys[1]; 00805 Tys[0] = TD->getIntPtrType(); 00806 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1); 00807 Value *Dst = CastToCStr(CI->getOperand(1), B); 00808 Value *Src = CastToCStr(CI->getOperand(2), B); 00809 Value *Size = CI->getOperand(3); 00810 Value *Align = ConstantInt::get(Type::Int32Ty, 1); 00811 B.CreateCall4(MemMove, Dst, Src, Size, Align); 00812 return CI->getOperand(1); 00813 } 00814 }; 00815 00816 //===---------------------------------------===// 00817 // 'memset' Optimizations 00818 00819 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization { 00820 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00821 const FunctionType *FT = Callee->getFunctionType(); 00822 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) || 00823 !isa<PointerType>(FT->getParamType(0)) || 00824 FT->getParamType(1) != TD->getIntPtrType() || 00825 FT->getParamType(2) != TD->getIntPtrType()) 00826 return 0; 00827 00828 // memset(p, v, n) -> llvm.memset(p, v, n, 1) 00829 Module *M = Caller->getParent(); 00830 Intrinsic::ID IID = Intrinsic::memset; 00831 const Type *Tys[1]; 00832 Tys[0] = TD->getIntPtrType(); 00833 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1); 00834 Value *Dst = CastToCStr(CI->getOperand(1), B); 00835 Value *Val = B.CreateTrunc(CI->getOperand(2), Type::Int8Ty); 00836 Value *Size = CI->getOperand(3); 00837 Value *Align = ConstantInt::get(Type::Int32Ty, 1); 00838 B.CreateCall4(MemSet, Dst, Val, Size, Align); 00839 return CI->getOperand(1); 00840 } 00841 }; 00842 00843 //===----------------------------------------------------------------------===// 00844 // Math Library Optimizations 00845 //===----------------------------------------------------------------------===// 00846 00847 //===---------------------------------------===// 00848 // 'pow*' Optimizations 00849 00850 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization { 00851 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00852 const FunctionType *FT = Callee->getFunctionType(); 00853 // Just make sure this has 2 arguments of the same FP type, which match the 00854 // result type. 00855 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) || 00856 FT->getParamType(0) != FT->getParamType(1) || 00857 !FT->getParamType(0)->isFloatingPoint()) 00858 return 0; 00859 00860 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2); 00861 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) { 00862 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0 00863 return Op1C; 00864 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x) 00865 return EmitUnaryFloatFnCall(Op2, "exp2", B); 00866 } 00867 00868 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2); 00869 if (Op2C == 0) return 0; 00870 00871 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0 00872 return ConstantFP::get(CI->getType(), 1.0); 00873 00874 if (Op2C->isExactlyValue(0.5)) { 00875 // FIXME: This is not safe for -0.0 and -inf. This can only be done when 00876 // 'unsafe' math optimizations are allowed. 00877 // x pow(x, 0.5) sqrt(x) 00878 // --------------------------------------------- 00879 // -0.0 +0.0 -0.0 00880 // -inf +inf NaN 00881 #if 0 00882 // pow(x, 0.5) -> sqrt(x) 00883 return B.CreateCall(get_sqrt(), Op1, "sqrt"); 00884 #endif 00885 } 00886 00887 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x 00888 return Op1; 00889 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x 00890 return B.CreateMul(Op1, Op1, "pow2"); 00891 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x 00892 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip"); 00893 return 0; 00894 } 00895 }; 00896 00897 //===---------------------------------------===// 00898 // 'exp2' Optimizations 00899 00900 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization { 00901 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00902 const FunctionType *FT = Callee->getFunctionType(); 00903 // Just make sure this has 1 argument of FP type, which matches the 00904 // result type. 00905 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 00906 !FT->getParamType(0)->isFloatingPoint()) 00907 return 0; 00908 00909 Value *Op = CI->getOperand(1); 00910 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32 00911 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32 00912 Value *LdExpArg = 0; 00913 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) { 00914 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32) 00915 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp"); 00916 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) { 00917 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32) 00918 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp"); 00919 } 00920 00921 if (LdExpArg) { 00922 const char *Name; 00923 if (Op->getType() == Type::FloatTy) 00924 Name = "ldexpf"; 00925 else if (Op->getType() == Type::DoubleTy) 00926 Name = "ldexp"; 00927 else 00928 Name = "ldexpl"; 00929 00930 Constant *One = ConstantFP::get(APFloat(1.0f)); 00931 if (Op->getType() != Type::FloatTy) 00932 One = ConstantExpr::getFPExtend(One, Op->getType()); 00933 00934 Module *M = Caller->getParent(); 00935 Value *Callee = M->getOrInsertFunction(Name, Op->getType(), 00936 Op->getType(), Type::Int32Ty,NULL); 00937 return B.CreateCall2(Callee, One, LdExpArg); 00938 } 00939 return 0; 00940 } 00941 }; 00942 00943 00944 //===---------------------------------------===// 00945 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor' 00946 00947 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization { 00948 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00949 const FunctionType *FT = Callee->getFunctionType(); 00950 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy || 00951 FT->getParamType(0) != Type::DoubleTy) 00952 return 0; 00953 00954 // If this is something like 'floor((double)floatval)', convert to floorf. 00955 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1)); 00956 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy) 00957 return 0; 00958 00959 // floor((double)floatval) -> (double)floorf(floatval) 00960 Value *V = Cast->getOperand(0); 00961 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B); 00962 return B.CreateFPExt(V, Type::DoubleTy); 00963 } 00964 }; 00965 00966 //===----------------------------------------------------------------------===// 00967 // Integer Optimizations 00968 //===----------------------------------------------------------------------===// 00969 00970 //===---------------------------------------===// 00971 // 'ffs*' Optimizations 00972 00973 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization { 00974 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 00975 const FunctionType *FT = Callee->getFunctionType(); 00976 // Just make sure this has 2 arguments of the same FP type, which match the 00977 // result type. 00978 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty || 00979 !isa<IntegerType>(FT->getParamType(0))) 00980 return 0; 00981 00982 Value *Op = CI->getOperand(1); 00983 00984 // Constant fold. 00985 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 00986 if (CI->getValue() == 0) // ffs(0) -> 0. 00987 return Constant::getNullValue(CI->getType()); 00988 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1 00989 CI->getValue().countTrailingZeros()+1); 00990 } 00991 00992 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 00993 const Type *ArgType = Op->getType(); 00994 Value *F = Intrinsic::getDeclaration(Callee->getParent(), 00995 Intrinsic::cttz, &ArgType, 1); 00996 Value *V = B.CreateCall(F, Op, "cttz"); 00997 V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp"); 00998 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp"); 00999 01000 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp"); 01001 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0)); 01002 } 01003 }; 01004 01005 //===---------------------------------------===// 01006 // 'isdigit' Optimizations 01007 01008 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization { 01009 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01010 const FunctionType *FT = Callee->getFunctionType(); 01011 // We require integer(i32) 01012 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) || 01013 FT->getParamType(0) != Type::Int32Ty) 01014 return 0; 01015 01016 // isdigit(c) -> (c-'0') <u 10 01017 Value *Op = CI->getOperand(1); 01018 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp"); 01019 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit"); 01020 return B.CreateZExt(Op, CI->getType()); 01021 } 01022 }; 01023 01024 //===---------------------------------------===// 01025 // 'isascii' Optimizations 01026 01027 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization { 01028 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01029 const FunctionType *FT = Callee->getFunctionType(); 01030 // We require integer(i32) 01031 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) || 01032 FT->getParamType(0) != Type::Int32Ty) 01033 return 0; 01034 01035 // isascii(c) -> c <u 128 01036 Value *Op = CI->getOperand(1); 01037 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii"); 01038 return B.CreateZExt(Op, CI->getType()); 01039 } 01040 }; 01041 01042 //===---------------------------------------===// 01043 // 'abs', 'labs', 'llabs' Optimizations 01044 01045 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization { 01046 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01047 const FunctionType *FT = Callee->getFunctionType(); 01048 // We require integer(integer) where the types agree. 01049 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) || 01050 FT->getParamType(0) != FT->getReturnType()) 01051 return 0; 01052 01053 // abs(x) -> x >s -1 ? x : -x 01054 Value *Op = CI->getOperand(1); 01055 Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()), 01056 "ispos"); 01057 Value *Neg = B.CreateNeg(Op, "neg"); 01058 return B.CreateSelect(Pos, Op, Neg); 01059 } 01060 }; 01061 01062 01063 //===---------------------------------------===// 01064 // 'toascii' Optimizations 01065 01066 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization { 01067 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01068 const FunctionType *FT = Callee->getFunctionType(); 01069 // We require i32(i32) 01070 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 01071 FT->getParamType(0) != Type::Int32Ty) 01072 return 0; 01073 01074 // isascii(c) -> c & 0x7f 01075 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F)); 01076 } 01077 }; 01078 01079 //===----------------------------------------------------------------------===// 01080 // Formatting and IO Optimizations 01081 //===----------------------------------------------------------------------===// 01082 01083 //===---------------------------------------===// 01084 // 'printf' Optimizations 01085 01086 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization { 01087 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01088 // Require one fixed pointer argument and an integer/void result. 01089 const FunctionType *FT = Callee->getFunctionType(); 01090 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) || 01091 !(isa<IntegerType>(FT->getReturnType()) || 01092 FT->getReturnType() == Type::VoidTy)) 01093 return 0; 01094 01095 // Check for a fixed format string. 01096 std::string FormatStr; 01097 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr)) 01098 return 0; 01099 01100 // Empty format string -> noop. 01101 if (FormatStr.empty()) // Tolerate printf's declared void. 01102 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0); 01103 01104 // printf("x") -> putchar('x'), even for '%'. 01105 if (FormatStr.size() == 1) { 01106 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B); 01107 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1); 01108 } 01109 01110 // printf("foo\n") --> puts("foo") 01111 if (FormatStr[FormatStr.size()-1] == '\n' && 01112 FormatStr.find('%') == std::string::npos) { // no format characters. 01113 // Create a string literal with no \n on it. We expect the constant merge 01114 // pass to be run after this pass, to merge duplicate strings. 01115 FormatStr.erase(FormatStr.end()-1); 01116 Constant *C = ConstantArray::get(FormatStr, true); 01117 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage, 01118 C, "str", Callee->getParent()); 01119 EmitPutS(C, B); 01120 return CI->use_empty() ? (Value*)CI : 01121 ConstantInt::get(CI->getType(), FormatStr.size()+1); 01122 } 01123 01124 // Optimize specific format strings. 01125 // printf("%c", chr) --> putchar(*(i8*)dst) 01126 if (FormatStr == "%c" && CI->getNumOperands() > 2 && 01127 isa<IntegerType>(CI->getOperand(2)->getType())) { 01128 EmitPutChar(CI->getOperand(2), B); 01129 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1); 01130 } 01131 01132 // printf("%s\n", str) --> puts(str) 01133 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 && 01134 isa<PointerType>(CI->getOperand(2)->getType()) && 01135 CI->use_empty()) { 01136 EmitPutS(CI->getOperand(2), B); 01137 return CI; 01138 } 01139 return 0; 01140 } 01141 }; 01142 01143 //===---------------------------------------===// 01144 // 'sprintf' Optimizations 01145 01146 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization { 01147 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01148 // Require two fixed pointer arguments and an integer result. 01149 const FunctionType *FT = Callee->getFunctionType(); 01150 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) || 01151 !isa<PointerType>(FT->getParamType(1)) || 01152 !isa<IntegerType>(FT->getReturnType())) 01153 return 0; 01154 01155 // Check for a fixed format string. 01156 std::string FormatStr; 01157 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr)) 01158 return 0; 01159 01160 // If we just have a format string (nothing else crazy) transform it. 01161 if (CI->getNumOperands() == 3) { 01162 // Make sure there's no % in the constant array. We could try to handle 01163 // %% -> % in the future if we cared. 01164 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 01165 if (FormatStr[i] == '%') 01166 return 0; // we found a format specifier, bail out. 01167 01168 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1) 01169 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte. 01170 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B); 01171 return ConstantInt::get(CI->getType(), FormatStr.size()); 01172 } 01173 01174 // The remaining optimizations require the format string to be "%s" or "%c" 01175 // and have an extra operand. 01176 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4) 01177 return 0; 01178 01179 // Decode the second character of the format string. 01180 if (FormatStr[1] == 'c') { 01181 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 01182 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0; 01183 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char"); 01184 Value *Ptr = CastToCStr(CI->getOperand(1), B); 01185 B.CreateStore(V, Ptr); 01186 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul"); 01187 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr); 01188 01189 return ConstantInt::get(CI->getType(), 1); 01190 } 01191 01192 if (FormatStr[1] == 's') { 01193 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1) 01194 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0; 01195 01196 Value *Len = EmitStrLen(CI->getOperand(3), B); 01197 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), 01198 "leninc"); 01199 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B); 01200 01201 // The sprintf result is the unincremented number of bytes in the string. 01202 return B.CreateIntCast(Len, CI->getType(), false); 01203 } 01204 return 0; 01205 } 01206 }; 01207 01208 //===---------------------------------------===// 01209 // 'fwrite' Optimizations 01210 01211 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization { 01212 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01213 // Require a pointer, an integer, an integer, a pointer, returning integer. 01214 const FunctionType *FT = Callee->getFunctionType(); 01215 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) || 01216 !isa<IntegerType>(FT->getParamType(1)) || 01217 !isa<IntegerType>(FT->getParamType(2)) || 01218 !isa<PointerType>(FT->getParamType(3)) || 01219 !isa<IntegerType>(FT->getReturnType())) 01220 return 0; 01221 01222 // Get the element size and count. 01223 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2)); 01224 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3)); 01225 if (!SizeC || !CountC) return 0; 01226 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue(); 01227 01228 // If this is writing zero records, remove the call (it's a noop). 01229 if (Bytes == 0) 01230 return ConstantInt::get(CI->getType(), 0); 01231 01232 // If this is writing one byte, turn it into fputc. 01233 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F) 01234 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char"); 01235 EmitFPutC(Char, CI->getOperand(4), B); 01236 return ConstantInt::get(CI->getType(), 1); 01237 } 01238 01239 return 0; 01240 } 01241 }; 01242 01243 //===---------------------------------------===// 01244 // 'fputs' Optimizations 01245 01246 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization { 01247 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01248 // Require two pointers. Also, we can't optimize if return value is used. 01249 const FunctionType *FT = Callee->getFunctionType(); 01250 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) || 01251 !isa<PointerType>(FT->getParamType(1)) || 01252 !CI->use_empty()) 01253 return 0; 01254 01255 // fputs(s,F) --> fwrite(s,1,strlen(s),F) 01256 uint64_t Len = GetStringLength(CI->getOperand(1)); 01257 if (!Len) return 0; 01258 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1), 01259 CI->getOperand(2), B); 01260 return CI; // Known to have no uses (see above). 01261 } 01262 }; 01263 01264 //===---------------------------------------===// 01265 // 'fprintf' Optimizations 01266 01267 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization { 01268 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 01269 // Require two fixed paramters as pointers and integer result. 01270 const FunctionType *FT = Callee->getFunctionType(); 01271 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) || 01272 !isa<PointerType>(FT->getParamType(1)) || 01273 !isa<IntegerType>(FT->getReturnType())) 01274 return 0; 01275 01276 // All the optimizations depend on the format string. 01277 std::string FormatStr; 01278 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr)) 01279 return 0; 01280 01281 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 01282 if (CI->getNumOperands() == 3) { 01283 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 01284 if (FormatStr[i] == '%') // Could handle %% -> % if we cared. 01285 return 0; // We found a format specifier. 01286 01287 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(), 01288 FormatStr.size()), 01289 CI->getOperand(1), B); 01290 return ConstantInt::get(CI->getType(), FormatStr.size()); 01291 } 01292 01293 // The remaining optimizations require the format string to be "%s" or "%c" 01294 // and have an extra operand. 01295 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4) 01296 return 0; 01297 01298 // Decode the second character of the format string. 01299 if (FormatStr[1] == 'c') { 01300 // fprintf(F, "%c", chr) --> *(i8*)dst = chr 01301 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0; 01302 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B); 01303 return ConstantInt::get(CI->getType(), 1); 01304 } 01305 01306 if (FormatStr[1] == 's') { 01307 // fprintf(F, "%s", str) -> fputs(str, F) 01308 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty()) 01309 return 0; 01310 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B); 01311 return CI; 01312 } 01313 return 0; 01314 } 01315 }; 01316 01317 } // end anonymous namespace. 01318 01319 //===----------------------------------------------------------------------===// 01320 // SimplifyLibCalls Pass Implementation 01321 //===----------------------------------------------------------------------===// 01322 01323 namespace { 01324 /// This pass optimizes well known library functions from libc and libm. 01325 /// 01326 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass { 01327 StringMap<LibCallOptimization*> Optimizations; 01328 // Miscellaneous LibCall Optimizations 01329 ExitOpt Exit; 01330 // String and Memory LibCall Optimizations 01331 StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; 01332 StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt MemCpy; 01333 MemMoveOpt MemMove; MemSetOpt MemSet; 01334 // Math Library Optimizations 01335 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP; 01336 // Integer Optimizations 01337 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii; 01338 ToAsciiOpt ToAscii; 01339 // Formatting and IO Optimizations 01340 SPrintFOpt SPrintF; PrintFOpt PrintF; 01341 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF; 01342 01343 bool Modified; // This is only used by doInitialization. 01344 public: 01345 static char ID; // Pass identification 01346 SimplifyLibCalls() : FunctionPass(&ID) {} 01347 01348 void InitOptimizations(); 01349 bool runOnFunction(Function &F); 01350 01351 void setDoesNotAccessMemory(Function &F); 01352 void setOnlyReadsMemory(Function &F); 01353 void setDoesNotThrow(Function &F); 01354 void setDoesNotCapture(Function &F, unsigned n); 01355 void setDoesNotAlias(Function &F, unsigned n); 01356 bool doInitialization(Module &M); 01357 01358 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 01359 AU.addRequired<TargetData>(); 01360 } 01361 }; 01362 char SimplifyLibCalls::ID = 0; 01363 } // end anonymous namespace. 01364 01365 static RegisterPass<SimplifyLibCalls> 01366 X("simplify-libcalls", "Simplify well-known library calls"); 01367 01368 // Public interface to the Simplify LibCalls pass. 01369 FunctionPass *llvm::createSimplifyLibCallsPass() { 01370 return new SimplifyLibCalls(); 01371 } 01372 01373 /// Optimizations - Populate the Optimizations map with all the optimizations 01374 /// we know. 01375 void SimplifyLibCalls::InitOptimizations() { 01376 // Miscellaneous LibCall Optimizations 01377 Optimizations["exit"] = &Exit; 01378 01379 // String and Memory LibCall Optimizations 01380 Optimizations["strcat"] = &StrCat; 01381 Optimizations["strchr"] = &StrChr; 01382 Optimizations["strcmp"] = &StrCmp; 01383 Optimizations["strncmp"] = &StrNCmp; 01384 Optimizations["strcpy"] = &StrCpy; 01385 Optimizations["strlen"] = &StrLen; 01386 Optimizations["memcmp"] = &MemCmp; 01387 Optimizations["memcpy"] = &MemCpy; 01388 Optimizations["memmove"] = &MemMove; 01389 Optimizations["memset"] = &MemSet; 01390 01391 // Math Library Optimizations 01392 Optimizations["powf"] = &Pow; 01393 Optimizations["pow"] = &Pow; 01394 Optimizations["powl"] = &Pow; 01395 Optimizations["llvm.pow.f32"] = &Pow; 01396 Optimizations["llvm.pow.f64"] = &Pow; 01397 Optimizations["llvm.pow.f80"] = &Pow; 01398 Optimizations["llvm.pow.f128"] = &Pow; 01399 Optimizations["llvm.pow.ppcf128"] = &Pow; 01400 Optimizations["exp2l"] = &Exp2; 01401 Optimizations["exp2"] = &Exp2; 01402 Optimizations["exp2f"] = &Exp2; 01403 Optimizations["llvm.exp2.ppcf128"] = &Exp2; 01404 Optimizations["llvm.exp2.f128"] = &Exp2; 01405 Optimizations["llvm.exp2.f80"] = &Exp2; 01406 Optimizations["llvm.exp2.f64"] = &Exp2; 01407 Optimizations["llvm.exp2.f32"] = &Exp2; 01408 01409 #ifdef HAVE_FLOORF 01410 Optimizations["floor"] = &UnaryDoubleFP; 01411 #endif 01412 #ifdef HAVE_CEILF 01413 Optimizations["ceil"] = &UnaryDoubleFP; 01414 #endif 01415 #ifdef HAVE_ROUNDF 01416 Optimizations["round"] = &UnaryDoubleFP; 01417 #endif 01418 #ifdef HAVE_RINTF 01419 Optimizations["rint"] = &UnaryDoubleFP; 01420 #endif 01421 #ifdef HAVE_NEARBYINTF 01422 Optimizations["nearbyint"] = &UnaryDoubleFP; 01423 #endif 01424 01425 // Integer Optimizations 01426 Optimizations["ffs"] = &FFS; 01427 Optimizations["ffsl"] = &FFS; 01428 Optimizations["ffsll"] = &FFS; 01429 Optimizations["abs"] = &Abs; 01430 Optimizations["labs"] = &Abs; 01431 Optimizations["llabs"] = &Abs; 01432 Optimizations["isdigit"] = &IsDigit; 01433 Optimizations["isascii"] = &IsAscii; 01434 Optimizations["toascii"] = &ToAscii; 01435 01436 // Formatting and IO Optimizations 01437 Optimizations["sprintf"] = &SPrintF; 01438 Optimizations["printf"] = &PrintF; 01439 Optimizations["fwrite"] = &FWrite; 01440 Optimizations["fputs"] = &FPuts; 01441 Optimizations["fprintf"] = &FPrintF; 01442 } 01443 01444 01445 /// runOnFunction - Top level algorithm. 01446 /// 01447 bool SimplifyLibCalls::runOnFunction(Function &F) { 01448 if (Optimizations.empty()) 01449 InitOptimizations(); 01450 01451 const TargetData &TD = getAnalysis<TargetData>(); 01452 01453 IRBuilder<> Builder; 01454 01455 bool Changed = false; 01456 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 01457 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { 01458 // Ignore non-calls. 01459 CallInst *CI = dyn_cast<CallInst>(I++); 01460 if (!CI) continue; 01461 01462 // Ignore indirect calls and calls to non-external functions. 01463 Function *Callee = CI->getCalledFunction(); 01464 if (Callee == 0 || !Callee->isDeclaration() || 01465 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage())) 01466 continue; 01467 01468 // Ignore unknown calls. 01469 const char *CalleeName = Callee->getNameStart(); 01470 StringMap<LibCallOptimization*>::iterator OMI = 01471 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen()); 01472 if (OMI == Optimizations.end()) continue; 01473 01474 // Set the builder to the instruction after the call. 01475 Builder.SetInsertPoint(BB, I); 01476 01477 // Try to optimize this call. 01478 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder); 01479 if (Result == 0) continue; 01480 01481 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI; 01482 DOUT << " into: " << *Result << "\n"); 01483 01484 // Something changed! 01485 Changed = true; 01486 ++NumSimplified; 01487 01488 // Inspect the instruction after the call (which was potentially just 01489 // added) next. 01490 I = CI; ++I; 01491 01492 if (CI != Result && !CI->use_empty()) { 01493 CI->replaceAllUsesWith(Result); 01494 if (!Result->hasName()) 01495 Result->takeName(CI); 01496 } 01497 CI->eraseFromParent(); 01498 } 01499 } 01500 return Changed; 01501 } 01502 01503 // Utility methods for doInitialization. 01504 01505 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) { 01506 if (!F.doesNotAccessMemory()) { 01507 F.setDoesNotAccessMemory(); 01508 ++NumAnnotated; 01509 Modified = true; 01510 } 01511 } 01512 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) { 01513 if (!F.onlyReadsMemory()) { 01514 F.setOnlyReadsMemory(); 01515 ++NumAnnotated; 01516 Modified = true; 01517 } 01518 } 01519 void SimplifyLibCalls::setDoesNotThrow(Function &F) { 01520 if (!F.doesNotThrow()) { 01521 F.setDoesNotThrow(); 01522 ++NumAnnotated; 01523 Modified = true; 01524 } 01525 } 01526 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) { 01527 if (!F.doesNotCapture(n)) { 01528 F.setDoesNotCapture(n); 01529 ++NumAnnotated; 01530 Modified = true; 01531 } 01532 } 01533 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) { 01534 if (!F.doesNotAlias(n)) { 01535 F.setDoesNotAlias(n); 01536 ++NumAnnotated; 01537 Modified = true; 01538 } 01539 } 01540 01541 /// doInitialization - Add attributes to well-known functions. 01542 /// 01543 bool SimplifyLibCalls::doInitialization(Module &M) { 01544 Modified = false; 01545 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 01546 Function &F = *I; 01547 if (!F.isDeclaration()) 01548 continue; 01549 01550 unsigned NameLen = F.getNameLen(); 01551 if (!NameLen) 01552 continue; 01553 01554 const FunctionType *FTy = F.getFunctionType(); 01555 01556 const char *NameStr = F.getNameStart(); 01557 switch (NameStr[0]) { 01558 case 's': 01559 if (NameLen == 6 && !strcmp(NameStr, "strlen")) { 01560 if (FTy->getNumParams() != 1 || 01561 !isa<PointerType>(FTy->getParamType(0))) 01562 continue; 01563 setOnlyReadsMemory(F); 01564 setDoesNotThrow(F); 01565 setDoesNotCapture(F, 1); 01566 } else if ((NameLen == 6 && !strcmp(NameStr, "strcpy")) || 01567 (NameLen == 6 && !strcmp(NameStr, "stpcpy")) || 01568 (NameLen == 6 && !strcmp(NameStr, "strcat")) || 01569 (NameLen == 7 && !strcmp(NameStr, "strncat")) || 01570 (NameLen == 7 && !strcmp(NameStr, "strncpy"))) { 01571 if (FTy->getNumParams() < 2 || 01572 !isa<PointerType>(FTy->getParamType(1))) 01573 continue; 01574 setDoesNotThrow(F); 01575 setDoesNotCapture(F, 2); 01576 } else if (NameLen == 7 && !strcmp(NameStr, "strxfrm")) { 01577 if (FTy->getNumParams() != 3 || 01578 !isa<PointerType>(FTy->getParamType(0)) || 01579 !isa<PointerType>(FTy->getParamType(1))) 01580 continue; 01581 setDoesNotThrow(F); 01582 setDoesNotCapture(F, 1); 01583 setDoesNotCapture(F, 2); 01584 } else if ((NameLen == 6 && !strcmp(NameStr, "strcmp")) || 01585 (NameLen == 6 && !strcmp(NameStr, "strspn")) || 01586 (NameLen == 6 && !strcmp(NameStr, "strtol")) || 01587 (NameLen == 6 && !strcmp(NameStr, "strtod")) || 01588 (NameLen == 6 && !strcmp(NameStr, "strtof")) || 01589 (NameLen == 7 && !strcmp(NameStr, "strtoul")) || 01590 (NameLen == 7 && !strcmp(NameStr, "strtoll")) || 01591 (NameLen == 7 && !strcmp(NameStr, "strtold")) || 01592 (NameLen == 7 && !strcmp(NameStr, "strncmp")) || 01593 (NameLen == 7 && !strcmp(NameStr, "strcspn")) || 01594 (NameLen == 7 && !strcmp(NameStr, "strcoll")) || 01595 (NameLen == 8 && !strcmp(NameStr, "strtoull")) || 01596 (NameLen == 10 && !strcmp(NameStr, "strcasecmp")) || 01597 (NameLen == 11 && !strcmp(NameStr, "strncasecmp"))) { 01598 if (FTy->getNumParams() < 2 || 01599 !isa<PointerType>(FTy->getParamType(0)) || 01600 !isa<PointerType>(FTy->getParamType(1))) 01601 continue; 01602 setOnlyReadsMemory(F); 01603 setDoesNotThrow(F); 01604 setDoesNotCapture(F, 1); 01605 setDoesNotCapture(F, 2); 01606 } else if ((NameLen == 6 && !strcmp(NameStr, "strstr")) || 01607 (NameLen == 7 && !strcmp(NameStr, "strpbrk"))) { 01608 if (FTy->getNumParams() != 2 || 01609 !isa<PointerType>(FTy->getParamType(1))) 01610 continue; 01611 setOnlyReadsMemory(F); 01612 setDoesNotThrow(F); 01613 setDoesNotCapture(F, 2); 01614 } else if ((NameLen == 6 && !strcmp(NameStr, "strtok")) || 01615 (NameLen == 8 && !strcmp(NameStr, "strtok_r"))) { 01616 if (FTy->getNumParams() < 2 || 01617 !isa<PointerType>(FTy->getParamType(1))) 01618 continue; 01619 setDoesNotThrow(F); 01620 setDoesNotCapture(F, 2); 01621 } else if ((NameLen == 5 && !strcmp(NameStr, "scanf")) || 01622 (NameLen == 6 && !strcmp(NameStr, "setbuf")) || 01623 (NameLen == 7 && !strcmp(NameStr, "setvbuf"))) { 01624 if (FTy->getNumParams() < 1 || 01625 !isa<PointerType>(FTy->getParamType(0))) 01626 continue; 01627 setDoesNotThrow(F); 01628 setDoesNotCapture(F, 1); 01629 } else if (NameLen == 6 && !strcmp(NameStr, "sscanf")) { 01630 if (FTy->getNumParams() < 2 || 01631 !isa<PointerType>(FTy->getParamType(0)) || 01632 !isa<PointerType>(FTy->getParamType(1))) 01633 continue; 01634 setDoesNotThrow(F); 01635 setDoesNotCapture(F, 1); 01636 setDoesNotCapture(F, 2); 01637 } else if ((NameLen == 6 && !strcmp(NameStr, "strdup")) || 01638 (NameLen == 7 && !strcmp(NameStr, "strndup"))) { 01639 if (FTy->getNumParams() < 1 || 01640 !isa<PointerType>(FTy->getReturnType()) || 01641 !isa<PointerType>(FTy->getParamType(0))) 01642 continue; 01643 setDoesNotThrow(F); 01644 setDoesNotAlias(F, 0); 01645 setDoesNotCapture(F, 1); 01646 } else if (NameLen == 7 && !strcmp(NameStr, "sprintf")) { 01647 if (FTy->getNumParams() != 2 || 01648 !isa<PointerType>(FTy->getParamType(0)) || 01649 !isa<PointerType>(FTy->getParamType(1))) 01650 continue; 01651 setDoesNotThrow(F); 01652 setDoesNotCapture(F, 1); 01653 setDoesNotCapture(F, 2); 01654 } else if (NameLen == 8 && !strcmp(NameStr, "snprintf")) { 01655 if (FTy->getNumParams() != 3 || 01656 !isa<PointerType>(FTy->getParamType(0)) || 01657 !isa<PointerType>(FTy->getParamType(2))) 01658 continue; 01659 setDoesNotThrow(F); 01660 setDoesNotCapture(F, 1); 01661 setDoesNotCapture(F, 3); 01662 } 01663 break; 01664 case 'm': 01665 if (NameLen == 6 && !strcmp(NameStr, "memcmp")) { 01666 if (FTy->getNumParams() != 3 || 01667 !isa<PointerType>(FTy->getParamType(0)) || 01668 !isa<PointerType>(FTy->getParamType(1))) 01669 continue; 01670 setOnlyReadsMemory(F); 01671 setDoesNotThrow(F); 01672 setDoesNotCapture(F, 1); 01673 setDoesNotCapture(F, 2); 01674 } else if ((NameLen == 6 && !strcmp(NameStr, "memchr")) || 01675 (NameLen == 7 && !strcmp(NameStr, "memrchr"))) { 01676 if (FTy->getNumParams() != 3) 01677 continue; 01678 setOnlyReadsMemory(F); 01679 setDoesNotThrow(F); 01680 } else if ((NameLen == 6 && !strcmp(NameStr, "memcpy")) || 01681 (NameLen == 7 && !strcmp(NameStr, "memccpy")) || 01682 (NameLen == 7 && !strcmp(NameStr, "memmove"))) { 01683 if (FTy->getNumParams() < 3 || 01684 !isa<PointerType>(FTy->getParamType(1))) 01685 continue; 01686 setDoesNotThrow(F); 01687 setDoesNotCapture(F, 2); 01688 } else if (NameLen == 8 && !strcmp(NameStr, "memalign")) { 01689 if (!isa<PointerType>(FTy->getReturnType())) 01690 continue; 01691 setDoesNotAlias(F, 0); 01692 } 01693 break; 01694 case 'r': 01695 if (NameLen == 7 && !strcmp(NameStr, "realloc")) { 01696 if (FTy->getNumParams() != 2 || 01697 !isa<PointerType>(FTy->getParamType(0)) || 01698 !isa<PointerType>(FTy->getReturnType())) 01699 continue; 01700 setDoesNotThrow(F); 01701 setDoesNotAlias(F, 0); 01702 setDoesNotCapture(F, 1); 01703 } else if (NameLen == 4 && !strcmp(NameStr, "read")) { 01704 if (FTy->getNumParams() != 3 || 01705 !isa<PointerType>(FTy->getParamType(1))) 01706 continue; 01707 // May throw; "read" is a valid pthread cancellation point. 01708 setDoesNotCapture(F, 2); 01709 } else if ((NameLen == 5 && !strcmp(NameStr, "rmdir")) || 01710 (NameLen == 6 && !strcmp(NameStr, "rewind")) || 01711 (NameLen == 6 && !strcmp(NameStr, "remove"))) { 01712 if (FTy->getNumParams() != 1 || 01713 !isa<PointerType>(FTy->getParamType(0))) 01714 continue; 01715 setDoesNotThrow(F); 01716 setDoesNotCapture(F, 1); 01717 } else if (NameLen == 6 && !strcmp(NameStr, "rename")) { 01718 if (FTy->getNumParams() != 2 || 01719 !isa<PointerType>(FTy->getParamType(0)) || 01720 !isa<PointerType>(FTy->getParamType(1))) 01721 continue; 01722 setDoesNotThrow(F); 01723 setDoesNotCapture(F, 1); 01724 setDoesNotCapture(F, 2); 01725 } 01726 break; 01727 case 'w': 01728 if (NameLen == 5 && !strcmp(NameStr, "write")) { 01729 if (FTy->getNumParams() != 3 || 01730 !isa<PointerType>(FTy->getParamType(1))) 01731 continue; 01732 // May throw; "write" is a valid pthread cancellation point. 01733 setDoesNotCapture(F, 2); 01734 } 01735 break; 01736 case 'b': 01737 if (NameLen == 5 && !strcmp(NameStr, "bcopy")) { 01738 if (FTy->getNumParams() != 3 || 01739 !isa<PointerType>(FTy->getParamType(0)) || 01740 !isa<PointerType>(FTy->getParamType(1))) 01741 continue; 01742 setDoesNotThrow(F); 01743 setDoesNotCapture(F, 1); 01744 setDoesNotCapture(F, 2); 01745 } else if (NameLen == 4 && !strcmp(NameStr, "bcmp")) { 01746 if (FTy->getNumParams() != 3 || 01747 !isa<PointerType>(FTy->getParamType(0)) || 01748 !isa<PointerType>(FTy->getParamType(1))) 01749 continue; 01750 setDoesNotThrow(F); 01751 setOnlyReadsMemory(F); 01752 setDoesNotCapture(F, 1); 01753 setDoesNotCapture(F, 2); 01754 } else if (NameLen == 5 && !strcmp(NameStr, "bzero")) { 01755 if (FTy->getNumParams() != 2 || 01756 !isa<PointerType>(FTy->getParamType(0))) 01757 continue; 01758 setDoesNotThrow(F); 01759 setDoesNotCapture(F, 1); 01760 } 01761 break; 01762 case 'c': 01763 if (NameLen == 6 && !strcmp(NameStr, "calloc")) { 01764 if (FTy->getNumParams() != 2 || 01765 !isa<PointerType>(FTy->getReturnType())) 01766 continue; 01767 setDoesNotThrow(F); 01768 setDoesNotAlias(F, 0); 01769 } else if ((NameLen == 5 && !strcmp(NameStr, "chown")) || 01770 (NameLen == 8 && !strcmp(NameStr, "clearerr")) || 01771 (NameLen == 8 && !strcmp(NameStr, "closedir"))) { 01772 if (FTy->getNumParams() == 0 || 01773 !isa<PointerType>(FTy->getParamType(0))) 01774 continue; 01775 setDoesNotThrow(F); 01776 setDoesNotCapture(F, 1); 01777 } 01778 break; 01779 case 'a': 01780 if ((NameLen == 4 && !strcmp(NameStr, "atoi")) || 01781 (NameLen == 4 && !strcmp(NameStr, "atol")) || 01782 (NameLen == 4 && !strcmp(NameStr, "atof")) || 01783 (NameLen == 5 && !strcmp(NameStr, "atoll"))) { 01784 if (FTy->getNumParams() != 1 || 01785 !isa<PointerType>(FTy->getParamType(0))) 01786 continue; 01787 setDoesNotThrow(F); 01788 setOnlyReadsMemory(F); 01789 setDoesNotCapture(F, 1); 01790 } else if (NameLen == 6 && !strcmp(NameStr, "access")) { 01791 if (FTy->getNumParams() != 2 || 01792 !isa<PointerType>(FTy->getParamType(0))) 01793 continue; 01794 setDoesNotThrow(F); 01795 setDoesNotCapture(F, 1); 01796 } 01797 break; 01798 case 'f': 01799 if (NameLen == 5 && !strcmp(NameStr, "fopen")) { 01800 if (FTy->getNumParams() != 2 || 01801 !isa<PointerType>(FTy->getReturnType()) || 01802 !isa<PointerType>(FTy->getParamType(0)) || 01803 !isa<PointerType>(FTy->getParamType(1))) 01804 continue; 01805 setDoesNotThrow(F); 01806 setDoesNotAlias(F, 0); 01807 setDoesNotCapture(F, 1); 01808 setDoesNotCapture(F, 2); 01809 } else if (NameLen == 6 && !strcmp(NameStr, "fdopen")) { 01810 if (FTy->getNumParams() != 2 || 01811 !isa<PointerType>(FTy->getReturnType()) || 01812 !isa<PointerType>(FTy->getParamType(1))) 01813 continue; 01814 setDoesNotThrow(F); 01815 setDoesNotAlias(F, 0); 01816 setDoesNotCapture(F, 2); 01817 } else if ((NameLen == 4 && !strcmp(NameStr, "feof")) || 01818 (NameLen == 4 && !strcmp(NameStr, "free")) || 01819 (NameLen == 5 && !strcmp(NameStr, "fseek")) || 01820 (NameLen == 5 && !strcmp(NameStr, "ftell")) || 01821 (NameLen == 5 && !strcmp(NameStr, "fgetc")) || 01822 (NameLen == 6 && !strcmp(NameStr, "fseeko")) || 01823 (NameLen == 6 && !strcmp(NameStr, "ftello")) || 01824 (NameLen == 6 && !strcmp(NameStr, "fileno")) || 01825 (NameLen == 6 && !strcmp(NameStr, "fflush")) || 01826 (NameLen == 6 && !strcmp(NameStr, "fclose")) || 01827 (NameLen == 7 && !strcmp(NameStr, "fsetpos"))) { 01828 if (FTy->getNumParams() == 0 || 01829 !isa<PointerType>(FTy->getParamType(0))) 01830 continue; 01831 setDoesNotThrow(F); 01832 setDoesNotCapture(F, 1); 01833 } else if (NameLen == 6 && !strcmp(NameStr, "ferror")) { 01834 if (FTy->getNumParams() != 1 || 01835 !isa<PointerType>(FTy->getParamType(0))) 01836 continue; 01837 setDoesNotThrow(F); 01838 setDoesNotCapture(F, 1); 01839 setOnlyReadsMemory(F); 01840 } else if ((NameLen == 5 && !strcmp(NameStr, "fputc")) || 01841 (NameLen == 5 && !strcmp(NameStr, "fputs"))) { 01842 if (FTy->getNumParams() != 2 || 01843 !isa<PointerType>(FTy->getParamType(1))) 01844 continue; 01845 setDoesNotThrow(F); 01846 setDoesNotCapture(F, 2); 01847 } else if (NameLen == 5 && !strcmp(NameStr, "fgets")) { 01848 if (FTy->getNumParams() != 3 || 01849 !isa<PointerType>(FTy->getParamType(0)) || 01850 !isa<PointerType>(FTy->getParamType(2))) 01851 continue; 01852 setDoesNotThrow(F); 01853 setDoesNotCapture(F, 3); 01854 } else if ((NameLen == 5 && !strcmp(NameStr, "fread")) || 01855 (NameLen == 6 && !strcmp(NameStr, "fwrite"))) { 01856 if (FTy->getNumParams() != 4 || 01857 !isa<PointerType>(FTy->getParamType(0)) || 01858 !isa<PointerType>(FTy->getParamType(3))) 01859 continue; 01860 setDoesNotThrow(F); 01861 setDoesNotCapture(F, 1); 01862 setDoesNotCapture(F, 4); 01863 } else if (NameLen == 7 && !strcmp(NameStr, "fgetpos")) { 01864 if (FTy->getNumParams() != 2 || 01865 !isa<PointerType>(FTy->getParamType(0)) || 01866 !isa<PointerType>(FTy->getParamType(1))) 01867 continue; 01868 setDoesNotThrow(F); 01869 setDoesNotCapture(F, 1); 01870 setDoesNotCapture(F, 2); 01871 } else if (NameLen == 6 && !strcmp(NameStr, "fscanf")) { 01872 if (FTy->getNumParams() < 2 || 01873 !isa<PointerType>(FTy->getParamType(0)) || 01874 !isa<PointerType>(FTy->getParamType(1))) 01875 continue; 01876 setDoesNotThrow(F); 01877 setDoesNotCapture(F, 1); 01878 setDoesNotCapture(F, 2); 01879 } else if (NameLen == 7 && !strcmp(NameStr, "fprintf")) { 01880 if (FTy->getNumParams() != 2 || 01881 !isa<PointerType>(FTy->getParamType(0)) || 01882 !isa<PointerType>(FTy->getParamType(1))) 01883 continue; 01884 setDoesNotThrow(F); 01885 setDoesNotCapture(F, 1); 01886 setDoesNotCapture(F, 2); 01887 } 01888 break; 01889 case 'g': 01890 if ((NameLen == 4 && !strcmp(NameStr, "getc")) || 01891 (NameLen == 10 && !strcmp(NameStr, "getlogin_r"))) { 01892 if (FTy->getNumParams() == 0 || 01893 !isa<PointerType>(FTy->getParamType(0))) 01894 continue; 01895 setDoesNotThrow(F); 01896 setDoesNotCapture(F, 1); 01897 } else if (NameLen == 6 && !strcmp(NameStr, "getenv")) { 01898 if (FTy->getNumParams() != 1 || 01899 !isa<PointerType>(FTy->getParamType(0))) 01900 continue; 01901 setDoesNotThrow(F); 01902 setOnlyReadsMemory(F); 01903 setDoesNotCapture(F, 1); 01904 } else if ((NameLen == 4 && !strcmp(NameStr, "gets")) || 01905 (NameLen == 7 && !strcmp(NameStr, "getchar"))) { 01906 setDoesNotThrow(F); 01907 } 01908 break; 01909 case 'u': 01910 if (NameLen == 6 && !strcmp(NameStr, "ungetc")) { 01911 if (FTy->getNumParams() != 2 || 01912 !isa<PointerType>(FTy->getParamType(1))) 01913 continue; 01914 setDoesNotThrow(F); 01915 setDoesNotCapture(F, 2); 01916 } else if (NameLen == 6 && !strcmp(NameStr, "unlink")) { 01917 if (FTy->getNumParams() != 1 || 01918 !isa<PointerType>(FTy->getParamType(0))) 01919 continue; 01920 setDoesNotThrow(F); 01921 setDoesNotCapture(F, 1); 01922 } 01923 break; 01924 case 'p': 01925 if (NameLen == 4 && !strcmp(NameStr, "putc")) { 01926 if (FTy->getNumParams() != 2 || 01927 !isa<PointerType>(FTy->getParamType(1))) 01928 continue; 01929 setDoesNotThrow(F); 01930 setDoesNotCapture(F, 2); 01931 } else if ((NameLen == 4 && !strcmp(NameStr, "puts")) || 01932 (NameLen == 6 && !strcmp(NameStr, "printf")) || 01933 (NameLen == 6 && !strcmp(NameStr, "perror"))) { 01934 if (FTy->getNumParams() != 1 || 01935 !isa<PointerType>(FTy->getParamType(0))) 01936 continue; 01937 setDoesNotThrow(F); 01938 setDoesNotCapture(F, 1); 01939 } else if ((NameLen == 5 && !strcmp(NameStr, "pread")) || 01940 (NameLen == 6 && !strcmp(NameStr, "pwrite"))) { 01941 if (FTy->getNumParams() != 4 || 01942 !isa<PointerType>(FTy->getParamType(1))) 01943 continue; 01944 // May throw; these are valid pthread cancellation points. 01945 setDoesNotCapture(F, 2); 01946 } else if (NameLen == 7 && !strcmp(NameStr, "putchar")) { 01947 setDoesNotThrow(F); 01948 } 01949 break; 01950 case 'v': 01951 if (NameLen == 6 && !strcmp(NameStr, "vscanf")) { 01952 if (FTy->getNumParams() != 2 || 01953 !isa<PointerType>(FTy->getParamType(1))) 01954 continue; 01955 setDoesNotThrow(F); 01956 setDoesNotCapture(F, 1); 01957 } else if ((NameLen == 7 && !strcmp(NameStr, "vsscanf")) || 01958 (NameLen == 7 && !strcmp(NameStr, "vfscanf"))) { 01959 if (FTy->getNumParams() != 3 || 01960 !isa<PointerType>(FTy->getParamType(1)) || 01961 !isa<PointerType>(FTy->getParamType(2))) 01962 continue; 01963 setDoesNotThrow(F); 01964 setDoesNotCapture(F, 1); 01965 setDoesNotCapture(F, 2); 01966 } else if (NameLen == 6 && !strcmp(NameStr, "valloc")) { 01967 if (!isa<PointerType>(FTy->getReturnType())) 01968 continue; 01969 setDoesNotThrow(F); 01970 setDoesNotAlias(F, 0); 01971 } else if (NameLen == 7 && !strcmp(NameStr, "vprintf")) { 01972 if (FTy->getNumParams() != 2 || 01973 !isa<PointerType>(FTy->getParamType(0))) 01974 continue; 01975 setDoesNotThrow(F); 01976 setDoesNotCapture(F, 1); 01977 } else if ((NameLen == 8 && !strcmp(NameStr, "vfprintf")) || 01978 (NameLen == 8 && !strcmp(NameStr, "vsprintf"))) { 01979 if (FTy->getNumParams() != 3 || 01980 !isa<PointerType>(FTy->getParamType(0)) || 01981 !isa<PointerType>(FTy->getParamType(1))) 01982 continue; 01983 setDoesNotThrow(F); 01984 setDoesNotCapture(F, 1); 01985 setDoesNotCapture(F, 2); 01986 } else if (NameLen == 9 && !strcmp(NameStr, "vsnprintf")) { 01987 if (FTy->getNumParams() != 4 || 01988 !isa<PointerType>(FTy->getParamType(0)) || 01989 !isa<PointerType>(FTy->getParamType(2))) 01990 continue; 01991 setDoesNotThrow(F); 01992 setDoesNotCapture(F, 1); 01993 setDoesNotCapture(F, 3); 01994 } 01995 break; 01996 case 'o': 01997 if (NameLen == 7 && !strcmp(NameStr, "opendir")) { 01998 // The description of fdopendir sounds like opening the same fd 01999 // twice might result in the same DIR* ! 02000 if (!isa<PointerType>(FTy->getReturnType())) 02001 continue; 02002 setDoesNotThrow(F); 02003 setDoesNotAlias(F, 0); 02004 } 02005 break; 02006 case 't': 02007 if (NameLen == 7 && !strcmp(NameStr, "tmpfile")) { 02008 if (!isa<PointerType>(FTy->getReturnType())) 02009 continue; 02010 setDoesNotThrow(F); 02011 setDoesNotAlias(F, 0); 02012 } 02013 case 'h': 02014 if ((NameLen == 5 && !strcmp(NameStr, "htonl")) || 02015 (NameLen == 5 && !strcmp(NameStr, "htons"))) { 02016 setDoesNotThrow(F); 02017 setDoesNotAccessMemory(F); 02018 } 02019 break; 02020 case 'n': 02021 if ((NameLen == 5 && !strcmp(NameStr, "ntohl")) || 02022 (NameLen == 5 && !strcmp(NameStr, "ntohs"))) { 02023 setDoesNotThrow(F); 02024 setDoesNotAccessMemory(F); 02025 } 02026 case '_': 02027 if ((NameLen == 8 && !strcmp(NameStr, "__strdup")) || 02028 (NameLen == 9 && !strcmp(NameStr, "__strndup"))) { 02029 if (FTy->getNumParams() < 1 || 02030 !isa<PointerType>(FTy->getReturnType()) || 02031 !isa<PointerType>(FTy->getParamType(0))) 02032 continue; 02033 setDoesNotThrow(F); 02034 setDoesNotAlias(F, 0); 02035 setDoesNotCapture(F, 1); 02036 } else if (NameLen == 10 && !strcmp(NameStr, "__strtok_r")) { 02037 if (FTy->getNumParams() != 3 || 02038 !isa<PointerType>(FTy->getParamType(1))) 02039 continue; 02040 setDoesNotThrow(F); 02041 setDoesNotCapture(F, 2); 02042 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_getc")) { 02043 if (FTy->getNumParams() != 1 || 02044 !isa<PointerType>(FTy->getParamType(0))) 02045 continue; 02046 setDoesNotThrow(F); 02047 setDoesNotCapture(F, 1); 02048 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_putc")) { 02049 if (FTy->getNumParams() != 2 || 02050 !isa<PointerType>(FTy->getParamType(1))) 02051 continue; 02052 setDoesNotThrow(F); 02053 setDoesNotCapture(F, 2); 02054 } 02055 case 1: 02056 if (NameLen == 15 && !strcmp(NameStr, "\1__isoc99_scanf")) { 02057 if (FTy->getNumParams() < 1 || 02058 !isa<PointerType>(FTy->getParamType(0))) 02059 continue; 02060 setDoesNotThrow(F); 02061 setDoesNotCapture(F, 1); 02062 } else if (NameLen == 16 && !strcmp(NameStr, "\1__isoc99_sscanf")) { 02063 if (FTy->getNumParams() < 1 || 02064 !isa<PointerType>(FTy->getParamType(0))) 02065 continue; 02066 setDoesNotThrow(F); 02067 setDoesNotCapture(F, 1); 02068 setDoesNotCapture(F, 2); 02069 } 02070 break; 02071 } 02072 } 02073 return Modified; 02074 } 02075 02076 // TODO: 02077 // Additional cases that we need to add to this file: 02078 // 02079 // cbrt: 02080 // * cbrt(expN(X)) -> expN(x/3) 02081 // * cbrt(sqrt(x)) -> pow(x,1/6) 02082 // * cbrt(sqrt(x)) -> pow(x,1/9) 02083 // 02084 // cos, cosf, cosl: 02085 // * cos(-x) -> cos(x) 02086 // 02087 // exp, expf, expl: 02088 // * exp(log(x)) -> x 02089 // 02090 // log, logf, logl: 02091 // * log(exp(x)) -> x 02092 // * log(x**y) -> y*log(x) 02093 // * log(exp(y)) -> y*log(e) 02094 // * log(exp2(y)) -> y*log(2) 02095 // * log(exp10(y)) -> y*log(10) 02096 // * log(sqrt(x)) -> 0.5*log(x) 02097 // * log(pow(x,y)) -> y*log(x) 02098 // 02099 // lround, lroundf, lroundl: 02100 // * lround(cnst) -> cnst' 02101 // 02102 // memcmp: 02103 // * memcmp(x,y,l) -> cnst 02104 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l) 02105 // 02106 // pow, powf, powl: 02107 // * pow(exp(x),y) -> exp(x*y) 02108 // * pow(sqrt(x),y) -> pow(x,y*0.5) 02109 // * pow(pow(x,y),z)-> pow(x,y*z) 02110 // 02111 // puts: 02112 // * puts("") -> putchar("\n") 02113 // 02114 // round, roundf, roundl: 02115 // * round(cnst) -> cnst' 02116 // 02117 // signbit: 02118 // * signbit(cnst) -> cnst' 02119 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 02120 // 02121 // sqrt, sqrtf, sqrtl: 02122 // * sqrt(expN(x)) -> expN(x*0.5) 02123 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 02124 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 02125 // 02126 // stpcpy: 02127 // * stpcpy(str, "literal") -> 02128 // llvm.memcpy(str,"literal",strlen("literal")+1,1) 02129 // strrchr: 02130 // * strrchr(s,c) -> reverse_offset_of_in(c,s) 02131 // (if c is a constant integer and s is a constant string) 02132 // * strrchr(s1,0) -> strchr(s1,0) 02133 // 02134 // strncat: 02135 // * strncat(x,y,0) -> x 02136 // * strncat(x,y,0) -> x (if strlen(y) = 0) 02137 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y)) 02138 // 02139 // strncpy: 02140 // * strncpy(d,s,0) -> d 02141 // * strncpy(d,s,l) -> memcpy(d,s,l,1) 02142 // (if s and l are constants) 02143 // 02144 // strpbrk: 02145 // * strpbrk(s,a) -> offset_in_for(s,a) 02146 // (if s and a are both constant strings) 02147 // * strpbrk(s,"") -> 0 02148 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1) 02149 // 02150 // strspn, strcspn: 02151 // * strspn(s,a) -> const_int (if both args are constant) 02152 // * strspn("",a) -> 0 02153 // * strspn(s,"") -> 0 02154 // * strcspn(s,a) -> const_int (if both args are constant) 02155 // * strcspn("",a) -> 0 02156 // * strcspn(s,"") -> strlen(a) 02157 // 02158 // strstr: 02159 // * strstr(x,x) -> x 02160 // * strstr(s1,s2) -> offset_of_s2_in(s1) 02161 // (if s1 and s2 are constant strings) 02162 // 02163 // tan, tanf, tanl: 02164 // * tan(atan(x)) -> x 02165 // 02166 // trunc, truncf, truncl: 02167 // * trunc(cnst) -> cnst' 02168 // 02169 //