1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This is a utility pass used for testing the InstructionSimplify analysis. 11 // The analysis is applied to every instruction, and if it simplifies then the 12 // instruction is replaced by the simplification. If you are looking for a pass 13 // that performs serious instruction folding, use the instcombine pass instead. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/StringMap.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/Function.h" 24 #include "llvm/IR/IRBuilder.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/Intrinsics.h" 27 #include "llvm/IR/LLVMContext.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/Support/Allocator.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Target/TargetLibraryInfo.h" 32 #include "llvm/Transforms/Utils/BuildLibCalls.h" 33 34 using namespace llvm; 35 36 static cl::opt<bool> 37 ColdErrorCalls("error-reporting-is-cold", cl::init(true), 38 cl::Hidden, cl::desc("Treat error-reporting calls as cold")); 39 40 /// This class is the abstract base class for the set of optimizations that 41 /// corresponds to one library call. 42 namespace { 43 class LibCallOptimization { 44 protected: 45 Function *Caller; 46 const DataLayout *TD; 47 const TargetLibraryInfo *TLI; 48 const LibCallSimplifier *LCS; 49 LLVMContext* Context; 50 public: 51 LibCallOptimization() { } 52 virtual ~LibCallOptimization() {} 53 54 /// callOptimizer - This pure virtual method is implemented by base classes to 55 /// do various optimizations. If this returns null then no transformation was 56 /// performed. If it returns CI, then it transformed the call and CI is to be 57 /// deleted. If it returns something else, replace CI with the new value and 58 /// delete CI. 59 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) 60 =0; 61 62 /// ignoreCallingConv - Returns false if this transformation could possibly 63 /// change the calling convention. 64 virtual bool ignoreCallingConv() { return false; } 65 66 Value *optimizeCall(CallInst *CI, const DataLayout *TD, 67 const TargetLibraryInfo *TLI, 68 const LibCallSimplifier *LCS, IRBuilder<> &B) { 69 Caller = CI->getParent()->getParent(); 70 this->TD = TD; 71 this->TLI = TLI; 72 this->LCS = LCS; 73 if (CI->getCalledFunction()) 74 Context = &CI->getCalledFunction()->getContext(); 75 76 // We never change the calling convention. 77 if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C) 78 return NULL; 79 80 return callOptimizer(CI->getCalledFunction(), CI, B); 81 } 82 }; 83 84 //===----------------------------------------------------------------------===// 85 // Helper Functions 86 //===----------------------------------------------------------------------===// 87 88 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 89 /// value is equal or not-equal to zero. 90 static bool isOnlyUsedInZeroEqualityComparison(Value *V) { 91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); 92 UI != E; ++UI) { 93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 94 if (IC->isEquality()) 95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 96 if (C->isNullValue()) 97 continue; 98 // Unknown instruction. 99 return false; 100 } 101 return true; 102 } 103 104 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality 105 /// comparisons with With. 106 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) { 107 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); 108 UI != E; ++UI) { 109 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 110 if (IC->isEquality() && IC->getOperand(1) == With) 111 continue; 112 // Unknown instruction. 113 return false; 114 } 115 return true; 116 } 117 118 static bool callHasFloatingPointArgument(const CallInst *CI) { 119 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end(); 120 it != e; ++it) { 121 if ((*it)->getType()->isFloatingPointTy()) 122 return true; 123 } 124 return false; 125 } 126 127 /// \brief Check whether the overloaded unary floating point function 128 /// corresponing to \a Ty is available. 129 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty, 130 LibFunc::Func DoubleFn, LibFunc::Func FloatFn, 131 LibFunc::Func LongDoubleFn) { 132 switch (Ty->getTypeID()) { 133 case Type::FloatTyID: 134 return TLI->has(FloatFn); 135 case Type::DoubleTyID: 136 return TLI->has(DoubleFn); 137 default: 138 return TLI->has(LongDoubleFn); 139 } 140 } 141 142 //===----------------------------------------------------------------------===// 143 // Fortified Library Call Optimizations 144 //===----------------------------------------------------------------------===// 145 146 struct FortifiedLibCallOptimization : public LibCallOptimization { 147 protected: 148 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, 149 bool isString) const = 0; 150 }; 151 152 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization { 153 CallInst *CI; 154 155 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const { 156 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp)) 157 return true; 158 if (ConstantInt *SizeCI = 159 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) { 160 if (SizeCI->isAllOnesValue()) 161 return true; 162 if (isString) { 163 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp)); 164 // If the length is 0 we don't know how long it is and so we can't 165 // remove the check. 166 if (Len == 0) return false; 167 return SizeCI->getZExtValue() >= Len; 168 } 169 if (ConstantInt *Arg = dyn_cast<ConstantInt>( 170 CI->getArgOperand(SizeArgOp))) 171 return SizeCI->getZExtValue() >= Arg->getZExtValue(); 172 } 173 return false; 174 } 175 }; 176 177 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization { 178 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 179 this->CI = CI; 180 FunctionType *FT = Callee->getFunctionType(); 181 LLVMContext &Context = CI->getParent()->getContext(); 182 183 // Check if this has the right signature. 184 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) || 185 !FT->getParamType(0)->isPointerTy() || 186 !FT->getParamType(1)->isPointerTy() || 187 FT->getParamType(2) != TD->getIntPtrType(Context) || 188 FT->getParamType(3) != TD->getIntPtrType(Context)) 189 return 0; 190 191 if (isFoldable(3, 2, false)) { 192 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 193 CI->getArgOperand(2), 1); 194 return CI->getArgOperand(0); 195 } 196 return 0; 197 } 198 }; 199 200 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization { 201 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 202 this->CI = CI; 203 FunctionType *FT = Callee->getFunctionType(); 204 LLVMContext &Context = CI->getParent()->getContext(); 205 206 // Check if this has the right signature. 207 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) || 208 !FT->getParamType(0)->isPointerTy() || 209 !FT->getParamType(1)->isPointerTy() || 210 FT->getParamType(2) != TD->getIntPtrType(Context) || 211 FT->getParamType(3) != TD->getIntPtrType(Context)) 212 return 0; 213 214 if (isFoldable(3, 2, false)) { 215 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1), 216 CI->getArgOperand(2), 1); 217 return CI->getArgOperand(0); 218 } 219 return 0; 220 } 221 }; 222 223 struct MemSetChkOpt : public InstFortifiedLibCallOptimization { 224 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 225 this->CI = CI; 226 FunctionType *FT = Callee->getFunctionType(); 227 LLVMContext &Context = CI->getParent()->getContext(); 228 229 // Check if this has the right signature. 230 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) || 231 !FT->getParamType(0)->isPointerTy() || 232 !FT->getParamType(1)->isIntegerTy() || 233 FT->getParamType(2) != TD->getIntPtrType(Context) || 234 FT->getParamType(3) != TD->getIntPtrType(Context)) 235 return 0; 236 237 if (isFoldable(3, 2, false)) { 238 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), 239 false); 240 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1); 241 return CI->getArgOperand(0); 242 } 243 return 0; 244 } 245 }; 246 247 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization { 248 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 249 this->CI = CI; 250 StringRef Name = Callee->getName(); 251 FunctionType *FT = Callee->getFunctionType(); 252 LLVMContext &Context = CI->getParent()->getContext(); 253 254 // Check if this has the right signature. 255 if (FT->getNumParams() != 3 || 256 FT->getReturnType() != FT->getParamType(0) || 257 FT->getParamType(0) != FT->getParamType(1) || 258 FT->getParamType(0) != Type::getInt8PtrTy(Context) || 259 FT->getParamType(2) != TD->getIntPtrType(Context)) 260 return 0; 261 262 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 263 if (Dst == Src) // __strcpy_chk(x,x) -> x 264 return Src; 265 266 // If a) we don't have any length information, or b) we know this will 267 // fit then just lower to a plain strcpy. Otherwise we'll keep our 268 // strcpy_chk call which may fail at runtime if the size is too long. 269 // TODO: It might be nice to get a maximum length out of the possible 270 // string lengths for varying. 271 if (isFoldable(2, 1, true)) { 272 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6)); 273 return Ret; 274 } else { 275 // Maybe we can stil fold __strcpy_chk to __memcpy_chk. 276 uint64_t Len = GetStringLength(Src); 277 if (Len == 0) return 0; 278 279 // This optimization require DataLayout. 280 if (!TD) return 0; 281 282 Value *Ret = 283 EmitMemCpyChk(Dst, Src, 284 ConstantInt::get(TD->getIntPtrType(Context), Len), 285 CI->getArgOperand(2), B, TD, TLI); 286 return Ret; 287 } 288 return 0; 289 } 290 }; 291 292 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization { 293 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 294 this->CI = CI; 295 StringRef Name = Callee->getName(); 296 FunctionType *FT = Callee->getFunctionType(); 297 LLVMContext &Context = CI->getParent()->getContext(); 298 299 // Check if this has the right signature. 300 if (FT->getNumParams() != 3 || 301 FT->getReturnType() != FT->getParamType(0) || 302 FT->getParamType(0) != FT->getParamType(1) || 303 FT->getParamType(0) != Type::getInt8PtrTy(Context) || 304 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0))) 305 return 0; 306 307 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 308 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 309 Value *StrLen = EmitStrLen(Src, B, TD, TLI); 310 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0; 311 } 312 313 // If a) we don't have any length information, or b) we know this will 314 // fit then just lower to a plain stpcpy. Otherwise we'll keep our 315 // stpcpy_chk call which may fail at runtime if the size is too long. 316 // TODO: It might be nice to get a maximum length out of the possible 317 // string lengths for varying. 318 if (isFoldable(2, 1, true)) { 319 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6)); 320 return Ret; 321 } else { 322 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk. 323 uint64_t Len = GetStringLength(Src); 324 if (Len == 0) return 0; 325 326 // This optimization require DataLayout. 327 if (!TD) return 0; 328 329 Type *PT = FT->getParamType(0); 330 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len); 331 Value *DstEnd = B.CreateGEP(Dst, 332 ConstantInt::get(TD->getIntPtrType(PT), 333 Len - 1)); 334 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI)) 335 return 0; 336 return DstEnd; 337 } 338 return 0; 339 } 340 }; 341 342 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization { 343 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 344 this->CI = CI; 345 StringRef Name = Callee->getName(); 346 FunctionType *FT = Callee->getFunctionType(); 347 LLVMContext &Context = CI->getParent()->getContext(); 348 349 // Check if this has the right signature. 350 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) || 351 FT->getParamType(0) != FT->getParamType(1) || 352 FT->getParamType(0) != Type::getInt8PtrTy(Context) || 353 !FT->getParamType(2)->isIntegerTy() || 354 FT->getParamType(3) != TD->getIntPtrType(Context)) 355 return 0; 356 357 if (isFoldable(3, 2, false)) { 358 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 359 CI->getArgOperand(2), B, TD, TLI, 360 Name.substr(2, 7)); 361 return Ret; 362 } 363 return 0; 364 } 365 }; 366 367 //===----------------------------------------------------------------------===// 368 // String and Memory Library Call Optimizations 369 //===----------------------------------------------------------------------===// 370 371 struct StrCatOpt : public LibCallOptimization { 372 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 373 // Verify the "strcat" function prototype. 374 FunctionType *FT = Callee->getFunctionType(); 375 if (FT->getNumParams() != 2 || 376 FT->getReturnType() != B.getInt8PtrTy() || 377 FT->getParamType(0) != FT->getReturnType() || 378 FT->getParamType(1) != FT->getReturnType()) 379 return 0; 380 381 // Extract some information from the instruction 382 Value *Dst = CI->getArgOperand(0); 383 Value *Src = CI->getArgOperand(1); 384 385 // See if we can get the length of the input string. 386 uint64_t Len = GetStringLength(Src); 387 if (Len == 0) return 0; 388 --Len; // Unbias length. 389 390 // Handle the simple, do-nothing case: strcat(x, "") -> x 391 if (Len == 0) 392 return Dst; 393 394 // These optimizations require DataLayout. 395 if (!TD) return 0; 396 397 return emitStrLenMemCpy(Src, Dst, Len, B); 398 } 399 400 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, 401 IRBuilder<> &B) { 402 // We need to find the end of the destination string. That's where the 403 // memory is to be moved to. We just generate a call to strlen. 404 Value *DstLen = EmitStrLen(Dst, B, TD, TLI); 405 if (!DstLen) 406 return 0; 407 408 // Now that we have the destination's length, we must index into the 409 // destination's pointer to get the actual memcpy destination (end of 410 // the string .. we're concatenating). 411 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr"); 412 413 // We have enough information to now generate the memcpy call to do the 414 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 415 B.CreateMemCpy(CpyDst, Src, 416 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1); 417 return Dst; 418 } 419 }; 420 421 struct StrNCatOpt : public StrCatOpt { 422 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 423 // Verify the "strncat" function prototype. 424 FunctionType *FT = Callee->getFunctionType(); 425 if (FT->getNumParams() != 3 || 426 FT->getReturnType() != B.getInt8PtrTy() || 427 FT->getParamType(0) != FT->getReturnType() || 428 FT->getParamType(1) != FT->getReturnType() || 429 !FT->getParamType(2)->isIntegerTy()) 430 return 0; 431 432 // Extract some information from the instruction 433 Value *Dst = CI->getArgOperand(0); 434 Value *Src = CI->getArgOperand(1); 435 uint64_t Len; 436 437 // We don't do anything if length is not constant 438 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2))) 439 Len = LengthArg->getZExtValue(); 440 else 441 return 0; 442 443 // See if we can get the length of the input string. 444 uint64_t SrcLen = GetStringLength(Src); 445 if (SrcLen == 0) return 0; 446 --SrcLen; // Unbias length. 447 448 // Handle the simple, do-nothing cases: 449 // strncat(x, "", c) -> x 450 // strncat(x, c, 0) -> x 451 if (SrcLen == 0 || Len == 0) return Dst; 452 453 // These optimizations require DataLayout. 454 if (!TD) return 0; 455 456 // We don't optimize this case 457 if (Len < SrcLen) return 0; 458 459 // strncat(x, s, c) -> strcat(x, s) 460 // s is constant so the strcat can be optimized further 461 return emitStrLenMemCpy(Src, Dst, SrcLen, B); 462 } 463 }; 464 465 struct StrChrOpt : public LibCallOptimization { 466 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 467 // Verify the "strchr" function prototype. 468 FunctionType *FT = Callee->getFunctionType(); 469 if (FT->getNumParams() != 2 || 470 FT->getReturnType() != B.getInt8PtrTy() || 471 FT->getParamType(0) != FT->getReturnType() || 472 !FT->getParamType(1)->isIntegerTy(32)) 473 return 0; 474 475 Value *SrcStr = CI->getArgOperand(0); 476 477 // If the second operand is non-constant, see if we can compute the length 478 // of the input string and turn this into memchr. 479 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 480 if (CharC == 0) { 481 // These optimizations require DataLayout. 482 if (!TD) return 0; 483 484 uint64_t Len = GetStringLength(SrcStr); 485 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32. 486 return 0; 487 488 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul. 489 ConstantInt::get(TD->getIntPtrType(*Context), Len), 490 B, TD, TLI); 491 } 492 493 // Otherwise, the character is a constant, see if the first argument is 494 // a string literal. If so, we can constant fold. 495 StringRef Str; 496 if (!getConstantStringInfo(SrcStr, Str)) 497 return 0; 498 499 // Compute the offset, make sure to handle the case when we're searching for 500 // zero (a weird way to spell strlen). 501 size_t I = (0xFF & CharC->getSExtValue()) == 0 ? 502 Str.size() : Str.find(CharC->getSExtValue()); 503 if (I == StringRef::npos) // Didn't find the char. strchr returns null. 504 return Constant::getNullValue(CI->getType()); 505 506 // strchr(s+n,c) -> gep(s+n+i,c) 507 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr"); 508 } 509 }; 510 511 struct StrRChrOpt : public LibCallOptimization { 512 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 513 // Verify the "strrchr" function prototype. 514 FunctionType *FT = Callee->getFunctionType(); 515 if (FT->getNumParams() != 2 || 516 FT->getReturnType() != B.getInt8PtrTy() || 517 FT->getParamType(0) != FT->getReturnType() || 518 !FT->getParamType(1)->isIntegerTy(32)) 519 return 0; 520 521 Value *SrcStr = CI->getArgOperand(0); 522 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 523 524 // Cannot fold anything if we're not looking for a constant. 525 if (!CharC) 526 return 0; 527 528 StringRef Str; 529 if (!getConstantStringInfo(SrcStr, Str)) { 530 // strrchr(s, 0) -> strchr(s, 0) 531 if (TD && CharC->isZero()) 532 return EmitStrChr(SrcStr, '\0', B, TD, TLI); 533 return 0; 534 } 535 536 // Compute the offset. 537 size_t I = (0xFF & CharC->getSExtValue()) == 0 ? 538 Str.size() : Str.rfind(CharC->getSExtValue()); 539 if (I == StringRef::npos) // Didn't find the char. Return null. 540 return Constant::getNullValue(CI->getType()); 541 542 // strrchr(s+n,c) -> gep(s+n+i,c) 543 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr"); 544 } 545 }; 546 547 struct StrCmpOpt : public LibCallOptimization { 548 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 549 // Verify the "strcmp" function prototype. 550 FunctionType *FT = Callee->getFunctionType(); 551 if (FT->getNumParams() != 2 || 552 !FT->getReturnType()->isIntegerTy(32) || 553 FT->getParamType(0) != FT->getParamType(1) || 554 FT->getParamType(0) != B.getInt8PtrTy()) 555 return 0; 556 557 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 558 if (Str1P == Str2P) // strcmp(x,x) -> 0 559 return ConstantInt::get(CI->getType(), 0); 560 561 StringRef Str1, Str2; 562 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 563 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 564 565 // strcmp(x, y) -> cnst (if both x and y are constant strings) 566 if (HasStr1 && HasStr2) 567 return ConstantInt::get(CI->getType(), Str1.compare(Str2)); 568 569 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x 570 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), 571 CI->getType())); 572 573 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 574 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 575 576 // strcmp(P, "x") -> memcmp(P, "x", 2) 577 uint64_t Len1 = GetStringLength(Str1P); 578 uint64_t Len2 = GetStringLength(Str2P); 579 if (Len1 && Len2) { 580 // These optimizations require DataLayout. 581 if (!TD) return 0; 582 583 return EmitMemCmp(Str1P, Str2P, 584 ConstantInt::get(TD->getIntPtrType(*Context), 585 std::min(Len1, Len2)), B, TD, TLI); 586 } 587 588 return 0; 589 } 590 }; 591 592 struct StrNCmpOpt : public LibCallOptimization { 593 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 594 // Verify the "strncmp" function prototype. 595 FunctionType *FT = Callee->getFunctionType(); 596 if (FT->getNumParams() != 3 || 597 !FT->getReturnType()->isIntegerTy(32) || 598 FT->getParamType(0) != FT->getParamType(1) || 599 FT->getParamType(0) != B.getInt8PtrTy() || 600 !FT->getParamType(2)->isIntegerTy()) 601 return 0; 602 603 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 604 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 605 return ConstantInt::get(CI->getType(), 0); 606 607 // Get the length argument if it is constant. 608 uint64_t Length; 609 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2))) 610 Length = LengthArg->getZExtValue(); 611 else 612 return 0; 613 614 if (Length == 0) // strncmp(x,y,0) -> 0 615 return ConstantInt::get(CI->getType(), 0); 616 617 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1) 618 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI); 619 620 StringRef Str1, Str2; 621 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 622 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 623 624 // strncmp(x, y) -> cnst (if both x and y are constant strings) 625 if (HasStr1 && HasStr2) { 626 StringRef SubStr1 = Str1.substr(0, Length); 627 StringRef SubStr2 = Str2.substr(0, Length); 628 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2)); 629 } 630 631 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x 632 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), 633 CI->getType())); 634 635 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 636 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 637 638 return 0; 639 } 640 }; 641 642 struct StrCpyOpt : public LibCallOptimization { 643 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 644 // Verify the "strcpy" function prototype. 645 FunctionType *FT = Callee->getFunctionType(); 646 if (FT->getNumParams() != 2 || 647 FT->getReturnType() != FT->getParamType(0) || 648 FT->getParamType(0) != FT->getParamType(1) || 649 FT->getParamType(0) != B.getInt8PtrTy()) 650 return 0; 651 652 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 653 if (Dst == Src) // strcpy(x,x) -> x 654 return Src; 655 656 // These optimizations require DataLayout. 657 if (!TD) return 0; 658 659 // See if we can get the length of the input string. 660 uint64_t Len = GetStringLength(Src); 661 if (Len == 0) return 0; 662 663 // We have enough information to now generate the memcpy call to do the 664 // copy for us. Make a memcpy to copy the nul byte with align = 1. 665 B.CreateMemCpy(Dst, Src, 666 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1); 667 return Dst; 668 } 669 }; 670 671 struct StpCpyOpt: public LibCallOptimization { 672 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 673 // Verify the "stpcpy" function prototype. 674 FunctionType *FT = Callee->getFunctionType(); 675 if (FT->getNumParams() != 2 || 676 FT->getReturnType() != FT->getParamType(0) || 677 FT->getParamType(0) != FT->getParamType(1) || 678 FT->getParamType(0) != B.getInt8PtrTy()) 679 return 0; 680 681 // These optimizations require DataLayout. 682 if (!TD) return 0; 683 684 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 685 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 686 Value *StrLen = EmitStrLen(Src, B, TD, TLI); 687 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0; 688 } 689 690 // See if we can get the length of the input string. 691 uint64_t Len = GetStringLength(Src); 692 if (Len == 0) return 0; 693 694 Type *PT = FT->getParamType(0); 695 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len); 696 Value *DstEnd = B.CreateGEP(Dst, 697 ConstantInt::get(TD->getIntPtrType(PT), 698 Len - 1)); 699 700 // We have enough information to now generate the memcpy call to do the 701 // copy for us. Make a memcpy to copy the nul byte with align = 1. 702 B.CreateMemCpy(Dst, Src, LenV, 1); 703 return DstEnd; 704 } 705 }; 706 707 struct StrNCpyOpt : public LibCallOptimization { 708 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 709 FunctionType *FT = Callee->getFunctionType(); 710 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) || 711 FT->getParamType(0) != FT->getParamType(1) || 712 FT->getParamType(0) != B.getInt8PtrTy() || 713 !FT->getParamType(2)->isIntegerTy()) 714 return 0; 715 716 Value *Dst = CI->getArgOperand(0); 717 Value *Src = CI->getArgOperand(1); 718 Value *LenOp = CI->getArgOperand(2); 719 720 // See if we can get the length of the input string. 721 uint64_t SrcLen = GetStringLength(Src); 722 if (SrcLen == 0) return 0; 723 --SrcLen; 724 725 if (SrcLen == 0) { 726 // strncpy(x, "", y) -> memset(x, '\0', y, 1) 727 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1); 728 return Dst; 729 } 730 731 uint64_t Len; 732 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp)) 733 Len = LengthArg->getZExtValue(); 734 else 735 return 0; 736 737 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x 738 739 // These optimizations require DataLayout. 740 if (!TD) return 0; 741 742 // Let strncpy handle the zero padding 743 if (Len > SrcLen+1) return 0; 744 745 Type *PT = FT->getParamType(0); 746 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant] 747 B.CreateMemCpy(Dst, Src, 748 ConstantInt::get(TD->getIntPtrType(PT), Len), 1); 749 750 return Dst; 751 } 752 }; 753 754 struct StrLenOpt : public LibCallOptimization { 755 virtual bool ignoreCallingConv() { return true; } 756 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 757 FunctionType *FT = Callee->getFunctionType(); 758 if (FT->getNumParams() != 1 || 759 FT->getParamType(0) != B.getInt8PtrTy() || 760 !FT->getReturnType()->isIntegerTy()) 761 return 0; 762 763 Value *Src = CI->getArgOperand(0); 764 765 // Constant folding: strlen("xyz") -> 3 766 if (uint64_t Len = GetStringLength(Src)) 767 return ConstantInt::get(CI->getType(), Len-1); 768 769 // strlen(x) != 0 --> *x != 0 770 // strlen(x) == 0 --> *x == 0 771 if (isOnlyUsedInZeroEqualityComparison(CI)) 772 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType()); 773 return 0; 774 } 775 }; 776 777 struct StrPBrkOpt : public LibCallOptimization { 778 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 779 FunctionType *FT = Callee->getFunctionType(); 780 if (FT->getNumParams() != 2 || 781 FT->getParamType(0) != B.getInt8PtrTy() || 782 FT->getParamType(1) != FT->getParamType(0) || 783 FT->getReturnType() != FT->getParamType(0)) 784 return 0; 785 786 StringRef S1, S2; 787 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 788 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 789 790 // strpbrk(s, "") -> NULL 791 // strpbrk("", s) -> NULL 792 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 793 return Constant::getNullValue(CI->getType()); 794 795 // Constant folding. 796 if (HasS1 && HasS2) { 797 size_t I = S1.find_first_of(S2); 798 if (I == StringRef::npos) // No match. 799 return Constant::getNullValue(CI->getType()); 800 801 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk"); 802 } 803 804 // strpbrk(s, "a") -> strchr(s, 'a') 805 if (TD && HasS2 && S2.size() == 1) 806 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI); 807 808 return 0; 809 } 810 }; 811 812 struct StrToOpt : public LibCallOptimization { 813 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 814 FunctionType *FT = Callee->getFunctionType(); 815 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) || 816 !FT->getParamType(0)->isPointerTy() || 817 !FT->getParamType(1)->isPointerTy()) 818 return 0; 819 820 Value *EndPtr = CI->getArgOperand(1); 821 if (isa<ConstantPointerNull>(EndPtr)) { 822 // With a null EndPtr, this function won't capture the main argument. 823 // It would be readonly too, except that it still may write to errno. 824 CI->addAttribute(1, Attribute::NoCapture); 825 } 826 827 return 0; 828 } 829 }; 830 831 struct StrSpnOpt : public LibCallOptimization { 832 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 833 FunctionType *FT = Callee->getFunctionType(); 834 if (FT->getNumParams() != 2 || 835 FT->getParamType(0) != B.getInt8PtrTy() || 836 FT->getParamType(1) != FT->getParamType(0) || 837 !FT->getReturnType()->isIntegerTy()) 838 return 0; 839 840 StringRef S1, S2; 841 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 842 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 843 844 // strspn(s, "") -> 0 845 // strspn("", s) -> 0 846 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 847 return Constant::getNullValue(CI->getType()); 848 849 // Constant folding. 850 if (HasS1 && HasS2) { 851 size_t Pos = S1.find_first_not_of(S2); 852 if (Pos == StringRef::npos) Pos = S1.size(); 853 return ConstantInt::get(CI->getType(), Pos); 854 } 855 856 return 0; 857 } 858 }; 859 860 struct StrCSpnOpt : public LibCallOptimization { 861 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 862 FunctionType *FT = Callee->getFunctionType(); 863 if (FT->getNumParams() != 2 || 864 FT->getParamType(0) != B.getInt8PtrTy() || 865 FT->getParamType(1) != FT->getParamType(0) || 866 !FT->getReturnType()->isIntegerTy()) 867 return 0; 868 869 StringRef S1, S2; 870 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 871 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 872 873 // strcspn("", s) -> 0 874 if (HasS1 && S1.empty()) 875 return Constant::getNullValue(CI->getType()); 876 877 // Constant folding. 878 if (HasS1 && HasS2) { 879 size_t Pos = S1.find_first_of(S2); 880 if (Pos == StringRef::npos) Pos = S1.size(); 881 return ConstantInt::get(CI->getType(), Pos); 882 } 883 884 // strcspn(s, "") -> strlen(s) 885 if (TD && HasS2 && S2.empty()) 886 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI); 887 888 return 0; 889 } 890 }; 891 892 struct StrStrOpt : public LibCallOptimization { 893 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 894 FunctionType *FT = Callee->getFunctionType(); 895 if (FT->getNumParams() != 2 || 896 !FT->getParamType(0)->isPointerTy() || 897 !FT->getParamType(1)->isPointerTy() || 898 !FT->getReturnType()->isPointerTy()) 899 return 0; 900 901 // fold strstr(x, x) -> x. 902 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 903 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 904 905 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 906 if (TD && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 907 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI); 908 if (!StrLen) 909 return 0; 910 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 911 StrLen, B, TD, TLI); 912 if (!StrNCmp) 913 return 0; 914 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end(); 915 UI != UE; ) { 916 ICmpInst *Old = cast<ICmpInst>(*UI++); 917 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp, 918 ConstantInt::getNullValue(StrNCmp->getType()), 919 "cmp"); 920 LCS->replaceAllUsesWith(Old, Cmp); 921 } 922 return CI; 923 } 924 925 // See if either input string is a constant string. 926 StringRef SearchStr, ToFindStr; 927 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 928 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 929 930 // fold strstr(x, "") -> x. 931 if (HasStr2 && ToFindStr.empty()) 932 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 933 934 // If both strings are known, constant fold it. 935 if (HasStr1 && HasStr2) { 936 size_t Offset = SearchStr.find(ToFindStr); 937 938 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 939 return Constant::getNullValue(CI->getType()); 940 941 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 942 Value *Result = CastToCStr(CI->getArgOperand(0), B); 943 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr"); 944 return B.CreateBitCast(Result, CI->getType()); 945 } 946 947 // fold strstr(x, "y") -> strchr(x, 'y'). 948 if (HasStr2 && ToFindStr.size() == 1) { 949 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI); 950 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0; 951 } 952 return 0; 953 } 954 }; 955 956 struct MemCmpOpt : public LibCallOptimization { 957 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 958 FunctionType *FT = Callee->getFunctionType(); 959 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() || 960 !FT->getParamType(1)->isPointerTy() || 961 !FT->getReturnType()->isIntegerTy(32)) 962 return 0; 963 964 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 965 966 if (LHS == RHS) // memcmp(s,s,x) -> 0 967 return Constant::getNullValue(CI->getType()); 968 969 // Make sure we have a constant length. 970 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 971 if (!LenC) return 0; 972 uint64_t Len = LenC->getZExtValue(); 973 974 if (Len == 0) // memcmp(s1,s2,0) -> 0 975 return Constant::getNullValue(CI->getType()); 976 977 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 978 if (Len == 1) { 979 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"), 980 CI->getType(), "lhsv"); 981 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"), 982 CI->getType(), "rhsv"); 983 return B.CreateSub(LHSV, RHSV, "chardiff"); 984 } 985 986 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant) 987 StringRef LHSStr, RHSStr; 988 if (getConstantStringInfo(LHS, LHSStr) && 989 getConstantStringInfo(RHS, RHSStr)) { 990 // Make sure we're not reading out-of-bounds memory. 991 if (Len > LHSStr.size() || Len > RHSStr.size()) 992 return 0; 993 // Fold the memcmp and normalize the result. This way we get consistent 994 // results across multiple platforms. 995 uint64_t Ret = 0; 996 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len); 997 if (Cmp < 0) 998 Ret = -1; 999 else if (Cmp > 0) 1000 Ret = 1; 1001 return ConstantInt::get(CI->getType(), Ret); 1002 } 1003 1004 return 0; 1005 } 1006 }; 1007 1008 struct MemCpyOpt : public LibCallOptimization { 1009 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1010 // These optimizations require DataLayout. 1011 if (!TD) return 0; 1012 1013 FunctionType *FT = Callee->getFunctionType(); 1014 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) || 1015 !FT->getParamType(0)->isPointerTy() || 1016 !FT->getParamType(1)->isPointerTy() || 1017 FT->getParamType(2) != TD->getIntPtrType(*Context)) 1018 return 0; 1019 1020 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1) 1021 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 1022 CI->getArgOperand(2), 1); 1023 return CI->getArgOperand(0); 1024 } 1025 }; 1026 1027 struct MemMoveOpt : public LibCallOptimization { 1028 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1029 // These optimizations require DataLayout. 1030 if (!TD) return 0; 1031 1032 FunctionType *FT = Callee->getFunctionType(); 1033 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) || 1034 !FT->getParamType(0)->isPointerTy() || 1035 !FT->getParamType(1)->isPointerTy() || 1036 FT->getParamType(2) != TD->getIntPtrType(*Context)) 1037 return 0; 1038 1039 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1) 1040 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1), 1041 CI->getArgOperand(2), 1); 1042 return CI->getArgOperand(0); 1043 } 1044 }; 1045 1046 struct MemSetOpt : public LibCallOptimization { 1047 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1048 // These optimizations require DataLayout. 1049 if (!TD) return 0; 1050 1051 FunctionType *FT = Callee->getFunctionType(); 1052 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) || 1053 !FT->getParamType(0)->isPointerTy() || 1054 !FT->getParamType(1)->isIntegerTy() || 1055 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0))) 1056 return 0; 1057 1058 // memset(p, v, n) -> llvm.memset(p, v, n, 1) 1059 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 1060 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1); 1061 return CI->getArgOperand(0); 1062 } 1063 }; 1064 1065 //===----------------------------------------------------------------------===// 1066 // Math Library Optimizations 1067 //===----------------------------------------------------------------------===// 1068 1069 //===----------------------------------------------------------------------===// 1070 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor' 1071 1072 struct UnaryDoubleFPOpt : public LibCallOptimization { 1073 bool CheckRetType; 1074 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {} 1075 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1076 FunctionType *FT = Callee->getFunctionType(); 1077 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() || 1078 !FT->getParamType(0)->isDoubleTy()) 1079 return 0; 1080 1081 if (CheckRetType) { 1082 // Check if all the uses for function like 'sin' are converted to float. 1083 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end(); 1084 ++UseI) { 1085 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI); 1086 if (Cast == 0 || !Cast->getType()->isFloatTy()) 1087 return 0; 1088 } 1089 } 1090 1091 // If this is something like 'floor((double)floatval)', convert to floorf. 1092 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0)); 1093 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy()) 1094 return 0; 1095 1096 // floor((double)floatval) -> (double)floorf(floatval) 1097 Value *V = Cast->getOperand(0); 1098 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes()); 1099 return B.CreateFPExt(V, B.getDoubleTy()); 1100 } 1101 }; 1102 1103 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax' 1104 struct BinaryDoubleFPOpt : public LibCallOptimization { 1105 bool CheckRetType; 1106 BinaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {} 1107 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1108 FunctionType *FT = Callee->getFunctionType(); 1109 // Just make sure this has 2 arguments of the same FP type, which match the 1110 // result type. 1111 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) || 1112 FT->getParamType(0) != FT->getParamType(1) || 1113 !FT->getParamType(0)->isFloatingPointTy()) 1114 return 0; 1115 1116 if (CheckRetType) { 1117 // Check if all the uses for function like 'fmin/fmax' are converted to 1118 // float. 1119 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end(); 1120 ++UseI) { 1121 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI); 1122 if (Cast == 0 || !Cast->getType()->isFloatTy()) 1123 return 0; 1124 } 1125 } 1126 1127 // If this is something like 'fmin((double)floatval1, (double)floatval2)', 1128 // we convert it to fminf. 1129 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0)); 1130 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1)); 1131 if (Cast1 == 0 || !Cast1->getOperand(0)->getType()->isFloatTy() || 1132 Cast2 == 0 || !Cast2->getOperand(0)->getType()->isFloatTy()) 1133 return 0; 1134 1135 // fmin((double)floatval1, (double)floatval2) 1136 // -> (double)fmin(floatval1, floatval2) 1137 Value *V = NULL; 1138 Value *V1 = Cast1->getOperand(0); 1139 Value *V2 = Cast2->getOperand(0); 1140 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B, 1141 Callee->getAttributes()); 1142 return B.CreateFPExt(V, B.getDoubleTy()); 1143 } 1144 }; 1145 1146 struct UnsafeFPLibCallOptimization : public LibCallOptimization { 1147 bool UnsafeFPShrink; 1148 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) { 1149 this->UnsafeFPShrink = UnsafeFPShrink; 1150 } 1151 }; 1152 1153 struct CosOpt : public UnsafeFPLibCallOptimization { 1154 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {} 1155 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1156 Value *Ret = NULL; 1157 if (UnsafeFPShrink && Callee->getName() == "cos" && 1158 TLI->has(LibFunc::cosf)) { 1159 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true); 1160 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B); 1161 } 1162 1163 FunctionType *FT = Callee->getFunctionType(); 1164 // Just make sure this has 1 argument of FP type, which matches the 1165 // result type. 1166 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1167 !FT->getParamType(0)->isFloatingPointTy()) 1168 return Ret; 1169 1170 // cos(-x) -> cos(x) 1171 Value *Op1 = CI->getArgOperand(0); 1172 if (BinaryOperator::isFNeg(Op1)) { 1173 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1); 1174 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos"); 1175 } 1176 return Ret; 1177 } 1178 }; 1179 1180 struct PowOpt : public UnsafeFPLibCallOptimization { 1181 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {} 1182 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1183 Value *Ret = NULL; 1184 if (UnsafeFPShrink && Callee->getName() == "pow" && 1185 TLI->has(LibFunc::powf)) { 1186 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true); 1187 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B); 1188 } 1189 1190 FunctionType *FT = Callee->getFunctionType(); 1191 // Just make sure this has 2 arguments of the same FP type, which match the 1192 // result type. 1193 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) || 1194 FT->getParamType(0) != FT->getParamType(1) || 1195 !FT->getParamType(0)->isFloatingPointTy()) 1196 return Ret; 1197 1198 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1); 1199 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) { 1200 // pow(1.0, x) -> 1.0 1201 if (Op1C->isExactlyValue(1.0)) 1202 return Op1C; 1203 // pow(2.0, x) -> exp2(x) 1204 if (Op1C->isExactlyValue(2.0) && 1205 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f, 1206 LibFunc::exp2l)) 1207 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes()); 1208 // pow(10.0, x) -> exp10(x) 1209 if (Op1C->isExactlyValue(10.0) && 1210 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f, 1211 LibFunc::exp10l)) 1212 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B, 1213 Callee->getAttributes()); 1214 } 1215 1216 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2); 1217 if (Op2C == 0) return Ret; 1218 1219 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0 1220 return ConstantFP::get(CI->getType(), 1.0); 1221 1222 if (Op2C->isExactlyValue(0.5) && 1223 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf, 1224 LibFunc::sqrtl) && 1225 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf, 1226 LibFunc::fabsl)) { 1227 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))). 1228 // This is faster than calling pow, and still handles negative zero 1229 // and negative infinity correctly. 1230 // TODO: In fast-math mode, this could be just sqrt(x). 1231 // TODO: In finite-only mode, this could be just fabs(sqrt(x)). 1232 Value *Inf = ConstantFP::getInfinity(CI->getType()); 1233 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true); 1234 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, 1235 Callee->getAttributes()); 1236 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B, 1237 Callee->getAttributes()); 1238 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf); 1239 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs); 1240 return Sel; 1241 } 1242 1243 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x 1244 return Op1; 1245 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x 1246 return B.CreateFMul(Op1, Op1, "pow2"); 1247 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x 1248 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), 1249 Op1, "powrecip"); 1250 return 0; 1251 } 1252 }; 1253 1254 struct Exp2Opt : public UnsafeFPLibCallOptimization { 1255 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {} 1256 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1257 Value *Ret = NULL; 1258 if (UnsafeFPShrink && Callee->getName() == "exp2" && 1259 TLI->has(LibFunc::exp2f)) { 1260 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true); 1261 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B); 1262 } 1263 1264 FunctionType *FT = Callee->getFunctionType(); 1265 // Just make sure this has 1 argument of FP type, which matches the 1266 // result type. 1267 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1268 !FT->getParamType(0)->isFloatingPointTy()) 1269 return Ret; 1270 1271 Value *Op = CI->getArgOperand(0); 1272 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32 1273 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32 1274 Value *LdExpArg = 0; 1275 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) { 1276 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32) 1277 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty()); 1278 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) { 1279 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32) 1280 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty()); 1281 } 1282 1283 if (LdExpArg) { 1284 const char *Name; 1285 if (Op->getType()->isFloatTy()) 1286 Name = "ldexpf"; 1287 else if (Op->getType()->isDoubleTy()) 1288 Name = "ldexp"; 1289 else 1290 Name = "ldexpl"; 1291 1292 Constant *One = ConstantFP::get(*Context, APFloat(1.0f)); 1293 if (!Op->getType()->isFloatTy()) 1294 One = ConstantExpr::getFPExtend(One, Op->getType()); 1295 1296 Module *M = Caller->getParent(); 1297 Value *Callee = M->getOrInsertFunction(Name, Op->getType(), 1298 Op->getType(), 1299 B.getInt32Ty(), NULL); 1300 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg); 1301 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) 1302 CI->setCallingConv(F->getCallingConv()); 1303 1304 return CI; 1305 } 1306 return Ret; 1307 } 1308 }; 1309 1310 struct SinCosPiOpt : public LibCallOptimization { 1311 SinCosPiOpt() {} 1312 1313 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1314 // Make sure the prototype is as expected, otherwise the rest of the 1315 // function is probably invalid and likely to abort. 1316 if (!isTrigLibCall(CI)) 1317 return 0; 1318 1319 Value *Arg = CI->getArgOperand(0); 1320 SmallVector<CallInst *, 1> SinCalls; 1321 SmallVector<CallInst *, 1> CosCalls; 1322 SmallVector<CallInst *, 1> SinCosCalls; 1323 1324 bool IsFloat = Arg->getType()->isFloatTy(); 1325 1326 // Look for all compatible sinpi, cospi and sincospi calls with the same 1327 // argument. If there are enough (in some sense) we can make the 1328 // substitution. 1329 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); 1330 UI != UE; ++UI) 1331 classifyArgUse(*UI, CI->getParent(), IsFloat, SinCalls, CosCalls, 1332 SinCosCalls); 1333 1334 // It's only worthwhile if both sinpi and cospi are actually used. 1335 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty())) 1336 return 0; 1337 1338 Value *Sin, *Cos, *SinCos; 1339 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, 1340 SinCos); 1341 1342 replaceTrigInsts(SinCalls, Sin); 1343 replaceTrigInsts(CosCalls, Cos); 1344 replaceTrigInsts(SinCosCalls, SinCos); 1345 1346 return 0; 1347 } 1348 1349 bool isTrigLibCall(CallInst *CI) { 1350 Function *Callee = CI->getCalledFunction(); 1351 FunctionType *FT = Callee->getFunctionType(); 1352 1353 // We can only hope to do anything useful if we can ignore things like errno 1354 // and floating-point exceptions. 1355 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) && 1356 CI->hasFnAttr(Attribute::ReadNone); 1357 1358 // Other than that we need float(float) or double(double) 1359 return AttributesSafe && FT->getNumParams() == 1 && 1360 FT->getReturnType() == FT->getParamType(0) && 1361 (FT->getParamType(0)->isFloatTy() || 1362 FT->getParamType(0)->isDoubleTy()); 1363 } 1364 1365 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat, 1366 SmallVectorImpl<CallInst *> &SinCalls, 1367 SmallVectorImpl<CallInst *> &CosCalls, 1368 SmallVectorImpl<CallInst *> &SinCosCalls) { 1369 CallInst *CI = dyn_cast<CallInst>(Val); 1370 1371 if (!CI) 1372 return; 1373 1374 Function *Callee = CI->getCalledFunction(); 1375 StringRef FuncName = Callee->getName(); 1376 LibFunc::Func Func; 1377 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || 1378 !isTrigLibCall(CI)) 1379 return; 1380 1381 if (IsFloat) { 1382 if (Func == LibFunc::sinpif) 1383 SinCalls.push_back(CI); 1384 else if (Func == LibFunc::cospif) 1385 CosCalls.push_back(CI); 1386 else if (Func == LibFunc::sincospi_stretf) 1387 SinCosCalls.push_back(CI); 1388 } else { 1389 if (Func == LibFunc::sinpi) 1390 SinCalls.push_back(CI); 1391 else if (Func == LibFunc::cospi) 1392 CosCalls.push_back(CI); 1393 else if (Func == LibFunc::sincospi_stret) 1394 SinCosCalls.push_back(CI); 1395 } 1396 } 1397 1398 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) { 1399 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(), 1400 E = Calls.end(); 1401 I != E; ++I) { 1402 LCS->replaceAllUsesWith(*I, Res); 1403 } 1404 } 1405 1406 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, 1407 bool UseFloat, Value *&Sin, Value *&Cos, 1408 Value *&SinCos) { 1409 Type *ArgTy = Arg->getType(); 1410 Type *ResTy; 1411 StringRef Name; 1412 1413 Triple T(OrigCallee->getParent()->getTargetTriple()); 1414 if (UseFloat) { 1415 Name = "__sincospi_stretf"; 1416 1417 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 1418 // x86_64 can't use {float, float} since that would be returned in both 1419 // xmm0 and xmm1, which isn't what a real struct would do. 1420 ResTy = T.getArch() == Triple::x86_64 1421 ? static_cast<Type *>(VectorType::get(ArgTy, 2)) 1422 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL)); 1423 } else { 1424 Name = "__sincospi_stret"; 1425 ResTy = StructType::get(ArgTy, ArgTy, NULL); 1426 } 1427 1428 Module *M = OrigCallee->getParent(); 1429 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(), 1430 ResTy, ArgTy, NULL); 1431 1432 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 1433 // If the argument is an instruction, it must dominate all uses so put our 1434 // sincos call there. 1435 BasicBlock::iterator Loc = ArgInst; 1436 B.SetInsertPoint(ArgInst->getParent(), ++Loc); 1437 } else { 1438 // Otherwise (e.g. for a constant) the beginning of the function is as 1439 // good a place as any. 1440 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 1441 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 1442 } 1443 1444 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 1445 1446 if (SinCos->getType()->isStructTy()) { 1447 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 1448 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 1449 } else { 1450 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 1451 "sinpi"); 1452 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 1453 "cospi"); 1454 } 1455 } 1456 1457 }; 1458 1459 //===----------------------------------------------------------------------===// 1460 // Integer Library Call Optimizations 1461 //===----------------------------------------------------------------------===// 1462 1463 struct FFSOpt : public LibCallOptimization { 1464 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1465 FunctionType *FT = Callee->getFunctionType(); 1466 // Just make sure this has 2 arguments of the same FP type, which match the 1467 // result type. 1468 if (FT->getNumParams() != 1 || 1469 !FT->getReturnType()->isIntegerTy(32) || 1470 !FT->getParamType(0)->isIntegerTy()) 1471 return 0; 1472 1473 Value *Op = CI->getArgOperand(0); 1474 1475 // Constant fold. 1476 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 1477 if (CI->isZero()) // ffs(0) -> 0. 1478 return B.getInt32(0); 1479 // ffs(c) -> cttz(c)+1 1480 return B.getInt32(CI->getValue().countTrailingZeros() + 1); 1481 } 1482 1483 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 1484 Type *ArgType = Op->getType(); 1485 Value *F = Intrinsic::getDeclaration(Callee->getParent(), 1486 Intrinsic::cttz, ArgType); 1487 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz"); 1488 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 1489 V = B.CreateIntCast(V, B.getInt32Ty(), false); 1490 1491 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 1492 return B.CreateSelect(Cond, V, B.getInt32(0)); 1493 } 1494 }; 1495 1496 struct AbsOpt : public LibCallOptimization { 1497 virtual bool ignoreCallingConv() { return true; } 1498 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1499 FunctionType *FT = Callee->getFunctionType(); 1500 // We require integer(integer) where the types agree. 1501 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() || 1502 FT->getParamType(0) != FT->getReturnType()) 1503 return 0; 1504 1505 // abs(x) -> x >s -1 ? x : -x 1506 Value *Op = CI->getArgOperand(0); 1507 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), 1508 "ispos"); 1509 Value *Neg = B.CreateNeg(Op, "neg"); 1510 return B.CreateSelect(Pos, Op, Neg); 1511 } 1512 }; 1513 1514 struct IsDigitOpt : public LibCallOptimization { 1515 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1516 FunctionType *FT = Callee->getFunctionType(); 1517 // We require integer(i32) 1518 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() || 1519 !FT->getParamType(0)->isIntegerTy(32)) 1520 return 0; 1521 1522 // isdigit(c) -> (c-'0') <u 10 1523 Value *Op = CI->getArgOperand(0); 1524 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp"); 1525 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit"); 1526 return B.CreateZExt(Op, CI->getType()); 1527 } 1528 }; 1529 1530 struct IsAsciiOpt : public LibCallOptimization { 1531 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1532 FunctionType *FT = Callee->getFunctionType(); 1533 // We require integer(i32) 1534 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() || 1535 !FT->getParamType(0)->isIntegerTy(32)) 1536 return 0; 1537 1538 // isascii(c) -> c <u 128 1539 Value *Op = CI->getArgOperand(0); 1540 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii"); 1541 return B.CreateZExt(Op, CI->getType()); 1542 } 1543 }; 1544 1545 struct ToAsciiOpt : public LibCallOptimization { 1546 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1547 FunctionType *FT = Callee->getFunctionType(); 1548 // We require i32(i32) 1549 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1550 !FT->getParamType(0)->isIntegerTy(32)) 1551 return 0; 1552 1553 // toascii(c) -> c & 0x7f 1554 return B.CreateAnd(CI->getArgOperand(0), 1555 ConstantInt::get(CI->getType(),0x7F)); 1556 } 1557 }; 1558 1559 //===----------------------------------------------------------------------===// 1560 // Formatting and IO Library Call Optimizations 1561 //===----------------------------------------------------------------------===// 1562 1563 struct ErrorReportingOpt : public LibCallOptimization { 1564 ErrorReportingOpt(int S = -1) : StreamArg(S) {} 1565 1566 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &) { 1567 // Error reporting calls should be cold, mark them as such. 1568 // This applies even to non-builtin calls: it is only a hint and applies to 1569 // functions that the frontend might not understand as builtins. 1570 1571 // This heuristic was suggested in: 1572 // Improving Static Branch Prediction in a Compiler 1573 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 1574 // Proceedings of PACT'98, Oct. 1998, IEEE 1575 1576 if (!CI->hasFnAttr(Attribute::Cold) && isReportingError(Callee, CI)) { 1577 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold); 1578 } 1579 1580 return 0; 1581 } 1582 1583 protected: 1584 bool isReportingError(Function *Callee, CallInst *CI) { 1585 if (!ColdErrorCalls) 1586 return false; 1587 1588 if (!Callee || !Callee->isDeclaration()) 1589 return false; 1590 1591 if (StreamArg < 0) 1592 return true; 1593 1594 // These functions might be considered cold, but only if their stream 1595 // argument is stderr. 1596 1597 if (StreamArg >= (int) CI->getNumArgOperands()) 1598 return false; 1599 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 1600 if (!LI) 1601 return false; 1602 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 1603 if (!GV || !GV->isDeclaration()) 1604 return false; 1605 return GV->getName() == "stderr"; 1606 } 1607 1608 int StreamArg; 1609 }; 1610 1611 struct PrintFOpt : public LibCallOptimization { 1612 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI, 1613 IRBuilder<> &B) { 1614 // Check for a fixed format string. 1615 StringRef FormatStr; 1616 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 1617 return 0; 1618 1619 // Empty format string -> noop. 1620 if (FormatStr.empty()) // Tolerate printf's declared void. 1621 return CI->use_empty() ? (Value*)CI : 1622 ConstantInt::get(CI->getType(), 0); 1623 1624 // Do not do any of the following transformations if the printf return value 1625 // is used, in general the printf return value is not compatible with either 1626 // putchar() or puts(). 1627 if (!CI->use_empty()) 1628 return 0; 1629 1630 // printf("x") -> putchar('x'), even for '%'. 1631 if (FormatStr.size() == 1) { 1632 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI); 1633 if (CI->use_empty() || !Res) return Res; 1634 return B.CreateIntCast(Res, CI->getType(), true); 1635 } 1636 1637 // printf("foo\n") --> puts("foo") 1638 if (FormatStr[FormatStr.size()-1] == '\n' && 1639 FormatStr.find('%') == StringRef::npos) { // No format characters. 1640 // Create a string literal with no \n on it. We expect the constant merge 1641 // pass to be run after this pass, to merge duplicate strings. 1642 FormatStr = FormatStr.drop_back(); 1643 Value *GV = B.CreateGlobalString(FormatStr, "str"); 1644 Value *NewCI = EmitPutS(GV, B, TD, TLI); 1645 return (CI->use_empty() || !NewCI) ? 1646 NewCI : 1647 ConstantInt::get(CI->getType(), FormatStr.size()+1); 1648 } 1649 1650 // Optimize specific format strings. 1651 // printf("%c", chr) --> putchar(chr) 1652 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 && 1653 CI->getArgOperand(1)->getType()->isIntegerTy()) { 1654 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI); 1655 1656 if (CI->use_empty() || !Res) return Res; 1657 return B.CreateIntCast(Res, CI->getType(), true); 1658 } 1659 1660 // printf("%s\n", str) --> puts(str) 1661 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 && 1662 CI->getArgOperand(1)->getType()->isPointerTy()) { 1663 return EmitPutS(CI->getArgOperand(1), B, TD, TLI); 1664 } 1665 return 0; 1666 } 1667 1668 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1669 // Require one fixed pointer argument and an integer/void result. 1670 FunctionType *FT = Callee->getFunctionType(); 1671 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() || 1672 !(FT->getReturnType()->isIntegerTy() || 1673 FT->getReturnType()->isVoidTy())) 1674 return 0; 1675 1676 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) { 1677 return V; 1678 } 1679 1680 // printf(format, ...) -> iprintf(format, ...) if no floating point 1681 // arguments. 1682 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) { 1683 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1684 Constant *IPrintFFn = 1685 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes()); 1686 CallInst *New = cast<CallInst>(CI->clone()); 1687 New->setCalledFunction(IPrintFFn); 1688 B.Insert(New); 1689 return New; 1690 } 1691 return 0; 1692 } 1693 }; 1694 1695 struct SPrintFOpt : public LibCallOptimization { 1696 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI, 1697 IRBuilder<> &B) { 1698 // Check for a fixed format string. 1699 StringRef FormatStr; 1700 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 1701 return 0; 1702 1703 // If we just have a format string (nothing else crazy) transform it. 1704 if (CI->getNumArgOperands() == 2) { 1705 // Make sure there's no % in the constant array. We could try to handle 1706 // %% -> % in the future if we cared. 1707 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 1708 if (FormatStr[i] == '%') 1709 return 0; // we found a format specifier, bail out. 1710 1711 // These optimizations require DataLayout. 1712 if (!TD) return 0; 1713 1714 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1) 1715 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 1716 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the 1717 FormatStr.size() + 1), 1); // nul byte. 1718 return ConstantInt::get(CI->getType(), FormatStr.size()); 1719 } 1720 1721 // The remaining optimizations require the format string to be "%s" or "%c" 1722 // and have an extra operand. 1723 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 1724 CI->getNumArgOperands() < 3) 1725 return 0; 1726 1727 // Decode the second character of the format string. 1728 if (FormatStr[1] == 'c') { 1729 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 1730 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0; 1731 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 1732 Value *Ptr = CastToCStr(CI->getArgOperand(0), B); 1733 B.CreateStore(V, Ptr); 1734 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul"); 1735 B.CreateStore(B.getInt8(0), Ptr); 1736 1737 return ConstantInt::get(CI->getType(), 1); 1738 } 1739 1740 if (FormatStr[1] == 's') { 1741 // These optimizations require DataLayout. 1742 if (!TD) return 0; 1743 1744 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1) 1745 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0; 1746 1747 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI); 1748 if (!Len) 1749 return 0; 1750 Value *IncLen = B.CreateAdd(Len, 1751 ConstantInt::get(Len->getType(), 1), 1752 "leninc"); 1753 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1); 1754 1755 // The sprintf result is the unincremented number of bytes in the string. 1756 return B.CreateIntCast(Len, CI->getType(), false); 1757 } 1758 return 0; 1759 } 1760 1761 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1762 // Require two fixed pointer arguments and an integer result. 1763 FunctionType *FT = Callee->getFunctionType(); 1764 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() || 1765 !FT->getParamType(1)->isPointerTy() || 1766 !FT->getReturnType()->isIntegerTy()) 1767 return 0; 1768 1769 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) { 1770 return V; 1771 } 1772 1773 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 1774 // point arguments. 1775 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) { 1776 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1777 Constant *SIPrintFFn = 1778 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes()); 1779 CallInst *New = cast<CallInst>(CI->clone()); 1780 New->setCalledFunction(SIPrintFFn); 1781 B.Insert(New); 1782 return New; 1783 } 1784 return 0; 1785 } 1786 }; 1787 1788 struct FPrintFOpt : public LibCallOptimization { 1789 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI, 1790 IRBuilder<> &B) { 1791 ErrorReportingOpt ER(/* StreamArg = */ 0); 1792 (void) ER.callOptimizer(Callee, CI, B); 1793 1794 // All the optimizations depend on the format string. 1795 StringRef FormatStr; 1796 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 1797 return 0; 1798 1799 // Do not do any of the following transformations if the fprintf return 1800 // value is used, in general the fprintf return value is not compatible 1801 // with fwrite(), fputc() or fputs(). 1802 if (!CI->use_empty()) 1803 return 0; 1804 1805 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 1806 if (CI->getNumArgOperands() == 2) { 1807 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 1808 if (FormatStr[i] == '%') // Could handle %% -> % if we cared. 1809 return 0; // We found a format specifier. 1810 1811 // These optimizations require DataLayout. 1812 if (!TD) return 0; 1813 1814 return EmitFWrite(CI->getArgOperand(1), 1815 ConstantInt::get(TD->getIntPtrType(*Context), 1816 FormatStr.size()), 1817 CI->getArgOperand(0), B, TD, TLI); 1818 } 1819 1820 // The remaining optimizations require the format string to be "%s" or "%c" 1821 // and have an extra operand. 1822 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 1823 CI->getNumArgOperands() < 3) 1824 return 0; 1825 1826 // Decode the second character of the format string. 1827 if (FormatStr[1] == 'c') { 1828 // fprintf(F, "%c", chr) --> fputc(chr, F) 1829 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0; 1830 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI); 1831 } 1832 1833 if (FormatStr[1] == 's') { 1834 // fprintf(F, "%s", str) --> fputs(str, F) 1835 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 1836 return 0; 1837 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI); 1838 } 1839 return 0; 1840 } 1841 1842 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1843 // Require two fixed paramters as pointers and integer result. 1844 FunctionType *FT = Callee->getFunctionType(); 1845 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() || 1846 !FT->getParamType(1)->isPointerTy() || 1847 !FT->getReturnType()->isIntegerTy()) 1848 return 0; 1849 1850 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) { 1851 return V; 1852 } 1853 1854 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 1855 // floating point arguments. 1856 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) { 1857 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1858 Constant *FIPrintFFn = 1859 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes()); 1860 CallInst *New = cast<CallInst>(CI->clone()); 1861 New->setCalledFunction(FIPrintFFn); 1862 B.Insert(New); 1863 return New; 1864 } 1865 return 0; 1866 } 1867 }; 1868 1869 struct FWriteOpt : public LibCallOptimization { 1870 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1871 ErrorReportingOpt ER(/* StreamArg = */ 3); 1872 (void) ER.callOptimizer(Callee, CI, B); 1873 1874 // Require a pointer, an integer, an integer, a pointer, returning integer. 1875 FunctionType *FT = Callee->getFunctionType(); 1876 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() || 1877 !FT->getParamType(1)->isIntegerTy() || 1878 !FT->getParamType(2)->isIntegerTy() || 1879 !FT->getParamType(3)->isPointerTy() || 1880 !FT->getReturnType()->isIntegerTy()) 1881 return 0; 1882 1883 // Get the element size and count. 1884 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 1885 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 1886 if (!SizeC || !CountC) return 0; 1887 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue(); 1888 1889 // If this is writing zero records, remove the call (it's a noop). 1890 if (Bytes == 0) 1891 return ConstantInt::get(CI->getType(), 0); 1892 1893 // If this is writing one byte, turn it into fputc. 1894 // This optimisation is only valid, if the return value is unused. 1895 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 1896 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char"); 1897 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI); 1898 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0; 1899 } 1900 1901 return 0; 1902 } 1903 }; 1904 1905 struct FPutsOpt : public LibCallOptimization { 1906 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1907 ErrorReportingOpt ER(/* StreamArg = */ 1); 1908 (void) ER.callOptimizer(Callee, CI, B); 1909 1910 // These optimizations require DataLayout. 1911 if (!TD) return 0; 1912 1913 // Require two pointers. Also, we can't optimize if return value is used. 1914 FunctionType *FT = Callee->getFunctionType(); 1915 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() || 1916 !FT->getParamType(1)->isPointerTy() || 1917 !CI->use_empty()) 1918 return 0; 1919 1920 // fputs(s,F) --> fwrite(s,1,strlen(s),F) 1921 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 1922 if (!Len) return 0; 1923 // Known to have no uses (see above). 1924 return EmitFWrite(CI->getArgOperand(0), 1925 ConstantInt::get(TD->getIntPtrType(*Context), Len-1), 1926 CI->getArgOperand(1), B, TD, TLI); 1927 } 1928 }; 1929 1930 struct PutsOpt : public LibCallOptimization { 1931 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) { 1932 // Require one fixed pointer argument and an integer/void result. 1933 FunctionType *FT = Callee->getFunctionType(); 1934 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() || 1935 !(FT->getReturnType()->isIntegerTy() || 1936 FT->getReturnType()->isVoidTy())) 1937 return 0; 1938 1939 // Check for a constant string. 1940 StringRef Str; 1941 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 1942 return 0; 1943 1944 if (Str.empty() && CI->use_empty()) { 1945 // puts("") -> putchar('\n') 1946 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI); 1947 if (CI->use_empty() || !Res) return Res; 1948 return B.CreateIntCast(Res, CI->getType(), true); 1949 } 1950 1951 return 0; 1952 } 1953 }; 1954 1955 } // End anonymous namespace. 1956 1957 namespace llvm { 1958 1959 class LibCallSimplifierImpl { 1960 const DataLayout *TD; 1961 const TargetLibraryInfo *TLI; 1962 const LibCallSimplifier *LCS; 1963 bool UnsafeFPShrink; 1964 1965 // Math library call optimizations. 1966 CosOpt Cos; 1967 PowOpt Pow; 1968 Exp2Opt Exp2; 1969 public: 1970 LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI, 1971 const LibCallSimplifier *LCS, 1972 bool UnsafeFPShrink = false) 1973 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) { 1974 this->TD = TD; 1975 this->TLI = TLI; 1976 this->LCS = LCS; 1977 this->UnsafeFPShrink = UnsafeFPShrink; 1978 } 1979 1980 Value *optimizeCall(CallInst *CI); 1981 LibCallOptimization *lookupOptimization(CallInst *CI); 1982 bool hasFloatVersion(StringRef FuncName); 1983 }; 1984 1985 bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) { 1986 LibFunc::Func Func; 1987 SmallString<20> FloatFuncName = FuncName; 1988 FloatFuncName += 'f'; 1989 if (TLI->getLibFunc(FloatFuncName, Func)) 1990 return TLI->has(Func); 1991 return false; 1992 } 1993 1994 // Fortified library call optimizations. 1995 static MemCpyChkOpt MemCpyChk; 1996 static MemMoveChkOpt MemMoveChk; 1997 static MemSetChkOpt MemSetChk; 1998 static StrCpyChkOpt StrCpyChk; 1999 static StpCpyChkOpt StpCpyChk; 2000 static StrNCpyChkOpt StrNCpyChk; 2001 2002 // String library call optimizations. 2003 static StrCatOpt StrCat; 2004 static StrNCatOpt StrNCat; 2005 static StrChrOpt StrChr; 2006 static StrRChrOpt StrRChr; 2007 static StrCmpOpt StrCmp; 2008 static StrNCmpOpt StrNCmp; 2009 static StrCpyOpt StrCpy; 2010 static StpCpyOpt StpCpy; 2011 static StrNCpyOpt StrNCpy; 2012 static StrLenOpt StrLen; 2013 static StrPBrkOpt StrPBrk; 2014 static StrToOpt StrTo; 2015 static StrSpnOpt StrSpn; 2016 static StrCSpnOpt StrCSpn; 2017 static StrStrOpt StrStr; 2018 2019 // Memory library call optimizations. 2020 static MemCmpOpt MemCmp; 2021 static MemCpyOpt MemCpy; 2022 static MemMoveOpt MemMove; 2023 static MemSetOpt MemSet; 2024 2025 // Math library call optimizations. 2026 static UnaryDoubleFPOpt UnaryDoubleFP(false); 2027 static BinaryDoubleFPOpt BinaryDoubleFP(false); 2028 static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true); 2029 static SinCosPiOpt SinCosPi; 2030 2031 // Integer library call optimizations. 2032 static FFSOpt FFS; 2033 static AbsOpt Abs; 2034 static IsDigitOpt IsDigit; 2035 static IsAsciiOpt IsAscii; 2036 static ToAsciiOpt ToAscii; 2037 2038 // Formatting and IO library call optimizations. 2039 static ErrorReportingOpt ErrorReporting; 2040 static ErrorReportingOpt ErrorReporting0(0); 2041 static ErrorReportingOpt ErrorReporting1(1); 2042 static PrintFOpt PrintF; 2043 static SPrintFOpt SPrintF; 2044 static FPrintFOpt FPrintF; 2045 static FWriteOpt FWrite; 2046 static FPutsOpt FPuts; 2047 static PutsOpt Puts; 2048 2049 LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) { 2050 LibFunc::Func Func; 2051 Function *Callee = CI->getCalledFunction(); 2052 StringRef FuncName = Callee->getName(); 2053 2054 // Next check for intrinsics. 2055 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 2056 switch (II->getIntrinsicID()) { 2057 case Intrinsic::pow: 2058 return &Pow; 2059 case Intrinsic::exp2: 2060 return &Exp2; 2061 default: 2062 return 0; 2063 } 2064 } 2065 2066 // Then check for known library functions. 2067 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) { 2068 switch (Func) { 2069 case LibFunc::strcat: 2070 return &StrCat; 2071 case LibFunc::strncat: 2072 return &StrNCat; 2073 case LibFunc::strchr: 2074 return &StrChr; 2075 case LibFunc::strrchr: 2076 return &StrRChr; 2077 case LibFunc::strcmp: 2078 return &StrCmp; 2079 case LibFunc::strncmp: 2080 return &StrNCmp; 2081 case LibFunc::strcpy: 2082 return &StrCpy; 2083 case LibFunc::stpcpy: 2084 return &StpCpy; 2085 case LibFunc::strncpy: 2086 return &StrNCpy; 2087 case LibFunc::strlen: 2088 return &StrLen; 2089 case LibFunc::strpbrk: 2090 return &StrPBrk; 2091 case LibFunc::strtol: 2092 case LibFunc::strtod: 2093 case LibFunc::strtof: 2094 case LibFunc::strtoul: 2095 case LibFunc::strtoll: 2096 case LibFunc::strtold: 2097 case LibFunc::strtoull: 2098 return &StrTo; 2099 case LibFunc::strspn: 2100 return &StrSpn; 2101 case LibFunc::strcspn: 2102 return &StrCSpn; 2103 case LibFunc::strstr: 2104 return &StrStr; 2105 case LibFunc::memcmp: 2106 return &MemCmp; 2107 case LibFunc::memcpy: 2108 return &MemCpy; 2109 case LibFunc::memmove: 2110 return &MemMove; 2111 case LibFunc::memset: 2112 return &MemSet; 2113 case LibFunc::cosf: 2114 case LibFunc::cos: 2115 case LibFunc::cosl: 2116 return &Cos; 2117 case LibFunc::sinpif: 2118 case LibFunc::sinpi: 2119 case LibFunc::cospif: 2120 case LibFunc::cospi: 2121 return &SinCosPi; 2122 case LibFunc::powf: 2123 case LibFunc::pow: 2124 case LibFunc::powl: 2125 return &Pow; 2126 case LibFunc::exp2l: 2127 case LibFunc::exp2: 2128 case LibFunc::exp2f: 2129 return &Exp2; 2130 case LibFunc::ffs: 2131 case LibFunc::ffsl: 2132 case LibFunc::ffsll: 2133 return &FFS; 2134 case LibFunc::abs: 2135 case LibFunc::labs: 2136 case LibFunc::llabs: 2137 return &Abs; 2138 case LibFunc::isdigit: 2139 return &IsDigit; 2140 case LibFunc::isascii: 2141 return &IsAscii; 2142 case LibFunc::toascii: 2143 return &ToAscii; 2144 case LibFunc::printf: 2145 return &PrintF; 2146 case LibFunc::sprintf: 2147 return &SPrintF; 2148 case LibFunc::fprintf: 2149 return &FPrintF; 2150 case LibFunc::fwrite: 2151 return &FWrite; 2152 case LibFunc::fputs: 2153 return &FPuts; 2154 case LibFunc::puts: 2155 return &Puts; 2156 case LibFunc::perror: 2157 return &ErrorReporting; 2158 case LibFunc::vfprintf: 2159 case LibFunc::fiprintf: 2160 return &ErrorReporting0; 2161 case LibFunc::fputc: 2162 return &ErrorReporting1; 2163 case LibFunc::ceil: 2164 case LibFunc::fabs: 2165 case LibFunc::floor: 2166 case LibFunc::rint: 2167 case LibFunc::round: 2168 case LibFunc::nearbyint: 2169 case LibFunc::trunc: 2170 if (hasFloatVersion(FuncName)) 2171 return &UnaryDoubleFP; 2172 return 0; 2173 case LibFunc::acos: 2174 case LibFunc::acosh: 2175 case LibFunc::asin: 2176 case LibFunc::asinh: 2177 case LibFunc::atan: 2178 case LibFunc::atanh: 2179 case LibFunc::cbrt: 2180 case LibFunc::cosh: 2181 case LibFunc::exp: 2182 case LibFunc::exp10: 2183 case LibFunc::expm1: 2184 case LibFunc::log: 2185 case LibFunc::log10: 2186 case LibFunc::log1p: 2187 case LibFunc::log2: 2188 case LibFunc::logb: 2189 case LibFunc::sin: 2190 case LibFunc::sinh: 2191 case LibFunc::sqrt: 2192 case LibFunc::tan: 2193 case LibFunc::tanh: 2194 if (UnsafeFPShrink && hasFloatVersion(FuncName)) 2195 return &UnsafeUnaryDoubleFP; 2196 return 0; 2197 case LibFunc::fmin: 2198 case LibFunc::fmax: 2199 if (hasFloatVersion(FuncName)) 2200 return &BinaryDoubleFP; 2201 return 0; 2202 case LibFunc::memcpy_chk: 2203 return &MemCpyChk; 2204 default: 2205 return 0; 2206 } 2207 } 2208 2209 // Finally check for fortified library calls. 2210 if (FuncName.endswith("_chk")) { 2211 if (FuncName == "__memmove_chk") 2212 return &MemMoveChk; 2213 else if (FuncName == "__memset_chk") 2214 return &MemSetChk; 2215 else if (FuncName == "__strcpy_chk") 2216 return &StrCpyChk; 2217 else if (FuncName == "__stpcpy_chk") 2218 return &StpCpyChk; 2219 else if (FuncName == "__strncpy_chk") 2220 return &StrNCpyChk; 2221 else if (FuncName == "__stpncpy_chk") 2222 return &StrNCpyChk; 2223 } 2224 2225 return 0; 2226 2227 } 2228 2229 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) { 2230 LibCallOptimization *LCO = lookupOptimization(CI); 2231 if (LCO) { 2232 IRBuilder<> Builder(CI); 2233 return LCO->optimizeCall(CI, TD, TLI, LCS, Builder); 2234 } 2235 return 0; 2236 } 2237 2238 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD, 2239 const TargetLibraryInfo *TLI, 2240 bool UnsafeFPShrink) { 2241 Impl = new LibCallSimplifierImpl(TD, TLI, this, UnsafeFPShrink); 2242 } 2243 2244 LibCallSimplifier::~LibCallSimplifier() { 2245 delete Impl; 2246 } 2247 2248 Value *LibCallSimplifier::optimizeCall(CallInst *CI) { 2249 if (CI->isNoBuiltin()) return 0; 2250 return Impl->optimizeCall(CI); 2251 } 2252 2253 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const { 2254 I->replaceAllUsesWith(With); 2255 I->eraseFromParent(); 2256 } 2257 2258 } 2259 2260 // TODO: 2261 // Additional cases that we need to add to this file: 2262 // 2263 // cbrt: 2264 // * cbrt(expN(X)) -> expN(x/3) 2265 // * cbrt(sqrt(x)) -> pow(x,1/6) 2266 // * cbrt(sqrt(x)) -> pow(x,1/9) 2267 // 2268 // exp, expf, expl: 2269 // * exp(log(x)) -> x 2270 // 2271 // log, logf, logl: 2272 // * log(exp(x)) -> x 2273 // * log(x**y) -> y*log(x) 2274 // * log(exp(y)) -> y*log(e) 2275 // * log(exp2(y)) -> y*log(2) 2276 // * log(exp10(y)) -> y*log(10) 2277 // * log(sqrt(x)) -> 0.5*log(x) 2278 // * log(pow(x,y)) -> y*log(x) 2279 // 2280 // lround, lroundf, lroundl: 2281 // * lround(cnst) -> cnst' 2282 // 2283 // pow, powf, powl: 2284 // * pow(exp(x),y) -> exp(x*y) 2285 // * pow(sqrt(x),y) -> pow(x,y*0.5) 2286 // * pow(pow(x,y),z)-> pow(x,y*z) 2287 // 2288 // round, roundf, roundl: 2289 // * round(cnst) -> cnst' 2290 // 2291 // signbit: 2292 // * signbit(cnst) -> cnst' 2293 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 2294 // 2295 // sqrt, sqrtf, sqrtl: 2296 // * sqrt(expN(x)) -> expN(x*0.5) 2297 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 2298 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 2299 // 2300 // strchr: 2301 // * strchr(p, 0) -> strlen(p) 2302 // tan, tanf, tanl: 2303 // * tan(atan(x)) -> x 2304 // 2305 // trunc, truncf, truncl: 2306 // * trunc(cnst) -> cnst' 2307 // 2308 // 2309