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