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