1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the library calls simplifier. It does not implement 10 // any pass, but can't be used by other passes to do simplifications. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 15 #include "llvm/ADT/APSInt.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/Analysis/BlockFrequencyInfo.h" 20 #include "llvm/Analysis/ConstantFolding.h" 21 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 22 #include "llvm/Analysis/ProfileSummaryInfo.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Transforms/Utils/Local.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/Analysis/CaptureTracking.h" 27 #include "llvm/Analysis/Loads.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/IRBuilder.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/LLVMContext.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/KnownBits.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Transforms/Utils/BuildLibCalls.h" 40 #include "llvm/Transforms/Utils/SizeOpts.h" 41 42 using namespace llvm; 43 using namespace PatternMatch; 44 45 static cl::opt<bool> 46 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden, 47 cl::init(false), 48 cl::desc("Enable unsafe double to float " 49 "shrinking for math lib calls")); 50 51 //===----------------------------------------------------------------------===// 52 // Helper Functions 53 //===----------------------------------------------------------------------===// 54 55 static bool ignoreCallingConv(LibFunc Func) { 56 return Func == LibFunc_abs || Func == LibFunc_labs || 57 Func == LibFunc_llabs || Func == LibFunc_strlen; 58 } 59 60 static bool isCallingConvCCompatible(CallInst *CI) { 61 switch(CI->getCallingConv()) { 62 default: 63 return false; 64 case llvm::CallingConv::C: 65 return true; 66 case llvm::CallingConv::ARM_APCS: 67 case llvm::CallingConv::ARM_AAPCS: 68 case llvm::CallingConv::ARM_AAPCS_VFP: { 69 70 // The iOS ABI diverges from the standard in some cases, so for now don't 71 // try to simplify those calls. 72 if (Triple(CI->getModule()->getTargetTriple()).isiOS()) 73 return false; 74 75 auto *FuncTy = CI->getFunctionType(); 76 77 if (!FuncTy->getReturnType()->isPointerTy() && 78 !FuncTy->getReturnType()->isIntegerTy() && 79 !FuncTy->getReturnType()->isVoidTy()) 80 return false; 81 82 for (auto Param : FuncTy->params()) { 83 if (!Param->isPointerTy() && !Param->isIntegerTy()) 84 return false; 85 } 86 return true; 87 } 88 } 89 return false; 90 } 91 92 /// Return true if it is only used in equality comparisons with With. 93 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) { 94 for (User *U : V->users()) { 95 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 96 if (IC->isEquality() && IC->getOperand(1) == With) 97 continue; 98 // Unknown instruction. 99 return false; 100 } 101 return true; 102 } 103 104 static bool callHasFloatingPointArgument(const CallInst *CI) { 105 return any_of(CI->operands(), [](const Use &OI) { 106 return OI->getType()->isFloatingPointTy(); 107 }); 108 } 109 110 static bool callHasFP128Argument(const CallInst *CI) { 111 return any_of(CI->operands(), [](const Use &OI) { 112 return OI->getType()->isFP128Ty(); 113 }); 114 } 115 116 static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) { 117 if (Base < 2 || Base > 36) 118 // handle special zero base 119 if (Base != 0) 120 return nullptr; 121 122 char *End; 123 std::string nptr = Str.str(); 124 errno = 0; 125 long long int Result = strtoll(nptr.c_str(), &End, Base); 126 if (errno) 127 return nullptr; 128 129 // if we assume all possible target locales are ASCII supersets, 130 // then if strtoll successfully parses a number on the host, 131 // it will also successfully parse the same way on the target 132 if (*End != '\0') 133 return nullptr; 134 135 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result)) 136 return nullptr; 137 138 return ConstantInt::get(CI->getType(), Result); 139 } 140 141 static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B, 142 const TargetLibraryInfo *TLI) { 143 CallInst *FOpen = dyn_cast<CallInst>(File); 144 if (!FOpen) 145 return false; 146 147 Function *InnerCallee = FOpen->getCalledFunction(); 148 if (!InnerCallee) 149 return false; 150 151 LibFunc Func; 152 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) || 153 Func != LibFunc_fopen) 154 return false; 155 156 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI); 157 if (PointerMayBeCaptured(File, true, true)) 158 return false; 159 160 return true; 161 } 162 163 static bool isOnlyUsedInComparisonWithZero(Value *V) { 164 for (User *U : V->users()) { 165 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 166 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 167 if (C->isNullValue()) 168 continue; 169 // Unknown instruction. 170 return false; 171 } 172 return true; 173 } 174 175 static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, 176 const DataLayout &DL) { 177 if (!isOnlyUsedInComparisonWithZero(CI)) 178 return false; 179 180 if (!isDereferenceableAndAlignedPointer(Str, Align::None(), APInt(64, Len), 181 DL)) 182 return false; 183 184 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory)) 185 return false; 186 187 return true; 188 } 189 190 static void annotateDereferenceableBytes(CallInst *CI, 191 ArrayRef<unsigned> ArgNos, 192 uint64_t DereferenceableBytes) { 193 const Function *F = CI->getCaller(); 194 if (!F) 195 return; 196 for (unsigned ArgNo : ArgNos) { 197 uint64_t DerefBytes = DereferenceableBytes; 198 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 199 if (!llvm::NullPointerIsDefined(F, AS) || 200 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 201 DerefBytes = std::max(CI->getDereferenceableOrNullBytes( 202 ArgNo + AttributeList::FirstArgIndex), 203 DereferenceableBytes); 204 205 if (CI->getDereferenceableBytes(ArgNo + AttributeList::FirstArgIndex) < 206 DerefBytes) { 207 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable); 208 if (!llvm::NullPointerIsDefined(F, AS) || 209 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 210 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull); 211 CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes( 212 CI->getContext(), DerefBytes)); 213 } 214 } 215 } 216 217 static void annotateNonNullBasedOnAccess(CallInst *CI, 218 ArrayRef<unsigned> ArgNos) { 219 Function *F = CI->getCaller(); 220 if (!F) 221 return; 222 223 for (unsigned ArgNo : ArgNos) { 224 if (CI->paramHasAttr(ArgNo, Attribute::NonNull)) 225 continue; 226 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 227 if (llvm::NullPointerIsDefined(F, AS)) 228 continue; 229 230 CI->addParamAttr(ArgNo, Attribute::NonNull); 231 annotateDereferenceableBytes(CI, ArgNo, 1); 232 } 233 } 234 235 static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos, 236 Value *Size, const DataLayout &DL) { 237 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) { 238 annotateNonNullBasedOnAccess(CI, ArgNos); 239 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue()); 240 } else if (isKnownNonZero(Size, DL)) { 241 annotateNonNullBasedOnAccess(CI, ArgNos); 242 const APInt *X, *Y; 243 uint64_t DerefMin = 1; 244 if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) { 245 DerefMin = std::min(X->getZExtValue(), Y->getZExtValue()); 246 annotateDereferenceableBytes(CI, ArgNos, DerefMin); 247 } 248 } 249 } 250 251 //===----------------------------------------------------------------------===// 252 // String and Memory Library Call Optimizations 253 //===----------------------------------------------------------------------===// 254 255 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) { 256 // Extract some information from the instruction 257 Value *Dst = CI->getArgOperand(0); 258 Value *Src = CI->getArgOperand(1); 259 annotateNonNullBasedOnAccess(CI, {0, 1}); 260 261 // See if we can get the length of the input string. 262 uint64_t Len = GetStringLength(Src); 263 if (Len) 264 annotateDereferenceableBytes(CI, 1, Len); 265 else 266 return nullptr; 267 --Len; // Unbias length. 268 269 // Handle the simple, do-nothing case: strcat(x, "") -> x 270 if (Len == 0) 271 return Dst; 272 273 return emitStrLenMemCpy(Src, Dst, Len, B); 274 } 275 276 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, 277 IRBuilder<> &B) { 278 // We need to find the end of the destination string. That's where the 279 // memory is to be moved to. We just generate a call to strlen. 280 Value *DstLen = emitStrLen(Dst, B, DL, TLI); 281 if (!DstLen) 282 return nullptr; 283 284 // Now that we have the destination's length, we must index into the 285 // destination's pointer to get the actual memcpy destination (end of 286 // the string .. we're concatenating). 287 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr"); 288 289 // We have enough information to now generate the memcpy call to do the 290 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 291 B.CreateMemCpy(CpyDst, 1, Src, 1, 292 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1)); 293 return Dst; 294 } 295 296 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) { 297 // Extract some information from the instruction. 298 Value *Dst = CI->getArgOperand(0); 299 Value *Src = CI->getArgOperand(1); 300 Value *Size = CI->getArgOperand(2); 301 uint64_t Len; 302 annotateNonNullBasedOnAccess(CI, 0); 303 if (isKnownNonZero(Size, DL)) 304 annotateNonNullBasedOnAccess(CI, 1); 305 306 // We don't do anything if length is not constant. 307 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size); 308 if (LengthArg) { 309 Len = LengthArg->getZExtValue(); 310 // strncat(x, c, 0) -> x 311 if (!Len) 312 return Dst; 313 } else { 314 return nullptr; 315 } 316 317 // See if we can get the length of the input string. 318 uint64_t SrcLen = GetStringLength(Src); 319 if (SrcLen) { 320 annotateDereferenceableBytes(CI, 1, SrcLen); 321 --SrcLen; // Unbias length. 322 } else { 323 return nullptr; 324 } 325 326 // strncat(x, "", c) -> x 327 if (SrcLen == 0) 328 return Dst; 329 330 // We don't optimize this case. 331 if (Len < SrcLen) 332 return nullptr; 333 334 // strncat(x, s, c) -> strcat(x, s) 335 // s is constant so the strcat can be optimized further. 336 return emitStrLenMemCpy(Src, Dst, SrcLen, B); 337 } 338 339 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) { 340 Function *Callee = CI->getCalledFunction(); 341 FunctionType *FT = Callee->getFunctionType(); 342 Value *SrcStr = CI->getArgOperand(0); 343 annotateNonNullBasedOnAccess(CI, 0); 344 345 // If the second operand is non-constant, see if we can compute the length 346 // of the input string and turn this into memchr. 347 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 348 if (!CharC) { 349 uint64_t Len = GetStringLength(SrcStr); 350 if (Len) 351 annotateDereferenceableBytes(CI, 0, Len); 352 else 353 return nullptr; 354 if (!FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32. 355 return nullptr; 356 357 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul. 358 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 359 B, DL, TLI); 360 } 361 362 // Otherwise, the character is a constant, see if the first argument is 363 // a string literal. If so, we can constant fold. 364 StringRef Str; 365 if (!getConstantStringInfo(SrcStr, Str)) { 366 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p) 367 if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI)) 368 return B.CreateGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr"); 369 return nullptr; 370 } 371 372 // Compute the offset, make sure to handle the case when we're searching for 373 // zero (a weird way to spell strlen). 374 size_t I = (0xFF & CharC->getSExtValue()) == 0 375 ? Str.size() 376 : Str.find(CharC->getSExtValue()); 377 if (I == StringRef::npos) // Didn't find the char. strchr returns null. 378 return Constant::getNullValue(CI->getType()); 379 380 // strchr(s+n,c) -> gep(s+n+i,c) 381 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr"); 382 } 383 384 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) { 385 Value *SrcStr = CI->getArgOperand(0); 386 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 387 annotateNonNullBasedOnAccess(CI, 0); 388 389 // Cannot fold anything if we're not looking for a constant. 390 if (!CharC) 391 return nullptr; 392 393 StringRef Str; 394 if (!getConstantStringInfo(SrcStr, Str)) { 395 // strrchr(s, 0) -> strchr(s, 0) 396 if (CharC->isZero()) 397 return emitStrChr(SrcStr, '\0', B, TLI); 398 return nullptr; 399 } 400 401 // Compute the offset. 402 size_t I = (0xFF & CharC->getSExtValue()) == 0 403 ? Str.size() 404 : Str.rfind(CharC->getSExtValue()); 405 if (I == StringRef::npos) // Didn't find the char. Return null. 406 return Constant::getNullValue(CI->getType()); 407 408 // strrchr(s+n,c) -> gep(s+n+i,c) 409 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr"); 410 } 411 412 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) { 413 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 414 if (Str1P == Str2P) // strcmp(x,x) -> 0 415 return ConstantInt::get(CI->getType(), 0); 416 417 StringRef Str1, Str2; 418 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 419 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 420 421 // strcmp(x, y) -> cnst (if both x and y are constant strings) 422 if (HasStr1 && HasStr2) 423 return ConstantInt::get(CI->getType(), Str1.compare(Str2)); 424 425 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x 426 return B.CreateNeg(B.CreateZExt( 427 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 428 429 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 430 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 431 CI->getType()); 432 433 // strcmp(P, "x") -> memcmp(P, "x", 2) 434 uint64_t Len1 = GetStringLength(Str1P); 435 if (Len1) 436 annotateDereferenceableBytes(CI, 0, Len1); 437 uint64_t Len2 = GetStringLength(Str2P); 438 if (Len2) 439 annotateDereferenceableBytes(CI, 1, Len2); 440 441 if (Len1 && Len2) { 442 return emitMemCmp(Str1P, Str2P, 443 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 444 std::min(Len1, Len2)), 445 B, DL, TLI); 446 } 447 448 // strcmp to memcmp 449 if (!HasStr1 && HasStr2) { 450 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 451 return emitMemCmp( 452 Str1P, Str2P, 453 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL, 454 TLI); 455 } else if (HasStr1 && !HasStr2) { 456 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 457 return emitMemCmp( 458 Str1P, Str2P, 459 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL, 460 TLI); 461 } 462 463 annotateNonNullBasedOnAccess(CI, {0, 1}); 464 return nullptr; 465 } 466 467 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) { 468 Value *Str1P = CI->getArgOperand(0); 469 Value *Str2P = CI->getArgOperand(1); 470 Value *Size = CI->getArgOperand(2); 471 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 472 return ConstantInt::get(CI->getType(), 0); 473 474 if (isKnownNonZero(Size, DL)) 475 annotateNonNullBasedOnAccess(CI, {0, 1}); 476 // Get the length argument if it is constant. 477 uint64_t Length; 478 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size)) 479 Length = LengthArg->getZExtValue(); 480 else 481 return nullptr; 482 483 if (Length == 0) // strncmp(x,y,0) -> 0 484 return ConstantInt::get(CI->getType(), 0); 485 486 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1) 487 return emitMemCmp(Str1P, Str2P, Size, B, DL, TLI); 488 489 StringRef Str1, Str2; 490 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 491 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 492 493 // strncmp(x, y) -> cnst (if both x and y are constant strings) 494 if (HasStr1 && HasStr2) { 495 StringRef SubStr1 = Str1.substr(0, Length); 496 StringRef SubStr2 = Str2.substr(0, Length); 497 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2)); 498 } 499 500 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x 501 return B.CreateNeg(B.CreateZExt( 502 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 503 504 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 505 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 506 CI->getType()); 507 508 uint64_t Len1 = GetStringLength(Str1P); 509 if (Len1) 510 annotateDereferenceableBytes(CI, 0, Len1); 511 uint64_t Len2 = GetStringLength(Str2P); 512 if (Len2) 513 annotateDereferenceableBytes(CI, 1, Len2); 514 515 // strncmp to memcmp 516 if (!HasStr1 && HasStr2) { 517 Len2 = std::min(Len2, Length); 518 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 519 return emitMemCmp( 520 Str1P, Str2P, 521 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL, 522 TLI); 523 } else if (HasStr1 && !HasStr2) { 524 Len1 = std::min(Len1, Length); 525 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 526 return emitMemCmp( 527 Str1P, Str2P, 528 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL, 529 TLI); 530 } 531 532 return nullptr; 533 } 534 535 Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilder<> &B) { 536 Value *Src = CI->getArgOperand(0); 537 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 538 uint64_t SrcLen = GetStringLength(Src); 539 if (SrcLen && Size) { 540 annotateDereferenceableBytes(CI, 0, SrcLen); 541 if (SrcLen <= Size->getZExtValue() + 1) 542 return emitStrDup(Src, B, TLI); 543 } 544 545 return nullptr; 546 } 547 548 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) { 549 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 550 if (Dst == Src) // strcpy(x,x) -> x 551 return Src; 552 553 annotateNonNullBasedOnAccess(CI, {0, 1}); 554 // See if we can get the length of the input string. 555 uint64_t Len = GetStringLength(Src); 556 if (Len) 557 annotateDereferenceableBytes(CI, 1, Len); 558 else 559 return nullptr; 560 561 // We have enough information to now generate the memcpy call to do the 562 // copy for us. Make a memcpy to copy the nul byte with align = 1. 563 CallInst *NewCI = 564 B.CreateMemCpy(Dst, 1, Src, 1, 565 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len)); 566 NewCI->setAttributes(CI->getAttributes()); 567 return Dst; 568 } 569 570 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) { 571 Function *Callee = CI->getCalledFunction(); 572 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 573 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 574 Value *StrLen = emitStrLen(Src, B, DL, TLI); 575 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 576 } 577 578 // See if we can get the length of the input string. 579 uint64_t Len = GetStringLength(Src); 580 if (Len) 581 annotateDereferenceableBytes(CI, 1, Len); 582 else 583 return nullptr; 584 585 Type *PT = Callee->getFunctionType()->getParamType(0); 586 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len); 587 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst, 588 ConstantInt::get(DL.getIntPtrType(PT), Len - 1)); 589 590 // We have enough information to now generate the memcpy call to do the 591 // copy for us. Make a memcpy to copy the nul byte with align = 1. 592 CallInst *NewCI = B.CreateMemCpy(Dst, 1, Src, 1, LenV); 593 NewCI->setAttributes(CI->getAttributes()); 594 return DstEnd; 595 } 596 597 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) { 598 Function *Callee = CI->getCalledFunction(); 599 Value *Dst = CI->getArgOperand(0); 600 Value *Src = CI->getArgOperand(1); 601 Value *Size = CI->getArgOperand(2); 602 annotateNonNullBasedOnAccess(CI, 0); 603 if (isKnownNonZero(Size, DL)) 604 annotateNonNullBasedOnAccess(CI, 1); 605 606 uint64_t Len; 607 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size)) 608 Len = LengthArg->getZExtValue(); 609 else 610 return nullptr; 611 612 // strncpy(x, y, 0) -> x 613 if (Len == 0) 614 return Dst; 615 616 // See if we can get the length of the input string. 617 uint64_t SrcLen = GetStringLength(Src); 618 if (SrcLen) { 619 annotateDereferenceableBytes(CI, 1, SrcLen); 620 --SrcLen; // Unbias length. 621 } else { 622 return nullptr; 623 } 624 625 if (SrcLen == 0) { 626 // strncpy(x, "", y) -> memset(align 1 x, '\0', y) 627 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, Align::None()); 628 AttrBuilder ArgAttrs(CI->getAttributes().getParamAttributes(0)); 629 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes( 630 CI->getContext(), 0, ArgAttrs)); 631 return Dst; 632 } 633 634 // Let strncpy handle the zero padding 635 if (Len > SrcLen + 1) 636 return nullptr; 637 638 Type *PT = Callee->getFunctionType()->getParamType(0); 639 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant] 640 CallInst *NewCI = B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len)); 641 NewCI->setAttributes(CI->getAttributes()); 642 return Dst; 643 } 644 645 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B, 646 unsigned CharSize) { 647 Value *Src = CI->getArgOperand(0); 648 649 // Constant folding: strlen("xyz") -> 3 650 if (uint64_t Len = GetStringLength(Src, CharSize)) 651 return ConstantInt::get(CI->getType(), Len - 1); 652 653 // If s is a constant pointer pointing to a string literal, we can fold 654 // strlen(s + x) to strlen(s) - x, when x is known to be in the range 655 // [0, strlen(s)] or the string has a single null terminator '\0' at the end. 656 // We only try to simplify strlen when the pointer s points to an array 657 // of i8. Otherwise, we would need to scale the offset x before doing the 658 // subtraction. This will make the optimization more complex, and it's not 659 // very useful because calling strlen for a pointer of other types is 660 // very uncommon. 661 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) { 662 if (!isGEPBasedOnPointerToString(GEP, CharSize)) 663 return nullptr; 664 665 ConstantDataArraySlice Slice; 666 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) { 667 uint64_t NullTermIdx; 668 if (Slice.Array == nullptr) { 669 NullTermIdx = 0; 670 } else { 671 NullTermIdx = ~((uint64_t)0); 672 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) { 673 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) { 674 NullTermIdx = I; 675 break; 676 } 677 } 678 // If the string does not have '\0', leave it to strlen to compute 679 // its length. 680 if (NullTermIdx == ~((uint64_t)0)) 681 return nullptr; 682 } 683 684 Value *Offset = GEP->getOperand(2); 685 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr); 686 Known.Zero.flipAllBits(); 687 uint64_t ArrSize = 688 cast<ArrayType>(GEP->getSourceElementType())->getNumElements(); 689 690 // KnownZero's bits are flipped, so zeros in KnownZero now represent 691 // bits known to be zeros in Offset, and ones in KnowZero represent 692 // bits unknown in Offset. Therefore, Offset is known to be in range 693 // [0, NullTermIdx] when the flipped KnownZero is non-negative and 694 // unsigned-less-than NullTermIdx. 695 // 696 // If Offset is not provably in the range [0, NullTermIdx], we can still 697 // optimize if we can prove that the program has undefined behavior when 698 // Offset is outside that range. That is the case when GEP->getOperand(0) 699 // is a pointer to an object whose memory extent is NullTermIdx+1. 700 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) || 701 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) && 702 NullTermIdx == ArrSize - 1)) { 703 Offset = B.CreateSExtOrTrunc(Offset, CI->getType()); 704 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx), 705 Offset); 706 } 707 } 708 709 return nullptr; 710 } 711 712 // strlen(x?"foo":"bars") --> x ? 3 : 4 713 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) { 714 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize); 715 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize); 716 if (LenTrue && LenFalse) { 717 ORE.emit([&]() { 718 return OptimizationRemark("instcombine", "simplify-libcalls", CI) 719 << "folded strlen(select) to select of constants"; 720 }); 721 return B.CreateSelect(SI->getCondition(), 722 ConstantInt::get(CI->getType(), LenTrue - 1), 723 ConstantInt::get(CI->getType(), LenFalse - 1)); 724 } 725 } 726 727 // strlen(x) != 0 --> *x != 0 728 // strlen(x) == 0 --> *x == 0 729 if (isOnlyUsedInZeroEqualityComparison(CI)) 730 return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"), 731 CI->getType()); 732 733 return nullptr; 734 } 735 736 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) { 737 if (Value *V = optimizeStringLength(CI, B, 8)) 738 return V; 739 annotateNonNullBasedOnAccess(CI, 0); 740 return nullptr; 741 } 742 743 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) { 744 Module &M = *CI->getModule(); 745 unsigned WCharSize = TLI->getWCharSize(M) * 8; 746 // We cannot perform this optimization without wchar_size metadata. 747 if (WCharSize == 0) 748 return nullptr; 749 750 return optimizeStringLength(CI, B, WCharSize); 751 } 752 753 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) { 754 StringRef S1, S2; 755 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 756 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 757 758 // strpbrk(s, "") -> nullptr 759 // strpbrk("", s) -> nullptr 760 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 761 return Constant::getNullValue(CI->getType()); 762 763 // Constant folding. 764 if (HasS1 && HasS2) { 765 size_t I = S1.find_first_of(S2); 766 if (I == StringRef::npos) // No match. 767 return Constant::getNullValue(CI->getType()); 768 769 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), 770 "strpbrk"); 771 } 772 773 // strpbrk(s, "a") -> strchr(s, 'a') 774 if (HasS2 && S2.size() == 1) 775 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI); 776 777 return nullptr; 778 } 779 780 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) { 781 Value *EndPtr = CI->getArgOperand(1); 782 if (isa<ConstantPointerNull>(EndPtr)) { 783 // With a null EndPtr, this function won't capture the main argument. 784 // It would be readonly too, except that it still may write to errno. 785 CI->addParamAttr(0, Attribute::NoCapture); 786 } 787 788 return nullptr; 789 } 790 791 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) { 792 StringRef S1, S2; 793 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 794 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 795 796 // strspn(s, "") -> 0 797 // strspn("", s) -> 0 798 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 799 return Constant::getNullValue(CI->getType()); 800 801 // Constant folding. 802 if (HasS1 && HasS2) { 803 size_t Pos = S1.find_first_not_of(S2); 804 if (Pos == StringRef::npos) 805 Pos = S1.size(); 806 return ConstantInt::get(CI->getType(), Pos); 807 } 808 809 return nullptr; 810 } 811 812 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) { 813 StringRef S1, S2; 814 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 815 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 816 817 // strcspn("", s) -> 0 818 if (HasS1 && S1.empty()) 819 return Constant::getNullValue(CI->getType()); 820 821 // Constant folding. 822 if (HasS1 && HasS2) { 823 size_t Pos = S1.find_first_of(S2); 824 if (Pos == StringRef::npos) 825 Pos = S1.size(); 826 return ConstantInt::get(CI->getType(), Pos); 827 } 828 829 // strcspn(s, "") -> strlen(s) 830 if (HasS2 && S2.empty()) 831 return emitStrLen(CI->getArgOperand(0), B, DL, TLI); 832 833 return nullptr; 834 } 835 836 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) { 837 // fold strstr(x, x) -> x. 838 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 839 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 840 841 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 842 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 843 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI); 844 if (!StrLen) 845 return nullptr; 846 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 847 StrLen, B, DL, TLI); 848 if (!StrNCmp) 849 return nullptr; 850 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) { 851 ICmpInst *Old = cast<ICmpInst>(*UI++); 852 Value *Cmp = 853 B.CreateICmp(Old->getPredicate(), StrNCmp, 854 ConstantInt::getNullValue(StrNCmp->getType()), "cmp"); 855 replaceAllUsesWith(Old, Cmp); 856 } 857 return CI; 858 } 859 860 // See if either input string is a constant string. 861 StringRef SearchStr, ToFindStr; 862 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 863 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 864 865 // fold strstr(x, "") -> x. 866 if (HasStr2 && ToFindStr.empty()) 867 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 868 869 // If both strings are known, constant fold it. 870 if (HasStr1 && HasStr2) { 871 size_t Offset = SearchStr.find(ToFindStr); 872 873 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 874 return Constant::getNullValue(CI->getType()); 875 876 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 877 Value *Result = castToCStr(CI->getArgOperand(0), B); 878 Result = 879 B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr"); 880 return B.CreateBitCast(Result, CI->getType()); 881 } 882 883 // fold strstr(x, "y") -> strchr(x, 'y'). 884 if (HasStr2 && ToFindStr.size() == 1) { 885 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI); 886 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr; 887 } 888 889 annotateNonNullBasedOnAccess(CI, {0, 1}); 890 return nullptr; 891 } 892 893 Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilder<> &B) { 894 if (isKnownNonZero(CI->getOperand(2), DL)) 895 annotateNonNullBasedOnAccess(CI, 0); 896 return nullptr; 897 } 898 899 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) { 900 Value *SrcStr = CI->getArgOperand(0); 901 Value *Size = CI->getArgOperand(2); 902 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 903 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 904 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 905 906 // memchr(x, y, 0) -> null 907 if (LenC) { 908 if (LenC->isZero()) 909 return Constant::getNullValue(CI->getType()); 910 } else { 911 // From now on we need at least constant length and string. 912 return nullptr; 913 } 914 915 StringRef Str; 916 if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false)) 917 return nullptr; 918 919 // Truncate the string to LenC. If Str is smaller than LenC we will still only 920 // scan the string, as reading past the end of it is undefined and we can just 921 // return null if we don't find the char. 922 Str = Str.substr(0, LenC->getZExtValue()); 923 924 // If the char is variable but the input str and length are not we can turn 925 // this memchr call into a simple bit field test. Of course this only works 926 // when the return value is only checked against null. 927 // 928 // It would be really nice to reuse switch lowering here but we can't change 929 // the CFG at this point. 930 // 931 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n'))) 932 // != 0 933 // after bounds check. 934 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) { 935 unsigned char Max = 936 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()), 937 reinterpret_cast<const unsigned char *>(Str.end())); 938 939 // Make sure the bit field we're about to create fits in a register on the 940 // target. 941 // FIXME: On a 64 bit architecture this prevents us from using the 942 // interesting range of alpha ascii chars. We could do better by emitting 943 // two bitfields or shifting the range by 64 if no lower chars are used. 944 if (!DL.fitsInLegalInteger(Max + 1)) 945 return nullptr; 946 947 // For the bit field use a power-of-2 type with at least 8 bits to avoid 948 // creating unnecessary illegal types. 949 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max)); 950 951 // Now build the bit field. 952 APInt Bitfield(Width, 0); 953 for (char C : Str) 954 Bitfield.setBit((unsigned char)C); 955 Value *BitfieldC = B.getInt(Bitfield); 956 957 // Adjust width of "C" to the bitfield width, then mask off the high bits. 958 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType()); 959 C = B.CreateAnd(C, B.getIntN(Width, 0xFF)); 960 961 // First check that the bit field access is within bounds. 962 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width), 963 "memchr.bounds"); 964 965 // Create code that checks if the given bit is set in the field. 966 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C); 967 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits"); 968 969 // Finally merge both checks and cast to pointer type. The inttoptr 970 // implicitly zexts the i1 to intptr type. 971 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType()); 972 } 973 974 // Check if all arguments are constants. If so, we can constant fold. 975 if (!CharC) 976 return nullptr; 977 978 // Compute the offset. 979 size_t I = Str.find(CharC->getSExtValue() & 0xFF); 980 if (I == StringRef::npos) // Didn't find the char. memchr returns null. 981 return Constant::getNullValue(CI->getType()); 982 983 // memchr(s+n,c,l) -> gep(s+n+i,c) 984 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr"); 985 } 986 987 static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS, 988 uint64_t Len, IRBuilder<> &B, 989 const DataLayout &DL) { 990 if (Len == 0) // memcmp(s1,s2,0) -> 0 991 return Constant::getNullValue(CI->getType()); 992 993 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 994 if (Len == 1) { 995 Value *LHSV = 996 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"), 997 CI->getType(), "lhsv"); 998 Value *RHSV = 999 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"), 1000 CI->getType(), "rhsv"); 1001 return B.CreateSub(LHSV, RHSV, "chardiff"); 1002 } 1003 1004 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0 1005 // TODO: The case where both inputs are constants does not need to be limited 1006 // to legal integers or equality comparison. See block below this. 1007 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) { 1008 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8); 1009 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType); 1010 1011 // First, see if we can fold either argument to a constant. 1012 Value *LHSV = nullptr; 1013 if (auto *LHSC = dyn_cast<Constant>(LHS)) { 1014 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo()); 1015 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL); 1016 } 1017 Value *RHSV = nullptr; 1018 if (auto *RHSC = dyn_cast<Constant>(RHS)) { 1019 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo()); 1020 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL); 1021 } 1022 1023 // Don't generate unaligned loads. If either source is constant data, 1024 // alignment doesn't matter for that source because there is no load. 1025 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) && 1026 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) { 1027 if (!LHSV) { 1028 Type *LHSPtrTy = 1029 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace()); 1030 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv"); 1031 } 1032 if (!RHSV) { 1033 Type *RHSPtrTy = 1034 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace()); 1035 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv"); 1036 } 1037 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp"); 1038 } 1039 } 1040 1041 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const). 1042 // TODO: This is limited to i8 arrays. 1043 StringRef LHSStr, RHSStr; 1044 if (getConstantStringInfo(LHS, LHSStr) && 1045 getConstantStringInfo(RHS, RHSStr)) { 1046 // Make sure we're not reading out-of-bounds memory. 1047 if (Len > LHSStr.size() || Len > RHSStr.size()) 1048 return nullptr; 1049 // Fold the memcmp and normalize the result. This way we get consistent 1050 // results across multiple platforms. 1051 uint64_t Ret = 0; 1052 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len); 1053 if (Cmp < 0) 1054 Ret = -1; 1055 else if (Cmp > 0) 1056 Ret = 1; 1057 return ConstantInt::get(CI->getType(), Ret); 1058 } 1059 1060 return nullptr; 1061 } 1062 1063 // Most simplifications for memcmp also apply to bcmp. 1064 Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI, 1065 IRBuilder<> &B) { 1066 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 1067 Value *Size = CI->getArgOperand(2); 1068 1069 if (LHS == RHS) // memcmp(s,s,x) -> 0 1070 return Constant::getNullValue(CI->getType()); 1071 1072 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1073 // Handle constant lengths. 1074 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1075 if (!LenC) 1076 return nullptr; 1077 1078 // memcmp(d,s,0) -> 0 1079 if (LenC->getZExtValue() == 0) 1080 return Constant::getNullValue(CI->getType()); 1081 1082 if (Value *Res = 1083 optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL)) 1084 return Res; 1085 return nullptr; 1086 } 1087 1088 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) { 1089 if (Value *V = optimizeMemCmpBCmpCommon(CI, B)) 1090 return V; 1091 1092 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0 1093 // bcmp can be more efficient than memcmp because it only has to know that 1094 // there is a difference, not how different one is to the other. 1095 if (TLI->has(LibFunc_bcmp) && isOnlyUsedInZeroEqualityComparison(CI)) { 1096 Value *LHS = CI->getArgOperand(0); 1097 Value *RHS = CI->getArgOperand(1); 1098 Value *Size = CI->getArgOperand(2); 1099 return emitBCmp(LHS, RHS, Size, B, DL, TLI); 1100 } 1101 1102 return nullptr; 1103 } 1104 1105 Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilder<> &B) { 1106 return optimizeMemCmpBCmpCommon(CI, B); 1107 } 1108 1109 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) { 1110 Value *Size = CI->getArgOperand(2); 1111 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1112 if (isa<IntrinsicInst>(CI)) 1113 return nullptr; 1114 1115 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n) 1116 CallInst *NewCI = 1117 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, Size); 1118 NewCI->setAttributes(CI->getAttributes()); 1119 return CI->getArgOperand(0); 1120 } 1121 1122 Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilder<> &B) { 1123 Value *Dst = CI->getArgOperand(0); 1124 Value *Src = CI->getArgOperand(1); 1125 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 1126 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3)); 1127 StringRef SrcStr; 1128 if (CI->use_empty() && Dst == Src) 1129 return Dst; 1130 // memccpy(d, s, c, 0) -> nullptr 1131 if (N) { 1132 if (N->isNullValue()) 1133 return Constant::getNullValue(CI->getType()); 1134 if (!getConstantStringInfo(Src, SrcStr, /*Offset=*/0, 1135 /*TrimAtNul=*/false) || 1136 !StopChar) 1137 return nullptr; 1138 } else { 1139 return nullptr; 1140 } 1141 1142 // Wrap arg 'c' of type int to char 1143 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF); 1144 if (Pos == StringRef::npos) { 1145 if (N->getZExtValue() <= SrcStr.size()) { 1146 B.CreateMemCpy(Dst, 1, Src, 1, CI->getArgOperand(3)); 1147 return Constant::getNullValue(CI->getType()); 1148 } 1149 return nullptr; 1150 } 1151 1152 Value *NewN = 1153 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue())); 1154 // memccpy -> llvm.memcpy 1155 B.CreateMemCpy(Dst, 1, Src, 1, NewN); 1156 return Pos + 1 <= N->getZExtValue() 1157 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN) 1158 : Constant::getNullValue(CI->getType()); 1159 } 1160 1161 Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilder<> &B) { 1162 Value *Dst = CI->getArgOperand(0); 1163 Value *N = CI->getArgOperand(2); 1164 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n 1165 CallInst *NewCI = B.CreateMemCpy(Dst, 1, CI->getArgOperand(1), 1, N); 1166 NewCI->setAttributes(CI->getAttributes()); 1167 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N); 1168 } 1169 1170 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) { 1171 Value *Size = CI->getArgOperand(2); 1172 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1173 if (isa<IntrinsicInst>(CI)) 1174 return nullptr; 1175 1176 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n) 1177 CallInst *NewCI = 1178 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, Size); 1179 NewCI->setAttributes(CI->getAttributes()); 1180 return CI->getArgOperand(0); 1181 } 1182 1183 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n). 1184 Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) { 1185 // This has to be a memset of zeros (bzero). 1186 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1)); 1187 if (!FillValue || FillValue->getZExtValue() != 0) 1188 return nullptr; 1189 1190 // TODO: We should handle the case where the malloc has more than one use. 1191 // This is necessary to optimize common patterns such as when the result of 1192 // the malloc is checked against null or when a memset intrinsic is used in 1193 // place of a memset library call. 1194 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0)); 1195 if (!Malloc || !Malloc->hasOneUse()) 1196 return nullptr; 1197 1198 // Is the inner call really malloc()? 1199 Function *InnerCallee = Malloc->getCalledFunction(); 1200 if (!InnerCallee) 1201 return nullptr; 1202 1203 LibFunc Func; 1204 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) || 1205 Func != LibFunc_malloc) 1206 return nullptr; 1207 1208 // The memset must cover the same number of bytes that are malloc'd. 1209 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0)) 1210 return nullptr; 1211 1212 // Replace the malloc with a calloc. We need the data layout to know what the 1213 // actual size of a 'size_t' parameter is. 1214 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator()); 1215 const DataLayout &DL = Malloc->getModule()->getDataLayout(); 1216 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext()); 1217 if (Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1), 1218 Malloc->getArgOperand(0), 1219 Malloc->getAttributes(), B, *TLI)) { 1220 substituteInParent(Malloc, Calloc); 1221 return Calloc; 1222 } 1223 1224 return nullptr; 1225 } 1226 1227 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) { 1228 Value *Size = CI->getArgOperand(2); 1229 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1230 if (isa<IntrinsicInst>(CI)) 1231 return nullptr; 1232 1233 if (auto *Calloc = foldMallocMemset(CI, B)) 1234 return Calloc; 1235 1236 // memset(p, v, n) -> llvm.memset(align 1 p, v, n) 1237 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 1238 CallInst *NewCI = 1239 B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align::None()); 1240 NewCI->setAttributes(CI->getAttributes()); 1241 return CI->getArgOperand(0); 1242 } 1243 1244 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) { 1245 if (isa<ConstantPointerNull>(CI->getArgOperand(0))) 1246 return emitMalloc(CI->getArgOperand(1), B, DL, TLI); 1247 1248 return nullptr; 1249 } 1250 1251 //===----------------------------------------------------------------------===// 1252 // Math Library Optimizations 1253 //===----------------------------------------------------------------------===// 1254 1255 // Replace a libcall \p CI with a call to intrinsic \p IID 1256 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) { 1257 // Propagate fast-math flags from the existing call to the new call. 1258 IRBuilder<>::FastMathFlagGuard Guard(B); 1259 B.setFastMathFlags(CI->getFastMathFlags()); 1260 1261 Module *M = CI->getModule(); 1262 Value *V = CI->getArgOperand(0); 1263 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType()); 1264 CallInst *NewCall = B.CreateCall(F, V); 1265 NewCall->takeName(CI); 1266 return NewCall; 1267 } 1268 1269 /// Return a variant of Val with float type. 1270 /// Currently this works in two cases: If Val is an FPExtension of a float 1271 /// value to something bigger, simply return the operand. 1272 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 1273 /// loss of precision do so. 1274 static Value *valueHasFloatPrecision(Value *Val) { 1275 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 1276 Value *Op = Cast->getOperand(0); 1277 if (Op->getType()->isFloatTy()) 1278 return Op; 1279 } 1280 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 1281 APFloat F = Const->getValueAPF(); 1282 bool losesInfo; 1283 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 1284 &losesInfo); 1285 if (!losesInfo) 1286 return ConstantFP::get(Const->getContext(), F); 1287 } 1288 return nullptr; 1289 } 1290 1291 /// Shrink double -> float functions. 1292 static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B, 1293 bool isBinary, bool isPrecise = false) { 1294 Function *CalleeFn = CI->getCalledFunction(); 1295 if (!CI->getType()->isDoubleTy() || !CalleeFn) 1296 return nullptr; 1297 1298 // If not all the uses of the function are converted to float, then bail out. 1299 // This matters if the precision of the result is more important than the 1300 // precision of the arguments. 1301 if (isPrecise) 1302 for (User *U : CI->users()) { 1303 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 1304 if (!Cast || !Cast->getType()->isFloatTy()) 1305 return nullptr; 1306 } 1307 1308 // If this is something like 'g((double) float)', convert to 'gf(float)'. 1309 Value *V[2]; 1310 V[0] = valueHasFloatPrecision(CI->getArgOperand(0)); 1311 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr; 1312 if (!V[0] || (isBinary && !V[1])) 1313 return nullptr; 1314 1315 // If call isn't an intrinsic, check that it isn't within a function with the 1316 // same name as the float version of this call, otherwise the result is an 1317 // infinite loop. For example, from MinGW-w64: 1318 // 1319 // float expf(float val) { return (float) exp((double) val); } 1320 StringRef CalleeName = CalleeFn->getName(); 1321 bool IsIntrinsic = CalleeFn->isIntrinsic(); 1322 if (!IsIntrinsic) { 1323 StringRef CallerName = CI->getFunction()->getName(); 1324 if (!CallerName.empty() && CallerName.back() == 'f' && 1325 CallerName.size() == (CalleeName.size() + 1) && 1326 CallerName.startswith(CalleeName)) 1327 return nullptr; 1328 } 1329 1330 // Propagate the math semantics from the current function to the new function. 1331 IRBuilder<>::FastMathFlagGuard Guard(B); 1332 B.setFastMathFlags(CI->getFastMathFlags()); 1333 1334 // g((double) float) -> (double) gf(float) 1335 Value *R; 1336 if (IsIntrinsic) { 1337 Module *M = CI->getModule(); 1338 Intrinsic::ID IID = CalleeFn->getIntrinsicID(); 1339 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy()); 1340 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]); 1341 } else { 1342 AttributeList CalleeAttrs = CalleeFn->getAttributes(); 1343 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeName, B, CalleeAttrs) 1344 : emitUnaryFloatFnCall(V[0], CalleeName, B, CalleeAttrs); 1345 } 1346 return B.CreateFPExt(R, B.getDoubleTy()); 1347 } 1348 1349 /// Shrink double -> float for unary functions. 1350 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B, 1351 bool isPrecise = false) { 1352 return optimizeDoubleFP(CI, B, false, isPrecise); 1353 } 1354 1355 /// Shrink double -> float for binary functions. 1356 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B, 1357 bool isPrecise = false) { 1358 return optimizeDoubleFP(CI, B, true, isPrecise); 1359 } 1360 1361 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1362 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) { 1363 if (!CI->isFast()) 1364 return nullptr; 1365 1366 // Propagate fast-math flags from the existing call to new instructions. 1367 IRBuilder<>::FastMathFlagGuard Guard(B); 1368 B.setFastMathFlags(CI->getFastMathFlags()); 1369 1370 Value *Real, *Imag; 1371 if (CI->getNumArgOperands() == 1) { 1372 Value *Op = CI->getArgOperand(0); 1373 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 1374 Real = B.CreateExtractValue(Op, 0, "real"); 1375 Imag = B.CreateExtractValue(Op, 1, "imag"); 1376 } else { 1377 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!"); 1378 Real = CI->getArgOperand(0); 1379 Imag = CI->getArgOperand(1); 1380 } 1381 1382 Value *RealReal = B.CreateFMul(Real, Real); 1383 Value *ImagImag = B.CreateFMul(Imag, Imag); 1384 1385 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt, 1386 CI->getType()); 1387 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs"); 1388 } 1389 1390 static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func, 1391 IRBuilder<> &B) { 1392 if (!isa<FPMathOperator>(Call)) 1393 return nullptr; 1394 1395 IRBuilder<>::FastMathFlagGuard Guard(B); 1396 B.setFastMathFlags(Call->getFastMathFlags()); 1397 1398 // TODO: Can this be shared to also handle LLVM intrinsics? 1399 Value *X; 1400 switch (Func) { 1401 case LibFunc_sin: 1402 case LibFunc_sinf: 1403 case LibFunc_sinl: 1404 case LibFunc_tan: 1405 case LibFunc_tanf: 1406 case LibFunc_tanl: 1407 // sin(-X) --> -sin(X) 1408 // tan(-X) --> -tan(X) 1409 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) 1410 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X)); 1411 break; 1412 case LibFunc_cos: 1413 case LibFunc_cosf: 1414 case LibFunc_cosl: 1415 // cos(-X) --> cos(X) 1416 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X)))) 1417 return B.CreateCall(Call->getCalledFunction(), X, "cos"); 1418 break; 1419 default: 1420 break; 1421 } 1422 return nullptr; 1423 } 1424 1425 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) { 1426 // Multiplications calculated using Addition Chains. 1427 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html 1428 1429 assert(Exp != 0 && "Incorrect exponent 0 not handled"); 1430 1431 if (InnerChain[Exp]) 1432 return InnerChain[Exp]; 1433 1434 static const unsigned AddChain[33][2] = { 1435 {0, 0}, // Unused. 1436 {0, 0}, // Unused (base case = pow1). 1437 {1, 1}, // Unused (pre-computed). 1438 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4}, 1439 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7}, 1440 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10}, 1441 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13}, 1442 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16}, 1443 }; 1444 1445 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B), 1446 getPow(InnerChain, AddChain[Exp][1], B)); 1447 return InnerChain[Exp]; 1448 } 1449 1450 // Return a properly extended 32-bit integer if the operation is an itofp. 1451 static Value *getIntToFPVal(Value *I2F, IRBuilder<> &B) { 1452 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) { 1453 Value *Op = cast<Instruction>(I2F)->getOperand(0); 1454 // Make sure that the exponent fits inside an int32_t, 1455 // thus avoiding any range issues that FP has not. 1456 unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits(); 1457 if (BitWidth < 32 || 1458 (BitWidth == 32 && isa<SIToFPInst>(I2F))) 1459 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getInt32Ty()) 1460 : B.CreateZExt(Op, B.getInt32Ty()); 1461 } 1462 1463 return nullptr; 1464 } 1465 1466 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y); 1467 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x); 1468 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x). 1469 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) { 1470 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1471 AttributeList Attrs = Pow->getCalledFunction()->getAttributes(); 1472 Module *Mod = Pow->getModule(); 1473 Type *Ty = Pow->getType(); 1474 bool Ignored; 1475 1476 // Evaluate special cases related to a nested function as the base. 1477 1478 // pow(exp(x), y) -> exp(x * y) 1479 // pow(exp2(x), y) -> exp2(x * y) 1480 // If exp{,2}() is used only once, it is better to fold two transcendental 1481 // math functions into one. If used again, exp{,2}() would still have to be 1482 // called with the original argument, then keep both original transcendental 1483 // functions. However, this transformation is only safe with fully relaxed 1484 // math semantics, since, besides rounding differences, it changes overflow 1485 // and underflow behavior quite dramatically. For example: 1486 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf 1487 // Whereas: 1488 // exp(1000 * 0.001) = exp(1) 1489 // TODO: Loosen the requirement for fully relaxed math semantics. 1490 // TODO: Handle exp10() when more targets have it available. 1491 CallInst *BaseFn = dyn_cast<CallInst>(Base); 1492 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) { 1493 LibFunc LibFn; 1494 1495 Function *CalleeFn = BaseFn->getCalledFunction(); 1496 if (CalleeFn && 1497 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) { 1498 StringRef ExpName; 1499 Intrinsic::ID ID; 1500 Value *ExpFn; 1501 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble; 1502 1503 switch (LibFn) { 1504 default: 1505 return nullptr; 1506 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl: 1507 ExpName = TLI->getName(LibFunc_exp); 1508 ID = Intrinsic::exp; 1509 LibFnFloat = LibFunc_expf; 1510 LibFnDouble = LibFunc_exp; 1511 LibFnLongDouble = LibFunc_expl; 1512 break; 1513 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l: 1514 ExpName = TLI->getName(LibFunc_exp2); 1515 ID = Intrinsic::exp2; 1516 LibFnFloat = LibFunc_exp2f; 1517 LibFnDouble = LibFunc_exp2; 1518 LibFnLongDouble = LibFunc_exp2l; 1519 break; 1520 } 1521 1522 // Create new exp{,2}() with the product as its argument. 1523 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul"); 1524 ExpFn = BaseFn->doesNotAccessMemory() 1525 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty), 1526 FMul, ExpName) 1527 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat, 1528 LibFnLongDouble, B, 1529 BaseFn->getAttributes()); 1530 1531 // Since the new exp{,2}() is different from the original one, dead code 1532 // elimination cannot be trusted to remove it, since it may have side 1533 // effects (e.g., errno). When the only consumer for the original 1534 // exp{,2}() is pow(), then it has to be explicitly erased. 1535 substituteInParent(BaseFn, ExpFn); 1536 return ExpFn; 1537 } 1538 } 1539 1540 // Evaluate special cases related to a constant base. 1541 1542 const APFloat *BaseF; 1543 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF))) 1544 return nullptr; 1545 1546 // pow(2.0, itofp(x)) -> ldexp(1.0, x) 1547 if (match(Base, m_SpecificFP(2.0)) && 1548 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) && 1549 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) { 1550 if (Value *ExpoI = getIntToFPVal(Expo, B)) 1551 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI, TLI, 1552 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl, 1553 B, Attrs); 1554 } 1555 1556 // pow(2.0 ** n, x) -> exp2(n * x) 1557 if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) { 1558 APFloat BaseR = APFloat(1.0); 1559 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored); 1560 BaseR = BaseR / *BaseF; 1561 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger(); 1562 const APFloat *NF = IsReciprocal ? &BaseR : BaseF; 1563 APSInt NI(64, false); 1564 if ((IsInteger || IsReciprocal) && 1565 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) == 1566 APFloat::opOK && 1567 NI > 1 && NI.isPowerOf2()) { 1568 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0); 1569 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul"); 1570 if (Pow->doesNotAccessMemory()) 1571 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty), 1572 FMul, "exp2"); 1573 else 1574 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f, 1575 LibFunc_exp2l, B, Attrs); 1576 } 1577 } 1578 1579 // pow(10.0, x) -> exp10(x) 1580 // TODO: There is no exp10() intrinsic yet, but some day there shall be one. 1581 if (match(Base, m_SpecificFP(10.0)) && 1582 hasFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) 1583 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f, 1584 LibFunc_exp10l, B, Attrs); 1585 1586 // pow(n, x) -> exp2(log2(n) * x) 1587 if (Pow->hasOneUse() && Pow->hasApproxFunc() && Pow->hasNoNaNs() && 1588 Pow->hasNoInfs() && BaseF->isNormal() && !BaseF->isNegative()) { 1589 Value *Log = nullptr; 1590 if (Ty->isFloatTy()) 1591 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat())); 1592 else if (Ty->isDoubleTy()) 1593 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble())); 1594 1595 if (Log) { 1596 Value *FMul = B.CreateFMul(Log, Expo, "mul"); 1597 if (Pow->doesNotAccessMemory()) 1598 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty), 1599 FMul, "exp2"); 1600 else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) 1601 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f, 1602 LibFunc_exp2l, B, Attrs); 1603 } 1604 } 1605 1606 return nullptr; 1607 } 1608 1609 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, 1610 Module *M, IRBuilder<> &B, 1611 const TargetLibraryInfo *TLI) { 1612 // If errno is never set, then use the intrinsic for sqrt(). 1613 if (NoErrno) { 1614 Function *SqrtFn = 1615 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType()); 1616 return B.CreateCall(SqrtFn, V, "sqrt"); 1617 } 1618 1619 // Otherwise, use the libcall for sqrt(). 1620 if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl)) 1621 // TODO: We also should check that the target can in fact lower the sqrt() 1622 // libcall. We currently have no way to ask this question, so we ask if 1623 // the target has a sqrt() libcall, which is not exactly the same. 1624 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf, 1625 LibFunc_sqrtl, B, Attrs); 1626 1627 return nullptr; 1628 } 1629 1630 /// Use square root in place of pow(x, +/-0.5). 1631 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) { 1632 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1633 AttributeList Attrs = Pow->getCalledFunction()->getAttributes(); 1634 Module *Mod = Pow->getModule(); 1635 Type *Ty = Pow->getType(); 1636 1637 const APFloat *ExpoF; 1638 if (!match(Expo, m_APFloat(ExpoF)) || 1639 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 1640 return nullptr; 1641 1642 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI); 1643 if (!Sqrt) 1644 return nullptr; 1645 1646 // Handle signed zero base by expanding to fabs(sqrt(x)). 1647 if (!Pow->hasNoSignedZeros()) { 1648 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty); 1649 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs"); 1650 } 1651 1652 // Handle non finite base by expanding to 1653 // (x == -infinity ? +infinity : sqrt(x)). 1654 if (!Pow->hasNoInfs()) { 1655 Value *PosInf = ConstantFP::getInfinity(Ty), 1656 *NegInf = ConstantFP::getInfinity(Ty, true); 1657 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 1658 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 1659 } 1660 1661 // If the exponent is negative, then get the reciprocal. 1662 if (ExpoF->isNegative()) 1663 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 1664 1665 return Sqrt; 1666 } 1667 1668 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, 1669 IRBuilder<> &B) { 1670 Value *Args[] = {Base, Expo}; 1671 Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Base->getType()); 1672 return B.CreateCall(F, Args); 1673 } 1674 1675 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) { 1676 Value *Base = Pow->getArgOperand(0); 1677 Value *Expo = Pow->getArgOperand(1); 1678 Function *Callee = Pow->getCalledFunction(); 1679 StringRef Name = Callee->getName(); 1680 Type *Ty = Pow->getType(); 1681 Module *M = Pow->getModule(); 1682 Value *Shrunk = nullptr; 1683 bool AllowApprox = Pow->hasApproxFunc(); 1684 bool Ignored; 1685 1686 // Bail out if simplifying libcalls to pow() is disabled. 1687 if (!hasFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl)) 1688 return nullptr; 1689 1690 // Propagate the math semantics from the call to any created instructions. 1691 IRBuilder<>::FastMathFlagGuard Guard(B); 1692 B.setFastMathFlags(Pow->getFastMathFlags()); 1693 1694 // Shrink pow() to powf() if the arguments are single precision, 1695 // unless the result is expected to be double precision. 1696 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) && 1697 hasFloatVersion(Name)) 1698 Shrunk = optimizeBinaryDoubleFP(Pow, B, true); 1699 1700 // Evaluate special cases related to the base. 1701 1702 // pow(1.0, x) -> 1.0 1703 if (match(Base, m_FPOne())) 1704 return Base; 1705 1706 if (Value *Exp = replacePowWithExp(Pow, B)) 1707 return Exp; 1708 1709 // Evaluate special cases related to the exponent. 1710 1711 // pow(x, -1.0) -> 1.0 / x 1712 if (match(Expo, m_SpecificFP(-1.0))) 1713 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 1714 1715 // pow(x, +/-0.0) -> 1.0 1716 if (match(Expo, m_AnyZeroFP())) 1717 return ConstantFP::get(Ty, 1.0); 1718 1719 // pow(x, 1.0) -> x 1720 if (match(Expo, m_FPOne())) 1721 return Base; 1722 1723 // pow(x, 2.0) -> x * x 1724 if (match(Expo, m_SpecificFP(2.0))) 1725 return B.CreateFMul(Base, Base, "square"); 1726 1727 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 1728 return Sqrt; 1729 1730 // pow(x, n) -> x * x * x * ... 1731 const APFloat *ExpoF; 1732 if (AllowApprox && match(Expo, m_APFloat(ExpoF))) { 1733 // We limit to a max of 7 multiplications, thus the maximum exponent is 32. 1734 // If the exponent is an integer+0.5 we generate a call to sqrt and an 1735 // additional fmul. 1736 // TODO: This whole transformation should be backend specific (e.g. some 1737 // backends might prefer libcalls or the limit for the exponent might 1738 // be different) and it should also consider optimizing for size. 1739 APFloat LimF(ExpoF->getSemantics(), 33), 1740 ExpoA(abs(*ExpoF)); 1741 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) { 1742 // This transformation applies to integer or integer+0.5 exponents only. 1743 // For integer+0.5, we create a sqrt(Base) call. 1744 Value *Sqrt = nullptr; 1745 if (!ExpoA.isInteger()) { 1746 APFloat Expo2 = ExpoA; 1747 // To check if ExpoA is an integer + 0.5, we add it to itself. If there 1748 // is no floating point exception and the result is an integer, then 1749 // ExpoA == integer + 0.5 1750 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK) 1751 return nullptr; 1752 1753 if (!Expo2.isInteger()) 1754 return nullptr; 1755 1756 Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(), 1757 Pow->doesNotAccessMemory(), M, B, TLI); 1758 } 1759 1760 // We will memoize intermediate products of the Addition Chain. 1761 Value *InnerChain[33] = {nullptr}; 1762 InnerChain[1] = Base; 1763 InnerChain[2] = B.CreateFMul(Base, Base, "square"); 1764 1765 // We cannot readily convert a non-double type (like float) to a double. 1766 // So we first convert it to something which could be converted to double. 1767 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored); 1768 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B); 1769 1770 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x). 1771 if (Sqrt) 1772 FMul = B.CreateFMul(FMul, Sqrt); 1773 1774 // If the exponent is negative, then get the reciprocal. 1775 if (ExpoF->isNegative()) 1776 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal"); 1777 1778 return FMul; 1779 } 1780 1781 APSInt IntExpo(32, /*isUnsigned=*/false); 1782 // powf(x, n) -> powi(x, n) if n is a constant signed integer value 1783 if (ExpoF->isInteger() && 1784 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) == 1785 APFloat::opOK) { 1786 return createPowWithIntegerExponent( 1787 Base, ConstantInt::get(B.getInt32Ty(), IntExpo), M, B); 1788 } 1789 } 1790 1791 // powf(x, itofp(y)) -> powi(x, y) 1792 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) { 1793 if (Value *ExpoI = getIntToFPVal(Expo, B)) 1794 return createPowWithIntegerExponent(Base, ExpoI, M, B); 1795 } 1796 1797 return Shrunk; 1798 } 1799 1800 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) { 1801 Function *Callee = CI->getCalledFunction(); 1802 StringRef Name = Callee->getName(); 1803 Value *Ret = nullptr; 1804 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) && 1805 hasFloatVersion(Name)) 1806 Ret = optimizeUnaryDoubleFP(CI, B, true); 1807 1808 Type *Ty = CI->getType(); 1809 Value *Op = CI->getArgOperand(0); 1810 1811 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32 1812 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32 1813 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) && 1814 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) { 1815 if (Value *Exp = getIntToFPVal(Op, B)) 1816 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI, 1817 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl, 1818 B, CI->getCalledFunction()->getAttributes()); 1819 } 1820 1821 return Ret; 1822 } 1823 1824 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) { 1825 // If we can shrink the call to a float function rather than a double 1826 // function, do that first. 1827 Function *Callee = CI->getCalledFunction(); 1828 StringRef Name = Callee->getName(); 1829 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name)) 1830 if (Value *Ret = optimizeBinaryDoubleFP(CI, B)) 1831 return Ret; 1832 1833 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to 1834 // the intrinsics for improved optimization (for example, vectorization). 1835 // No-signed-zeros is implied by the definitions of fmax/fmin themselves. 1836 // From the C standard draft WG14/N1256: 1837 // "Ideally, fmax would be sensitive to the sign of zero, for example 1838 // fmax(-0.0, +0.0) would return +0; however, implementation in software 1839 // might be impractical." 1840 IRBuilder<>::FastMathFlagGuard Guard(B); 1841 FastMathFlags FMF = CI->getFastMathFlags(); 1842 FMF.setNoSignedZeros(); 1843 B.setFastMathFlags(FMF); 1844 1845 Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum 1846 : Intrinsic::maxnum; 1847 Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType()); 1848 return B.CreateCall(F, { CI->getArgOperand(0), CI->getArgOperand(1) }); 1849 } 1850 1851 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilder<> &B) { 1852 Function *LogFn = Log->getCalledFunction(); 1853 AttributeList Attrs = LogFn->getAttributes(); 1854 StringRef LogNm = LogFn->getName(); 1855 Intrinsic::ID LogID = LogFn->getIntrinsicID(); 1856 Module *Mod = Log->getModule(); 1857 Type *Ty = Log->getType(); 1858 Value *Ret = nullptr; 1859 1860 if (UnsafeFPShrink && hasFloatVersion(LogNm)) 1861 Ret = optimizeUnaryDoubleFP(Log, B, true); 1862 1863 // The earlier call must also be 'fast' in order to do these transforms. 1864 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0)); 1865 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse()) 1866 return Ret; 1867 1868 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb; 1869 1870 // This is only applicable to log(), log2(), log10(). 1871 if (TLI->getLibFunc(LogNm, LogLb)) 1872 switch (LogLb) { 1873 case LibFunc_logf: 1874 LogID = Intrinsic::log; 1875 ExpLb = LibFunc_expf; 1876 Exp2Lb = LibFunc_exp2f; 1877 Exp10Lb = LibFunc_exp10f; 1878 PowLb = LibFunc_powf; 1879 break; 1880 case LibFunc_log: 1881 LogID = Intrinsic::log; 1882 ExpLb = LibFunc_exp; 1883 Exp2Lb = LibFunc_exp2; 1884 Exp10Lb = LibFunc_exp10; 1885 PowLb = LibFunc_pow; 1886 break; 1887 case LibFunc_logl: 1888 LogID = Intrinsic::log; 1889 ExpLb = LibFunc_expl; 1890 Exp2Lb = LibFunc_exp2l; 1891 Exp10Lb = LibFunc_exp10l; 1892 PowLb = LibFunc_powl; 1893 break; 1894 case LibFunc_log2f: 1895 LogID = Intrinsic::log2; 1896 ExpLb = LibFunc_expf; 1897 Exp2Lb = LibFunc_exp2f; 1898 Exp10Lb = LibFunc_exp10f; 1899 PowLb = LibFunc_powf; 1900 break; 1901 case LibFunc_log2: 1902 LogID = Intrinsic::log2; 1903 ExpLb = LibFunc_exp; 1904 Exp2Lb = LibFunc_exp2; 1905 Exp10Lb = LibFunc_exp10; 1906 PowLb = LibFunc_pow; 1907 break; 1908 case LibFunc_log2l: 1909 LogID = Intrinsic::log2; 1910 ExpLb = LibFunc_expl; 1911 Exp2Lb = LibFunc_exp2l; 1912 Exp10Lb = LibFunc_exp10l; 1913 PowLb = LibFunc_powl; 1914 break; 1915 case LibFunc_log10f: 1916 LogID = Intrinsic::log10; 1917 ExpLb = LibFunc_expf; 1918 Exp2Lb = LibFunc_exp2f; 1919 Exp10Lb = LibFunc_exp10f; 1920 PowLb = LibFunc_powf; 1921 break; 1922 case LibFunc_log10: 1923 LogID = Intrinsic::log10; 1924 ExpLb = LibFunc_exp; 1925 Exp2Lb = LibFunc_exp2; 1926 Exp10Lb = LibFunc_exp10; 1927 PowLb = LibFunc_pow; 1928 break; 1929 case LibFunc_log10l: 1930 LogID = Intrinsic::log10; 1931 ExpLb = LibFunc_expl; 1932 Exp2Lb = LibFunc_exp2l; 1933 Exp10Lb = LibFunc_exp10l; 1934 PowLb = LibFunc_powl; 1935 break; 1936 default: 1937 return Ret; 1938 } 1939 else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 || 1940 LogID == Intrinsic::log10) { 1941 if (Ty->getScalarType()->isFloatTy()) { 1942 ExpLb = LibFunc_expf; 1943 Exp2Lb = LibFunc_exp2f; 1944 Exp10Lb = LibFunc_exp10f; 1945 PowLb = LibFunc_powf; 1946 } else if (Ty->getScalarType()->isDoubleTy()) { 1947 ExpLb = LibFunc_exp; 1948 Exp2Lb = LibFunc_exp2; 1949 Exp10Lb = LibFunc_exp10; 1950 PowLb = LibFunc_pow; 1951 } else 1952 return Ret; 1953 } else 1954 return Ret; 1955 1956 IRBuilder<>::FastMathFlagGuard Guard(B); 1957 B.setFastMathFlags(FastMathFlags::getFast()); 1958 1959 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 1960 LibFunc ArgLb = NotLibFunc; 1961 TLI->getLibFunc(Arg, ArgLb); 1962 1963 // log(pow(x,y)) -> y*log(x) 1964 if (ArgLb == PowLb || ArgID == Intrinsic::pow) { 1965 Value *LogX = 1966 Log->doesNotAccessMemory() 1967 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty), 1968 Arg->getOperand(0), "log") 1969 : emitUnaryFloatFnCall(Arg->getOperand(0), LogNm, B, Attrs); 1970 Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul"); 1971 // Since pow() may have side effects, e.g. errno, 1972 // dead code elimination may not be trusted to remove it. 1973 substituteInParent(Arg, MulY); 1974 return MulY; 1975 } 1976 1977 // log(exp{,2,10}(y)) -> y*log({e,2,10}) 1978 // TODO: There is no exp10() intrinsic yet. 1979 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb || 1980 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) { 1981 Constant *Eul; 1982 if (ArgLb == ExpLb || ArgID == Intrinsic::exp) 1983 // FIXME: Add more precise value of e for long double. 1984 Eul = ConstantFP::get(Log->getType(), numbers::e); 1985 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2) 1986 Eul = ConstantFP::get(Log->getType(), 2.0); 1987 else 1988 Eul = ConstantFP::get(Log->getType(), 10.0); 1989 Value *LogE = Log->doesNotAccessMemory() 1990 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty), 1991 Eul, "log") 1992 : emitUnaryFloatFnCall(Eul, LogNm, B, Attrs); 1993 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul"); 1994 // Since exp() may have side effects, e.g. errno, 1995 // dead code elimination may not be trusted to remove it. 1996 substituteInParent(Arg, MulY); 1997 return MulY; 1998 } 1999 2000 return Ret; 2001 } 2002 2003 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) { 2004 Function *Callee = CI->getCalledFunction(); 2005 Value *Ret = nullptr; 2006 // TODO: Once we have a way (other than checking for the existince of the 2007 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 2008 // condition below. 2009 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" || 2010 Callee->getIntrinsicID() == Intrinsic::sqrt)) 2011 Ret = optimizeUnaryDoubleFP(CI, B, true); 2012 2013 if (!CI->isFast()) 2014 return Ret; 2015 2016 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 2017 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 2018 return Ret; 2019 2020 // We're looking for a repeated factor in a multiplication tree, 2021 // so we can do this fold: sqrt(x * x) -> fabs(x); 2022 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 2023 Value *Op0 = I->getOperand(0); 2024 Value *Op1 = I->getOperand(1); 2025 Value *RepeatOp = nullptr; 2026 Value *OtherOp = nullptr; 2027 if (Op0 == Op1) { 2028 // Simple match: the operands of the multiply are identical. 2029 RepeatOp = Op0; 2030 } else { 2031 // Look for a more complicated pattern: one of the operands is itself 2032 // a multiply, so search for a common factor in that multiply. 2033 // Note: We don't bother looking any deeper than this first level or for 2034 // variations of this pattern because instcombine's visitFMUL and/or the 2035 // reassociation pass should give us this form. 2036 Value *OtherMul0, *OtherMul1; 2037 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) { 2038 // Pattern: sqrt((x * y) * z) 2039 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) { 2040 // Matched: sqrt((x * x) * z) 2041 RepeatOp = OtherMul0; 2042 OtherOp = Op1; 2043 } 2044 } 2045 } 2046 if (!RepeatOp) 2047 return Ret; 2048 2049 // Fast math flags for any created instructions should match the sqrt 2050 // and multiply. 2051 IRBuilder<>::FastMathFlagGuard Guard(B); 2052 B.setFastMathFlags(I->getFastMathFlags()); 2053 2054 // If we found a repeated factor, hoist it out of the square root and 2055 // replace it with the fabs of that factor. 2056 Module *M = Callee->getParent(); 2057 Type *ArgType = I->getType(); 2058 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType); 2059 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs"); 2060 if (OtherOp) { 2061 // If we found a non-repeated factor, we still need to get its square 2062 // root. We then multiply that by the value that was simplified out 2063 // of the square root calculation. 2064 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType); 2065 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt"); 2066 return B.CreateFMul(FabsCall, SqrtCall); 2067 } 2068 return FabsCall; 2069 } 2070 2071 // TODO: Generalize to handle any trig function and its inverse. 2072 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) { 2073 Function *Callee = CI->getCalledFunction(); 2074 Value *Ret = nullptr; 2075 StringRef Name = Callee->getName(); 2076 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name)) 2077 Ret = optimizeUnaryDoubleFP(CI, B, true); 2078 2079 Value *Op1 = CI->getArgOperand(0); 2080 auto *OpC = dyn_cast<CallInst>(Op1); 2081 if (!OpC) 2082 return Ret; 2083 2084 // Both calls must be 'fast' in order to remove them. 2085 if (!CI->isFast() || !OpC->isFast()) 2086 return Ret; 2087 2088 // tan(atan(x)) -> x 2089 // tanf(atanf(x)) -> x 2090 // tanl(atanl(x)) -> x 2091 LibFunc Func; 2092 Function *F = OpC->getCalledFunction(); 2093 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 2094 ((Func == LibFunc_atan && Callee->getName() == "tan") || 2095 (Func == LibFunc_atanf && Callee->getName() == "tanf") || 2096 (Func == LibFunc_atanl && Callee->getName() == "tanl"))) 2097 Ret = OpC->getArgOperand(0); 2098 return Ret; 2099 } 2100 2101 static bool isTrigLibCall(CallInst *CI) { 2102 // We can only hope to do anything useful if we can ignore things like errno 2103 // and floating-point exceptions. 2104 // We already checked the prototype. 2105 return CI->hasFnAttr(Attribute::NoUnwind) && 2106 CI->hasFnAttr(Attribute::ReadNone); 2107 } 2108 2109 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, 2110 bool UseFloat, Value *&Sin, Value *&Cos, 2111 Value *&SinCos) { 2112 Type *ArgTy = Arg->getType(); 2113 Type *ResTy; 2114 StringRef Name; 2115 2116 Triple T(OrigCallee->getParent()->getTargetTriple()); 2117 if (UseFloat) { 2118 Name = "__sincospif_stret"; 2119 2120 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 2121 // x86_64 can't use {float, float} since that would be returned in both 2122 // xmm0 and xmm1, which isn't what a real struct would do. 2123 ResTy = T.getArch() == Triple::x86_64 2124 ? static_cast<Type *>(VectorType::get(ArgTy, 2)) 2125 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 2126 } else { 2127 Name = "__sincospi_stret"; 2128 ResTy = StructType::get(ArgTy, ArgTy); 2129 } 2130 2131 Module *M = OrigCallee->getParent(); 2132 FunctionCallee Callee = 2133 M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy); 2134 2135 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 2136 // If the argument is an instruction, it must dominate all uses so put our 2137 // sincos call there. 2138 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 2139 } else { 2140 // Otherwise (e.g. for a constant) the beginning of the function is as 2141 // good a place as any. 2142 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 2143 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 2144 } 2145 2146 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 2147 2148 if (SinCos->getType()->isStructTy()) { 2149 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 2150 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 2151 } else { 2152 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 2153 "sinpi"); 2154 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 2155 "cospi"); 2156 } 2157 } 2158 2159 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) { 2160 // Make sure the prototype is as expected, otherwise the rest of the 2161 // function is probably invalid and likely to abort. 2162 if (!isTrigLibCall(CI)) 2163 return nullptr; 2164 2165 Value *Arg = CI->getArgOperand(0); 2166 SmallVector<CallInst *, 1> SinCalls; 2167 SmallVector<CallInst *, 1> CosCalls; 2168 SmallVector<CallInst *, 1> SinCosCalls; 2169 2170 bool IsFloat = Arg->getType()->isFloatTy(); 2171 2172 // Look for all compatible sinpi, cospi and sincospi calls with the same 2173 // argument. If there are enough (in some sense) we can make the 2174 // substitution. 2175 Function *F = CI->getFunction(); 2176 for (User *U : Arg->users()) 2177 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 2178 2179 // It's only worthwhile if both sinpi and cospi are actually used. 2180 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty())) 2181 return nullptr; 2182 2183 Value *Sin, *Cos, *SinCos; 2184 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos); 2185 2186 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 2187 Value *Res) { 2188 for (CallInst *C : Calls) 2189 replaceAllUsesWith(C, Res); 2190 }; 2191 2192 replaceTrigInsts(SinCalls, Sin); 2193 replaceTrigInsts(CosCalls, Cos); 2194 replaceTrigInsts(SinCosCalls, SinCos); 2195 2196 return nullptr; 2197 } 2198 2199 void LibCallSimplifier::classifyArgUse( 2200 Value *Val, Function *F, bool IsFloat, 2201 SmallVectorImpl<CallInst *> &SinCalls, 2202 SmallVectorImpl<CallInst *> &CosCalls, 2203 SmallVectorImpl<CallInst *> &SinCosCalls) { 2204 CallInst *CI = dyn_cast<CallInst>(Val); 2205 2206 if (!CI) 2207 return; 2208 2209 // Don't consider calls in other functions. 2210 if (CI->getFunction() != F) 2211 return; 2212 2213 Function *Callee = CI->getCalledFunction(); 2214 LibFunc Func; 2215 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) || 2216 !isTrigLibCall(CI)) 2217 return; 2218 2219 if (IsFloat) { 2220 if (Func == LibFunc_sinpif) 2221 SinCalls.push_back(CI); 2222 else if (Func == LibFunc_cospif) 2223 CosCalls.push_back(CI); 2224 else if (Func == LibFunc_sincospif_stret) 2225 SinCosCalls.push_back(CI); 2226 } else { 2227 if (Func == LibFunc_sinpi) 2228 SinCalls.push_back(CI); 2229 else if (Func == LibFunc_cospi) 2230 CosCalls.push_back(CI); 2231 else if (Func == LibFunc_sincospi_stret) 2232 SinCosCalls.push_back(CI); 2233 } 2234 } 2235 2236 //===----------------------------------------------------------------------===// 2237 // Integer Library Call Optimizations 2238 //===----------------------------------------------------------------------===// 2239 2240 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) { 2241 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 2242 Value *Op = CI->getArgOperand(0); 2243 Type *ArgType = Op->getType(); 2244 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 2245 Intrinsic::cttz, ArgType); 2246 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz"); 2247 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 2248 V = B.CreateIntCast(V, B.getInt32Ty(), false); 2249 2250 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 2251 return B.CreateSelect(Cond, V, B.getInt32(0)); 2252 } 2253 2254 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) { 2255 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false)) 2256 Value *Op = CI->getArgOperand(0); 2257 Type *ArgType = Op->getType(); 2258 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 2259 Intrinsic::ctlz, ArgType); 2260 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz"); 2261 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 2262 V); 2263 return B.CreateIntCast(V, CI->getType(), false); 2264 } 2265 2266 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) { 2267 // abs(x) -> x <s 0 ? -x : x 2268 // The negation has 'nsw' because abs of INT_MIN is undefined. 2269 Value *X = CI->getArgOperand(0); 2270 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType())); 2271 Value *NegX = B.CreateNSWNeg(X, "neg"); 2272 return B.CreateSelect(IsNeg, NegX, X); 2273 } 2274 2275 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) { 2276 // isdigit(c) -> (c-'0') <u 10 2277 Value *Op = CI->getArgOperand(0); 2278 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp"); 2279 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit"); 2280 return B.CreateZExt(Op, CI->getType()); 2281 } 2282 2283 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) { 2284 // isascii(c) -> c <u 128 2285 Value *Op = CI->getArgOperand(0); 2286 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii"); 2287 return B.CreateZExt(Op, CI->getType()); 2288 } 2289 2290 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) { 2291 // toascii(c) -> c & 0x7f 2292 return B.CreateAnd(CI->getArgOperand(0), 2293 ConstantInt::get(CI->getType(), 0x7F)); 2294 } 2295 2296 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) { 2297 StringRef Str; 2298 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2299 return nullptr; 2300 2301 return convertStrToNumber(CI, Str, 10); 2302 } 2303 2304 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) { 2305 StringRef Str; 2306 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2307 return nullptr; 2308 2309 if (!isa<ConstantPointerNull>(CI->getArgOperand(1))) 2310 return nullptr; 2311 2312 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) { 2313 return convertStrToNumber(CI, Str, CInt->getSExtValue()); 2314 } 2315 2316 return nullptr; 2317 } 2318 2319 //===----------------------------------------------------------------------===// 2320 // Formatting and IO Library Call Optimizations 2321 //===----------------------------------------------------------------------===// 2322 2323 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 2324 2325 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B, 2326 int StreamArg) { 2327 Function *Callee = CI->getCalledFunction(); 2328 // Error reporting calls should be cold, mark them as such. 2329 // This applies even to non-builtin calls: it is only a hint and applies to 2330 // functions that the frontend might not understand as builtins. 2331 2332 // This heuristic was suggested in: 2333 // Improving Static Branch Prediction in a Compiler 2334 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 2335 // Proceedings of PACT'98, Oct. 1998, IEEE 2336 if (!CI->hasFnAttr(Attribute::Cold) && 2337 isReportingError(Callee, CI, StreamArg)) { 2338 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold); 2339 } 2340 2341 return nullptr; 2342 } 2343 2344 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 2345 if (!Callee || !Callee->isDeclaration()) 2346 return false; 2347 2348 if (StreamArg < 0) 2349 return true; 2350 2351 // These functions might be considered cold, but only if their stream 2352 // argument is stderr. 2353 2354 if (StreamArg >= (int)CI->getNumArgOperands()) 2355 return false; 2356 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 2357 if (!LI) 2358 return false; 2359 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 2360 if (!GV || !GV->isDeclaration()) 2361 return false; 2362 return GV->getName() == "stderr"; 2363 } 2364 2365 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) { 2366 // Check for a fixed format string. 2367 StringRef FormatStr; 2368 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 2369 return nullptr; 2370 2371 // Empty format string -> noop. 2372 if (FormatStr.empty()) // Tolerate printf's declared void. 2373 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 2374 2375 // Do not do any of the following transformations if the printf return value 2376 // is used, in general the printf return value is not compatible with either 2377 // putchar() or puts(). 2378 if (!CI->use_empty()) 2379 return nullptr; 2380 2381 // printf("x") -> putchar('x'), even for "%" and "%%". 2382 if (FormatStr.size() == 1 || FormatStr == "%%") 2383 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI); 2384 2385 // printf("%s", "a") --> putchar('a') 2386 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) { 2387 StringRef ChrStr; 2388 if (!getConstantStringInfo(CI->getOperand(1), ChrStr)) 2389 return nullptr; 2390 if (ChrStr.size() != 1) 2391 return nullptr; 2392 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI); 2393 } 2394 2395 // printf("foo\n") --> puts("foo") 2396 if (FormatStr[FormatStr.size() - 1] == '\n' && 2397 FormatStr.find('%') == StringRef::npos) { // No format characters. 2398 // Create a string literal with no \n on it. We expect the constant merge 2399 // pass to be run after this pass, to merge duplicate strings. 2400 FormatStr = FormatStr.drop_back(); 2401 Value *GV = B.CreateGlobalString(FormatStr, "str"); 2402 return emitPutS(GV, B, TLI); 2403 } 2404 2405 // Optimize specific format strings. 2406 // printf("%c", chr) --> putchar(chr) 2407 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 && 2408 CI->getArgOperand(1)->getType()->isIntegerTy()) 2409 return emitPutChar(CI->getArgOperand(1), B, TLI); 2410 2411 // printf("%s\n", str) --> puts(str) 2412 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 && 2413 CI->getArgOperand(1)->getType()->isPointerTy()) 2414 return emitPutS(CI->getArgOperand(1), B, TLI); 2415 return nullptr; 2416 } 2417 2418 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) { 2419 2420 Function *Callee = CI->getCalledFunction(); 2421 FunctionType *FT = Callee->getFunctionType(); 2422 if (Value *V = optimizePrintFString(CI, B)) { 2423 return V; 2424 } 2425 2426 // printf(format, ...) -> iprintf(format, ...) if no floating point 2427 // arguments. 2428 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) { 2429 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2430 FunctionCallee IPrintFFn = 2431 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes()); 2432 CallInst *New = cast<CallInst>(CI->clone()); 2433 New->setCalledFunction(IPrintFFn); 2434 B.Insert(New); 2435 return New; 2436 } 2437 2438 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point 2439 // arguments. 2440 if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) { 2441 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2442 auto SmallPrintFFn = 2443 M->getOrInsertFunction(TLI->getName(LibFunc_small_printf), 2444 FT, Callee->getAttributes()); 2445 CallInst *New = cast<CallInst>(CI->clone()); 2446 New->setCalledFunction(SmallPrintFFn); 2447 B.Insert(New); 2448 return New; 2449 } 2450 2451 annotateNonNullBasedOnAccess(CI, 0); 2452 return nullptr; 2453 } 2454 2455 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) { 2456 // Check for a fixed format string. 2457 StringRef FormatStr; 2458 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 2459 return nullptr; 2460 2461 // If we just have a format string (nothing else crazy) transform it. 2462 if (CI->getNumArgOperands() == 2) { 2463 // Make sure there's no % in the constant array. We could try to handle 2464 // %% -> % in the future if we cared. 2465 if (FormatStr.find('%') != StringRef::npos) 2466 return nullptr; // we found a format specifier, bail out. 2467 2468 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1) 2469 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, 2470 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2471 FormatStr.size() + 1)); // Copy the null byte. 2472 return ConstantInt::get(CI->getType(), FormatStr.size()); 2473 } 2474 2475 // The remaining optimizations require the format string to be "%s" or "%c" 2476 // and have an extra operand. 2477 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 2478 CI->getNumArgOperands() < 3) 2479 return nullptr; 2480 2481 // Decode the second character of the format string. 2482 if (FormatStr[1] == 'c') { 2483 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 2484 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 2485 return nullptr; 2486 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 2487 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 2488 B.CreateStore(V, Ptr); 2489 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 2490 B.CreateStore(B.getInt8(0), Ptr); 2491 2492 return ConstantInt::get(CI->getType(), 1); 2493 } 2494 2495 if (FormatStr[1] == 's') { 2496 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str, 2497 // strlen(str)+1) 2498 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2499 return nullptr; 2500 2501 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 2502 if (!Len) 2503 return nullptr; 2504 Value *IncLen = 2505 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 2506 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen); 2507 2508 // The sprintf result is the unincremented number of bytes in the string. 2509 return B.CreateIntCast(Len, CI->getType(), false); 2510 } 2511 return nullptr; 2512 } 2513 2514 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) { 2515 Function *Callee = CI->getCalledFunction(); 2516 FunctionType *FT = Callee->getFunctionType(); 2517 if (Value *V = optimizeSPrintFString(CI, B)) { 2518 return V; 2519 } 2520 2521 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 2522 // point arguments. 2523 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) { 2524 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2525 FunctionCallee SIPrintFFn = 2526 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes()); 2527 CallInst *New = cast<CallInst>(CI->clone()); 2528 New->setCalledFunction(SIPrintFFn); 2529 B.Insert(New); 2530 return New; 2531 } 2532 2533 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit 2534 // floating point arguments. 2535 if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) { 2536 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2537 auto SmallSPrintFFn = 2538 M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf), 2539 FT, Callee->getAttributes()); 2540 CallInst *New = cast<CallInst>(CI->clone()); 2541 New->setCalledFunction(SmallSPrintFFn); 2542 B.Insert(New); 2543 return New; 2544 } 2545 2546 annotateNonNullBasedOnAccess(CI, {0, 1}); 2547 return nullptr; 2548 } 2549 2550 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) { 2551 // Check for size 2552 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2553 if (!Size) 2554 return nullptr; 2555 2556 uint64_t N = Size->getZExtValue(); 2557 // Check for a fixed format string. 2558 StringRef FormatStr; 2559 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr)) 2560 return nullptr; 2561 2562 // If we just have a format string (nothing else crazy) transform it. 2563 if (CI->getNumArgOperands() == 3) { 2564 // Make sure there's no % in the constant array. We could try to handle 2565 // %% -> % in the future if we cared. 2566 if (FormatStr.find('%') != StringRef::npos) 2567 return nullptr; // we found a format specifier, bail out. 2568 2569 if (N == 0) 2570 return ConstantInt::get(CI->getType(), FormatStr.size()); 2571 else if (N < FormatStr.size() + 1) 2572 return nullptr; 2573 2574 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt, 2575 // strlen(fmt)+1) 2576 B.CreateMemCpy( 2577 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, 2578 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2579 FormatStr.size() + 1)); // Copy the null byte. 2580 return ConstantInt::get(CI->getType(), FormatStr.size()); 2581 } 2582 2583 // The remaining optimizations require the format string to be "%s" or "%c" 2584 // and have an extra operand. 2585 if (FormatStr.size() == 2 && FormatStr[0] == '%' && 2586 CI->getNumArgOperands() == 4) { 2587 2588 // Decode the second character of the format string. 2589 if (FormatStr[1] == 'c') { 2590 if (N == 0) 2591 return ConstantInt::get(CI->getType(), 1); 2592 else if (N == 1) 2593 return nullptr; 2594 2595 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 2596 if (!CI->getArgOperand(3)->getType()->isIntegerTy()) 2597 return nullptr; 2598 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char"); 2599 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 2600 B.CreateStore(V, Ptr); 2601 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 2602 B.CreateStore(B.getInt8(0), Ptr); 2603 2604 return ConstantInt::get(CI->getType(), 1); 2605 } 2606 2607 if (FormatStr[1] == 's') { 2608 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1) 2609 StringRef Str; 2610 if (!getConstantStringInfo(CI->getArgOperand(3), Str)) 2611 return nullptr; 2612 2613 if (N == 0) 2614 return ConstantInt::get(CI->getType(), Str.size()); 2615 else if (N < Str.size() + 1) 2616 return nullptr; 2617 2618 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1, 2619 ConstantInt::get(CI->getType(), Str.size() + 1)); 2620 2621 // The snprintf result is the unincremented number of bytes in the string. 2622 return ConstantInt::get(CI->getType(), Str.size()); 2623 } 2624 } 2625 return nullptr; 2626 } 2627 2628 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) { 2629 if (Value *V = optimizeSnPrintFString(CI, B)) { 2630 return V; 2631 } 2632 2633 if (isKnownNonZero(CI->getOperand(1), DL)) 2634 annotateNonNullBasedOnAccess(CI, 0); 2635 return nullptr; 2636 } 2637 2638 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) { 2639 optimizeErrorReporting(CI, B, 0); 2640 2641 // All the optimizations depend on the format string. 2642 StringRef FormatStr; 2643 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 2644 return nullptr; 2645 2646 // Do not do any of the following transformations if the fprintf return 2647 // value is used, in general the fprintf return value is not compatible 2648 // with fwrite(), fputc() or fputs(). 2649 if (!CI->use_empty()) 2650 return nullptr; 2651 2652 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 2653 if (CI->getNumArgOperands() == 2) { 2654 // Could handle %% -> % if we cared. 2655 if (FormatStr.find('%') != StringRef::npos) 2656 return nullptr; // We found a format specifier. 2657 2658 return emitFWrite( 2659 CI->getArgOperand(1), 2660 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()), 2661 CI->getArgOperand(0), B, DL, TLI); 2662 } 2663 2664 // The remaining optimizations require the format string to be "%s" or "%c" 2665 // and have an extra operand. 2666 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 2667 CI->getNumArgOperands() < 3) 2668 return nullptr; 2669 2670 // Decode the second character of the format string. 2671 if (FormatStr[1] == 'c') { 2672 // fprintf(F, "%c", chr) --> fputc(chr, F) 2673 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 2674 return nullptr; 2675 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 2676 } 2677 2678 if (FormatStr[1] == 's') { 2679 // fprintf(F, "%s", str) --> fputs(str, F) 2680 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2681 return nullptr; 2682 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 2683 } 2684 return nullptr; 2685 } 2686 2687 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) { 2688 Function *Callee = CI->getCalledFunction(); 2689 FunctionType *FT = Callee->getFunctionType(); 2690 if (Value *V = optimizeFPrintFString(CI, B)) { 2691 return V; 2692 } 2693 2694 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 2695 // floating point arguments. 2696 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) { 2697 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2698 FunctionCallee FIPrintFFn = 2699 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes()); 2700 CallInst *New = cast<CallInst>(CI->clone()); 2701 New->setCalledFunction(FIPrintFFn); 2702 B.Insert(New); 2703 return New; 2704 } 2705 2706 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no 2707 // 128-bit floating point arguments. 2708 if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) { 2709 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2710 auto SmallFPrintFFn = 2711 M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf), 2712 FT, Callee->getAttributes()); 2713 CallInst *New = cast<CallInst>(CI->clone()); 2714 New->setCalledFunction(SmallFPrintFFn); 2715 B.Insert(New); 2716 return New; 2717 } 2718 2719 return nullptr; 2720 } 2721 2722 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) { 2723 optimizeErrorReporting(CI, B, 3); 2724 2725 // Get the element size and count. 2726 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2727 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 2728 if (SizeC && CountC) { 2729 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 2730 2731 // If this is writing zero records, remove the call (it's a noop). 2732 if (Bytes == 0) 2733 return ConstantInt::get(CI->getType(), 0); 2734 2735 // If this is writing one byte, turn it into fputc. 2736 // This optimisation is only valid, if the return value is unused. 2737 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 2738 Value *Char = B.CreateLoad(B.getInt8Ty(), 2739 castToCStr(CI->getArgOperand(0), B), "char"); 2740 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI); 2741 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 2742 } 2743 } 2744 2745 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI)) 2746 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), 2747 CI->getArgOperand(2), CI->getArgOperand(3), B, DL, 2748 TLI); 2749 2750 return nullptr; 2751 } 2752 2753 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) { 2754 optimizeErrorReporting(CI, B, 1); 2755 2756 // Don't rewrite fputs to fwrite when optimising for size because fwrite 2757 // requires more arguments and thus extra MOVs are required. 2758 bool OptForSize = CI->getFunction()->hasOptSize() || 2759 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 2760 PGSOQueryType::IRPass); 2761 if (OptForSize) 2762 return nullptr; 2763 2764 // Check if has any use 2765 if (!CI->use_empty()) { 2766 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI)) 2767 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B, 2768 TLI); 2769 else 2770 // We can't optimize if return value is used. 2771 return nullptr; 2772 } 2773 2774 // fputs(s,F) --> fwrite(s,strlen(s),1,F) 2775 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 2776 if (!Len) 2777 return nullptr; 2778 2779 // Known to have no uses (see above). 2780 return emitFWrite( 2781 CI->getArgOperand(0), 2782 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1), 2783 CI->getArgOperand(1), B, DL, TLI); 2784 } 2785 2786 Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) { 2787 optimizeErrorReporting(CI, B, 1); 2788 2789 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI)) 2790 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B, 2791 TLI); 2792 2793 return nullptr; 2794 } 2795 2796 Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) { 2797 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI)) 2798 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI); 2799 2800 return nullptr; 2801 } 2802 2803 Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) { 2804 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI)) 2805 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), 2806 CI->getArgOperand(2), B, TLI); 2807 2808 return nullptr; 2809 } 2810 2811 Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) { 2812 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI)) 2813 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), 2814 CI->getArgOperand(2), CI->getArgOperand(3), B, DL, 2815 TLI); 2816 2817 return nullptr; 2818 } 2819 2820 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) { 2821 annotateNonNullBasedOnAccess(CI, 0); 2822 if (!CI->use_empty()) 2823 return nullptr; 2824 2825 // Check for a constant string. 2826 // puts("") -> putchar('\n') 2827 StringRef Str; 2828 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) 2829 return emitPutChar(B.getInt32('\n'), B, TLI); 2830 2831 return nullptr; 2832 } 2833 2834 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilder<> &B) { 2835 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n) 2836 return B.CreateMemMove(CI->getArgOperand(1), 1, CI->getArgOperand(0), 1, 2837 CI->getArgOperand(2)); 2838 } 2839 2840 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) { 2841 LibFunc Func; 2842 SmallString<20> FloatFuncName = FuncName; 2843 FloatFuncName += 'f'; 2844 if (TLI->getLibFunc(FloatFuncName, Func)) 2845 return TLI->has(Func); 2846 return false; 2847 } 2848 2849 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 2850 IRBuilder<> &Builder) { 2851 LibFunc Func; 2852 Function *Callee = CI->getCalledFunction(); 2853 // Check for string/memory library functions. 2854 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 2855 // Make sure we never change the calling convention. 2856 assert((ignoreCallingConv(Func) || 2857 isCallingConvCCompatible(CI)) && 2858 "Optimizing string/memory libcall would change the calling convention"); 2859 switch (Func) { 2860 case LibFunc_strcat: 2861 return optimizeStrCat(CI, Builder); 2862 case LibFunc_strncat: 2863 return optimizeStrNCat(CI, Builder); 2864 case LibFunc_strchr: 2865 return optimizeStrChr(CI, Builder); 2866 case LibFunc_strrchr: 2867 return optimizeStrRChr(CI, Builder); 2868 case LibFunc_strcmp: 2869 return optimizeStrCmp(CI, Builder); 2870 case LibFunc_strncmp: 2871 return optimizeStrNCmp(CI, Builder); 2872 case LibFunc_strcpy: 2873 return optimizeStrCpy(CI, Builder); 2874 case LibFunc_stpcpy: 2875 return optimizeStpCpy(CI, Builder); 2876 case LibFunc_strncpy: 2877 return optimizeStrNCpy(CI, Builder); 2878 case LibFunc_strlen: 2879 return optimizeStrLen(CI, Builder); 2880 case LibFunc_strpbrk: 2881 return optimizeStrPBrk(CI, Builder); 2882 case LibFunc_strndup: 2883 return optimizeStrNDup(CI, Builder); 2884 case LibFunc_strtol: 2885 case LibFunc_strtod: 2886 case LibFunc_strtof: 2887 case LibFunc_strtoul: 2888 case LibFunc_strtoll: 2889 case LibFunc_strtold: 2890 case LibFunc_strtoull: 2891 return optimizeStrTo(CI, Builder); 2892 case LibFunc_strspn: 2893 return optimizeStrSpn(CI, Builder); 2894 case LibFunc_strcspn: 2895 return optimizeStrCSpn(CI, Builder); 2896 case LibFunc_strstr: 2897 return optimizeStrStr(CI, Builder); 2898 case LibFunc_memchr: 2899 return optimizeMemChr(CI, Builder); 2900 case LibFunc_memrchr: 2901 return optimizeMemRChr(CI, Builder); 2902 case LibFunc_bcmp: 2903 return optimizeBCmp(CI, Builder); 2904 case LibFunc_memcmp: 2905 return optimizeMemCmp(CI, Builder); 2906 case LibFunc_memcpy: 2907 return optimizeMemCpy(CI, Builder); 2908 case LibFunc_memccpy: 2909 return optimizeMemCCpy(CI, Builder); 2910 case LibFunc_mempcpy: 2911 return optimizeMemPCpy(CI, Builder); 2912 case LibFunc_memmove: 2913 return optimizeMemMove(CI, Builder); 2914 case LibFunc_memset: 2915 return optimizeMemSet(CI, Builder); 2916 case LibFunc_realloc: 2917 return optimizeRealloc(CI, Builder); 2918 case LibFunc_wcslen: 2919 return optimizeWcslen(CI, Builder); 2920 case LibFunc_bcopy: 2921 return optimizeBCopy(CI, Builder); 2922 default: 2923 break; 2924 } 2925 } 2926 return nullptr; 2927 } 2928 2929 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 2930 LibFunc Func, 2931 IRBuilder<> &Builder) { 2932 // Don't optimize calls that require strict floating point semantics. 2933 if (CI->isStrictFP()) 2934 return nullptr; 2935 2936 if (Value *V = optimizeTrigReflections(CI, Func, Builder)) 2937 return V; 2938 2939 switch (Func) { 2940 case LibFunc_sinpif: 2941 case LibFunc_sinpi: 2942 case LibFunc_cospif: 2943 case LibFunc_cospi: 2944 return optimizeSinCosPi(CI, Builder); 2945 case LibFunc_powf: 2946 case LibFunc_pow: 2947 case LibFunc_powl: 2948 return optimizePow(CI, Builder); 2949 case LibFunc_exp2l: 2950 case LibFunc_exp2: 2951 case LibFunc_exp2f: 2952 return optimizeExp2(CI, Builder); 2953 case LibFunc_fabsf: 2954 case LibFunc_fabs: 2955 case LibFunc_fabsl: 2956 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 2957 case LibFunc_sqrtf: 2958 case LibFunc_sqrt: 2959 case LibFunc_sqrtl: 2960 return optimizeSqrt(CI, Builder); 2961 case LibFunc_logf: 2962 case LibFunc_log: 2963 case LibFunc_logl: 2964 case LibFunc_log10f: 2965 case LibFunc_log10: 2966 case LibFunc_log10l: 2967 case LibFunc_log1pf: 2968 case LibFunc_log1p: 2969 case LibFunc_log1pl: 2970 case LibFunc_log2f: 2971 case LibFunc_log2: 2972 case LibFunc_log2l: 2973 case LibFunc_logbf: 2974 case LibFunc_logb: 2975 case LibFunc_logbl: 2976 return optimizeLog(CI, Builder); 2977 case LibFunc_tan: 2978 case LibFunc_tanf: 2979 case LibFunc_tanl: 2980 return optimizeTan(CI, Builder); 2981 case LibFunc_ceil: 2982 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 2983 case LibFunc_floor: 2984 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 2985 case LibFunc_round: 2986 return replaceUnaryCall(CI, Builder, Intrinsic::round); 2987 case LibFunc_nearbyint: 2988 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 2989 case LibFunc_rint: 2990 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 2991 case LibFunc_trunc: 2992 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 2993 case LibFunc_acos: 2994 case LibFunc_acosh: 2995 case LibFunc_asin: 2996 case LibFunc_asinh: 2997 case LibFunc_atan: 2998 case LibFunc_atanh: 2999 case LibFunc_cbrt: 3000 case LibFunc_cosh: 3001 case LibFunc_exp: 3002 case LibFunc_exp10: 3003 case LibFunc_expm1: 3004 case LibFunc_cos: 3005 case LibFunc_sin: 3006 case LibFunc_sinh: 3007 case LibFunc_tanh: 3008 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName())) 3009 return optimizeUnaryDoubleFP(CI, Builder, true); 3010 return nullptr; 3011 case LibFunc_copysign: 3012 if (hasFloatVersion(CI->getCalledFunction()->getName())) 3013 return optimizeBinaryDoubleFP(CI, Builder); 3014 return nullptr; 3015 case LibFunc_fminf: 3016 case LibFunc_fmin: 3017 case LibFunc_fminl: 3018 case LibFunc_fmaxf: 3019 case LibFunc_fmax: 3020 case LibFunc_fmaxl: 3021 return optimizeFMinFMax(CI, Builder); 3022 case LibFunc_cabs: 3023 case LibFunc_cabsf: 3024 case LibFunc_cabsl: 3025 return optimizeCAbs(CI, Builder); 3026 default: 3027 return nullptr; 3028 } 3029 } 3030 3031 Value *LibCallSimplifier::optimizeCall(CallInst *CI) { 3032 // TODO: Split out the code below that operates on FP calls so that 3033 // we can all non-FP calls with the StrictFP attribute to be 3034 // optimized. 3035 if (CI->isNoBuiltin()) 3036 return nullptr; 3037 3038 LibFunc Func; 3039 Function *Callee = CI->getCalledFunction(); 3040 3041 SmallVector<OperandBundleDef, 2> OpBundles; 3042 CI->getOperandBundlesAsDefs(OpBundles); 3043 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 3044 bool isCallingConvC = isCallingConvCCompatible(CI); 3045 3046 // Command-line parameter overrides instruction attribute. 3047 // This can't be moved to optimizeFloatingPointLibCall() because it may be 3048 // used by the intrinsic optimizations. 3049 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 3050 UnsafeFPShrink = EnableUnsafeFPShrink; 3051 else if (isa<FPMathOperator>(CI) && CI->isFast()) 3052 UnsafeFPShrink = true; 3053 3054 // First, check for intrinsics. 3055 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 3056 if (!isCallingConvC) 3057 return nullptr; 3058 // The FP intrinsics have corresponding constrained versions so we don't 3059 // need to check for the StrictFP attribute here. 3060 switch (II->getIntrinsicID()) { 3061 case Intrinsic::pow: 3062 return optimizePow(CI, Builder); 3063 case Intrinsic::exp2: 3064 return optimizeExp2(CI, Builder); 3065 case Intrinsic::log: 3066 case Intrinsic::log2: 3067 case Intrinsic::log10: 3068 return optimizeLog(CI, Builder); 3069 case Intrinsic::sqrt: 3070 return optimizeSqrt(CI, Builder); 3071 // TODO: Use foldMallocMemset() with memset intrinsic. 3072 case Intrinsic::memset: 3073 return optimizeMemSet(CI, Builder); 3074 case Intrinsic::memcpy: 3075 return optimizeMemCpy(CI, Builder); 3076 case Intrinsic::memmove: 3077 return optimizeMemMove(CI, Builder); 3078 default: 3079 return nullptr; 3080 } 3081 } 3082 3083 // Also try to simplify calls to fortified library functions. 3084 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) { 3085 // Try to further simplify the result. 3086 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI); 3087 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) { 3088 // Use an IR Builder from SimplifiedCI if available instead of CI 3089 // to guarantee we reach all uses we might replace later on. 3090 IRBuilder<> TmpBuilder(SimplifiedCI); 3091 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) { 3092 // If we were able to further simplify, remove the now redundant call. 3093 substituteInParent(SimplifiedCI, V); 3094 return V; 3095 } 3096 } 3097 return SimplifiedFortifiedCI; 3098 } 3099 3100 // Then check for known library functions. 3101 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 3102 // We never change the calling convention. 3103 if (!ignoreCallingConv(Func) && !isCallingConvC) 3104 return nullptr; 3105 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 3106 return V; 3107 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 3108 return V; 3109 switch (Func) { 3110 case LibFunc_ffs: 3111 case LibFunc_ffsl: 3112 case LibFunc_ffsll: 3113 return optimizeFFS(CI, Builder); 3114 case LibFunc_fls: 3115 case LibFunc_flsl: 3116 case LibFunc_flsll: 3117 return optimizeFls(CI, Builder); 3118 case LibFunc_abs: 3119 case LibFunc_labs: 3120 case LibFunc_llabs: 3121 return optimizeAbs(CI, Builder); 3122 case LibFunc_isdigit: 3123 return optimizeIsDigit(CI, Builder); 3124 case LibFunc_isascii: 3125 return optimizeIsAscii(CI, Builder); 3126 case LibFunc_toascii: 3127 return optimizeToAscii(CI, Builder); 3128 case LibFunc_atoi: 3129 case LibFunc_atol: 3130 case LibFunc_atoll: 3131 return optimizeAtoi(CI, Builder); 3132 case LibFunc_strtol: 3133 case LibFunc_strtoll: 3134 return optimizeStrtol(CI, Builder); 3135 case LibFunc_printf: 3136 return optimizePrintF(CI, Builder); 3137 case LibFunc_sprintf: 3138 return optimizeSPrintF(CI, Builder); 3139 case LibFunc_snprintf: 3140 return optimizeSnPrintF(CI, Builder); 3141 case LibFunc_fprintf: 3142 return optimizeFPrintF(CI, Builder); 3143 case LibFunc_fwrite: 3144 return optimizeFWrite(CI, Builder); 3145 case LibFunc_fread: 3146 return optimizeFRead(CI, Builder); 3147 case LibFunc_fputs: 3148 return optimizeFPuts(CI, Builder); 3149 case LibFunc_fgets: 3150 return optimizeFGets(CI, Builder); 3151 case LibFunc_fputc: 3152 return optimizeFPutc(CI, Builder); 3153 case LibFunc_fgetc: 3154 return optimizeFGetc(CI, Builder); 3155 case LibFunc_puts: 3156 return optimizePuts(CI, Builder); 3157 case LibFunc_perror: 3158 return optimizeErrorReporting(CI, Builder); 3159 case LibFunc_vfprintf: 3160 case LibFunc_fiprintf: 3161 return optimizeErrorReporting(CI, Builder, 0); 3162 default: 3163 return nullptr; 3164 } 3165 } 3166 return nullptr; 3167 } 3168 3169 LibCallSimplifier::LibCallSimplifier( 3170 const DataLayout &DL, const TargetLibraryInfo *TLI, 3171 OptimizationRemarkEmitter &ORE, 3172 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 3173 function_ref<void(Instruction *, Value *)> Replacer, 3174 function_ref<void(Instruction *)> Eraser) 3175 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI), 3176 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {} 3177 3178 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 3179 // Indirect through the replacer used in this instance. 3180 Replacer(I, With); 3181 } 3182 3183 void LibCallSimplifier::eraseFromParent(Instruction *I) { 3184 Eraser(I); 3185 } 3186 3187 // TODO: 3188 // Additional cases that we need to add to this file: 3189 // 3190 // cbrt: 3191 // * cbrt(expN(X)) -> expN(x/3) 3192 // * cbrt(sqrt(x)) -> pow(x,1/6) 3193 // * cbrt(cbrt(x)) -> pow(x,1/9) 3194 // 3195 // exp, expf, expl: 3196 // * exp(log(x)) -> x 3197 // 3198 // log, logf, logl: 3199 // * log(exp(x)) -> x 3200 // * log(exp(y)) -> y*log(e) 3201 // * log(exp10(y)) -> y*log(10) 3202 // * log(sqrt(x)) -> 0.5*log(x) 3203 // 3204 // pow, powf, powl: 3205 // * pow(sqrt(x),y) -> pow(x,y*0.5) 3206 // * pow(pow(x,y),z)-> pow(x,y*z) 3207 // 3208 // signbit: 3209 // * signbit(cnst) -> cnst' 3210 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 3211 // 3212 // sqrt, sqrtf, sqrtl: 3213 // * sqrt(expN(x)) -> expN(x*0.5) 3214 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 3215 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 3216 // 3217 3218 //===----------------------------------------------------------------------===// 3219 // Fortified Library Call Optimizations 3220 //===----------------------------------------------------------------------===// 3221 3222 bool 3223 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI, 3224 unsigned ObjSizeOp, 3225 Optional<unsigned> SizeOp, 3226 Optional<unsigned> StrOp, 3227 Optional<unsigned> FlagOp) { 3228 // If this function takes a flag argument, the implementation may use it to 3229 // perform extra checks. Don't fold into the non-checking variant. 3230 if (FlagOp) { 3231 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp)); 3232 if (!Flag || !Flag->isZero()) 3233 return false; 3234 } 3235 3236 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp)) 3237 return true; 3238 3239 if (ConstantInt *ObjSizeCI = 3240 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 3241 if (ObjSizeCI->isMinusOne()) 3242 return true; 3243 // If the object size wasn't -1 (unknown), bail out if we were asked to. 3244 if (OnlyLowerUnknownSize) 3245 return false; 3246 if (StrOp) { 3247 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp)); 3248 // If the length is 0 we don't know how long it is and so we can't 3249 // remove the check. 3250 if (Len) 3251 annotateDereferenceableBytes(CI, *StrOp, Len); 3252 else 3253 return false; 3254 return ObjSizeCI->getZExtValue() >= Len; 3255 } 3256 3257 if (SizeOp) { 3258 if (ConstantInt *SizeCI = 3259 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp))) 3260 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 3261 } 3262 } 3263 return false; 3264 } 3265 3266 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 3267 IRBuilder<> &B) { 3268 if (isFortifiedCallFoldable(CI, 3, 2)) { 3269 CallInst *NewCI = B.CreateMemCpy( 3270 CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, CI->getArgOperand(2)); 3271 NewCI->setAttributes(CI->getAttributes()); 3272 return CI->getArgOperand(0); 3273 } 3274 return nullptr; 3275 } 3276 3277 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 3278 IRBuilder<> &B) { 3279 if (isFortifiedCallFoldable(CI, 3, 2)) { 3280 CallInst *NewCI = B.CreateMemMove( 3281 CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, CI->getArgOperand(2)); 3282 NewCI->setAttributes(CI->getAttributes()); 3283 return CI->getArgOperand(0); 3284 } 3285 return nullptr; 3286 } 3287 3288 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 3289 IRBuilder<> &B) { 3290 // TODO: Try foldMallocMemset() here. 3291 3292 if (isFortifiedCallFoldable(CI, 3, 2)) { 3293 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 3294 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, 3295 CI->getArgOperand(2), Align::None()); 3296 NewCI->setAttributes(CI->getAttributes()); 3297 return CI->getArgOperand(0); 3298 } 3299 return nullptr; 3300 } 3301 3302 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 3303 IRBuilder<> &B, 3304 LibFunc Func) { 3305 const DataLayout &DL = CI->getModule()->getDataLayout(); 3306 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 3307 *ObjSize = CI->getArgOperand(2); 3308 3309 // __stpcpy_chk(x,x,...) -> x+strlen(x) 3310 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 3311 Value *StrLen = emitStrLen(Src, B, DL, TLI); 3312 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 3313 } 3314 3315 // If a) we don't have any length information, or b) we know this will 3316 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 3317 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 3318 // TODO: It might be nice to get a maximum length out of the possible 3319 // string lengths for varying. 3320 if (isFortifiedCallFoldable(CI, 2, None, 1)) { 3321 if (Func == LibFunc_strcpy_chk) 3322 return emitStrCpy(Dst, Src, B, TLI); 3323 else 3324 return emitStpCpy(Dst, Src, B, TLI); 3325 } 3326 3327 if (OnlyLowerUnknownSize) 3328 return nullptr; 3329 3330 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 3331 uint64_t Len = GetStringLength(Src); 3332 if (Len) 3333 annotateDereferenceableBytes(CI, 1, Len); 3334 else 3335 return nullptr; 3336 3337 Type *SizeTTy = DL.getIntPtrType(CI->getContext()); 3338 Value *LenV = ConstantInt::get(SizeTTy, Len); 3339 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 3340 // If the function was an __stpcpy_chk, and we were able to fold it into 3341 // a __memcpy_chk, we still need to return the correct end pointer. 3342 if (Ret && Func == LibFunc_stpcpy_chk) 3343 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1)); 3344 return Ret; 3345 } 3346 3347 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 3348 IRBuilder<> &B, 3349 LibFunc Func) { 3350 if (isFortifiedCallFoldable(CI, 3, 2)) { 3351 if (Func == LibFunc_strncpy_chk) 3352 return emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3353 CI->getArgOperand(2), B, TLI); 3354 else 3355 return emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3356 CI->getArgOperand(2), B, TLI); 3357 } 3358 3359 return nullptr; 3360 } 3361 3362 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI, 3363 IRBuilder<> &B) { 3364 if (isFortifiedCallFoldable(CI, 4, 3)) 3365 return emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3366 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI); 3367 3368 return nullptr; 3369 } 3370 3371 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI, 3372 IRBuilder<> &B) { 3373 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) { 3374 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 5, CI->arg_end()); 3375 return emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3376 CI->getArgOperand(4), VariadicArgs, B, TLI); 3377 } 3378 3379 return nullptr; 3380 } 3381 3382 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI, 3383 IRBuilder<> &B) { 3384 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) { 3385 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 4, CI->arg_end()); 3386 return emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), VariadicArgs, 3387 B, TLI); 3388 } 3389 3390 return nullptr; 3391 } 3392 3393 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI, 3394 IRBuilder<> &B) { 3395 if (isFortifiedCallFoldable(CI, 2)) 3396 return emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI); 3397 3398 return nullptr; 3399 } 3400 3401 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI, 3402 IRBuilder<> &B) { 3403 if (isFortifiedCallFoldable(CI, 3)) 3404 return emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1), 3405 CI->getArgOperand(2), B, TLI); 3406 3407 return nullptr; 3408 } 3409 3410 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI, 3411 IRBuilder<> &B) { 3412 if (isFortifiedCallFoldable(CI, 3)) 3413 return emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1), 3414 CI->getArgOperand(2), B, TLI); 3415 3416 return nullptr; 3417 } 3418 3419 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI, 3420 IRBuilder<> &B) { 3421 if (isFortifiedCallFoldable(CI, 3)) 3422 return emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3423 CI->getArgOperand(2), B, TLI); 3424 3425 return nullptr; 3426 } 3427 3428 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI, 3429 IRBuilder<> &B) { 3430 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) 3431 return emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3432 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI); 3433 3434 return nullptr; 3435 } 3436 3437 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI, 3438 IRBuilder<> &B) { 3439 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) 3440 return emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 3441 CI->getArgOperand(4), B, TLI); 3442 3443 return nullptr; 3444 } 3445 3446 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) { 3447 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 3448 // Some clang users checked for _chk libcall availability using: 3449 // __has_builtin(__builtin___memcpy_chk) 3450 // When compiling with -fno-builtin, this is always true. 3451 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 3452 // end up with fortified libcalls, which isn't acceptable in a freestanding 3453 // environment which only provides their non-fortified counterparts. 3454 // 3455 // Until we change clang and/or teach external users to check for availability 3456 // differently, disregard the "nobuiltin" attribute and TLI::has. 3457 // 3458 // PR23093. 3459 3460 LibFunc Func; 3461 Function *Callee = CI->getCalledFunction(); 3462 3463 SmallVector<OperandBundleDef, 2> OpBundles; 3464 CI->getOperandBundlesAsDefs(OpBundles); 3465 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 3466 bool isCallingConvC = isCallingConvCCompatible(CI); 3467 3468 // First, check that this is a known library functions and that the prototype 3469 // is correct. 3470 if (!TLI->getLibFunc(*Callee, Func)) 3471 return nullptr; 3472 3473 // We never change the calling convention. 3474 if (!ignoreCallingConv(Func) && !isCallingConvC) 3475 return nullptr; 3476 3477 switch (Func) { 3478 case LibFunc_memcpy_chk: 3479 return optimizeMemCpyChk(CI, Builder); 3480 case LibFunc_memmove_chk: 3481 return optimizeMemMoveChk(CI, Builder); 3482 case LibFunc_memset_chk: 3483 return optimizeMemSetChk(CI, Builder); 3484 case LibFunc_stpcpy_chk: 3485 case LibFunc_strcpy_chk: 3486 return optimizeStrpCpyChk(CI, Builder, Func); 3487 case LibFunc_stpncpy_chk: 3488 case LibFunc_strncpy_chk: 3489 return optimizeStrpNCpyChk(CI, Builder, Func); 3490 case LibFunc_memccpy_chk: 3491 return optimizeMemCCpyChk(CI, Builder); 3492 case LibFunc_snprintf_chk: 3493 return optimizeSNPrintfChk(CI, Builder); 3494 case LibFunc_sprintf_chk: 3495 return optimizeSPrintfChk(CI, Builder); 3496 case LibFunc_strcat_chk: 3497 return optimizeStrCatChk(CI, Builder); 3498 case LibFunc_strlcat_chk: 3499 return optimizeStrLCat(CI, Builder); 3500 case LibFunc_strncat_chk: 3501 return optimizeStrNCatChk(CI, Builder); 3502 case LibFunc_strlcpy_chk: 3503 return optimizeStrLCpyChk(CI, Builder); 3504 case LibFunc_vsnprintf_chk: 3505 return optimizeVSNPrintfChk(CI, Builder); 3506 case LibFunc_vsprintf_chk: 3507 return optimizeVSPrintfChk(CI, Builder); 3508 default: 3509 break; 3510 } 3511 return nullptr; 3512 } 3513 3514 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 3515 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 3516 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 3517