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