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