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