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