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 //===----------------------------------------------------------------------===// 957 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor' 958 959 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B, 960 bool CheckRetType) { 961 Function *Callee = CI->getCalledFunction(); 962 FunctionType *FT = Callee->getFunctionType(); 963 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() || 964 !FT->getParamType(0)->isDoubleTy()) 965 return nullptr; 966 967 if (CheckRetType) { 968 // Check if all the uses for function like 'sin' are converted to float. 969 for (User *U : CI->users()) { 970 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 971 if (!Cast || !Cast->getType()->isFloatTy()) 972 return nullptr; 973 } 974 } 975 976 // If this is something like 'floor((double)floatval)', convert to floorf. 977 Value *V = valueHasFloatPrecision(CI->getArgOperand(0)); 978 if (V == nullptr) 979 return nullptr; 980 981 // Propagate fast-math flags from the existing call to the new call. 982 IRBuilder<>::FastMathFlagGuard Guard(B); 983 B.setFastMathFlags(CI->getFastMathFlags()); 984 985 // floor((double)floatval) -> (double)floorf(floatval) 986 if (Callee->isIntrinsic()) { 987 Module *M = CI->getModule(); 988 Intrinsic::ID IID = Callee->getIntrinsicID(); 989 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy()); 990 V = B.CreateCall(F, V); 991 } else { 992 // The call is a library call rather than an intrinsic. 993 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes()); 994 } 995 996 return B.CreateFPExt(V, B.getDoubleTy()); 997 } 998 999 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax' 1000 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) { 1001 Function *Callee = CI->getCalledFunction(); 1002 FunctionType *FT = Callee->getFunctionType(); 1003 // Just make sure this has 2 arguments of the same FP type, which match the 1004 // result type. 1005 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) || 1006 FT->getParamType(0) != FT->getParamType(1) || 1007 !FT->getParamType(0)->isFloatingPointTy()) 1008 return nullptr; 1009 1010 // If this is something like 'fmin((double)floatval1, (double)floatval2)', 1011 // or fmin(1.0, (double)floatval), then we convert it to fminf. 1012 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0)); 1013 if (V1 == nullptr) 1014 return nullptr; 1015 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1)); 1016 if (V2 == nullptr) 1017 return nullptr; 1018 1019 // Propagate fast-math flags from the existing call to the new call. 1020 IRBuilder<>::FastMathFlagGuard Guard(B); 1021 B.setFastMathFlags(CI->getFastMathFlags()); 1022 1023 // fmin((double)floatval1, (double)floatval2) 1024 // -> (double)fminf(floatval1, floatval2) 1025 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP(). 1026 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B, 1027 Callee->getAttributes()); 1028 return B.CreateFPExt(V, B.getDoubleTy()); 1029 } 1030 1031 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) { 1032 Function *Callee = CI->getCalledFunction(); 1033 Value *Ret = nullptr; 1034 StringRef Name = Callee->getName(); 1035 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name)) 1036 Ret = optimizeUnaryDoubleFP(CI, B, true); 1037 1038 FunctionType *FT = Callee->getFunctionType(); 1039 // Just make sure this has 1 argument of FP type, which matches the 1040 // result type. 1041 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1042 !FT->getParamType(0)->isFloatingPointTy()) 1043 return Ret; 1044 1045 // cos(-x) -> cos(x) 1046 Value *Op1 = CI->getArgOperand(0); 1047 if (BinaryOperator::isFNeg(Op1)) { 1048 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1); 1049 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos"); 1050 } 1051 return Ret; 1052 } 1053 1054 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) { 1055 // Multiplications calculated using Addition Chains. 1056 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html 1057 1058 assert(Exp != 0 && "Incorrect exponent 0 not handled"); 1059 1060 if (InnerChain[Exp]) 1061 return InnerChain[Exp]; 1062 1063 static const unsigned AddChain[33][2] = { 1064 {0, 0}, // Unused. 1065 {0, 0}, // Unused (base case = pow1). 1066 {1, 1}, // Unused (pre-computed). 1067 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4}, 1068 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7}, 1069 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10}, 1070 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13}, 1071 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16}, 1072 }; 1073 1074 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B), 1075 getPow(InnerChain, AddChain[Exp][1], B)); 1076 return InnerChain[Exp]; 1077 } 1078 1079 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) { 1080 Function *Callee = CI->getCalledFunction(); 1081 Value *Ret = nullptr; 1082 StringRef Name = Callee->getName(); 1083 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name)) 1084 Ret = optimizeUnaryDoubleFP(CI, B, true); 1085 1086 FunctionType *FT = Callee->getFunctionType(); 1087 // Just make sure this has 2 arguments of the same FP type, which match the 1088 // result type. 1089 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) || 1090 FT->getParamType(0) != FT->getParamType(1) || 1091 !FT->getParamType(0)->isFloatingPointTy()) 1092 return Ret; 1093 1094 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1); 1095 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) { 1096 // pow(1.0, x) -> 1.0 1097 if (Op1C->isExactlyValue(1.0)) 1098 return Op1C; 1099 // pow(2.0, x) -> exp2(x) 1100 if (Op1C->isExactlyValue(2.0) && 1101 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f, 1102 LibFunc::exp2l)) 1103 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B, 1104 Callee->getAttributes()); 1105 // pow(10.0, x) -> exp10(x) 1106 if (Op1C->isExactlyValue(10.0) && 1107 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f, 1108 LibFunc::exp10l)) 1109 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B, 1110 Callee->getAttributes()); 1111 } 1112 1113 // pow(exp(x), y) -> exp(x * y) 1114 // pow(exp2(x), y) -> exp2(x * y) 1115 // We enable these only with fast-math. Besides rounding differences, the 1116 // transformation changes overflow and underflow behavior quite dramatically. 1117 // Example: x = 1000, y = 0.001. 1118 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1). 1119 auto *OpC = dyn_cast<CallInst>(Op1); 1120 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) { 1121 LibFunc::Func Func; 1122 Function *OpCCallee = OpC->getCalledFunction(); 1123 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) && 1124 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) { 1125 IRBuilder<>::FastMathFlagGuard Guard(B); 1126 B.setFastMathFlags(CI->getFastMathFlags()); 1127 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"); 1128 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B, 1129 OpCCallee->getAttributes()); 1130 } 1131 } 1132 1133 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2); 1134 if (!Op2C) 1135 return Ret; 1136 1137 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0 1138 return ConstantFP::get(CI->getType(), 1.0); 1139 1140 if (Op2C->isExactlyValue(0.5) && 1141 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf, 1142 LibFunc::sqrtl) && 1143 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf, 1144 LibFunc::fabsl)) { 1145 1146 // In -ffast-math, pow(x, 0.5) -> sqrt(x). 1147 if (CI->hasUnsafeAlgebra()) { 1148 IRBuilder<>::FastMathFlagGuard Guard(B); 1149 B.setFastMathFlags(CI->getFastMathFlags()); 1150 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B, 1151 Callee->getAttributes()); 1152 } 1153 1154 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))). 1155 // This is faster than calling pow, and still handles negative zero 1156 // and negative infinity correctly. 1157 // TODO: In finite-only mode, this could be just fabs(sqrt(x)). 1158 Value *Inf = ConstantFP::getInfinity(CI->getType()); 1159 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true); 1160 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes()); 1161 Value *FAbs = 1162 emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes()); 1163 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf); 1164 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs); 1165 return Sel; 1166 } 1167 1168 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x 1169 return Op1; 1170 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x 1171 return B.CreateFMul(Op1, Op1, "pow2"); 1172 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x 1173 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip"); 1174 1175 // In -ffast-math, generate repeated fmul instead of generating pow(x, n). 1176 if (CI->hasUnsafeAlgebra()) { 1177 APFloat V = abs(Op2C->getValueAPF()); 1178 // We limit to a max of 7 fmul(s). Thus max exponent is 32. 1179 // This transformation applies to integer exponents only. 1180 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan || 1181 !V.isInteger()) 1182 return nullptr; 1183 1184 // We will memoize intermediate products of the Addition Chain. 1185 Value *InnerChain[33] = {nullptr}; 1186 InnerChain[1] = Op1; 1187 InnerChain[2] = B.CreateFMul(Op1, Op1); 1188 1189 // We cannot readily convert a non-double type (like float) to a double. 1190 // So we first convert V to something which could be converted to double. 1191 bool ignored; 1192 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored); 1193 1194 // TODO: Should the new instructions propagate the 'fast' flag of the pow()? 1195 Value *FMul = getPow(InnerChain, V.convertToDouble(), B); 1196 // For negative exponents simply compute the reciprocal. 1197 if (Op2C->isNegative()) 1198 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul); 1199 return FMul; 1200 } 1201 1202 return nullptr; 1203 } 1204 1205 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) { 1206 Function *Callee = CI->getCalledFunction(); 1207 Function *Caller = CI->getParent()->getParent(); 1208 Value *Ret = nullptr; 1209 StringRef Name = Callee->getName(); 1210 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name)) 1211 Ret = optimizeUnaryDoubleFP(CI, B, true); 1212 1213 FunctionType *FT = Callee->getFunctionType(); 1214 // Just make sure this has 1 argument of FP type, which matches the 1215 // result type. 1216 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1217 !FT->getParamType(0)->isFloatingPointTy()) 1218 return Ret; 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 = Caller->getParent(); 1245 Value *Callee = 1246 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(), 1247 Op->getType(), B.getInt32Ty(), nullptr); 1248 CallInst *CI = B.CreateCall(Callee, {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 Value *Ret = nullptr; 1261 StringRef Name = Callee->getName(); 1262 if (Name == "fabs" && hasFloatVersion(Name)) 1263 Ret = optimizeUnaryDoubleFP(CI, B, false); 1264 1265 FunctionType *FT = Callee->getFunctionType(); 1266 // Make sure this has 1 argument of FP type which matches the result type. 1267 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1268 !FT->getParamType(0)->isFloatingPointTy()) 1269 return Ret; 1270 1271 Value *Op = CI->getArgOperand(0); 1272 if (Instruction *I = dyn_cast<Instruction>(Op)) { 1273 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive. 1274 if (I->getOpcode() == Instruction::FMul) 1275 if (I->getOperand(0) == I->getOperand(1)) 1276 return Op; 1277 } 1278 return Ret; 1279 } 1280 1281 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) { 1282 // If we can shrink the call to a float function rather than a double 1283 // function, do that first. 1284 Function *Callee = CI->getCalledFunction(); 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 // Make sure this has 2 arguments of FP type which match the result type. 1291 FunctionType *FT = Callee->getFunctionType(); 1292 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) || 1293 FT->getParamType(0) != FT->getParamType(1) || 1294 !FT->getParamType(0)->isFloatingPointTy()) 1295 return nullptr; 1296 1297 IRBuilder<>::FastMathFlagGuard Guard(B); 1298 FastMathFlags FMF; 1299 if (CI->hasUnsafeAlgebra()) { 1300 // Unsafe algebra sets all fast-math-flags to true. 1301 FMF.setUnsafeAlgebra(); 1302 } else { 1303 // At a minimum, no-nans-fp-math must be true. 1304 if (!CI->hasNoNaNs()) 1305 return nullptr; 1306 // No-signed-zeros is implied by the definitions of fmax/fmin themselves: 1307 // "Ideally, fmax would be sensitive to the sign of zero, for example 1308 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software 1309 // might be impractical." 1310 FMF.setNoSignedZeros(); 1311 FMF.setNoNaNs(); 1312 } 1313 B.setFastMathFlags(FMF); 1314 1315 // We have a relaxed floating-point environment. We can ignore NaN-handling 1316 // and transform to a compare and select. We do not have to consider errno or 1317 // exceptions, because fmin/fmax do not have those. 1318 Value *Op0 = CI->getArgOperand(0); 1319 Value *Op1 = CI->getArgOperand(1); 1320 Value *Cmp = Callee->getName().startswith("fmin") ? 1321 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1); 1322 return B.CreateSelect(Cmp, Op0, Op1); 1323 } 1324 1325 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) { 1326 Function *Callee = CI->getCalledFunction(); 1327 Value *Ret = nullptr; 1328 StringRef Name = Callee->getName(); 1329 if (UnsafeFPShrink && hasFloatVersion(Name)) 1330 Ret = optimizeUnaryDoubleFP(CI, B, true); 1331 FunctionType *FT = Callee->getFunctionType(); 1332 1333 // Just make sure this has 1 argument of FP type, which matches the 1334 // result type. 1335 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1336 !FT->getParamType(0)->isFloatingPointTy()) 1337 return Ret; 1338 1339 if (!CI->hasUnsafeAlgebra()) 1340 return Ret; 1341 Value *Op1 = CI->getArgOperand(0); 1342 auto *OpC = dyn_cast<CallInst>(Op1); 1343 1344 // The earlier call must also be unsafe in order to do these transforms. 1345 if (!OpC || !OpC->hasUnsafeAlgebra()) 1346 return Ret; 1347 1348 // log(pow(x,y)) -> y*log(x) 1349 // This is only applicable to log, log2, log10. 1350 if (Name != "log" && Name != "log2" && Name != "log10") 1351 return Ret; 1352 1353 IRBuilder<>::FastMathFlagGuard Guard(B); 1354 FastMathFlags FMF; 1355 FMF.setUnsafeAlgebra(); 1356 B.setFastMathFlags(FMF); 1357 1358 LibFunc::Func Func; 1359 Function *F = OpC->getCalledFunction(); 1360 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 1361 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow)) 1362 return B.CreateFMul(OpC->getArgOperand(1), 1363 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B, 1364 Callee->getAttributes()), "mul"); 1365 1366 // log(exp2(y)) -> y*log(2) 1367 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) && 1368 TLI->has(Func) && Func == LibFunc::exp2) 1369 return B.CreateFMul( 1370 OpC->getArgOperand(0), 1371 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0), 1372 Callee->getName(), B, Callee->getAttributes()), 1373 "logmul"); 1374 return Ret; 1375 } 1376 1377 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) { 1378 Function *Callee = CI->getCalledFunction(); 1379 1380 Value *Ret = nullptr; 1381 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" || 1382 Callee->getIntrinsicID() == Intrinsic::sqrt)) 1383 Ret = optimizeUnaryDoubleFP(CI, B, true); 1384 1385 if (!CI->hasUnsafeAlgebra()) 1386 return Ret; 1387 1388 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 1389 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra()) 1390 return Ret; 1391 1392 // We're looking for a repeated factor in a multiplication tree, 1393 // so we can do this fold: sqrt(x * x) -> fabs(x); 1394 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 1395 Value *Op0 = I->getOperand(0); 1396 Value *Op1 = I->getOperand(1); 1397 Value *RepeatOp = nullptr; 1398 Value *OtherOp = nullptr; 1399 if (Op0 == Op1) { 1400 // Simple match: the operands of the multiply are identical. 1401 RepeatOp = Op0; 1402 } else { 1403 // Look for a more complicated pattern: one of the operands is itself 1404 // a multiply, so search for a common factor in that multiply. 1405 // Note: We don't bother looking any deeper than this first level or for 1406 // variations of this pattern because instcombine's visitFMUL and/or the 1407 // reassociation pass should give us this form. 1408 Value *OtherMul0, *OtherMul1; 1409 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) { 1410 // Pattern: sqrt((x * y) * z) 1411 if (OtherMul0 == OtherMul1 && 1412 cast<Instruction>(Op0)->hasUnsafeAlgebra()) { 1413 // Matched: sqrt((x * x) * z) 1414 RepeatOp = OtherMul0; 1415 OtherOp = Op1; 1416 } 1417 } 1418 } 1419 if (!RepeatOp) 1420 return Ret; 1421 1422 // Fast math flags for any created instructions should match the sqrt 1423 // and multiply. 1424 IRBuilder<>::FastMathFlagGuard Guard(B); 1425 B.setFastMathFlags(I->getFastMathFlags()); 1426 1427 // If we found a repeated factor, hoist it out of the square root and 1428 // replace it with the fabs of that factor. 1429 Module *M = Callee->getParent(); 1430 Type *ArgType = I->getType(); 1431 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType); 1432 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs"); 1433 if (OtherOp) { 1434 // If we found a non-repeated factor, we still need to get its square 1435 // root. We then multiply that by the value that was simplified out 1436 // of the square root calculation. 1437 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType); 1438 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt"); 1439 return B.CreateFMul(FabsCall, SqrtCall); 1440 } 1441 return FabsCall; 1442 } 1443 1444 // TODO: Generalize to handle any trig function and its inverse. 1445 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) { 1446 Function *Callee = CI->getCalledFunction(); 1447 Value *Ret = nullptr; 1448 StringRef Name = Callee->getName(); 1449 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name)) 1450 Ret = optimizeUnaryDoubleFP(CI, B, true); 1451 FunctionType *FT = Callee->getFunctionType(); 1452 1453 // Just make sure this has 1 argument of FP type, which matches the 1454 // result type. 1455 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) || 1456 !FT->getParamType(0)->isFloatingPointTy()) 1457 return Ret; 1458 1459 Value *Op1 = CI->getArgOperand(0); 1460 auto *OpC = dyn_cast<CallInst>(Op1); 1461 if (!OpC) 1462 return Ret; 1463 1464 // Both calls must allow unsafe optimizations in order to remove them. 1465 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra()) 1466 return Ret; 1467 1468 // tan(atan(x)) -> x 1469 // tanf(atanf(x)) -> x 1470 // tanl(atanl(x)) -> x 1471 LibFunc::Func Func; 1472 Function *F = OpC->getCalledFunction(); 1473 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 1474 ((Func == LibFunc::atan && Callee->getName() == "tan") || 1475 (Func == LibFunc::atanf && Callee->getName() == "tanf") || 1476 (Func == LibFunc::atanl && Callee->getName() == "tanl"))) 1477 Ret = OpC->getArgOperand(0); 1478 return Ret; 1479 } 1480 1481 static bool isTrigLibCall(CallInst *CI); 1482 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, 1483 bool UseFloat, Value *&Sin, Value *&Cos, 1484 Value *&SinCos); 1485 1486 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) { 1487 1488 // Make sure the prototype is as expected, otherwise the rest of the 1489 // function is probably invalid and likely to abort. 1490 if (!isTrigLibCall(CI)) 1491 return nullptr; 1492 1493 Value *Arg = CI->getArgOperand(0); 1494 SmallVector<CallInst *, 1> SinCalls; 1495 SmallVector<CallInst *, 1> CosCalls; 1496 SmallVector<CallInst *, 1> SinCosCalls; 1497 1498 bool IsFloat = Arg->getType()->isFloatTy(); 1499 1500 // Look for all compatible sinpi, cospi and sincospi calls with the same 1501 // argument. If there are enough (in some sense) we can make the 1502 // substitution. 1503 for (User *U : Arg->users()) 1504 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls, 1505 SinCosCalls); 1506 1507 // It's only worthwhile if both sinpi and cospi are actually used. 1508 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty())) 1509 return nullptr; 1510 1511 Value *Sin, *Cos, *SinCos; 1512 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos); 1513 1514 replaceTrigInsts(SinCalls, Sin); 1515 replaceTrigInsts(CosCalls, Cos); 1516 replaceTrigInsts(SinCosCalls, SinCos); 1517 1518 return nullptr; 1519 } 1520 1521 static bool isTrigLibCall(CallInst *CI) { 1522 Function *Callee = CI->getCalledFunction(); 1523 FunctionType *FT = Callee->getFunctionType(); 1524 1525 // We can only hope to do anything useful if we can ignore things like errno 1526 // and floating-point exceptions. 1527 bool AttributesSafe = 1528 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone); 1529 1530 // Other than that we need float(float) or double(double) 1531 return AttributesSafe && FT->getNumParams() == 1 && 1532 FT->getReturnType() == FT->getParamType(0) && 1533 (FT->getParamType(0)->isFloatTy() || 1534 FT->getParamType(0)->isDoubleTy()); 1535 } 1536 1537 void 1538 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat, 1539 SmallVectorImpl<CallInst *> &SinCalls, 1540 SmallVectorImpl<CallInst *> &CosCalls, 1541 SmallVectorImpl<CallInst *> &SinCosCalls) { 1542 CallInst *CI = dyn_cast<CallInst>(Val); 1543 1544 if (!CI) 1545 return; 1546 1547 Function *Callee = CI->getCalledFunction(); 1548 LibFunc::Func Func; 1549 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) || 1550 !isTrigLibCall(CI)) 1551 return; 1552 1553 if (IsFloat) { 1554 if (Func == LibFunc::sinpif) 1555 SinCalls.push_back(CI); 1556 else if (Func == LibFunc::cospif) 1557 CosCalls.push_back(CI); 1558 else if (Func == LibFunc::sincospif_stret) 1559 SinCosCalls.push_back(CI); 1560 } else { 1561 if (Func == LibFunc::sinpi) 1562 SinCalls.push_back(CI); 1563 else if (Func == LibFunc::cospi) 1564 CosCalls.push_back(CI); 1565 else if (Func == LibFunc::sincospi_stret) 1566 SinCosCalls.push_back(CI); 1567 } 1568 } 1569 1570 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls, 1571 Value *Res) { 1572 for (CallInst *C : Calls) 1573 replaceAllUsesWith(C, Res); 1574 } 1575 1576 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, 1577 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) { 1578 Type *ArgTy = Arg->getType(); 1579 Type *ResTy; 1580 StringRef Name; 1581 1582 Triple T(OrigCallee->getParent()->getTargetTriple()); 1583 if (UseFloat) { 1584 Name = "__sincospif_stret"; 1585 1586 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 1587 // x86_64 can't use {float, float} since that would be returned in both 1588 // xmm0 and xmm1, which isn't what a real struct would do. 1589 ResTy = T.getArch() == Triple::x86_64 1590 ? static_cast<Type *>(VectorType::get(ArgTy, 2)) 1591 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr)); 1592 } else { 1593 Name = "__sincospi_stret"; 1594 ResTy = StructType::get(ArgTy, ArgTy, nullptr); 1595 } 1596 1597 Module *M = OrigCallee->getParent(); 1598 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(), 1599 ResTy, ArgTy, nullptr); 1600 1601 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 1602 // If the argument is an instruction, it must dominate all uses so put our 1603 // sincos call there. 1604 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 1605 } else { 1606 // Otherwise (e.g. for a constant) the beginning of the function is as 1607 // good a place as any. 1608 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 1609 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 1610 } 1611 1612 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 1613 1614 if (SinCos->getType()->isStructTy()) { 1615 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 1616 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 1617 } else { 1618 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 1619 "sinpi"); 1620 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 1621 "cospi"); 1622 } 1623 } 1624 1625 //===----------------------------------------------------------------------===// 1626 // Integer Library Call Optimizations 1627 //===----------------------------------------------------------------------===// 1628 1629 static bool checkIntUnaryReturnAndParam(Function *Callee) { 1630 FunctionType *FT = Callee->getFunctionType(); 1631 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) && 1632 FT->getParamType(0)->isIntegerTy(); 1633 } 1634 1635 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) { 1636 Function *Callee = CI->getCalledFunction(); 1637 if (!checkIntUnaryReturnAndParam(Callee)) 1638 return nullptr; 1639 Value *Op = CI->getArgOperand(0); 1640 1641 // Constant fold. 1642 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 1643 if (CI->isZero()) // ffs(0) -> 0. 1644 return B.getInt32(0); 1645 // ffs(c) -> cttz(c)+1 1646 return B.getInt32(CI->getValue().countTrailingZeros() + 1); 1647 } 1648 1649 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 1650 Type *ArgType = Op->getType(); 1651 Value *F = 1652 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType); 1653 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz"); 1654 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 1655 V = B.CreateIntCast(V, B.getInt32Ty(), false); 1656 1657 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 1658 return B.CreateSelect(Cond, V, B.getInt32(0)); 1659 } 1660 1661 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) { 1662 Function *Callee = CI->getCalledFunction(); 1663 FunctionType *FT = Callee->getFunctionType(); 1664 // We require integer(integer) where the types agree. 1665 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() || 1666 FT->getParamType(0) != FT->getReturnType()) 1667 return nullptr; 1668 1669 // abs(x) -> x >s -1 ? x : -x 1670 Value *Op = CI->getArgOperand(0); 1671 Value *Pos = 1672 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos"); 1673 Value *Neg = B.CreateNeg(Op, "neg"); 1674 return B.CreateSelect(Pos, Op, Neg); 1675 } 1676 1677 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) { 1678 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction())) 1679 return nullptr; 1680 1681 // isdigit(c) -> (c-'0') <u 10 1682 Value *Op = CI->getArgOperand(0); 1683 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp"); 1684 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit"); 1685 return B.CreateZExt(Op, CI->getType()); 1686 } 1687 1688 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) { 1689 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction())) 1690 return nullptr; 1691 1692 // isascii(c) -> c <u 128 1693 Value *Op = CI->getArgOperand(0); 1694 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii"); 1695 return B.CreateZExt(Op, CI->getType()); 1696 } 1697 1698 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) { 1699 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction())) 1700 return nullptr; 1701 1702 // toascii(c) -> c & 0x7f 1703 return B.CreateAnd(CI->getArgOperand(0), 1704 ConstantInt::get(CI->getType(), 0x7F)); 1705 } 1706 1707 //===----------------------------------------------------------------------===// 1708 // Formatting and IO Library Call Optimizations 1709 //===----------------------------------------------------------------------===// 1710 1711 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 1712 1713 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B, 1714 int StreamArg) { 1715 // Error reporting calls should be cold, mark them as such. 1716 // This applies even to non-builtin calls: it is only a hint and applies to 1717 // functions that the frontend might not understand as builtins. 1718 1719 // This heuristic was suggested in: 1720 // Improving Static Branch Prediction in a Compiler 1721 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 1722 // Proceedings of PACT'98, Oct. 1998, IEEE 1723 Function *Callee = CI->getCalledFunction(); 1724 1725 if (!CI->hasFnAttr(Attribute::Cold) && 1726 isReportingError(Callee, CI, StreamArg)) { 1727 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold); 1728 } 1729 1730 return nullptr; 1731 } 1732 1733 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 1734 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration()) 1735 return false; 1736 1737 if (StreamArg < 0) 1738 return true; 1739 1740 // These functions might be considered cold, but only if their stream 1741 // argument is stderr. 1742 1743 if (StreamArg >= (int)CI->getNumArgOperands()) 1744 return false; 1745 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 1746 if (!LI) 1747 return false; 1748 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 1749 if (!GV || !GV->isDeclaration()) 1750 return false; 1751 return GV->getName() == "stderr"; 1752 } 1753 1754 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) { 1755 // Check for a fixed format string. 1756 StringRef FormatStr; 1757 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 1758 return nullptr; 1759 1760 // Empty format string -> noop. 1761 if (FormatStr.empty()) // Tolerate printf's declared void. 1762 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 1763 1764 // Do not do any of the following transformations if the printf return value 1765 // is used, in general the printf return value is not compatible with either 1766 // putchar() or puts(). 1767 if (!CI->use_empty()) 1768 return nullptr; 1769 1770 // printf("x") -> putchar('x'), even for '%'. 1771 if (FormatStr.size() == 1) { 1772 Value *Res = emitPutChar(B.getInt32(FormatStr[0]), B, TLI); 1773 if (CI->use_empty() || !Res) 1774 return Res; 1775 return B.CreateIntCast(Res, CI->getType(), true); 1776 } 1777 1778 // printf("foo\n") --> puts("foo") 1779 if (FormatStr[FormatStr.size() - 1] == '\n' && 1780 FormatStr.find('%') == StringRef::npos) { // No format characters. 1781 // Create a string literal with no \n on it. We expect the constant merge 1782 // pass to be run after this pass, to merge duplicate strings. 1783 FormatStr = FormatStr.drop_back(); 1784 Value *GV = B.CreateGlobalString(FormatStr, "str"); 1785 Value *NewCI = emitPutS(GV, B, TLI); 1786 return (CI->use_empty() || !NewCI) 1787 ? NewCI 1788 : ConstantInt::get(CI->getType(), FormatStr.size() + 1); 1789 } 1790 1791 // Optimize specific format strings. 1792 // printf("%c", chr) --> putchar(chr) 1793 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 && 1794 CI->getArgOperand(1)->getType()->isIntegerTy()) { 1795 Value *Res = emitPutChar(CI->getArgOperand(1), B, TLI); 1796 1797 if (CI->use_empty() || !Res) 1798 return Res; 1799 return B.CreateIntCast(Res, CI->getType(), true); 1800 } 1801 1802 // printf("%s\n", str) --> puts(str) 1803 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 && 1804 CI->getArgOperand(1)->getType()->isPointerTy()) { 1805 return emitPutS(CI->getArgOperand(1), B, TLI); 1806 } 1807 return nullptr; 1808 } 1809 1810 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) { 1811 1812 Function *Callee = CI->getCalledFunction(); 1813 // Require one fixed pointer argument and an integer/void result. 1814 FunctionType *FT = Callee->getFunctionType(); 1815 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() || 1816 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy())) 1817 return nullptr; 1818 1819 if (Value *V = optimizePrintFString(CI, B)) { 1820 return V; 1821 } 1822 1823 // printf(format, ...) -> iprintf(format, ...) if no floating point 1824 // arguments. 1825 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) { 1826 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1827 Constant *IPrintFFn = 1828 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes()); 1829 CallInst *New = cast<CallInst>(CI->clone()); 1830 New->setCalledFunction(IPrintFFn); 1831 B.Insert(New); 1832 return New; 1833 } 1834 return nullptr; 1835 } 1836 1837 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) { 1838 // Check for a fixed format string. 1839 StringRef FormatStr; 1840 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 1841 return nullptr; 1842 1843 // If we just have a format string (nothing else crazy) transform it. 1844 if (CI->getNumArgOperands() == 2) { 1845 // Make sure there's no % in the constant array. We could try to handle 1846 // %% -> % in the future if we cared. 1847 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 1848 if (FormatStr[i] == '%') 1849 return nullptr; // we found a format specifier, bail out. 1850 1851 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1) 1852 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 1853 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 1854 FormatStr.size() + 1), 1855 1); // Copy the null byte. 1856 return ConstantInt::get(CI->getType(), FormatStr.size()); 1857 } 1858 1859 // The remaining optimizations require the format string to be "%s" or "%c" 1860 // and have an extra operand. 1861 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 1862 CI->getNumArgOperands() < 3) 1863 return nullptr; 1864 1865 // Decode the second character of the format string. 1866 if (FormatStr[1] == 'c') { 1867 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 1868 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 1869 return nullptr; 1870 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 1871 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 1872 B.CreateStore(V, Ptr); 1873 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 1874 B.CreateStore(B.getInt8(0), Ptr); 1875 1876 return ConstantInt::get(CI->getType(), 1); 1877 } 1878 1879 if (FormatStr[1] == 's') { 1880 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1) 1881 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 1882 return nullptr; 1883 1884 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 1885 if (!Len) 1886 return nullptr; 1887 Value *IncLen = 1888 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 1889 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1); 1890 1891 // The sprintf result is the unincremented number of bytes in the string. 1892 return B.CreateIntCast(Len, CI->getType(), false); 1893 } 1894 return nullptr; 1895 } 1896 1897 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) { 1898 Function *Callee = CI->getCalledFunction(); 1899 // Require two fixed pointer arguments and an integer result. 1900 FunctionType *FT = Callee->getFunctionType(); 1901 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() || 1902 !FT->getParamType(1)->isPointerTy() || 1903 !FT->getReturnType()->isIntegerTy()) 1904 return nullptr; 1905 1906 if (Value *V = optimizeSPrintFString(CI, B)) { 1907 return V; 1908 } 1909 1910 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 1911 // point arguments. 1912 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) { 1913 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1914 Constant *SIPrintFFn = 1915 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes()); 1916 CallInst *New = cast<CallInst>(CI->clone()); 1917 New->setCalledFunction(SIPrintFFn); 1918 B.Insert(New); 1919 return New; 1920 } 1921 return nullptr; 1922 } 1923 1924 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) { 1925 optimizeErrorReporting(CI, B, 0); 1926 1927 // All the optimizations depend on the format string. 1928 StringRef FormatStr; 1929 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 1930 return nullptr; 1931 1932 // Do not do any of the following transformations if the fprintf return 1933 // value is used, in general the fprintf return value is not compatible 1934 // with fwrite(), fputc() or fputs(). 1935 if (!CI->use_empty()) 1936 return nullptr; 1937 1938 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 1939 if (CI->getNumArgOperands() == 2) { 1940 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 1941 if (FormatStr[i] == '%') // Could handle %% -> % if we cared. 1942 return nullptr; // We found a format specifier. 1943 1944 return emitFWrite( 1945 CI->getArgOperand(1), 1946 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()), 1947 CI->getArgOperand(0), B, DL, TLI); 1948 } 1949 1950 // The remaining optimizations require the format string to be "%s" or "%c" 1951 // and have an extra operand. 1952 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 1953 CI->getNumArgOperands() < 3) 1954 return nullptr; 1955 1956 // Decode the second character of the format string. 1957 if (FormatStr[1] == 'c') { 1958 // fprintf(F, "%c", chr) --> fputc(chr, F) 1959 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 1960 return nullptr; 1961 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 1962 } 1963 1964 if (FormatStr[1] == 's') { 1965 // fprintf(F, "%s", str) --> fputs(str, F) 1966 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 1967 return nullptr; 1968 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 1969 } 1970 return nullptr; 1971 } 1972 1973 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) { 1974 Function *Callee = CI->getCalledFunction(); 1975 // Require two fixed paramters as pointers and integer result. 1976 FunctionType *FT = Callee->getFunctionType(); 1977 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() || 1978 !FT->getParamType(1)->isPointerTy() || 1979 !FT->getReturnType()->isIntegerTy()) 1980 return nullptr; 1981 1982 if (Value *V = optimizeFPrintFString(CI, B)) { 1983 return V; 1984 } 1985 1986 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 1987 // floating point arguments. 1988 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) { 1989 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1990 Constant *FIPrintFFn = 1991 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes()); 1992 CallInst *New = cast<CallInst>(CI->clone()); 1993 New->setCalledFunction(FIPrintFFn); 1994 B.Insert(New); 1995 return New; 1996 } 1997 return nullptr; 1998 } 1999 2000 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) { 2001 optimizeErrorReporting(CI, B, 3); 2002 2003 Function *Callee = CI->getCalledFunction(); 2004 // Require a pointer, an integer, an integer, a pointer, returning integer. 2005 FunctionType *FT = Callee->getFunctionType(); 2006 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() || 2007 !FT->getParamType(1)->isIntegerTy() || 2008 !FT->getParamType(2)->isIntegerTy() || 2009 !FT->getParamType(3)->isPointerTy() || 2010 !FT->getReturnType()->isIntegerTy()) 2011 return nullptr; 2012 2013 // Get the element size and count. 2014 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2015 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 2016 if (!SizeC || !CountC) 2017 return nullptr; 2018 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 2019 2020 // If this is writing zero records, remove the call (it's a noop). 2021 if (Bytes == 0) 2022 return ConstantInt::get(CI->getType(), 0); 2023 2024 // If this is writing one byte, turn it into fputc. 2025 // This optimisation is only valid, if the return value is unused. 2026 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 2027 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char"); 2028 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI); 2029 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 2030 } 2031 2032 return nullptr; 2033 } 2034 2035 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) { 2036 optimizeErrorReporting(CI, B, 1); 2037 2038 Function *Callee = CI->getCalledFunction(); 2039 2040 // Require two pointers. Also, we can't optimize if return value is used. 2041 FunctionType *FT = Callee->getFunctionType(); 2042 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() || 2043 !FT->getParamType(1)->isPointerTy() || !CI->use_empty()) 2044 return nullptr; 2045 2046 // fputs(s,F) --> fwrite(s,1,strlen(s),F) 2047 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 2048 if (!Len) 2049 return nullptr; 2050 2051 // Known to have no uses (see above). 2052 return emitFWrite( 2053 CI->getArgOperand(0), 2054 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1), 2055 CI->getArgOperand(1), B, DL, TLI); 2056 } 2057 2058 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) { 2059 Function *Callee = CI->getCalledFunction(); 2060 // Require one fixed pointer argument and an integer/void result. 2061 FunctionType *FT = Callee->getFunctionType(); 2062 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() || 2063 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy())) 2064 return nullptr; 2065 2066 // Check for a constant string. 2067 StringRef Str; 2068 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2069 return nullptr; 2070 2071 if (Str.empty() && CI->use_empty()) { 2072 // puts("") -> putchar('\n') 2073 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI); 2074 if (CI->use_empty() || !Res) 2075 return Res; 2076 return B.CreateIntCast(Res, CI->getType(), true); 2077 } 2078 2079 return nullptr; 2080 } 2081 2082 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) { 2083 LibFunc::Func Func; 2084 SmallString<20> FloatFuncName = FuncName; 2085 FloatFuncName += 'f'; 2086 if (TLI->getLibFunc(FloatFuncName, Func)) 2087 return TLI->has(Func); 2088 return false; 2089 } 2090 2091 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 2092 IRBuilder<> &Builder) { 2093 LibFunc::Func Func; 2094 Function *Callee = CI->getCalledFunction(); 2095 StringRef FuncName = Callee->getName(); 2096 2097 // Check for string/memory library functions. 2098 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) { 2099 // Make sure we never change the calling convention. 2100 assert((ignoreCallingConv(Func) || 2101 CI->getCallingConv() == llvm::CallingConv::C) && 2102 "Optimizing string/memory libcall would change the calling convention"); 2103 switch (Func) { 2104 case LibFunc::strcat: 2105 return optimizeStrCat(CI, Builder); 2106 case LibFunc::strncat: 2107 return optimizeStrNCat(CI, Builder); 2108 case LibFunc::strchr: 2109 return optimizeStrChr(CI, Builder); 2110 case LibFunc::strrchr: 2111 return optimizeStrRChr(CI, Builder); 2112 case LibFunc::strcmp: 2113 return optimizeStrCmp(CI, Builder); 2114 case LibFunc::strncmp: 2115 return optimizeStrNCmp(CI, Builder); 2116 case LibFunc::strcpy: 2117 return optimizeStrCpy(CI, Builder); 2118 case LibFunc::stpcpy: 2119 return optimizeStpCpy(CI, Builder); 2120 case LibFunc::strncpy: 2121 return optimizeStrNCpy(CI, Builder); 2122 case LibFunc::strlen: 2123 return optimizeStrLen(CI, Builder); 2124 case LibFunc::strpbrk: 2125 return optimizeStrPBrk(CI, Builder); 2126 case LibFunc::strtol: 2127 case LibFunc::strtod: 2128 case LibFunc::strtof: 2129 case LibFunc::strtoul: 2130 case LibFunc::strtoll: 2131 case LibFunc::strtold: 2132 case LibFunc::strtoull: 2133 return optimizeStrTo(CI, Builder); 2134 case LibFunc::strspn: 2135 return optimizeStrSpn(CI, Builder); 2136 case LibFunc::strcspn: 2137 return optimizeStrCSpn(CI, Builder); 2138 case LibFunc::strstr: 2139 return optimizeStrStr(CI, Builder); 2140 case LibFunc::memchr: 2141 return optimizeMemChr(CI, Builder); 2142 case LibFunc::memcmp: 2143 return optimizeMemCmp(CI, Builder); 2144 case LibFunc::memcpy: 2145 return optimizeMemCpy(CI, Builder); 2146 case LibFunc::memmove: 2147 return optimizeMemMove(CI, Builder); 2148 case LibFunc::memset: 2149 return optimizeMemSet(CI, Builder); 2150 default: 2151 break; 2152 } 2153 } 2154 return nullptr; 2155 } 2156 2157 Value *LibCallSimplifier::optimizeCall(CallInst *CI) { 2158 if (CI->isNoBuiltin()) 2159 return nullptr; 2160 2161 LibFunc::Func Func; 2162 Function *Callee = CI->getCalledFunction(); 2163 StringRef FuncName = Callee->getName(); 2164 2165 SmallVector<OperandBundleDef, 2> OpBundles; 2166 CI->getOperandBundlesAsDefs(OpBundles); 2167 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 2168 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C; 2169 2170 // Command-line parameter overrides instruction attribute. 2171 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 2172 UnsafeFPShrink = EnableUnsafeFPShrink; 2173 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra()) 2174 UnsafeFPShrink = true; 2175 2176 // First, check for intrinsics. 2177 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 2178 if (!isCallingConvC) 2179 return nullptr; 2180 switch (II->getIntrinsicID()) { 2181 case Intrinsic::pow: 2182 return optimizePow(CI, Builder); 2183 case Intrinsic::exp2: 2184 return optimizeExp2(CI, Builder); 2185 case Intrinsic::fabs: 2186 return optimizeFabs(CI, Builder); 2187 case Intrinsic::log: 2188 return optimizeLog(CI, Builder); 2189 case Intrinsic::sqrt: 2190 return optimizeSqrt(CI, Builder); 2191 default: 2192 return nullptr; 2193 } 2194 } 2195 2196 // Also try to simplify calls to fortified library functions. 2197 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) { 2198 // Try to further simplify the result. 2199 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI); 2200 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) { 2201 // Use an IR Builder from SimplifiedCI if available instead of CI 2202 // to guarantee we reach all uses we might replace later on. 2203 IRBuilder<> TmpBuilder(SimplifiedCI); 2204 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) { 2205 // If we were able to further simplify, remove the now redundant call. 2206 SimplifiedCI->replaceAllUsesWith(V); 2207 SimplifiedCI->eraseFromParent(); 2208 return V; 2209 } 2210 } 2211 return SimplifiedFortifiedCI; 2212 } 2213 2214 // Then check for known library functions. 2215 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) { 2216 // We never change the calling convention. 2217 if (!ignoreCallingConv(Func) && !isCallingConvC) 2218 return nullptr; 2219 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 2220 return V; 2221 switch (Func) { 2222 case LibFunc::cosf: 2223 case LibFunc::cos: 2224 case LibFunc::cosl: 2225 return optimizeCos(CI, Builder); 2226 case LibFunc::sinpif: 2227 case LibFunc::sinpi: 2228 case LibFunc::cospif: 2229 case LibFunc::cospi: 2230 return optimizeSinCosPi(CI, Builder); 2231 case LibFunc::powf: 2232 case LibFunc::pow: 2233 case LibFunc::powl: 2234 return optimizePow(CI, Builder); 2235 case LibFunc::exp2l: 2236 case LibFunc::exp2: 2237 case LibFunc::exp2f: 2238 return optimizeExp2(CI, Builder); 2239 case LibFunc::fabsf: 2240 case LibFunc::fabs: 2241 case LibFunc::fabsl: 2242 return optimizeFabs(CI, Builder); 2243 case LibFunc::sqrtf: 2244 case LibFunc::sqrt: 2245 case LibFunc::sqrtl: 2246 return optimizeSqrt(CI, Builder); 2247 case LibFunc::ffs: 2248 case LibFunc::ffsl: 2249 case LibFunc::ffsll: 2250 return optimizeFFS(CI, Builder); 2251 case LibFunc::abs: 2252 case LibFunc::labs: 2253 case LibFunc::llabs: 2254 return optimizeAbs(CI, Builder); 2255 case LibFunc::isdigit: 2256 return optimizeIsDigit(CI, Builder); 2257 case LibFunc::isascii: 2258 return optimizeIsAscii(CI, Builder); 2259 case LibFunc::toascii: 2260 return optimizeToAscii(CI, Builder); 2261 case LibFunc::printf: 2262 return optimizePrintF(CI, Builder); 2263 case LibFunc::sprintf: 2264 return optimizeSPrintF(CI, Builder); 2265 case LibFunc::fprintf: 2266 return optimizeFPrintF(CI, Builder); 2267 case LibFunc::fwrite: 2268 return optimizeFWrite(CI, Builder); 2269 case LibFunc::fputs: 2270 return optimizeFPuts(CI, Builder); 2271 case LibFunc::log: 2272 case LibFunc::log10: 2273 case LibFunc::log1p: 2274 case LibFunc::log2: 2275 case LibFunc::logb: 2276 return optimizeLog(CI, Builder); 2277 case LibFunc::puts: 2278 return optimizePuts(CI, Builder); 2279 case LibFunc::tan: 2280 case LibFunc::tanf: 2281 case LibFunc::tanl: 2282 return optimizeTan(CI, Builder); 2283 case LibFunc::perror: 2284 return optimizeErrorReporting(CI, Builder); 2285 case LibFunc::vfprintf: 2286 case LibFunc::fiprintf: 2287 return optimizeErrorReporting(CI, Builder, 0); 2288 case LibFunc::fputc: 2289 return optimizeErrorReporting(CI, Builder, 1); 2290 case LibFunc::ceil: 2291 case LibFunc::floor: 2292 case LibFunc::rint: 2293 case LibFunc::round: 2294 case LibFunc::nearbyint: 2295 case LibFunc::trunc: 2296 if (hasFloatVersion(FuncName)) 2297 return optimizeUnaryDoubleFP(CI, Builder, false); 2298 return nullptr; 2299 case LibFunc::acos: 2300 case LibFunc::acosh: 2301 case LibFunc::asin: 2302 case LibFunc::asinh: 2303 case LibFunc::atan: 2304 case LibFunc::atanh: 2305 case LibFunc::cbrt: 2306 case LibFunc::cosh: 2307 case LibFunc::exp: 2308 case LibFunc::exp10: 2309 case LibFunc::expm1: 2310 case LibFunc::sin: 2311 case LibFunc::sinh: 2312 case LibFunc::tanh: 2313 if (UnsafeFPShrink && hasFloatVersion(FuncName)) 2314 return optimizeUnaryDoubleFP(CI, Builder, true); 2315 return nullptr; 2316 case LibFunc::copysign: 2317 if (hasFloatVersion(FuncName)) 2318 return optimizeBinaryDoubleFP(CI, Builder); 2319 return nullptr; 2320 case LibFunc::fminf: 2321 case LibFunc::fmin: 2322 case LibFunc::fminl: 2323 case LibFunc::fmaxf: 2324 case LibFunc::fmax: 2325 case LibFunc::fmaxl: 2326 return optimizeFMinFMax(CI, Builder); 2327 default: 2328 return nullptr; 2329 } 2330 } 2331 return nullptr; 2332 } 2333 2334 LibCallSimplifier::LibCallSimplifier( 2335 const DataLayout &DL, const TargetLibraryInfo *TLI, 2336 function_ref<void(Instruction *, Value *)> Replacer) 2337 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false), 2338 Replacer(Replacer) {} 2339 2340 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 2341 // Indirect through the replacer used in this instance. 2342 Replacer(I, With); 2343 } 2344 2345 // TODO: 2346 // Additional cases that we need to add to this file: 2347 // 2348 // cbrt: 2349 // * cbrt(expN(X)) -> expN(x/3) 2350 // * cbrt(sqrt(x)) -> pow(x,1/6) 2351 // * cbrt(cbrt(x)) -> pow(x,1/9) 2352 // 2353 // exp, expf, expl: 2354 // * exp(log(x)) -> x 2355 // 2356 // log, logf, logl: 2357 // * log(exp(x)) -> x 2358 // * log(exp(y)) -> y*log(e) 2359 // * log(exp10(y)) -> y*log(10) 2360 // * log(sqrt(x)) -> 0.5*log(x) 2361 // 2362 // lround, lroundf, lroundl: 2363 // * lround(cnst) -> cnst' 2364 // 2365 // pow, powf, powl: 2366 // * pow(sqrt(x),y) -> pow(x,y*0.5) 2367 // * pow(pow(x,y),z)-> pow(x,y*z) 2368 // 2369 // round, roundf, roundl: 2370 // * round(cnst) -> cnst' 2371 // 2372 // signbit: 2373 // * signbit(cnst) -> cnst' 2374 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 2375 // 2376 // sqrt, sqrtf, sqrtl: 2377 // * sqrt(expN(x)) -> expN(x*0.5) 2378 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 2379 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 2380 // 2381 // trunc, truncf, truncl: 2382 // * trunc(cnst) -> cnst' 2383 // 2384 // 2385 2386 //===----------------------------------------------------------------------===// 2387 // Fortified Library Call Optimizations 2388 //===----------------------------------------------------------------------===// 2389 2390 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI, 2391 unsigned ObjSizeOp, 2392 unsigned SizeOp, 2393 bool isString) { 2394 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp)) 2395 return true; 2396 if (ConstantInt *ObjSizeCI = 2397 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 2398 if (ObjSizeCI->isAllOnesValue()) 2399 return true; 2400 // If the object size wasn't -1 (unknown), bail out if we were asked to. 2401 if (OnlyLowerUnknownSize) 2402 return false; 2403 if (isString) { 2404 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp)); 2405 // If the length is 0 we don't know how long it is and so we can't 2406 // remove the check. 2407 if (Len == 0) 2408 return false; 2409 return ObjSizeCI->getZExtValue() >= Len; 2410 } 2411 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp))) 2412 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 2413 } 2414 return false; 2415 } 2416 2417 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 2418 IRBuilder<> &B) { 2419 Function *Callee = CI->getCalledFunction(); 2420 2421 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk)) 2422 return nullptr; 2423 2424 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2425 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 2426 CI->getArgOperand(2), 1); 2427 return CI->getArgOperand(0); 2428 } 2429 return nullptr; 2430 } 2431 2432 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 2433 IRBuilder<> &B) { 2434 Function *Callee = CI->getCalledFunction(); 2435 2436 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk)) 2437 return nullptr; 2438 2439 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2440 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1), 2441 CI->getArgOperand(2), 1); 2442 return CI->getArgOperand(0); 2443 } 2444 return nullptr; 2445 } 2446 2447 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 2448 IRBuilder<> &B) { 2449 Function *Callee = CI->getCalledFunction(); 2450 2451 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk)) 2452 return nullptr; 2453 2454 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2455 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 2456 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1); 2457 return CI->getArgOperand(0); 2458 } 2459 return nullptr; 2460 } 2461 2462 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 2463 IRBuilder<> &B, 2464 LibFunc::Func Func) { 2465 Function *Callee = CI->getCalledFunction(); 2466 StringRef Name = Callee->getName(); 2467 const DataLayout &DL = CI->getModule()->getDataLayout(); 2468 2469 if (!checkStringCopyLibFuncSignature(Callee, Func)) 2470 return nullptr; 2471 2472 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 2473 *ObjSize = CI->getArgOperand(2); 2474 2475 // __stpcpy_chk(x,x,...) -> x+strlen(x) 2476 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 2477 Value *StrLen = emitStrLen(Src, B, DL, TLI); 2478 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 2479 } 2480 2481 // If a) we don't have any length information, or b) we know this will 2482 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 2483 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 2484 // TODO: It might be nice to get a maximum length out of the possible 2485 // string lengths for varying. 2486 if (isFortifiedCallFoldable(CI, 2, 1, true)) 2487 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6)); 2488 2489 if (OnlyLowerUnknownSize) 2490 return nullptr; 2491 2492 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 2493 uint64_t Len = GetStringLength(Src); 2494 if (Len == 0) 2495 return nullptr; 2496 2497 Type *SizeTTy = DL.getIntPtrType(CI->getContext()); 2498 Value *LenV = ConstantInt::get(SizeTTy, Len); 2499 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 2500 // If the function was an __stpcpy_chk, and we were able to fold it into 2501 // a __memcpy_chk, we still need to return the correct end pointer. 2502 if (Ret && Func == LibFunc::stpcpy_chk) 2503 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1)); 2504 return Ret; 2505 } 2506 2507 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 2508 IRBuilder<> &B, 2509 LibFunc::Func Func) { 2510 Function *Callee = CI->getCalledFunction(); 2511 StringRef Name = Callee->getName(); 2512 2513 if (!checkStringCopyLibFuncSignature(Callee, Func)) 2514 return nullptr; 2515 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2516 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 2517 CI->getArgOperand(2), B, TLI, Name.substr(2, 7)); 2518 return Ret; 2519 } 2520 return nullptr; 2521 } 2522 2523 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) { 2524 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 2525 // Some clang users checked for _chk libcall availability using: 2526 // __has_builtin(__builtin___memcpy_chk) 2527 // When compiling with -fno-builtin, this is always true. 2528 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 2529 // end up with fortified libcalls, which isn't acceptable in a freestanding 2530 // environment which only provides their non-fortified counterparts. 2531 // 2532 // Until we change clang and/or teach external users to check for availability 2533 // differently, disregard the "nobuiltin" attribute and TLI::has. 2534 // 2535 // PR23093. 2536 2537 LibFunc::Func Func; 2538 Function *Callee = CI->getCalledFunction(); 2539 StringRef FuncName = Callee->getName(); 2540 2541 SmallVector<OperandBundleDef, 2> OpBundles; 2542 CI->getOperandBundlesAsDefs(OpBundles); 2543 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 2544 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C; 2545 2546 // First, check that this is a known library functions. 2547 if (!TLI->getLibFunc(FuncName, Func)) 2548 return nullptr; 2549 2550 // We never change the calling convention. 2551 if (!ignoreCallingConv(Func) && !isCallingConvC) 2552 return nullptr; 2553 2554 switch (Func) { 2555 case LibFunc::memcpy_chk: 2556 return optimizeMemCpyChk(CI, Builder); 2557 case LibFunc::memmove_chk: 2558 return optimizeMemMoveChk(CI, Builder); 2559 case LibFunc::memset_chk: 2560 return optimizeMemSetChk(CI, Builder); 2561 case LibFunc::stpcpy_chk: 2562 case LibFunc::strcpy_chk: 2563 return optimizeStrpCpyChk(CI, Builder, Func); 2564 case LibFunc::stpncpy_chk: 2565 case LibFunc::strncpy_chk: 2566 return optimizeStrpNCpyChk(CI, Builder, Func); 2567 default: 2568 break; 2569 } 2570 return nullptr; 2571 } 2572 2573 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 2574 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 2575 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 2576