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