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/StringExtras.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/Loads.h" 20 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 21 #include "llvm/Analysis/TargetLibraryInfo.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/AttributeMask.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/IRBuilder.h" 27 #include "llvm/IR/IntrinsicInst.h" 28 #include "llvm/IR/Intrinsics.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/PatternMatch.h" 31 #include "llvm/Support/Casting.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/KnownBits.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/TargetParser/Triple.h" 36 #include "llvm/Transforms/Utils/BuildLibCalls.h" 37 #include "llvm/Transforms/Utils/Local.h" 38 #include "llvm/Transforms/Utils/SizeOpts.h" 39 40 #include <cmath> 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 // Enable conversion of operator new calls with a MemProf hot or cold hint 52 // to an operator new call that takes a hot/cold hint. Off by default since 53 // not all allocators currently support this extension. 54 static cl::opt<bool> 55 OptimizeHotColdNew("optimize-hot-cold-new", cl::Hidden, cl::init(false), 56 cl::desc("Enable hot/cold operator new library calls")); 57 static cl::opt<bool> OptimizeExistingHotColdNew( 58 "optimize-existing-hot-cold-new", cl::Hidden, cl::init(false), 59 cl::desc( 60 "Enable optimization of existing hot/cold operator new library calls")); 61 62 namespace { 63 64 // Specialized parser to ensure the hint is an 8 bit value (we can't specify 65 // uint8_t to opt<> as that is interpreted to mean that we are passing a char 66 // option with a specific set of values. 67 struct HotColdHintParser : public cl::parser<unsigned> { 68 HotColdHintParser(cl::Option &O) : cl::parser<unsigned>(O) {} 69 70 bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) { 71 if (Arg.getAsInteger(0, Value)) 72 return O.error("'" + Arg + "' value invalid for uint argument!"); 73 74 if (Value > 255) 75 return O.error("'" + Arg + "' value must be in the range [0, 255]!"); 76 77 return false; 78 } 79 }; 80 81 } // end anonymous namespace 82 83 // Hot/cold operator new takes an 8 bit hotness hint, where 0 is the coldest 84 // and 255 is the hottest. Default to 1 value away from the coldest and hottest 85 // hints, so that the compiler hinted allocations are slightly less strong than 86 // manually inserted hints at the two extremes. 87 static cl::opt<unsigned, false, HotColdHintParser> ColdNewHintValue( 88 "cold-new-hint-value", cl::Hidden, cl::init(1), 89 cl::desc("Value to pass to hot/cold operator new for cold allocation")); 90 static cl::opt<unsigned, false, HotColdHintParser> 91 NotColdNewHintValue("notcold-new-hint-value", cl::Hidden, cl::init(128), 92 cl::desc("Value to pass to hot/cold operator new for " 93 "notcold (warm) allocation")); 94 static cl::opt<unsigned, false, HotColdHintParser> HotNewHintValue( 95 "hot-new-hint-value", cl::Hidden, cl::init(254), 96 cl::desc("Value to pass to hot/cold operator new for hot allocation")); 97 98 //===----------------------------------------------------------------------===// 99 // Helper Functions 100 //===----------------------------------------------------------------------===// 101 102 static bool ignoreCallingConv(LibFunc Func) { 103 return Func == LibFunc_abs || Func == LibFunc_labs || 104 Func == LibFunc_llabs || Func == LibFunc_strlen; 105 } 106 107 /// Return true if it is only used in equality comparisons with With. 108 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) { 109 for (User *U : V->users()) { 110 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 111 if (IC->isEquality() && IC->getOperand(1) == With) 112 continue; 113 // Unknown instruction. 114 return false; 115 } 116 return true; 117 } 118 119 static bool callHasFloatingPointArgument(const CallInst *CI) { 120 return any_of(CI->operands(), [](const Use &OI) { 121 return OI->getType()->isFloatingPointTy(); 122 }); 123 } 124 125 static bool callHasFP128Argument(const CallInst *CI) { 126 return any_of(CI->operands(), [](const Use &OI) { 127 return OI->getType()->isFP128Ty(); 128 }); 129 } 130 131 // Convert the entire string Str representing an integer in Base, up to 132 // the terminating nul if present, to a constant according to the rules 133 // of strtoul[l] or, when AsSigned is set, of strtol[l]. On success 134 // return the result, otherwise null. 135 // The function assumes the string is encoded in ASCII and carefully 136 // avoids converting sequences (including "") that the corresponding 137 // library call might fail and set errno for. 138 static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr, 139 uint64_t Base, bool AsSigned, IRBuilderBase &B) { 140 if (Base < 2 || Base > 36) 141 if (Base != 0) 142 // Fail for an invalid base (required by POSIX). 143 return nullptr; 144 145 // Current offset into the original string to reflect in EndPtr. 146 size_t Offset = 0; 147 // Strip leading whitespace. 148 for ( ; Offset != Str.size(); ++Offset) 149 if (!isSpace((unsigned char)Str[Offset])) { 150 Str = Str.substr(Offset); 151 break; 152 } 153 154 if (Str.empty()) 155 // Fail for empty subject sequences (POSIX allows but doesn't require 156 // strtol[l]/strtoul[l] to fail with EINVAL). 157 return nullptr; 158 159 // Strip but remember the sign. 160 bool Negate = Str[0] == '-'; 161 if (Str[0] == '-' || Str[0] == '+') { 162 Str = Str.drop_front(); 163 if (Str.empty()) 164 // Fail for a sign with nothing after it. 165 return nullptr; 166 ++Offset; 167 } 168 169 // Set Max to the absolute value of the minimum (for signed), or 170 // to the maximum (for unsigned) value representable in the type. 171 Type *RetTy = CI->getType(); 172 unsigned NBits = RetTy->getPrimitiveSizeInBits(); 173 uint64_t Max = AsSigned && Negate ? 1 : 0; 174 Max += AsSigned ? maxIntN(NBits) : maxUIntN(NBits); 175 176 // Autodetect Base if it's zero and consume the "0x" prefix. 177 if (Str.size() > 1) { 178 if (Str[0] == '0') { 179 if (toUpper((unsigned char)Str[1]) == 'X') { 180 if (Str.size() == 2 || (Base && Base != 16)) 181 // Fail if Base doesn't allow the "0x" prefix or for the prefix 182 // alone that implementations like BSD set errno to EINVAL for. 183 return nullptr; 184 185 Str = Str.drop_front(2); 186 Offset += 2; 187 Base = 16; 188 } 189 else if (Base == 0) 190 Base = 8; 191 } else if (Base == 0) 192 Base = 10; 193 } 194 else if (Base == 0) 195 Base = 10; 196 197 // Convert the rest of the subject sequence, not including the sign, 198 // to its uint64_t representation (this assumes the source character 199 // set is ASCII). 200 uint64_t Result = 0; 201 for (unsigned i = 0; i != Str.size(); ++i) { 202 unsigned char DigVal = Str[i]; 203 if (isDigit(DigVal)) 204 DigVal = DigVal - '0'; 205 else { 206 DigVal = toUpper(DigVal); 207 if (isAlpha(DigVal)) 208 DigVal = DigVal - 'A' + 10; 209 else 210 return nullptr; 211 } 212 213 if (DigVal >= Base) 214 // Fail if the digit is not valid in the Base. 215 return nullptr; 216 217 // Add the digit and fail if the result is not representable in 218 // the (unsigned form of the) destination type. 219 bool VFlow; 220 Result = SaturatingMultiplyAdd(Result, Base, (uint64_t)DigVal, &VFlow); 221 if (VFlow || Result > Max) 222 return nullptr; 223 } 224 225 if (EndPtr) { 226 // Store the pointer to the end. 227 Value *Off = B.getInt64(Offset + Str.size()); 228 Value *StrBeg = CI->getArgOperand(0); 229 Value *StrEnd = B.CreateInBoundsGEP(B.getInt8Ty(), StrBeg, Off, "endptr"); 230 B.CreateStore(StrEnd, EndPtr); 231 } 232 233 if (Negate) 234 // Unsigned negation doesn't overflow. 235 Result = -Result; 236 237 return ConstantInt::get(RetTy, Result); 238 } 239 240 static bool isOnlyUsedInComparisonWithZero(Value *V) { 241 for (User *U : V->users()) { 242 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 243 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 244 if (C->isNullValue()) 245 continue; 246 // Unknown instruction. 247 return false; 248 } 249 return true; 250 } 251 252 static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, 253 const DataLayout &DL) { 254 if (!isOnlyUsedInComparisonWithZero(CI)) 255 return false; 256 257 if (!isDereferenceableAndAlignedPointer(Str, Align(1), APInt(64, Len), DL)) 258 return false; 259 260 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory)) 261 return false; 262 263 return true; 264 } 265 266 static void annotateDereferenceableBytes(CallInst *CI, 267 ArrayRef<unsigned> ArgNos, 268 uint64_t DereferenceableBytes) { 269 const Function *F = CI->getCaller(); 270 if (!F) 271 return; 272 for (unsigned ArgNo : ArgNos) { 273 uint64_t DerefBytes = DereferenceableBytes; 274 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 275 if (!llvm::NullPointerIsDefined(F, AS) || 276 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 277 DerefBytes = std::max(CI->getParamDereferenceableOrNullBytes(ArgNo), 278 DereferenceableBytes); 279 280 if (CI->getParamDereferenceableBytes(ArgNo) < DerefBytes) { 281 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable); 282 if (!llvm::NullPointerIsDefined(F, AS) || 283 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 284 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull); 285 CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes( 286 CI->getContext(), DerefBytes)); 287 } 288 } 289 } 290 291 static void annotateNonNullNoUndefBasedOnAccess(CallInst *CI, 292 ArrayRef<unsigned> ArgNos) { 293 Function *F = CI->getCaller(); 294 if (!F) 295 return; 296 297 for (unsigned ArgNo : ArgNos) { 298 if (!CI->paramHasAttr(ArgNo, Attribute::NoUndef)) 299 CI->addParamAttr(ArgNo, Attribute::NoUndef); 300 301 if (!CI->paramHasAttr(ArgNo, Attribute::NonNull)) { 302 unsigned AS = 303 CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 304 if (llvm::NullPointerIsDefined(F, AS)) 305 continue; 306 CI->addParamAttr(ArgNo, Attribute::NonNull); 307 } 308 309 annotateDereferenceableBytes(CI, ArgNo, 1); 310 } 311 } 312 313 static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos, 314 Value *Size, const DataLayout &DL) { 315 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) { 316 annotateNonNullNoUndefBasedOnAccess(CI, ArgNos); 317 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue()); 318 } else if (isKnownNonZero(Size, DL)) { 319 annotateNonNullNoUndefBasedOnAccess(CI, ArgNos); 320 const APInt *X, *Y; 321 uint64_t DerefMin = 1; 322 if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) { 323 DerefMin = std::min(X->getZExtValue(), Y->getZExtValue()); 324 annotateDereferenceableBytes(CI, ArgNos, DerefMin); 325 } 326 } 327 } 328 329 // Copy CallInst "flags" like musttail, notail, and tail. Return New param for 330 // easier chaining. Calls to emit* and B.createCall should probably be wrapped 331 // in this function when New is created to replace Old. Callers should take 332 // care to check Old.isMustTailCall() if they aren't replacing Old directly 333 // with New. 334 static Value *copyFlags(const CallInst &Old, Value *New) { 335 assert(!Old.isMustTailCall() && "do not copy musttail call flags"); 336 assert(!Old.isNoTailCall() && "do not copy notail call flags"); 337 if (auto *NewCI = dyn_cast_or_null<CallInst>(New)) 338 NewCI->setTailCallKind(Old.getTailCallKind()); 339 return New; 340 } 341 342 static Value *mergeAttributesAndFlags(CallInst *NewCI, const CallInst &Old) { 343 NewCI->setAttributes(AttributeList::get( 344 NewCI->getContext(), {NewCI->getAttributes(), Old.getAttributes()})); 345 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible( 346 NewCI->getType(), NewCI->getRetAttributes())); 347 for (unsigned I = 0; I < NewCI->arg_size(); ++I) 348 NewCI->removeParamAttrs( 349 I, AttributeFuncs::typeIncompatible(NewCI->getArgOperand(I)->getType(), 350 NewCI->getParamAttributes(I))); 351 352 return copyFlags(Old, NewCI); 353 } 354 355 // Helper to avoid truncating the length if size_t is 32-bits. 356 static StringRef substr(StringRef Str, uint64_t Len) { 357 return Len >= Str.size() ? Str : Str.substr(0, Len); 358 } 359 360 //===----------------------------------------------------------------------===// 361 // String and Memory Library Call Optimizations 362 //===----------------------------------------------------------------------===// 363 364 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilderBase &B) { 365 // Extract some information from the instruction 366 Value *Dst = CI->getArgOperand(0); 367 Value *Src = CI->getArgOperand(1); 368 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 369 370 // See if we can get the length of the input string. 371 uint64_t Len = GetStringLength(Src); 372 if (Len) 373 annotateDereferenceableBytes(CI, 1, Len); 374 else 375 return nullptr; 376 --Len; // Unbias length. 377 378 // Handle the simple, do-nothing case: strcat(x, "") -> x 379 if (Len == 0) 380 return Dst; 381 382 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, Len, B)); 383 } 384 385 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, 386 IRBuilderBase &B) { 387 // We need to find the end of the destination string. That's where the 388 // memory is to be moved to. We just generate a call to strlen. 389 Value *DstLen = emitStrLen(Dst, B, DL, TLI); 390 if (!DstLen) 391 return nullptr; 392 393 // Now that we have the destination's length, we must index into the 394 // destination's pointer to get the actual memcpy destination (end of 395 // the string .. we're concatenating). 396 Value *CpyDst = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, DstLen, "endptr"); 397 398 // We have enough information to now generate the memcpy call to do the 399 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 400 B.CreateMemCpy( 401 CpyDst, Align(1), Src, Align(1), 402 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1)); 403 return Dst; 404 } 405 406 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilderBase &B) { 407 // Extract some information from the instruction. 408 Value *Dst = CI->getArgOperand(0); 409 Value *Src = CI->getArgOperand(1); 410 Value *Size = CI->getArgOperand(2); 411 uint64_t Len; 412 annotateNonNullNoUndefBasedOnAccess(CI, 0); 413 if (isKnownNonZero(Size, DL)) 414 annotateNonNullNoUndefBasedOnAccess(CI, 1); 415 416 // We don't do anything if length is not constant. 417 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size); 418 if (LengthArg) { 419 Len = LengthArg->getZExtValue(); 420 // strncat(x, c, 0) -> x 421 if (!Len) 422 return Dst; 423 } else { 424 return nullptr; 425 } 426 427 // See if we can get the length of the input string. 428 uint64_t SrcLen = GetStringLength(Src); 429 if (SrcLen) { 430 annotateDereferenceableBytes(CI, 1, SrcLen); 431 --SrcLen; // Unbias length. 432 } else { 433 return nullptr; 434 } 435 436 // strncat(x, "", c) -> x 437 if (SrcLen == 0) 438 return Dst; 439 440 // We don't optimize this case. 441 if (Len < SrcLen) 442 return nullptr; 443 444 // strncat(x, s, c) -> strcat(x, s) 445 // s is constant so the strcat can be optimized further. 446 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, SrcLen, B)); 447 } 448 449 // Helper to transform memchr(S, C, N) == S to N && *S == C and, when 450 // NBytes is null, strchr(S, C) to *S == C. A precondition of the function 451 // is that either S is dereferenceable or the value of N is nonzero. 452 static Value* memChrToCharCompare(CallInst *CI, Value *NBytes, 453 IRBuilderBase &B, const DataLayout &DL) 454 { 455 Value *Src = CI->getArgOperand(0); 456 Value *CharVal = CI->getArgOperand(1); 457 458 // Fold memchr(A, C, N) == A to N && *A == C. 459 Type *CharTy = B.getInt8Ty(); 460 Value *Char0 = B.CreateLoad(CharTy, Src); 461 CharVal = B.CreateTrunc(CharVal, CharTy); 462 Value *Cmp = B.CreateICmpEQ(Char0, CharVal, "char0cmp"); 463 464 if (NBytes) { 465 Value *Zero = ConstantInt::get(NBytes->getType(), 0); 466 Value *And = B.CreateICmpNE(NBytes, Zero); 467 Cmp = B.CreateLogicalAnd(And, Cmp); 468 } 469 470 Value *NullPtr = Constant::getNullValue(CI->getType()); 471 return B.CreateSelect(Cmp, Src, NullPtr); 472 } 473 474 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilderBase &B) { 475 Value *SrcStr = CI->getArgOperand(0); 476 Value *CharVal = CI->getArgOperand(1); 477 annotateNonNullNoUndefBasedOnAccess(CI, 0); 478 479 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 480 return memChrToCharCompare(CI, nullptr, B, DL); 481 482 // If the second operand is non-constant, see if we can compute the length 483 // of the input string and turn this into memchr. 484 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 485 if (!CharC) { 486 uint64_t Len = GetStringLength(SrcStr); 487 if (Len) 488 annotateDereferenceableBytes(CI, 0, Len); 489 else 490 return nullptr; 491 492 Function *Callee = CI->getCalledFunction(); 493 FunctionType *FT = Callee->getFunctionType(); 494 unsigned IntBits = TLI->getIntSize(); 495 if (!FT->getParamType(1)->isIntegerTy(IntBits)) // memchr needs 'int'. 496 return nullptr; 497 498 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 499 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 500 return copyFlags(*CI, 501 emitMemChr(SrcStr, CharVal, // include nul. 502 ConstantInt::get(SizeTTy, Len), B, 503 DL, TLI)); 504 } 505 506 if (CharC->isZero()) { 507 Value *NullPtr = Constant::getNullValue(CI->getType()); 508 if (isOnlyUsedInEqualityComparison(CI, NullPtr)) 509 // Pre-empt the transformation to strlen below and fold 510 // strchr(A, '\0') == null to false. 511 return B.CreateIntToPtr(B.getTrue(), CI->getType()); 512 } 513 514 // Otherwise, the character is a constant, see if the first argument is 515 // a string literal. If so, we can constant fold. 516 StringRef Str; 517 if (!getConstantStringInfo(SrcStr, Str)) { 518 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p) 519 if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI)) 520 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr"); 521 return nullptr; 522 } 523 524 // Compute the offset, make sure to handle the case when we're searching for 525 // zero (a weird way to spell strlen). 526 size_t I = (0xFF & CharC->getSExtValue()) == 0 527 ? Str.size() 528 : Str.find(CharC->getSExtValue()); 529 if (I == StringRef::npos) // Didn't find the char. strchr returns null. 530 return Constant::getNullValue(CI->getType()); 531 532 // strchr(s+n,c) -> gep(s+n+i,c) 533 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr"); 534 } 535 536 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilderBase &B) { 537 Value *SrcStr = CI->getArgOperand(0); 538 Value *CharVal = CI->getArgOperand(1); 539 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 540 annotateNonNullNoUndefBasedOnAccess(CI, 0); 541 542 StringRef Str; 543 if (!getConstantStringInfo(SrcStr, Str)) { 544 // strrchr(s, 0) -> strchr(s, 0) 545 if (CharC && CharC->isZero()) 546 return copyFlags(*CI, emitStrChr(SrcStr, '\0', B, TLI)); 547 return nullptr; 548 } 549 550 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 551 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 552 553 // Try to expand strrchr to the memrchr nonstandard extension if it's 554 // available, or simply fail otherwise. 555 uint64_t NBytes = Str.size() + 1; // Include the terminating nul. 556 Value *Size = ConstantInt::get(SizeTTy, NBytes); 557 return copyFlags(*CI, emitMemRChr(SrcStr, CharVal, Size, B, DL, TLI)); 558 } 559 560 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) { 561 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 562 if (Str1P == Str2P) // strcmp(x,x) -> 0 563 return ConstantInt::get(CI->getType(), 0); 564 565 StringRef Str1, Str2; 566 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 567 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 568 569 // strcmp(x, y) -> cnst (if both x and y are constant strings) 570 if (HasStr1 && HasStr2) 571 return ConstantInt::get(CI->getType(), 572 std::clamp(Str1.compare(Str2), -1, 1)); 573 574 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x 575 return B.CreateNeg(B.CreateZExt( 576 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 577 578 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 579 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 580 CI->getType()); 581 582 // strcmp(P, "x") -> memcmp(P, "x", 2) 583 uint64_t Len1 = GetStringLength(Str1P); 584 if (Len1) 585 annotateDereferenceableBytes(CI, 0, Len1); 586 uint64_t Len2 = GetStringLength(Str2P); 587 if (Len2) 588 annotateDereferenceableBytes(CI, 1, Len2); 589 590 if (Len1 && Len2) { 591 return copyFlags( 592 *CI, emitMemCmp(Str1P, Str2P, 593 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 594 std::min(Len1, Len2)), 595 B, DL, TLI)); 596 } 597 598 // strcmp to memcmp 599 if (!HasStr1 && HasStr2) { 600 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 601 return copyFlags( 602 *CI, 603 emitMemCmp(Str1P, Str2P, 604 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), 605 B, DL, TLI)); 606 } else if (HasStr1 && !HasStr2) { 607 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 608 return copyFlags( 609 *CI, 610 emitMemCmp(Str1P, Str2P, 611 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), 612 B, DL, TLI)); 613 } 614 615 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 616 return nullptr; 617 } 618 619 // Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant 620 // arrays LHS and RHS and nonconstant Size. 621 static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS, 622 Value *Size, bool StrNCmp, 623 IRBuilderBase &B, const DataLayout &DL); 624 625 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) { 626 Value *Str1P = CI->getArgOperand(0); 627 Value *Str2P = CI->getArgOperand(1); 628 Value *Size = CI->getArgOperand(2); 629 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 630 return ConstantInt::get(CI->getType(), 0); 631 632 if (isKnownNonZero(Size, DL)) 633 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 634 // Get the length argument if it is constant. 635 uint64_t Length; 636 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size)) 637 Length = LengthArg->getZExtValue(); 638 else 639 return optimizeMemCmpVarSize(CI, Str1P, Str2P, Size, true, B, DL); 640 641 if (Length == 0) // strncmp(x,y,0) -> 0 642 return ConstantInt::get(CI->getType(), 0); 643 644 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1) 645 return copyFlags(*CI, emitMemCmp(Str1P, Str2P, Size, B, DL, TLI)); 646 647 StringRef Str1, Str2; 648 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 649 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 650 651 // strncmp(x, y) -> cnst (if both x and y are constant strings) 652 if (HasStr1 && HasStr2) { 653 // Avoid truncating the 64-bit Length to 32 bits in ILP32. 654 StringRef SubStr1 = substr(Str1, Length); 655 StringRef SubStr2 = substr(Str2, Length); 656 return ConstantInt::get(CI->getType(), 657 std::clamp(SubStr1.compare(SubStr2), -1, 1)); 658 } 659 660 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x 661 return B.CreateNeg(B.CreateZExt( 662 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 663 664 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 665 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 666 CI->getType()); 667 668 uint64_t Len1 = GetStringLength(Str1P); 669 if (Len1) 670 annotateDereferenceableBytes(CI, 0, Len1); 671 uint64_t Len2 = GetStringLength(Str2P); 672 if (Len2) 673 annotateDereferenceableBytes(CI, 1, Len2); 674 675 // strncmp to memcmp 676 if (!HasStr1 && HasStr2) { 677 Len2 = std::min(Len2, Length); 678 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 679 return copyFlags( 680 *CI, 681 emitMemCmp(Str1P, Str2P, 682 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), 683 B, DL, TLI)); 684 } else if (HasStr1 && !HasStr2) { 685 Len1 = std::min(Len1, Length); 686 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 687 return copyFlags( 688 *CI, 689 emitMemCmp(Str1P, Str2P, 690 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), 691 B, DL, TLI)); 692 } 693 694 return nullptr; 695 } 696 697 Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilderBase &B) { 698 Value *Src = CI->getArgOperand(0); 699 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 700 uint64_t SrcLen = GetStringLength(Src); 701 if (SrcLen && Size) { 702 annotateDereferenceableBytes(CI, 0, SrcLen); 703 if (SrcLen <= Size->getZExtValue() + 1) 704 return copyFlags(*CI, emitStrDup(Src, B, TLI)); 705 } 706 707 return nullptr; 708 } 709 710 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilderBase &B) { 711 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 712 if (Dst == Src) // strcpy(x,x) -> x 713 return Src; 714 715 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 716 // See if we can get the length of the input string. 717 uint64_t Len = GetStringLength(Src); 718 if (Len) 719 annotateDereferenceableBytes(CI, 1, Len); 720 else 721 return nullptr; 722 723 // We have enough information to now generate the memcpy call to do the 724 // copy for us. Make a memcpy to copy the nul byte with align = 1. 725 CallInst *NewCI = 726 B.CreateMemCpy(Dst, Align(1), Src, Align(1), 727 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len)); 728 mergeAttributesAndFlags(NewCI, *CI); 729 return Dst; 730 } 731 732 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilderBase &B) { 733 Function *Callee = CI->getCalledFunction(); 734 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 735 736 // stpcpy(d,s) -> strcpy(d,s) if the result is not used. 737 if (CI->use_empty()) 738 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI)); 739 740 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 741 Value *StrLen = emitStrLen(Src, B, DL, TLI); 742 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 743 } 744 745 // See if we can get the length of the input string. 746 uint64_t Len = GetStringLength(Src); 747 if (Len) 748 annotateDereferenceableBytes(CI, 1, Len); 749 else 750 return nullptr; 751 752 Type *PT = Callee->getFunctionType()->getParamType(0); 753 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len); 754 Value *DstEnd = B.CreateInBoundsGEP( 755 B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1)); 756 757 // We have enough information to now generate the memcpy call to do the 758 // copy for us. Make a memcpy to copy the nul byte with align = 1. 759 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), LenV); 760 mergeAttributesAndFlags(NewCI, *CI); 761 return DstEnd; 762 } 763 764 // Optimize a call to size_t strlcpy(char*, const char*, size_t). 765 766 Value *LibCallSimplifier::optimizeStrLCpy(CallInst *CI, IRBuilderBase &B) { 767 Value *Size = CI->getArgOperand(2); 768 if (isKnownNonZero(Size, DL)) 769 // Like snprintf, the function stores into the destination only when 770 // the size argument is nonzero. 771 annotateNonNullNoUndefBasedOnAccess(CI, 0); 772 // The function reads the source argument regardless of Size (it returns 773 // its length). 774 annotateNonNullNoUndefBasedOnAccess(CI, 1); 775 776 uint64_t NBytes; 777 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size)) 778 NBytes = SizeC->getZExtValue(); 779 else 780 return nullptr; 781 782 Value *Dst = CI->getArgOperand(0); 783 Value *Src = CI->getArgOperand(1); 784 if (NBytes <= 1) { 785 if (NBytes == 1) 786 // For a call to strlcpy(D, S, 1) first store a nul in *D. 787 B.CreateStore(B.getInt8(0), Dst); 788 789 // Transform strlcpy(D, S, 0) to a call to strlen(S). 790 return copyFlags(*CI, emitStrLen(Src, B, DL, TLI)); 791 } 792 793 // Try to determine the length of the source, substituting its size 794 // when it's not nul-terminated (as it's required to be) to avoid 795 // reading past its end. 796 StringRef Str; 797 if (!getConstantStringInfo(Src, Str, /*TrimAtNul=*/false)) 798 return nullptr; 799 800 uint64_t SrcLen = Str.find('\0'); 801 // Set if the terminating nul should be copied by the call to memcpy 802 // below. 803 bool NulTerm = SrcLen < NBytes; 804 805 if (NulTerm) 806 // Overwrite NBytes with the number of bytes to copy, including 807 // the terminating nul. 808 NBytes = SrcLen + 1; 809 else { 810 // Set the length of the source for the function to return to its 811 // size, and cap NBytes at the same. 812 SrcLen = std::min(SrcLen, uint64_t(Str.size())); 813 NBytes = std::min(NBytes - 1, SrcLen); 814 } 815 816 if (SrcLen == 0) { 817 // Transform strlcpy(D, "", N) to (*D = '\0, 0). 818 B.CreateStore(B.getInt8(0), Dst); 819 return ConstantInt::get(CI->getType(), 0); 820 } 821 822 Function *Callee = CI->getCalledFunction(); 823 Type *PT = Callee->getFunctionType()->getParamType(0); 824 // Transform strlcpy(D, S, N) to memcpy(D, S, N') where N' is the lower 825 // bound on strlen(S) + 1 and N, optionally followed by a nul store to 826 // D[N' - 1] if necessary. 827 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), 828 ConstantInt::get(DL.getIntPtrType(PT), NBytes)); 829 mergeAttributesAndFlags(NewCI, *CI); 830 831 if (!NulTerm) { 832 Value *EndOff = ConstantInt::get(CI->getType(), NBytes); 833 Value *EndPtr = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, EndOff); 834 B.CreateStore(B.getInt8(0), EndPtr); 835 } 836 837 // Like snprintf, strlcpy returns the number of nonzero bytes that would 838 // have been copied if the bound had been sufficiently big (which in this 839 // case is strlen(Src)). 840 return ConstantInt::get(CI->getType(), SrcLen); 841 } 842 843 // Optimize a call CI to either stpncpy when RetEnd is true, or to strncpy 844 // otherwise. 845 Value *LibCallSimplifier::optimizeStringNCpy(CallInst *CI, bool RetEnd, 846 IRBuilderBase &B) { 847 Function *Callee = CI->getCalledFunction(); 848 Value *Dst = CI->getArgOperand(0); 849 Value *Src = CI->getArgOperand(1); 850 Value *Size = CI->getArgOperand(2); 851 852 if (isKnownNonZero(Size, DL)) { 853 // Both st{p,r}ncpy(D, S, N) access the source and destination arrays 854 // only when N is nonzero. 855 annotateNonNullNoUndefBasedOnAccess(CI, 0); 856 annotateNonNullNoUndefBasedOnAccess(CI, 1); 857 } 858 859 // If the "bound" argument is known set N to it. Otherwise set it to 860 // UINT64_MAX and handle it later. 861 uint64_t N = UINT64_MAX; 862 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size)) 863 N = SizeC->getZExtValue(); 864 865 if (N == 0) 866 // Fold st{p,r}ncpy(D, S, 0) to D. 867 return Dst; 868 869 if (N == 1) { 870 Type *CharTy = B.getInt8Ty(); 871 Value *CharVal = B.CreateLoad(CharTy, Src, "stxncpy.char0"); 872 B.CreateStore(CharVal, Dst); 873 if (!RetEnd) 874 // Transform strncpy(D, S, 1) to return (*D = *S), D. 875 return Dst; 876 877 // Transform stpncpy(D, S, 1) to return (*D = *S) ? D + 1 : D. 878 Value *ZeroChar = ConstantInt::get(CharTy, 0); 879 Value *Cmp = B.CreateICmpEQ(CharVal, ZeroChar, "stpncpy.char0cmp"); 880 881 Value *Off1 = B.getInt32(1); 882 Value *EndPtr = B.CreateInBoundsGEP(CharTy, Dst, Off1, "stpncpy.end"); 883 return B.CreateSelect(Cmp, Dst, EndPtr, "stpncpy.sel"); 884 } 885 886 // If the length of the input string is known set SrcLen to it. 887 uint64_t SrcLen = GetStringLength(Src); 888 if (SrcLen) 889 annotateDereferenceableBytes(CI, 1, SrcLen); 890 else 891 return nullptr; 892 893 --SrcLen; // Unbias length. 894 895 if (SrcLen == 0) { 896 // Transform st{p,r}ncpy(D, "", N) to memset(D, '\0', N) for any N. 897 Align MemSetAlign = 898 CI->getAttributes().getParamAttrs(0).getAlignment().valueOrOne(); 899 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, MemSetAlign); 900 AttrBuilder ArgAttrs(CI->getContext(), CI->getAttributes().getParamAttrs(0)); 901 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes( 902 CI->getContext(), 0, ArgAttrs)); 903 copyFlags(*CI, NewCI); 904 return Dst; 905 } 906 907 if (N > SrcLen + 1) { 908 if (N > 128) 909 // Bail if N is large or unknown. 910 return nullptr; 911 912 // st{p,r}ncpy(D, "a", N) -> memcpy(D, "a\0\0\0", N) for N <= 128. 913 StringRef Str; 914 if (!getConstantStringInfo(Src, Str)) 915 return nullptr; 916 std::string SrcStr = Str.str(); 917 // Create a bigger, nul-padded array with the same length, SrcLen, 918 // as the original string. 919 SrcStr.resize(N, '\0'); 920 Src = B.CreateGlobalString(SrcStr, "str", /*AddressSpace=*/0, 921 /*M=*/nullptr, /*AddNull=*/false); 922 } 923 924 Type *PT = Callee->getFunctionType()->getParamType(0); 925 // st{p,r}ncpy(D, S, N) -> memcpy(align 1 D, align 1 S, N) when both 926 // S and N are constant. 927 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), 928 ConstantInt::get(DL.getIntPtrType(PT), N)); 929 mergeAttributesAndFlags(NewCI, *CI); 930 if (!RetEnd) 931 return Dst; 932 933 // stpncpy(D, S, N) returns the address of the first null in D if it writes 934 // one, otherwise D + N. 935 Value *Off = B.getInt64(std::min(SrcLen, N)); 936 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, Off, "endptr"); 937 } 938 939 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B, 940 unsigned CharSize, 941 Value *Bound) { 942 Value *Src = CI->getArgOperand(0); 943 Type *CharTy = B.getIntNTy(CharSize); 944 945 if (isOnlyUsedInZeroEqualityComparison(CI) && 946 (!Bound || isKnownNonZero(Bound, DL))) { 947 // Fold strlen: 948 // strlen(x) != 0 --> *x != 0 949 // strlen(x) == 0 --> *x == 0 950 // and likewise strnlen with constant N > 0: 951 // strnlen(x, N) != 0 --> *x != 0 952 // strnlen(x, N) == 0 --> *x == 0 953 return B.CreateZExt(B.CreateLoad(CharTy, Src, "char0"), 954 CI->getType()); 955 } 956 957 if (Bound) { 958 if (ConstantInt *BoundCst = dyn_cast<ConstantInt>(Bound)) { 959 if (BoundCst->isZero()) 960 // Fold strnlen(s, 0) -> 0 for any s, constant or otherwise. 961 return ConstantInt::get(CI->getType(), 0); 962 963 if (BoundCst->isOne()) { 964 // Fold strnlen(s, 1) -> *s ? 1 : 0 for any s. 965 Value *CharVal = B.CreateLoad(CharTy, Src, "strnlen.char0"); 966 Value *ZeroChar = ConstantInt::get(CharTy, 0); 967 Value *Cmp = B.CreateICmpNE(CharVal, ZeroChar, "strnlen.char0cmp"); 968 return B.CreateZExt(Cmp, CI->getType()); 969 } 970 } 971 } 972 973 if (uint64_t Len = GetStringLength(Src, CharSize)) { 974 Value *LenC = ConstantInt::get(CI->getType(), Len - 1); 975 // Fold strlen("xyz") -> 3 and strnlen("xyz", 2) -> 2 976 // and strnlen("xyz", Bound) -> min(3, Bound) for nonconstant Bound. 977 if (Bound) 978 return B.CreateBinaryIntrinsic(Intrinsic::umin, LenC, Bound); 979 return LenC; 980 } 981 982 if (Bound) 983 // Punt for strnlen for now. 984 return nullptr; 985 986 // If s is a constant pointer pointing to a string literal, we can fold 987 // strlen(s + x) to strlen(s) - x, when x is known to be in the range 988 // [0, strlen(s)] or the string has a single null terminator '\0' at the end. 989 // We only try to simplify strlen when the pointer s points to an array 990 // of CharSize elements. Otherwise, we would need to scale the offset x before 991 // doing the subtraction. This will make the optimization more complex, and 992 // it's not very useful because calling strlen for a pointer of other types is 993 // very uncommon. 994 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) { 995 // TODO: Handle subobjects. 996 if (!isGEPBasedOnPointerToString(GEP, CharSize)) 997 return nullptr; 998 999 ConstantDataArraySlice Slice; 1000 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) { 1001 uint64_t NullTermIdx; 1002 if (Slice.Array == nullptr) { 1003 NullTermIdx = 0; 1004 } else { 1005 NullTermIdx = ~((uint64_t)0); 1006 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) { 1007 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) { 1008 NullTermIdx = I; 1009 break; 1010 } 1011 } 1012 // If the string does not have '\0', leave it to strlen to compute 1013 // its length. 1014 if (NullTermIdx == ~((uint64_t)0)) 1015 return nullptr; 1016 } 1017 1018 Value *Offset = GEP->getOperand(2); 1019 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr); 1020 uint64_t ArrSize = 1021 cast<ArrayType>(GEP->getSourceElementType())->getNumElements(); 1022 1023 // If Offset is not provably in the range [0, NullTermIdx], we can still 1024 // optimize if we can prove that the program has undefined behavior when 1025 // Offset is outside that range. That is the case when GEP->getOperand(0) 1026 // is a pointer to an object whose memory extent is NullTermIdx+1. 1027 if ((Known.isNonNegative() && Known.getMaxValue().ule(NullTermIdx)) || 1028 (isa<GlobalVariable>(GEP->getOperand(0)) && 1029 NullTermIdx == ArrSize - 1)) { 1030 Offset = B.CreateSExtOrTrunc(Offset, CI->getType()); 1031 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx), 1032 Offset); 1033 } 1034 } 1035 } 1036 1037 // strlen(x?"foo":"bars") --> x ? 3 : 4 1038 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) { 1039 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize); 1040 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize); 1041 if (LenTrue && LenFalse) { 1042 ORE.emit([&]() { 1043 return OptimizationRemark("instcombine", "simplify-libcalls", CI) 1044 << "folded strlen(select) to select of constants"; 1045 }); 1046 return B.CreateSelect(SI->getCondition(), 1047 ConstantInt::get(CI->getType(), LenTrue - 1), 1048 ConstantInt::get(CI->getType(), LenFalse - 1)); 1049 } 1050 } 1051 1052 return nullptr; 1053 } 1054 1055 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) { 1056 if (Value *V = optimizeStringLength(CI, B, 8)) 1057 return V; 1058 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1059 return nullptr; 1060 } 1061 1062 Value *LibCallSimplifier::optimizeStrNLen(CallInst *CI, IRBuilderBase &B) { 1063 Value *Bound = CI->getArgOperand(1); 1064 if (Value *V = optimizeStringLength(CI, B, 8, Bound)) 1065 return V; 1066 1067 if (isKnownNonZero(Bound, DL)) 1068 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1069 return nullptr; 1070 } 1071 1072 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) { 1073 Module &M = *CI->getModule(); 1074 unsigned WCharSize = TLI->getWCharSize(M) * 8; 1075 // We cannot perform this optimization without wchar_size metadata. 1076 if (WCharSize == 0) 1077 return nullptr; 1078 1079 return optimizeStringLength(CI, B, WCharSize); 1080 } 1081 1082 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) { 1083 StringRef S1, S2; 1084 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1085 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1086 1087 // strpbrk(s, "") -> nullptr 1088 // strpbrk("", s) -> nullptr 1089 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 1090 return Constant::getNullValue(CI->getType()); 1091 1092 // Constant folding. 1093 if (HasS1 && HasS2) { 1094 size_t I = S1.find_first_of(S2); 1095 if (I == StringRef::npos) // No match. 1096 return Constant::getNullValue(CI->getType()); 1097 1098 return B.CreateInBoundsGEP(B.getInt8Ty(), CI->getArgOperand(0), 1099 B.getInt64(I), "strpbrk"); 1100 } 1101 1102 // strpbrk(s, "a") -> strchr(s, 'a') 1103 if (HasS2 && S2.size() == 1) 1104 return copyFlags(*CI, emitStrChr(CI->getArgOperand(0), S2[0], B, TLI)); 1105 1106 return nullptr; 1107 } 1108 1109 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) { 1110 Value *EndPtr = CI->getArgOperand(1); 1111 if (isa<ConstantPointerNull>(EndPtr)) { 1112 // With a null EndPtr, this function won't capture the main argument. 1113 // It would be readonly too, except that it still may write to errno. 1114 CI->addParamAttr(0, Attribute::NoCapture); 1115 } 1116 1117 return nullptr; 1118 } 1119 1120 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) { 1121 StringRef S1, S2; 1122 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1123 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1124 1125 // strspn(s, "") -> 0 1126 // strspn("", s) -> 0 1127 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 1128 return Constant::getNullValue(CI->getType()); 1129 1130 // Constant folding. 1131 if (HasS1 && HasS2) { 1132 size_t Pos = S1.find_first_not_of(S2); 1133 if (Pos == StringRef::npos) 1134 Pos = S1.size(); 1135 return ConstantInt::get(CI->getType(), Pos); 1136 } 1137 1138 return nullptr; 1139 } 1140 1141 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) { 1142 StringRef S1, S2; 1143 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1144 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1145 1146 // strcspn("", s) -> 0 1147 if (HasS1 && S1.empty()) 1148 return Constant::getNullValue(CI->getType()); 1149 1150 // Constant folding. 1151 if (HasS1 && HasS2) { 1152 size_t Pos = S1.find_first_of(S2); 1153 if (Pos == StringRef::npos) 1154 Pos = S1.size(); 1155 return ConstantInt::get(CI->getType(), Pos); 1156 } 1157 1158 // strcspn(s, "") -> strlen(s) 1159 if (HasS2 && S2.empty()) 1160 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, DL, TLI)); 1161 1162 return nullptr; 1163 } 1164 1165 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) { 1166 // fold strstr(x, x) -> x. 1167 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 1168 return CI->getArgOperand(0); 1169 1170 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 1171 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 1172 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI); 1173 if (!StrLen) 1174 return nullptr; 1175 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 1176 StrLen, B, DL, TLI); 1177 if (!StrNCmp) 1178 return nullptr; 1179 for (User *U : llvm::make_early_inc_range(CI->users())) { 1180 ICmpInst *Old = cast<ICmpInst>(U); 1181 Value *Cmp = 1182 B.CreateICmp(Old->getPredicate(), StrNCmp, 1183 ConstantInt::getNullValue(StrNCmp->getType()), "cmp"); 1184 replaceAllUsesWith(Old, Cmp); 1185 } 1186 return CI; 1187 } 1188 1189 // See if either input string is a constant string. 1190 StringRef SearchStr, ToFindStr; 1191 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 1192 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 1193 1194 // fold strstr(x, "") -> x. 1195 if (HasStr2 && ToFindStr.empty()) 1196 return CI->getArgOperand(0); 1197 1198 // If both strings are known, constant fold it. 1199 if (HasStr1 && HasStr2) { 1200 size_t Offset = SearchStr.find(ToFindStr); 1201 1202 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 1203 return Constant::getNullValue(CI->getType()); 1204 1205 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 1206 return B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), CI->getArgOperand(0), 1207 Offset, "strstr"); 1208 } 1209 1210 // fold strstr(x, "y") -> strchr(x, 'y'). 1211 if (HasStr2 && ToFindStr.size() == 1) { 1212 return emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI); 1213 } 1214 1215 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 1216 return nullptr; 1217 } 1218 1219 Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) { 1220 Value *SrcStr = CI->getArgOperand(0); 1221 Value *Size = CI->getArgOperand(2); 1222 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1223 Value *CharVal = CI->getArgOperand(1); 1224 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1225 Value *NullPtr = Constant::getNullValue(CI->getType()); 1226 1227 if (LenC) { 1228 if (LenC->isZero()) 1229 // Fold memrchr(x, y, 0) --> null. 1230 return NullPtr; 1231 1232 if (LenC->isOne()) { 1233 // Fold memrchr(x, y, 1) --> *x == y ? x : null for any x and y, 1234 // constant or otherwise. 1235 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memrchr.char0"); 1236 // Slice off the character's high end bits. 1237 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1238 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memrchr.char0cmp"); 1239 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memrchr.sel"); 1240 } 1241 } 1242 1243 StringRef Str; 1244 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false)) 1245 return nullptr; 1246 1247 if (Str.size() == 0) 1248 // If the array is empty fold memrchr(A, C, N) to null for any value 1249 // of C and N on the basis that the only valid value of N is zero 1250 // (otherwise the call is undefined). 1251 return NullPtr; 1252 1253 uint64_t EndOff = UINT64_MAX; 1254 if (LenC) { 1255 EndOff = LenC->getZExtValue(); 1256 if (Str.size() < EndOff) 1257 // Punt out-of-bounds accesses to sanitizers and/or libc. 1258 return nullptr; 1259 } 1260 1261 if (ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal)) { 1262 // Fold memrchr(S, C, N) for a constant C. 1263 size_t Pos = Str.rfind(CharC->getZExtValue(), EndOff); 1264 if (Pos == StringRef::npos) 1265 // When the character is not in the source array fold the result 1266 // to null regardless of Size. 1267 return NullPtr; 1268 1269 if (LenC) 1270 // Fold memrchr(s, c, N) --> s + Pos for constant N > Pos. 1271 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos)); 1272 1273 if (Str.find(Str[Pos]) == Pos) { 1274 // When there is just a single occurrence of C in S, i.e., the one 1275 // in Str[Pos], fold 1276 // memrchr(s, c, N) --> N <= Pos ? null : s + Pos 1277 // for nonconstant N. 1278 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos), 1279 "memrchr.cmp"); 1280 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, 1281 B.getInt64(Pos), "memrchr.ptr_plus"); 1282 return B.CreateSelect(Cmp, NullPtr, SrcPlus, "memrchr.sel"); 1283 } 1284 } 1285 1286 // Truncate the string to search at most EndOff characters. 1287 Str = Str.substr(0, EndOff); 1288 if (Str.find_first_not_of(Str[0]) != StringRef::npos) 1289 return nullptr; 1290 1291 // If the source array consists of all equal characters, then for any 1292 // C and N (whether in bounds or not), fold memrchr(S, C, N) to 1293 // N != 0 && *S == C ? S + N - 1 : null 1294 Type *SizeTy = Size->getType(); 1295 Type *Int8Ty = B.getInt8Ty(); 1296 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1297 // Slice off the sought character's high end bits. 1298 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1299 Value *CEqS0 = B.CreateICmpEQ(ConstantInt::get(Int8Ty, Str[0]), CharVal); 1300 Value *And = B.CreateLogicalAnd(NNeZ, CEqS0); 1301 Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1)); 1302 Value *SrcPlus = 1303 B.CreateInBoundsGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus"); 1304 return B.CreateSelect(And, SrcPlus, NullPtr, "memrchr.sel"); 1305 } 1306 1307 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) { 1308 Value *SrcStr = CI->getArgOperand(0); 1309 Value *Size = CI->getArgOperand(2); 1310 1311 if (isKnownNonZero(Size, DL)) { 1312 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1313 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 1314 return memChrToCharCompare(CI, Size, B, DL); 1315 } 1316 1317 Value *CharVal = CI->getArgOperand(1); 1318 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 1319 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1320 Value *NullPtr = Constant::getNullValue(CI->getType()); 1321 1322 // memchr(x, y, 0) -> null 1323 if (LenC) { 1324 if (LenC->isZero()) 1325 return NullPtr; 1326 1327 if (LenC->isOne()) { 1328 // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y, 1329 // constant or otherwise. 1330 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0"); 1331 // Slice off the character's high end bits. 1332 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1333 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp"); 1334 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memchr.sel"); 1335 } 1336 } 1337 1338 StringRef Str; 1339 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false)) 1340 return nullptr; 1341 1342 if (CharC) { 1343 size_t Pos = Str.find(CharC->getZExtValue()); 1344 if (Pos == StringRef::npos) 1345 // When the character is not in the source array fold the result 1346 // to null regardless of Size. 1347 return NullPtr; 1348 1349 // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos 1350 // When the constant Size is less than or equal to the character 1351 // position also fold the result to null. 1352 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos), 1353 "memchr.cmp"); 1354 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos), 1355 "memchr.ptr"); 1356 return B.CreateSelect(Cmp, NullPtr, SrcPlus); 1357 } 1358 1359 if (Str.size() == 0) 1360 // If the array is empty fold memchr(A, C, N) to null for any value 1361 // of C and N on the basis that the only valid value of N is zero 1362 // (otherwise the call is undefined). 1363 return NullPtr; 1364 1365 if (LenC) 1366 Str = substr(Str, LenC->getZExtValue()); 1367 1368 size_t Pos = Str.find_first_not_of(Str[0]); 1369 if (Pos == StringRef::npos 1370 || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) { 1371 // If the source array consists of at most two consecutive sequences 1372 // of the same characters, then for any C and N (whether in bounds or 1373 // not), fold memchr(S, C, N) to 1374 // N != 0 && *S == C ? S : null 1375 // or for the two sequences to: 1376 // N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null) 1377 // ^Sel2 ^Sel1 are denoted above. 1378 // The latter makes it also possible to fold strchr() calls with strings 1379 // of the same characters. 1380 Type *SizeTy = Size->getType(); 1381 Type *Int8Ty = B.getInt8Ty(); 1382 1383 // Slice off the sought character's high end bits. 1384 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1385 1386 Value *Sel1 = NullPtr; 1387 if (Pos != StringRef::npos) { 1388 // Handle two consecutive sequences of the same characters. 1389 Value *PosVal = ConstantInt::get(SizeTy, Pos); 1390 Value *StrPos = ConstantInt::get(Int8Ty, Str[Pos]); 1391 Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos); 1392 Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal); 1393 Value *And = B.CreateAnd(CEqSPos, NGtPos); 1394 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal); 1395 Sel1 = B.CreateSelect(And, SrcPlus, NullPtr, "memchr.sel1"); 1396 } 1397 1398 Value *Str0 = ConstantInt::get(Int8Ty, Str[0]); 1399 Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal); 1400 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1401 Value *And = B.CreateAnd(NNeZ, CEqS0); 1402 return B.CreateSelect(And, SrcStr, Sel1, "memchr.sel2"); 1403 } 1404 1405 if (!LenC) { 1406 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 1407 // S is dereferenceable so it's safe to load from it and fold 1408 // memchr(S, C, N) == S to N && *S == C for any C and N. 1409 // TODO: This is safe even for nonconstant S. 1410 return memChrToCharCompare(CI, Size, B, DL); 1411 1412 // From now on we need a constant length and constant array. 1413 return nullptr; 1414 } 1415 1416 bool OptForSize = CI->getFunction()->hasOptSize() || 1417 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 1418 PGSOQueryType::IRPass); 1419 1420 // If the char is variable but the input str and length are not we can turn 1421 // this memchr call into a simple bit field test. Of course this only works 1422 // when the return value is only checked against null. 1423 // 1424 // It would be really nice to reuse switch lowering here but we can't change 1425 // the CFG at this point. 1426 // 1427 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n'))) 1428 // != 0 1429 // after bounds check. 1430 if (OptForSize || Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI)) 1431 return nullptr; 1432 1433 unsigned char Max = 1434 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()), 1435 reinterpret_cast<const unsigned char *>(Str.end())); 1436 1437 // Make sure the bit field we're about to create fits in a register on the 1438 // target. 1439 // FIXME: On a 64 bit architecture this prevents us from using the 1440 // interesting range of alpha ascii chars. We could do better by emitting 1441 // two bitfields or shifting the range by 64 if no lower chars are used. 1442 if (!DL.fitsInLegalInteger(Max + 1)) { 1443 // Build chain of ORs 1444 // Transform: 1445 // memchr("abcd", C, 4) != nullptr 1446 // to: 1447 // (C == 'a' || C == 'b' || C == 'c' || C == 'd') != 0 1448 std::string SortedStr = Str.str(); 1449 llvm::sort(SortedStr); 1450 // Compute the number of of non-contiguous ranges. 1451 unsigned NonContRanges = 1; 1452 for (size_t i = 1; i < SortedStr.size(); ++i) { 1453 if (SortedStr[i] > SortedStr[i - 1] + 1) { 1454 NonContRanges++; 1455 } 1456 } 1457 1458 // Restrict this optimization to profitable cases with one or two range 1459 // checks. 1460 if (NonContRanges > 2) 1461 return nullptr; 1462 1463 // Slice off the character's high end bits. 1464 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1465 1466 SmallVector<Value *> CharCompares; 1467 for (unsigned char C : SortedStr) 1468 CharCompares.push_back(B.CreateICmpEQ(CharVal, B.getInt8(C))); 1469 1470 return B.CreateIntToPtr(B.CreateOr(CharCompares), CI->getType()); 1471 } 1472 1473 // For the bit field use a power-of-2 type with at least 8 bits to avoid 1474 // creating unnecessary illegal types. 1475 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max)); 1476 1477 // Now build the bit field. 1478 APInt Bitfield(Width, 0); 1479 for (char C : Str) 1480 Bitfield.setBit((unsigned char)C); 1481 Value *BitfieldC = B.getInt(Bitfield); 1482 1483 // Adjust width of "C" to the bitfield width, then mask off the high bits. 1484 Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType()); 1485 C = B.CreateAnd(C, B.getIntN(Width, 0xFF)); 1486 1487 // First check that the bit field access is within bounds. 1488 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width), 1489 "memchr.bounds"); 1490 1491 // Create code that checks if the given bit is set in the field. 1492 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C); 1493 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits"); 1494 1495 // Finally merge both checks and cast to pointer type. The inttoptr 1496 // implicitly zexts the i1 to intptr type. 1497 return B.CreateIntToPtr(B.CreateLogicalAnd(Bounds, Bits, "memchr"), 1498 CI->getType()); 1499 } 1500 1501 // Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant 1502 // arrays LHS and RHS and nonconstant Size. 1503 static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS, 1504 Value *Size, bool StrNCmp, 1505 IRBuilderBase &B, const DataLayout &DL) { 1506 if (LHS == RHS) // memcmp(s,s,x) -> 0 1507 return Constant::getNullValue(CI->getType()); 1508 1509 StringRef LStr, RStr; 1510 if (!getConstantStringInfo(LHS, LStr, /*TrimAtNul=*/false) || 1511 !getConstantStringInfo(RHS, RStr, /*TrimAtNul=*/false)) 1512 return nullptr; 1513 1514 // If the contents of both constant arrays are known, fold a call to 1515 // memcmp(A, B, N) to 1516 // N <= Pos ? 0 : (A < B ? -1 : B < A ? +1 : 0) 1517 // where Pos is the first mismatch between A and B, determined below. 1518 1519 uint64_t Pos = 0; 1520 Value *Zero = ConstantInt::get(CI->getType(), 0); 1521 for (uint64_t MinSize = std::min(LStr.size(), RStr.size()); ; ++Pos) { 1522 if (Pos == MinSize || 1523 (StrNCmp && (LStr[Pos] == '\0' && RStr[Pos] == '\0'))) { 1524 // One array is a leading part of the other of equal or greater 1525 // size, or for strncmp, the arrays are equal strings. 1526 // Fold the result to zero. Size is assumed to be in bounds, since 1527 // otherwise the call would be undefined. 1528 return Zero; 1529 } 1530 1531 if (LStr[Pos] != RStr[Pos]) 1532 break; 1533 } 1534 1535 // Normalize the result. 1536 typedef unsigned char UChar; 1537 int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1; 1538 Value *MaxSize = ConstantInt::get(Size->getType(), Pos); 1539 Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize); 1540 Value *Res = ConstantInt::get(CI->getType(), IRes); 1541 return B.CreateSelect(Cmp, Zero, Res); 1542 } 1543 1544 // Optimize a memcmp call CI with constant size Len. 1545 static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS, 1546 uint64_t Len, IRBuilderBase &B, 1547 const DataLayout &DL) { 1548 if (Len == 0) // memcmp(s1,s2,0) -> 0 1549 return Constant::getNullValue(CI->getType()); 1550 1551 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 1552 if (Len == 1) { 1553 Value *LHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), LHS, "lhsc"), 1554 CI->getType(), "lhsv"); 1555 Value *RHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), RHS, "rhsc"), 1556 CI->getType(), "rhsv"); 1557 return B.CreateSub(LHSV, RHSV, "chardiff"); 1558 } 1559 1560 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0 1561 // TODO: The case where both inputs are constants does not need to be limited 1562 // to legal integers or equality comparison. See block below this. 1563 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) { 1564 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8); 1565 Align PrefAlignment = DL.getPrefTypeAlign(IntType); 1566 1567 // First, see if we can fold either argument to a constant. 1568 Value *LHSV = nullptr; 1569 if (auto *LHSC = dyn_cast<Constant>(LHS)) 1570 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL); 1571 1572 Value *RHSV = nullptr; 1573 if (auto *RHSC = dyn_cast<Constant>(RHS)) 1574 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL); 1575 1576 // Don't generate unaligned loads. If either source is constant data, 1577 // alignment doesn't matter for that source because there is no load. 1578 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) && 1579 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) { 1580 if (!LHSV) 1581 LHSV = B.CreateLoad(IntType, LHS, "lhsv"); 1582 if (!RHSV) 1583 RHSV = B.CreateLoad(IntType, RHS, "rhsv"); 1584 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp"); 1585 } 1586 } 1587 1588 return nullptr; 1589 } 1590 1591 // Most simplifications for memcmp also apply to bcmp. 1592 Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI, 1593 IRBuilderBase &B) { 1594 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 1595 Value *Size = CI->getArgOperand(2); 1596 1597 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1598 1599 if (Value *Res = optimizeMemCmpVarSize(CI, LHS, RHS, Size, false, B, DL)) 1600 return Res; 1601 1602 // Handle constant Size. 1603 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1604 if (!LenC) 1605 return nullptr; 1606 1607 return optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL); 1608 } 1609 1610 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) { 1611 Module *M = CI->getModule(); 1612 if (Value *V = optimizeMemCmpBCmpCommon(CI, B)) 1613 return V; 1614 1615 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0 1616 // bcmp can be more efficient than memcmp because it only has to know that 1617 // there is a difference, not how different one is to the other. 1618 if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) && 1619 isOnlyUsedInZeroEqualityComparison(CI)) { 1620 Value *LHS = CI->getArgOperand(0); 1621 Value *RHS = CI->getArgOperand(1); 1622 Value *Size = CI->getArgOperand(2); 1623 return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI)); 1624 } 1625 1626 return nullptr; 1627 } 1628 1629 Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) { 1630 return optimizeMemCmpBCmpCommon(CI, B); 1631 } 1632 1633 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) { 1634 Value *Size = CI->getArgOperand(2); 1635 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1636 if (isa<IntrinsicInst>(CI)) 1637 return nullptr; 1638 1639 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n) 1640 CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1), 1641 CI->getArgOperand(1), Align(1), Size); 1642 mergeAttributesAndFlags(NewCI, *CI); 1643 return CI->getArgOperand(0); 1644 } 1645 1646 Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) { 1647 Value *Dst = CI->getArgOperand(0); 1648 Value *Src = CI->getArgOperand(1); 1649 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 1650 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3)); 1651 StringRef SrcStr; 1652 if (CI->use_empty() && Dst == Src) 1653 return Dst; 1654 // memccpy(d, s, c, 0) -> nullptr 1655 if (N) { 1656 if (N->isNullValue()) 1657 return Constant::getNullValue(CI->getType()); 1658 if (!getConstantStringInfo(Src, SrcStr, /*TrimAtNul=*/false) || 1659 // TODO: Handle zeroinitializer. 1660 !StopChar) 1661 return nullptr; 1662 } else { 1663 return nullptr; 1664 } 1665 1666 // Wrap arg 'c' of type int to char 1667 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF); 1668 if (Pos == StringRef::npos) { 1669 if (N->getZExtValue() <= SrcStr.size()) { 1670 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), 1671 CI->getArgOperand(3))); 1672 return Constant::getNullValue(CI->getType()); 1673 } 1674 return nullptr; 1675 } 1676 1677 Value *NewN = 1678 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue())); 1679 // memccpy -> llvm.memcpy 1680 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN)); 1681 return Pos + 1 <= N->getZExtValue() 1682 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN) 1683 : Constant::getNullValue(CI->getType()); 1684 } 1685 1686 Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) { 1687 Value *Dst = CI->getArgOperand(0); 1688 Value *N = CI->getArgOperand(2); 1689 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n 1690 CallInst *NewCI = 1691 B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N); 1692 // Propagate attributes, but memcpy has no return value, so make sure that 1693 // any return attributes are compliant. 1694 // TODO: Attach return value attributes to the 1st operand to preserve them? 1695 mergeAttributesAndFlags(NewCI, *CI); 1696 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N); 1697 } 1698 1699 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) { 1700 Value *Size = CI->getArgOperand(2); 1701 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1702 if (isa<IntrinsicInst>(CI)) 1703 return nullptr; 1704 1705 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n) 1706 CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1), 1707 CI->getArgOperand(1), Align(1), Size); 1708 mergeAttributesAndFlags(NewCI, *CI); 1709 return CI->getArgOperand(0); 1710 } 1711 1712 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) { 1713 Value *Size = CI->getArgOperand(2); 1714 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1715 if (isa<IntrinsicInst>(CI)) 1716 return nullptr; 1717 1718 // memset(p, v, n) -> llvm.memset(align 1 p, v, n) 1719 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 1720 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1)); 1721 mergeAttributesAndFlags(NewCI, *CI); 1722 return CI->getArgOperand(0); 1723 } 1724 1725 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) { 1726 if (isa<ConstantPointerNull>(CI->getArgOperand(0))) 1727 return copyFlags(*CI, emitMalloc(CI->getArgOperand(1), B, DL, TLI)); 1728 1729 return nullptr; 1730 } 1731 1732 // When enabled, replace operator new() calls marked with a hot or cold memprof 1733 // attribute with an operator new() call that takes a __hot_cold_t parameter. 1734 // Currently this is supported by the open source version of tcmalloc, see: 1735 // https://github.com/google/tcmalloc/blob/master/tcmalloc/new_extension.h 1736 Value *LibCallSimplifier::optimizeNew(CallInst *CI, IRBuilderBase &B, 1737 LibFunc &Func) { 1738 if (!OptimizeHotColdNew) 1739 return nullptr; 1740 1741 uint8_t HotCold; 1742 if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "cold") 1743 HotCold = ColdNewHintValue; 1744 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == 1745 "notcold") 1746 HotCold = NotColdNewHintValue; 1747 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "hot") 1748 HotCold = HotNewHintValue; 1749 else 1750 return nullptr; 1751 1752 // For calls that already pass a hot/cold hint, only update the hint if 1753 // directed by OptimizeExistingHotColdNew. For other calls to new, add a hint 1754 // if cold or hot, and leave as-is for default handling if "notcold" aka warm. 1755 // Note that in cases where we decide it is "notcold", it might be slightly 1756 // better to replace the hinted call with a non hinted call, to avoid the 1757 // extra parameter and the if condition check of the hint value in the 1758 // allocator. This can be considered in the future. 1759 switch (Func) { 1760 case LibFunc_Znwm12__hot_cold_t: 1761 if (OptimizeExistingHotColdNew) 1762 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1763 LibFunc_Znwm12__hot_cold_t, HotCold); 1764 break; 1765 case LibFunc_Znwm: 1766 if (HotCold != NotColdNewHintValue) 1767 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1768 LibFunc_Znwm12__hot_cold_t, HotCold); 1769 break; 1770 case LibFunc_Znam12__hot_cold_t: 1771 if (OptimizeExistingHotColdNew) 1772 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1773 LibFunc_Znam12__hot_cold_t, HotCold); 1774 break; 1775 case LibFunc_Znam: 1776 if (HotCold != NotColdNewHintValue) 1777 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1778 LibFunc_Znam12__hot_cold_t, HotCold); 1779 break; 1780 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t: 1781 if (OptimizeExistingHotColdNew) 1782 return emitHotColdNewNoThrow( 1783 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1784 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold); 1785 break; 1786 case LibFunc_ZnwmRKSt9nothrow_t: 1787 if (HotCold != NotColdNewHintValue) 1788 return emitHotColdNewNoThrow( 1789 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1790 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold); 1791 break; 1792 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t: 1793 if (OptimizeExistingHotColdNew) 1794 return emitHotColdNewNoThrow( 1795 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1796 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold); 1797 break; 1798 case LibFunc_ZnamRKSt9nothrow_t: 1799 if (HotCold != NotColdNewHintValue) 1800 return emitHotColdNewNoThrow( 1801 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1802 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold); 1803 break; 1804 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t: 1805 if (OptimizeExistingHotColdNew) 1806 return emitHotColdNewAligned( 1807 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1808 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold); 1809 break; 1810 case LibFunc_ZnwmSt11align_val_t: 1811 if (HotCold != NotColdNewHintValue) 1812 return emitHotColdNewAligned( 1813 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1814 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold); 1815 break; 1816 case LibFunc_ZnamSt11align_val_t12__hot_cold_t: 1817 if (OptimizeExistingHotColdNew) 1818 return emitHotColdNewAligned( 1819 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1820 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold); 1821 break; 1822 case LibFunc_ZnamSt11align_val_t: 1823 if (HotCold != NotColdNewHintValue) 1824 return emitHotColdNewAligned( 1825 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1826 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold); 1827 break; 1828 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 1829 if (OptimizeExistingHotColdNew) 1830 return emitHotColdNewAlignedNoThrow( 1831 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1832 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1833 HotCold); 1834 break; 1835 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t: 1836 if (HotCold != NotColdNewHintValue) 1837 return emitHotColdNewAlignedNoThrow( 1838 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1839 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1840 HotCold); 1841 break; 1842 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 1843 if (OptimizeExistingHotColdNew) 1844 return emitHotColdNewAlignedNoThrow( 1845 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1846 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1847 HotCold); 1848 break; 1849 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t: 1850 if (HotCold != NotColdNewHintValue) 1851 return emitHotColdNewAlignedNoThrow( 1852 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1853 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1854 HotCold); 1855 break; 1856 case LibFunc_size_returning_new: 1857 if (HotCold != NotColdNewHintValue) 1858 return emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI, 1859 LibFunc_size_returning_new_hot_cold, 1860 HotCold); 1861 break; 1862 case LibFunc_size_returning_new_hot_cold: 1863 if (OptimizeExistingHotColdNew) 1864 return emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI, 1865 LibFunc_size_returning_new_hot_cold, 1866 HotCold); 1867 break; 1868 case LibFunc_size_returning_new_aligned: 1869 if (HotCold != NotColdNewHintValue) 1870 return emitHotColdSizeReturningNewAligned( 1871 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1872 LibFunc_size_returning_new_aligned_hot_cold, HotCold); 1873 break; 1874 case LibFunc_size_returning_new_aligned_hot_cold: 1875 if (OptimizeExistingHotColdNew) 1876 return emitHotColdSizeReturningNewAligned( 1877 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1878 LibFunc_size_returning_new_aligned_hot_cold, HotCold); 1879 break; 1880 default: 1881 return nullptr; 1882 } 1883 return nullptr; 1884 } 1885 1886 //===----------------------------------------------------------------------===// 1887 // Math Library Optimizations 1888 //===----------------------------------------------------------------------===// 1889 1890 // Replace a libcall \p CI with a call to intrinsic \p IID 1891 static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B, 1892 Intrinsic::ID IID) { 1893 CallInst *NewCall = B.CreateUnaryIntrinsic(IID, CI->getArgOperand(0), CI); 1894 NewCall->takeName(CI); 1895 return copyFlags(*CI, NewCall); 1896 } 1897 1898 /// Return a variant of Val with float type. 1899 /// Currently this works in two cases: If Val is an FPExtension of a float 1900 /// value to something bigger, simply return the operand. 1901 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 1902 /// loss of precision do so. 1903 static Value *valueHasFloatPrecision(Value *Val) { 1904 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 1905 Value *Op = Cast->getOperand(0); 1906 if (Op->getType()->isFloatTy()) 1907 return Op; 1908 } 1909 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 1910 APFloat F = Const->getValueAPF(); 1911 bool losesInfo; 1912 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 1913 &losesInfo); 1914 if (!losesInfo) 1915 return ConstantFP::get(Const->getContext(), F); 1916 } 1917 return nullptr; 1918 } 1919 1920 /// Shrink double -> float functions. 1921 static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B, 1922 bool isBinary, const TargetLibraryInfo *TLI, 1923 bool isPrecise = false) { 1924 Function *CalleeFn = CI->getCalledFunction(); 1925 if (!CI->getType()->isDoubleTy() || !CalleeFn) 1926 return nullptr; 1927 1928 // If not all the uses of the function are converted to float, then bail out. 1929 // This matters if the precision of the result is more important than the 1930 // precision of the arguments. 1931 if (isPrecise) 1932 for (User *U : CI->users()) { 1933 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 1934 if (!Cast || !Cast->getType()->isFloatTy()) 1935 return nullptr; 1936 } 1937 1938 // If this is something like 'g((double) float)', convert to 'gf(float)'. 1939 Value *V[2]; 1940 V[0] = valueHasFloatPrecision(CI->getArgOperand(0)); 1941 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr; 1942 if (!V[0] || (isBinary && !V[1])) 1943 return nullptr; 1944 1945 // If call isn't an intrinsic, check that it isn't within a function with the 1946 // same name as the float version of this call, otherwise the result is an 1947 // infinite loop. For example, from MinGW-w64: 1948 // 1949 // float expf(float val) { return (float) exp((double) val); } 1950 StringRef CalleeName = CalleeFn->getName(); 1951 bool IsIntrinsic = CalleeFn->isIntrinsic(); 1952 if (!IsIntrinsic) { 1953 StringRef CallerName = CI->getFunction()->getName(); 1954 if (!CallerName.empty() && CallerName.back() == 'f' && 1955 CallerName.size() == (CalleeName.size() + 1) && 1956 CallerName.starts_with(CalleeName)) 1957 return nullptr; 1958 } 1959 1960 // Propagate the math semantics from the current function to the new function. 1961 IRBuilderBase::FastMathFlagGuard Guard(B); 1962 B.setFastMathFlags(CI->getFastMathFlags()); 1963 1964 // g((double) float) -> (double) gf(float) 1965 Value *R; 1966 if (IsIntrinsic) { 1967 Intrinsic::ID IID = CalleeFn->getIntrinsicID(); 1968 R = isBinary ? B.CreateIntrinsic(IID, B.getFloatTy(), V) 1969 : B.CreateIntrinsic(IID, B.getFloatTy(), V[0]); 1970 } else { 1971 AttributeList CalleeAttrs = CalleeFn->getAttributes(); 1972 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B, 1973 CalleeAttrs) 1974 : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CalleeAttrs); 1975 } 1976 return B.CreateFPExt(R, B.getDoubleTy()); 1977 } 1978 1979 /// Shrink double -> float for unary functions. 1980 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1981 const TargetLibraryInfo *TLI, 1982 bool isPrecise = false) { 1983 return optimizeDoubleFP(CI, B, false, TLI, isPrecise); 1984 } 1985 1986 /// Shrink double -> float for binary functions. 1987 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1988 const TargetLibraryInfo *TLI, 1989 bool isPrecise = false) { 1990 return optimizeDoubleFP(CI, B, true, TLI, isPrecise); 1991 } 1992 1993 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1994 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) { 1995 Value *Real, *Imag; 1996 1997 if (CI->arg_size() == 1) { 1998 1999 if (!CI->isFast()) 2000 return nullptr; 2001 2002 Value *Op = CI->getArgOperand(0); 2003 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 2004 2005 Real = B.CreateExtractValue(Op, 0, "real"); 2006 Imag = B.CreateExtractValue(Op, 1, "imag"); 2007 2008 } else { 2009 assert(CI->arg_size() == 2 && "Unexpected signature for cabs!"); 2010 2011 Real = CI->getArgOperand(0); 2012 Imag = CI->getArgOperand(1); 2013 2014 // if real or imaginary part is zero, simplify to abs(cimag(z)) 2015 // or abs(creal(z)) 2016 Value *AbsOp = nullptr; 2017 if (ConstantFP *ConstReal = dyn_cast<ConstantFP>(Real)) { 2018 if (ConstReal->isZero()) 2019 AbsOp = Imag; 2020 2021 } else if (ConstantFP *ConstImag = dyn_cast<ConstantFP>(Imag)) { 2022 if (ConstImag->isZero()) 2023 AbsOp = Real; 2024 } 2025 2026 if (AbsOp) { 2027 IRBuilderBase::FastMathFlagGuard Guard(B); 2028 B.setFastMathFlags(CI->getFastMathFlags()); 2029 2030 return copyFlags( 2031 *CI, B.CreateUnaryIntrinsic(Intrinsic::fabs, AbsOp, nullptr, "cabs")); 2032 } 2033 2034 if (!CI->isFast()) 2035 return nullptr; 2036 } 2037 2038 // Propagate fast-math flags from the existing call to new instructions. 2039 IRBuilderBase::FastMathFlagGuard Guard(B); 2040 B.setFastMathFlags(CI->getFastMathFlags()); 2041 2042 Value *RealReal = B.CreateFMul(Real, Real); 2043 Value *ImagImag = B.CreateFMul(Imag, Imag); 2044 2045 return copyFlags(*CI, B.CreateUnaryIntrinsic(Intrinsic::sqrt, 2046 B.CreateFAdd(RealReal, ImagImag), 2047 nullptr, "cabs")); 2048 } 2049 2050 // Return a properly extended integer (DstWidth bits wide) if the operation is 2051 // an itofp. 2052 static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) { 2053 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) { 2054 Value *Op = cast<Instruction>(I2F)->getOperand(0); 2055 // Make sure that the exponent fits inside an "int" of size DstWidth, 2056 // thus avoiding any range issues that FP has not. 2057 unsigned BitWidth = Op->getType()->getScalarSizeInBits(); 2058 if (BitWidth < DstWidth || (BitWidth == DstWidth && isa<SIToFPInst>(I2F))) { 2059 Type *IntTy = Op->getType()->getWithNewBitWidth(DstWidth); 2060 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, IntTy) 2061 : B.CreateZExt(Op, IntTy); 2062 } 2063 } 2064 2065 return nullptr; 2066 } 2067 2068 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y); 2069 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x); 2070 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x). 2071 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) { 2072 Module *M = Pow->getModule(); 2073 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 2074 Type *Ty = Pow->getType(); 2075 bool Ignored; 2076 2077 // Evaluate special cases related to a nested function as the base. 2078 2079 // pow(exp(x), y) -> exp(x * y) 2080 // pow(exp2(x), y) -> exp2(x * y) 2081 // If exp{,2}() is used only once, it is better to fold two transcendental 2082 // math functions into one. If used again, exp{,2}() would still have to be 2083 // called with the original argument, then keep both original transcendental 2084 // functions. However, this transformation is only safe with fully relaxed 2085 // math semantics, since, besides rounding differences, it changes overflow 2086 // and underflow behavior quite dramatically. For example: 2087 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf 2088 // Whereas: 2089 // exp(1000 * 0.001) = exp(1) 2090 // TODO: Loosen the requirement for fully relaxed math semantics. 2091 // TODO: Handle exp10() when more targets have it available. 2092 CallInst *BaseFn = dyn_cast<CallInst>(Base); 2093 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) { 2094 LibFunc LibFn; 2095 2096 Function *CalleeFn = BaseFn->getCalledFunction(); 2097 if (CalleeFn && TLI->getLibFunc(CalleeFn->getName(), LibFn) && 2098 isLibFuncEmittable(M, TLI, LibFn)) { 2099 StringRef ExpName; 2100 Intrinsic::ID ID; 2101 Value *ExpFn; 2102 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble; 2103 2104 switch (LibFn) { 2105 default: 2106 return nullptr; 2107 case LibFunc_expf: 2108 case LibFunc_exp: 2109 case LibFunc_expl: 2110 ExpName = TLI->getName(LibFunc_exp); 2111 ID = Intrinsic::exp; 2112 LibFnFloat = LibFunc_expf; 2113 LibFnDouble = LibFunc_exp; 2114 LibFnLongDouble = LibFunc_expl; 2115 break; 2116 case LibFunc_exp2f: 2117 case LibFunc_exp2: 2118 case LibFunc_exp2l: 2119 ExpName = TLI->getName(LibFunc_exp2); 2120 ID = Intrinsic::exp2; 2121 LibFnFloat = LibFunc_exp2f; 2122 LibFnDouble = LibFunc_exp2; 2123 LibFnLongDouble = LibFunc_exp2l; 2124 break; 2125 } 2126 2127 // Create new exp{,2}() with the product as its argument. 2128 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul"); 2129 ExpFn = BaseFn->doesNotAccessMemory() 2130 ? B.CreateUnaryIntrinsic(ID, FMul, nullptr, ExpName) 2131 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat, 2132 LibFnLongDouble, B, 2133 BaseFn->getAttributes()); 2134 2135 // Since the new exp{,2}() is different from the original one, dead code 2136 // elimination cannot be trusted to remove it, since it may have side 2137 // effects (e.g., errno). When the only consumer for the original 2138 // exp{,2}() is pow(), then it has to be explicitly erased. 2139 substituteInParent(BaseFn, ExpFn); 2140 return ExpFn; 2141 } 2142 } 2143 2144 // Evaluate special cases related to a constant base. 2145 2146 const APFloat *BaseF; 2147 if (!match(Base, m_APFloat(BaseF))) 2148 return nullptr; 2149 2150 AttributeList NoAttrs; // Attributes are only meaningful on the original call 2151 2152 const bool UseIntrinsic = Pow->doesNotAccessMemory(); 2153 2154 // pow(2.0, itofp(x)) -> ldexp(1.0, x) 2155 if ((UseIntrinsic || !Ty->isVectorTy()) && BaseF->isExactlyValue(2.0) && 2156 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) && 2157 (UseIntrinsic || 2158 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) { 2159 2160 // TODO: Shouldn't really need to depend on getIntToFPVal for intrinsic. Can 2161 // just directly use the original integer type. 2162 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) { 2163 Constant *One = ConstantFP::get(Ty, 1.0); 2164 2165 if (UseIntrinsic) { 2166 return copyFlags(*Pow, B.CreateIntrinsic(Intrinsic::ldexp, 2167 {Ty, ExpoI->getType()}, 2168 {One, ExpoI}, Pow, "exp2")); 2169 } 2170 2171 return copyFlags(*Pow, emitBinaryFloatFnCall( 2172 One, ExpoI, TLI, LibFunc_ldexp, LibFunc_ldexpf, 2173 LibFunc_ldexpl, B, NoAttrs)); 2174 } 2175 } 2176 2177 // pow(2.0 ** n, x) -> exp2(n * x) 2178 if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) { 2179 APFloat BaseR = APFloat(1.0); 2180 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored); 2181 BaseR = BaseR / *BaseF; 2182 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger(); 2183 const APFloat *NF = IsReciprocal ? &BaseR : BaseF; 2184 APSInt NI(64, false); 2185 if ((IsInteger || IsReciprocal) && 2186 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) == 2187 APFloat::opOK && 2188 NI > 1 && NI.isPowerOf2()) { 2189 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0); 2190 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul"); 2191 if (Pow->doesNotAccessMemory()) 2192 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul, 2193 nullptr, "exp2")); 2194 else 2195 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 2196 LibFunc_exp2f, 2197 LibFunc_exp2l, B, NoAttrs)); 2198 } 2199 } 2200 2201 // pow(10.0, x) -> exp10(x) 2202 if (BaseF->isExactlyValue(10.0) && 2203 hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) { 2204 2205 if (Pow->doesNotAccessMemory()) { 2206 CallInst *NewExp10 = 2207 B.CreateIntrinsic(Intrinsic::exp10, {Ty}, {Expo}, Pow, "exp10"); 2208 return copyFlags(*Pow, NewExp10); 2209 } 2210 2211 return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, 2212 LibFunc_exp10f, LibFunc_exp10l, 2213 B, NoAttrs)); 2214 } 2215 2216 // pow(x, y) -> exp2(log2(x) * y) 2217 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() && 2218 !BaseF->isNegative()) { 2219 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN. 2220 // Luckily optimizePow has already handled the x == 1 case. 2221 assert(!match(Base, m_FPOne()) && 2222 "pow(1.0, y) should have been simplified earlier!"); 2223 2224 Value *Log = nullptr; 2225 if (Ty->isFloatTy()) 2226 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat())); 2227 else if (Ty->isDoubleTy()) 2228 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble())); 2229 2230 if (Log) { 2231 Value *FMul = B.CreateFMul(Log, Expo, "mul"); 2232 if (Pow->doesNotAccessMemory()) 2233 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul, 2234 nullptr, "exp2")); 2235 else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, 2236 LibFunc_exp2l)) 2237 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 2238 LibFunc_exp2f, 2239 LibFunc_exp2l, B, NoAttrs)); 2240 } 2241 } 2242 2243 return nullptr; 2244 } 2245 2246 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, 2247 Module *M, IRBuilderBase &B, 2248 const TargetLibraryInfo *TLI) { 2249 // If errno is never set, then use the intrinsic for sqrt(). 2250 if (NoErrno) 2251 return B.CreateUnaryIntrinsic(Intrinsic::sqrt, V, nullptr, "sqrt"); 2252 2253 // Otherwise, use the libcall for sqrt(). 2254 if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, 2255 LibFunc_sqrtl)) 2256 // TODO: We also should check that the target can in fact lower the sqrt() 2257 // libcall. We currently have no way to ask this question, so we ask if 2258 // the target has a sqrt() libcall, which is not exactly the same. 2259 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf, 2260 LibFunc_sqrtl, B, Attrs); 2261 2262 return nullptr; 2263 } 2264 2265 /// Use square root in place of pow(x, +/-0.5). 2266 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) { 2267 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 2268 Module *Mod = Pow->getModule(); 2269 Type *Ty = Pow->getType(); 2270 2271 const APFloat *ExpoF; 2272 if (!match(Expo, m_APFloat(ExpoF)) || 2273 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 2274 return nullptr; 2275 2276 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step, 2277 // so that requires fast-math-flags (afn or reassoc). 2278 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc())) 2279 return nullptr; 2280 2281 // If we have a pow() library call (accesses memory) and we can't guarantee 2282 // that the base is not an infinity, give up: 2283 // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting 2284 // errno), but sqrt(-Inf) is required by various standards to set errno. 2285 if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() && 2286 !isKnownNeverInfinity( 2287 Base, 0, SimplifyQuery(DL, TLI, DT, AC, Pow, true, true, DC))) 2288 return nullptr; 2289 2290 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), Mod, B, 2291 TLI); 2292 if (!Sqrt) 2293 return nullptr; 2294 2295 // Handle signed zero base by expanding to fabs(sqrt(x)). 2296 if (!Pow->hasNoSignedZeros()) 2297 Sqrt = B.CreateUnaryIntrinsic(Intrinsic::fabs, Sqrt, nullptr, "abs"); 2298 2299 Sqrt = copyFlags(*Pow, Sqrt); 2300 2301 // Handle non finite base by expanding to 2302 // (x == -infinity ? +infinity : sqrt(x)). 2303 if (!Pow->hasNoInfs()) { 2304 Value *PosInf = ConstantFP::getInfinity(Ty), 2305 *NegInf = ConstantFP::getInfinity(Ty, true); 2306 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 2307 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 2308 } 2309 2310 // If the exponent is negative, then get the reciprocal. 2311 if (ExpoF->isNegative()) 2312 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 2313 2314 return Sqrt; 2315 } 2316 2317 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, 2318 IRBuilderBase &B) { 2319 Value *Args[] = {Base, Expo}; 2320 Type *Types[] = {Base->getType(), Expo->getType()}; 2321 return B.CreateIntrinsic(Intrinsic::powi, Types, Args); 2322 } 2323 2324 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) { 2325 Value *Base = Pow->getArgOperand(0); 2326 Value *Expo = Pow->getArgOperand(1); 2327 Function *Callee = Pow->getCalledFunction(); 2328 StringRef Name = Callee->getName(); 2329 Type *Ty = Pow->getType(); 2330 Module *M = Pow->getModule(); 2331 bool AllowApprox = Pow->hasApproxFunc(); 2332 bool Ignored; 2333 2334 // Propagate the math semantics from the call to any created instructions. 2335 IRBuilderBase::FastMathFlagGuard Guard(B); 2336 B.setFastMathFlags(Pow->getFastMathFlags()); 2337 // Evaluate special cases related to the base. 2338 2339 // pow(1.0, x) -> 1.0 2340 if (match(Base, m_FPOne())) 2341 return Base; 2342 2343 if (Value *Exp = replacePowWithExp(Pow, B)) 2344 return Exp; 2345 2346 // Evaluate special cases related to the exponent. 2347 2348 // pow(x, -1.0) -> 1.0 / x 2349 if (match(Expo, m_SpecificFP(-1.0))) 2350 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 2351 2352 // pow(x, +/-0.0) -> 1.0 2353 if (match(Expo, m_AnyZeroFP())) 2354 return ConstantFP::get(Ty, 1.0); 2355 2356 // pow(x, 1.0) -> x 2357 if (match(Expo, m_FPOne())) 2358 return Base; 2359 2360 // pow(x, 2.0) -> x * x 2361 if (match(Expo, m_SpecificFP(2.0))) 2362 return B.CreateFMul(Base, Base, "square"); 2363 2364 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 2365 return Sqrt; 2366 2367 // If we can approximate pow: 2368 // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction 2369 // pow(x, n) -> powi(x, n) if n is a constant signed integer value 2370 const APFloat *ExpoF; 2371 if (AllowApprox && match(Expo, m_APFloat(ExpoF)) && 2372 !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) { 2373 APFloat ExpoA(abs(*ExpoF)); 2374 APFloat ExpoI(*ExpoF); 2375 Value *Sqrt = nullptr; 2376 if (!ExpoA.isInteger()) { 2377 APFloat Expo2 = ExpoA; 2378 // To check if ExpoA is an integer + 0.5, we add it to itself. If there 2379 // is no floating point exception and the result is an integer, then 2380 // ExpoA == integer + 0.5 2381 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK) 2382 return nullptr; 2383 2384 if (!Expo2.isInteger()) 2385 return nullptr; 2386 2387 if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) != 2388 APFloat::opInexact) 2389 return nullptr; 2390 if (!ExpoI.isInteger()) 2391 return nullptr; 2392 ExpoF = &ExpoI; 2393 2394 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), M, 2395 B, TLI); 2396 if (!Sqrt) 2397 return nullptr; 2398 } 2399 2400 // 0.5 fraction is now optionally handled. 2401 // Do pow -> powi for remaining integer exponent 2402 APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false); 2403 if (ExpoF->isInteger() && 2404 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) == 2405 APFloat::opOK) { 2406 Value *PowI = copyFlags( 2407 *Pow, 2408 createPowWithIntegerExponent( 2409 Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo), 2410 M, B)); 2411 2412 if (PowI && Sqrt) 2413 return B.CreateFMul(PowI, Sqrt); 2414 2415 return PowI; 2416 } 2417 } 2418 2419 // powf(x, itofp(y)) -> powi(x, y) 2420 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) { 2421 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) 2422 return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B)); 2423 } 2424 2425 // Shrink pow() to powf() if the arguments are single precision, 2426 // unless the result is expected to be double precision. 2427 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) && 2428 hasFloatVersion(M, Name)) { 2429 if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true)) 2430 return Shrunk; 2431 } 2432 2433 return nullptr; 2434 } 2435 2436 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) { 2437 Module *M = CI->getModule(); 2438 Function *Callee = CI->getCalledFunction(); 2439 StringRef Name = Callee->getName(); 2440 Value *Ret = nullptr; 2441 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) && 2442 hasFloatVersion(M, Name)) 2443 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2444 2445 // If we have an llvm.exp2 intrinsic, emit the llvm.ldexp intrinsic. If we 2446 // have the libcall, emit the libcall. 2447 // 2448 // TODO: In principle we should be able to just always use the intrinsic for 2449 // any doesNotAccessMemory callsite. 2450 2451 const bool UseIntrinsic = Callee->isIntrinsic(); 2452 // Bail out for vectors because the code below only expects scalars. 2453 Type *Ty = CI->getType(); 2454 if (!UseIntrinsic && Ty->isVectorTy()) 2455 return Ret; 2456 2457 // exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize 2458 // exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize 2459 Value *Op = CI->getArgOperand(0); 2460 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) && 2461 (UseIntrinsic || 2462 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) { 2463 if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize())) { 2464 Constant *One = ConstantFP::get(Ty, 1.0); 2465 2466 if (UseIntrinsic) { 2467 return copyFlags(*CI, B.CreateIntrinsic(Intrinsic::ldexp, 2468 {Ty, Exp->getType()}, 2469 {One, Exp}, CI)); 2470 } 2471 2472 IRBuilderBase::FastMathFlagGuard Guard(B); 2473 B.setFastMathFlags(CI->getFastMathFlags()); 2474 return copyFlags(*CI, emitBinaryFloatFnCall( 2475 One, Exp, TLI, LibFunc_ldexp, LibFunc_ldexpf, 2476 LibFunc_ldexpl, B, AttributeList())); 2477 } 2478 } 2479 2480 return Ret; 2481 } 2482 2483 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) { 2484 Module *M = CI->getModule(); 2485 2486 // If we can shrink the call to a float function rather than a double 2487 // function, do that first. 2488 Function *Callee = CI->getCalledFunction(); 2489 StringRef Name = Callee->getName(); 2490 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(M, Name)) 2491 if (Value *Ret = optimizeBinaryDoubleFP(CI, B, TLI)) 2492 return Ret; 2493 2494 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to 2495 // the intrinsics for improved optimization (for example, vectorization). 2496 // No-signed-zeros is implied by the definitions of fmax/fmin themselves. 2497 // From the C standard draft WG14/N1256: 2498 // "Ideally, fmax would be sensitive to the sign of zero, for example 2499 // fmax(-0.0, +0.0) would return +0; however, implementation in software 2500 // might be impractical." 2501 IRBuilderBase::FastMathFlagGuard Guard(B); 2502 FastMathFlags FMF = CI->getFastMathFlags(); 2503 FMF.setNoSignedZeros(); 2504 B.setFastMathFlags(FMF); 2505 2506 Intrinsic::ID IID = Callee->getName().starts_with("fmin") ? Intrinsic::minnum 2507 : Intrinsic::maxnum; 2508 return copyFlags(*CI, B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0), 2509 CI->getArgOperand(1))); 2510 } 2511 2512 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) { 2513 Function *LogFn = Log->getCalledFunction(); 2514 StringRef LogNm = LogFn->getName(); 2515 Intrinsic::ID LogID = LogFn->getIntrinsicID(); 2516 Module *Mod = Log->getModule(); 2517 Type *Ty = Log->getType(); 2518 2519 if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm)) 2520 if (Value *Ret = optimizeUnaryDoubleFP(Log, B, TLI, true)) 2521 return Ret; 2522 2523 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb; 2524 2525 // This is only applicable to log(), log2(), log10(). 2526 if (TLI->getLibFunc(LogNm, LogLb)) { 2527 switch (LogLb) { 2528 case LibFunc_logf: 2529 LogID = Intrinsic::log; 2530 ExpLb = LibFunc_expf; 2531 Exp2Lb = LibFunc_exp2f; 2532 Exp10Lb = LibFunc_exp10f; 2533 PowLb = LibFunc_powf; 2534 break; 2535 case LibFunc_log: 2536 LogID = Intrinsic::log; 2537 ExpLb = LibFunc_exp; 2538 Exp2Lb = LibFunc_exp2; 2539 Exp10Lb = LibFunc_exp10; 2540 PowLb = LibFunc_pow; 2541 break; 2542 case LibFunc_logl: 2543 LogID = Intrinsic::log; 2544 ExpLb = LibFunc_expl; 2545 Exp2Lb = LibFunc_exp2l; 2546 Exp10Lb = LibFunc_exp10l; 2547 PowLb = LibFunc_powl; 2548 break; 2549 case LibFunc_log2f: 2550 LogID = Intrinsic::log2; 2551 ExpLb = LibFunc_expf; 2552 Exp2Lb = LibFunc_exp2f; 2553 Exp10Lb = LibFunc_exp10f; 2554 PowLb = LibFunc_powf; 2555 break; 2556 case LibFunc_log2: 2557 LogID = Intrinsic::log2; 2558 ExpLb = LibFunc_exp; 2559 Exp2Lb = LibFunc_exp2; 2560 Exp10Lb = LibFunc_exp10; 2561 PowLb = LibFunc_pow; 2562 break; 2563 case LibFunc_log2l: 2564 LogID = Intrinsic::log2; 2565 ExpLb = LibFunc_expl; 2566 Exp2Lb = LibFunc_exp2l; 2567 Exp10Lb = LibFunc_exp10l; 2568 PowLb = LibFunc_powl; 2569 break; 2570 case LibFunc_log10f: 2571 LogID = Intrinsic::log10; 2572 ExpLb = LibFunc_expf; 2573 Exp2Lb = LibFunc_exp2f; 2574 Exp10Lb = LibFunc_exp10f; 2575 PowLb = LibFunc_powf; 2576 break; 2577 case LibFunc_log10: 2578 LogID = Intrinsic::log10; 2579 ExpLb = LibFunc_exp; 2580 Exp2Lb = LibFunc_exp2; 2581 Exp10Lb = LibFunc_exp10; 2582 PowLb = LibFunc_pow; 2583 break; 2584 case LibFunc_log10l: 2585 LogID = Intrinsic::log10; 2586 ExpLb = LibFunc_expl; 2587 Exp2Lb = LibFunc_exp2l; 2588 Exp10Lb = LibFunc_exp10l; 2589 PowLb = LibFunc_powl; 2590 break; 2591 default: 2592 return nullptr; 2593 } 2594 2595 // Convert libcall to intrinsic if the value is known > 0. 2596 bool IsKnownNoErrno = Log->hasNoNaNs() && Log->hasNoInfs(); 2597 if (!IsKnownNoErrno) { 2598 SimplifyQuery SQ(DL, TLI, DT, AC, Log, true, true, DC); 2599 KnownFPClass Known = computeKnownFPClass( 2600 Log->getOperand(0), 2601 KnownFPClass::OrderedLessThanZeroMask | fcSubnormal, 2602 /*Depth=*/0, SQ); 2603 Function *F = Log->getParent()->getParent(); 2604 IsKnownNoErrno = Known.cannotBeOrderedLessThanZero() && 2605 Known.isKnownNeverLogicalZero(*F, Ty); 2606 } 2607 if (IsKnownNoErrno) { 2608 auto *NewLog = B.CreateUnaryIntrinsic(LogID, Log->getArgOperand(0), Log); 2609 NewLog->copyMetadata(*Log); 2610 return copyFlags(*Log, NewLog); 2611 } 2612 } else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 || 2613 LogID == Intrinsic::log10) { 2614 if (Ty->getScalarType()->isFloatTy()) { 2615 ExpLb = LibFunc_expf; 2616 Exp2Lb = LibFunc_exp2f; 2617 Exp10Lb = LibFunc_exp10f; 2618 PowLb = LibFunc_powf; 2619 } else if (Ty->getScalarType()->isDoubleTy()) { 2620 ExpLb = LibFunc_exp; 2621 Exp2Lb = LibFunc_exp2; 2622 Exp10Lb = LibFunc_exp10; 2623 PowLb = LibFunc_pow; 2624 } else 2625 return nullptr; 2626 } else 2627 return nullptr; 2628 2629 // The earlier call must also be 'fast' in order to do these transforms. 2630 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0)); 2631 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse()) 2632 return nullptr; 2633 2634 IRBuilderBase::FastMathFlagGuard Guard(B); 2635 B.setFastMathFlags(FastMathFlags::getFast()); 2636 2637 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 2638 LibFunc ArgLb = NotLibFunc; 2639 TLI->getLibFunc(*Arg, ArgLb); 2640 2641 // log(pow(x,y)) -> y*log(x) 2642 AttributeList NoAttrs; 2643 if (ArgLb == PowLb || ArgID == Intrinsic::pow || ArgID == Intrinsic::powi) { 2644 Value *LogX = 2645 Log->doesNotAccessMemory() 2646 ? B.CreateUnaryIntrinsic(LogID, Arg->getOperand(0), nullptr, "log") 2647 : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, NoAttrs); 2648 Value *Y = Arg->getArgOperand(1); 2649 // Cast exponent to FP if integer. 2650 if (ArgID == Intrinsic::powi) 2651 Y = B.CreateSIToFP(Y, Ty, "cast"); 2652 Value *MulY = B.CreateFMul(Y, LogX, "mul"); 2653 // Since pow() may have side effects, e.g. errno, 2654 // dead code elimination may not be trusted to remove it. 2655 substituteInParent(Arg, MulY); 2656 return MulY; 2657 } 2658 2659 // log(exp{,2,10}(y)) -> y*log({e,2,10}) 2660 // TODO: There is no exp10() intrinsic yet. 2661 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb || 2662 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) { 2663 Constant *Eul; 2664 if (ArgLb == ExpLb || ArgID == Intrinsic::exp) 2665 // FIXME: Add more precise value of e for long double. 2666 Eul = ConstantFP::get(Log->getType(), numbers::e); 2667 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2) 2668 Eul = ConstantFP::get(Log->getType(), 2.0); 2669 else 2670 Eul = ConstantFP::get(Log->getType(), 10.0); 2671 Value *LogE = Log->doesNotAccessMemory() 2672 ? B.CreateUnaryIntrinsic(LogID, Eul, nullptr, "log") 2673 : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, NoAttrs); 2674 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul"); 2675 // Since exp() may have side effects, e.g. errno, 2676 // dead code elimination may not be trusted to remove it. 2677 substituteInParent(Arg, MulY); 2678 return MulY; 2679 } 2680 2681 return nullptr; 2682 } 2683 2684 // sqrt(exp(X)) -> exp(X * 0.5) 2685 Value *LibCallSimplifier::mergeSqrtToExp(CallInst *CI, IRBuilderBase &B) { 2686 if (!CI->hasAllowReassoc()) 2687 return nullptr; 2688 2689 Function *SqrtFn = CI->getCalledFunction(); 2690 CallInst *Arg = dyn_cast<CallInst>(CI->getArgOperand(0)); 2691 if (!Arg || !Arg->hasAllowReassoc() || !Arg->hasOneUse()) 2692 return nullptr; 2693 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 2694 LibFunc ArgLb = NotLibFunc; 2695 TLI->getLibFunc(*Arg, ArgLb); 2696 2697 LibFunc SqrtLb, ExpLb, Exp2Lb, Exp10Lb; 2698 2699 if (TLI->getLibFunc(SqrtFn->getName(), SqrtLb)) 2700 switch (SqrtLb) { 2701 case LibFunc_sqrtf: 2702 ExpLb = LibFunc_expf; 2703 Exp2Lb = LibFunc_exp2f; 2704 Exp10Lb = LibFunc_exp10f; 2705 break; 2706 case LibFunc_sqrt: 2707 ExpLb = LibFunc_exp; 2708 Exp2Lb = LibFunc_exp2; 2709 Exp10Lb = LibFunc_exp10; 2710 break; 2711 case LibFunc_sqrtl: 2712 ExpLb = LibFunc_expl; 2713 Exp2Lb = LibFunc_exp2l; 2714 Exp10Lb = LibFunc_exp10l; 2715 break; 2716 default: 2717 return nullptr; 2718 } 2719 else if (SqrtFn->getIntrinsicID() == Intrinsic::sqrt) { 2720 if (CI->getType()->getScalarType()->isFloatTy()) { 2721 ExpLb = LibFunc_expf; 2722 Exp2Lb = LibFunc_exp2f; 2723 Exp10Lb = LibFunc_exp10f; 2724 } else if (CI->getType()->getScalarType()->isDoubleTy()) { 2725 ExpLb = LibFunc_exp; 2726 Exp2Lb = LibFunc_exp2; 2727 Exp10Lb = LibFunc_exp10; 2728 } else 2729 return nullptr; 2730 } else 2731 return nullptr; 2732 2733 if (ArgLb != ExpLb && ArgLb != Exp2Lb && ArgLb != Exp10Lb && 2734 ArgID != Intrinsic::exp && ArgID != Intrinsic::exp2) 2735 return nullptr; 2736 2737 IRBuilderBase::InsertPointGuard Guard(B); 2738 B.SetInsertPoint(Arg); 2739 auto *ExpOperand = Arg->getOperand(0); 2740 auto *FMul = 2741 B.CreateFMulFMF(ExpOperand, ConstantFP::get(ExpOperand->getType(), 0.5), 2742 CI, "merged.sqrt"); 2743 2744 Arg->setOperand(0, FMul); 2745 return Arg; 2746 } 2747 2748 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) { 2749 Module *M = CI->getModule(); 2750 Function *Callee = CI->getCalledFunction(); 2751 Value *Ret = nullptr; 2752 // TODO: Once we have a way (other than checking for the existince of the 2753 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 2754 // condition below. 2755 if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) && 2756 (Callee->getName() == "sqrt" || 2757 Callee->getIntrinsicID() == Intrinsic::sqrt)) 2758 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2759 2760 if (Value *Opt = mergeSqrtToExp(CI, B)) 2761 return Opt; 2762 2763 if (!CI->isFast()) 2764 return Ret; 2765 2766 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 2767 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 2768 return Ret; 2769 2770 // We're looking for a repeated factor in a multiplication tree, 2771 // so we can do this fold: sqrt(x * x) -> fabs(x); 2772 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 2773 Value *Op0 = I->getOperand(0); 2774 Value *Op1 = I->getOperand(1); 2775 Value *RepeatOp = nullptr; 2776 Value *OtherOp = nullptr; 2777 if (Op0 == Op1) { 2778 // Simple match: the operands of the multiply are identical. 2779 RepeatOp = Op0; 2780 } else { 2781 // Look for a more complicated pattern: one of the operands is itself 2782 // a multiply, so search for a common factor in that multiply. 2783 // Note: We don't bother looking any deeper than this first level or for 2784 // variations of this pattern because instcombine's visitFMUL and/or the 2785 // reassociation pass should give us this form. 2786 Value *MulOp; 2787 if (match(Op0, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) && 2788 cast<Instruction>(Op0)->isFast()) { 2789 // Pattern: sqrt((x * x) * z) 2790 RepeatOp = MulOp; 2791 OtherOp = Op1; 2792 } else if (match(Op1, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) && 2793 cast<Instruction>(Op1)->isFast()) { 2794 // Pattern: sqrt(z * (x * x)) 2795 RepeatOp = MulOp; 2796 OtherOp = Op0; 2797 } 2798 } 2799 if (!RepeatOp) 2800 return Ret; 2801 2802 // Fast math flags for any created instructions should match the sqrt 2803 // and multiply. 2804 IRBuilderBase::FastMathFlagGuard Guard(B); 2805 B.setFastMathFlags(I->getFastMathFlags()); 2806 2807 // If we found a repeated factor, hoist it out of the square root and 2808 // replace it with the fabs of that factor. 2809 Value *FabsCall = 2810 B.CreateUnaryIntrinsic(Intrinsic::fabs, RepeatOp, nullptr, "fabs"); 2811 if (OtherOp) { 2812 // If we found a non-repeated factor, we still need to get its square 2813 // root. We then multiply that by the value that was simplified out 2814 // of the square root calculation. 2815 Value *SqrtCall = 2816 B.CreateUnaryIntrinsic(Intrinsic::sqrt, OtherOp, nullptr, "sqrt"); 2817 return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall)); 2818 } 2819 return copyFlags(*CI, FabsCall); 2820 } 2821 2822 Value *LibCallSimplifier::optimizeFMod(CallInst *CI, IRBuilderBase &B) { 2823 2824 // fmod(x,y) can set errno if y == 0 or x == +/-inf, and returns Nan in those 2825 // case. If we know those do not happen, then we can convert the fmod into 2826 // frem. 2827 bool IsNoNan = CI->hasNoNaNs(); 2828 if (!IsNoNan) { 2829 SimplifyQuery SQ(DL, TLI, DT, AC, CI, true, true, DC); 2830 KnownFPClass Known0 = computeKnownFPClass(CI->getOperand(0), fcInf, 2831 /*Depth=*/0, SQ); 2832 if (Known0.isKnownNeverInfinity()) { 2833 KnownFPClass Known1 = 2834 computeKnownFPClass(CI->getOperand(1), fcZero | fcSubnormal, 2835 /*Depth=*/0, SQ); 2836 Function *F = CI->getParent()->getParent(); 2837 IsNoNan = Known1.isKnownNeverLogicalZero(*F, CI->getType()); 2838 } 2839 } 2840 2841 if (IsNoNan) { 2842 Value *FRem = B.CreateFRemFMF(CI->getOperand(0), CI->getOperand(1), CI); 2843 if (auto *FRemI = dyn_cast<Instruction>(FRem)) 2844 FRemI->setHasNoNaNs(true); 2845 return FRem; 2846 } 2847 return nullptr; 2848 } 2849 2850 Value *LibCallSimplifier::optimizeTrigInversionPairs(CallInst *CI, 2851 IRBuilderBase &B) { 2852 Module *M = CI->getModule(); 2853 Function *Callee = CI->getCalledFunction(); 2854 Value *Ret = nullptr; 2855 StringRef Name = Callee->getName(); 2856 if (UnsafeFPShrink && 2857 (Name == "tan" || Name == "atanh" || Name == "sinh" || Name == "cosh" || 2858 Name == "asinh") && 2859 hasFloatVersion(M, Name)) 2860 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2861 2862 Value *Op1 = CI->getArgOperand(0); 2863 auto *OpC = dyn_cast<CallInst>(Op1); 2864 if (!OpC) 2865 return Ret; 2866 2867 // Both calls must be 'fast' in order to remove them. 2868 if (!CI->isFast() || !OpC->isFast()) 2869 return Ret; 2870 2871 // tan(atan(x)) -> x 2872 // atanh(tanh(x)) -> x 2873 // sinh(asinh(x)) -> x 2874 // asinh(sinh(x)) -> x 2875 // cosh(acosh(x)) -> x 2876 LibFunc Func; 2877 Function *F = OpC->getCalledFunction(); 2878 if (F && TLI->getLibFunc(F->getName(), Func) && 2879 isLibFuncEmittable(M, TLI, Func)) { 2880 LibFunc inverseFunc = llvm::StringSwitch<LibFunc>(Callee->getName()) 2881 .Case("tan", LibFunc_atan) 2882 .Case("atanh", LibFunc_tanh) 2883 .Case("sinh", LibFunc_asinh) 2884 .Case("cosh", LibFunc_acosh) 2885 .Case("tanf", LibFunc_atanf) 2886 .Case("atanhf", LibFunc_tanhf) 2887 .Case("sinhf", LibFunc_asinhf) 2888 .Case("coshf", LibFunc_acoshf) 2889 .Case("tanl", LibFunc_atanl) 2890 .Case("atanhl", LibFunc_tanhl) 2891 .Case("sinhl", LibFunc_asinhl) 2892 .Case("coshl", LibFunc_acoshl) 2893 .Case("asinh", LibFunc_sinh) 2894 .Case("asinhf", LibFunc_sinhf) 2895 .Case("asinhl", LibFunc_sinhl) 2896 .Default(NumLibFuncs); // Used as error value 2897 if (Func == inverseFunc) 2898 Ret = OpC->getArgOperand(0); 2899 } 2900 return Ret; 2901 } 2902 2903 static bool isTrigLibCall(CallInst *CI) { 2904 // We can only hope to do anything useful if we can ignore things like errno 2905 // and floating-point exceptions. 2906 // We already checked the prototype. 2907 return CI->doesNotThrow() && CI->doesNotAccessMemory(); 2908 } 2909 2910 static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg, 2911 bool UseFloat, Value *&Sin, Value *&Cos, 2912 Value *&SinCos, const TargetLibraryInfo *TLI) { 2913 Module *M = OrigCallee->getParent(); 2914 Type *ArgTy = Arg->getType(); 2915 Type *ResTy; 2916 StringRef Name; 2917 2918 Triple T(OrigCallee->getParent()->getTargetTriple()); 2919 if (UseFloat) { 2920 Name = "__sincospif_stret"; 2921 2922 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 2923 // x86_64 can't use {float, float} since that would be returned in both 2924 // xmm0 and xmm1, which isn't what a real struct would do. 2925 ResTy = T.getArch() == Triple::x86_64 2926 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2)) 2927 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 2928 } else { 2929 Name = "__sincospi_stret"; 2930 ResTy = StructType::get(ArgTy, ArgTy); 2931 } 2932 2933 if (!isLibFuncEmittable(M, TLI, Name)) 2934 return false; 2935 LibFunc TheLibFunc; 2936 TLI->getLibFunc(Name, TheLibFunc); 2937 FunctionCallee Callee = getOrInsertLibFunc( 2938 M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy); 2939 2940 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 2941 // If the argument is an instruction, it must dominate all uses so put our 2942 // sincos call there. 2943 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 2944 } else { 2945 // Otherwise (e.g. for a constant) the beginning of the function is as 2946 // good a place as any. 2947 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 2948 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 2949 } 2950 2951 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 2952 2953 if (SinCos->getType()->isStructTy()) { 2954 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 2955 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 2956 } else { 2957 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 2958 "sinpi"); 2959 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 2960 "cospi"); 2961 } 2962 2963 return true; 2964 } 2965 2966 static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven, 2967 IRBuilderBase &B) { 2968 Value *X; 2969 Value *Src = CI->getArgOperand(0); 2970 2971 if (match(Src, m_OneUse(m_FNeg(m_Value(X))))) { 2972 IRBuilderBase::FastMathFlagGuard Guard(B); 2973 B.setFastMathFlags(CI->getFastMathFlags()); 2974 2975 auto *CallInst = copyFlags(*CI, B.CreateCall(CI->getCalledFunction(), {X})); 2976 if (IsEven) { 2977 // Even function: f(-x) = f(x) 2978 return CallInst; 2979 } 2980 // Odd function: f(-x) = -f(x) 2981 return B.CreateFNeg(CallInst); 2982 } 2983 2984 // Even function: f(abs(x)) = f(x), f(copysign(x, y)) = f(x) 2985 if (IsEven && (match(Src, m_FAbs(m_Value(X))) || 2986 match(Src, m_CopySign(m_Value(X), m_Value())))) { 2987 IRBuilderBase::FastMathFlagGuard Guard(B); 2988 B.setFastMathFlags(CI->getFastMathFlags()); 2989 2990 auto *CallInst = copyFlags(*CI, B.CreateCall(CI->getCalledFunction(), {X})); 2991 return CallInst; 2992 } 2993 2994 return nullptr; 2995 } 2996 2997 Value *LibCallSimplifier::optimizeSymmetric(CallInst *CI, LibFunc Func, 2998 IRBuilderBase &B) { 2999 switch (Func) { 3000 case LibFunc_cos: 3001 case LibFunc_cosf: 3002 case LibFunc_cosl: 3003 return optimizeSymmetricCall(CI, /*IsEven*/ true, B); 3004 3005 case LibFunc_sin: 3006 case LibFunc_sinf: 3007 case LibFunc_sinl: 3008 3009 case LibFunc_tan: 3010 case LibFunc_tanf: 3011 case LibFunc_tanl: 3012 3013 case LibFunc_erf: 3014 case LibFunc_erff: 3015 case LibFunc_erfl: 3016 return optimizeSymmetricCall(CI, /*IsEven*/ false, B); 3017 3018 default: 3019 return nullptr; 3020 } 3021 } 3022 3023 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, bool IsSin, IRBuilderBase &B) { 3024 // Make sure the prototype is as expected, otherwise the rest of the 3025 // function is probably invalid and likely to abort. 3026 if (!isTrigLibCall(CI)) 3027 return nullptr; 3028 3029 Value *Arg = CI->getArgOperand(0); 3030 SmallVector<CallInst *, 1> SinCalls; 3031 SmallVector<CallInst *, 1> CosCalls; 3032 SmallVector<CallInst *, 1> SinCosCalls; 3033 3034 bool IsFloat = Arg->getType()->isFloatTy(); 3035 3036 // Look for all compatible sinpi, cospi and sincospi calls with the same 3037 // argument. If there are enough (in some sense) we can make the 3038 // substitution. 3039 Function *F = CI->getFunction(); 3040 for (User *U : Arg->users()) 3041 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 3042 3043 // It's only worthwhile if both sinpi and cospi are actually used. 3044 if (SinCalls.empty() || CosCalls.empty()) 3045 return nullptr; 3046 3047 Value *Sin, *Cos, *SinCos; 3048 if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, 3049 SinCos, TLI)) 3050 return nullptr; 3051 3052 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 3053 Value *Res) { 3054 for (CallInst *C : Calls) 3055 replaceAllUsesWith(C, Res); 3056 }; 3057 3058 replaceTrigInsts(SinCalls, Sin); 3059 replaceTrigInsts(CosCalls, Cos); 3060 replaceTrigInsts(SinCosCalls, SinCos); 3061 3062 return IsSin ? Sin : Cos; 3063 } 3064 3065 void LibCallSimplifier::classifyArgUse( 3066 Value *Val, Function *F, bool IsFloat, 3067 SmallVectorImpl<CallInst *> &SinCalls, 3068 SmallVectorImpl<CallInst *> &CosCalls, 3069 SmallVectorImpl<CallInst *> &SinCosCalls) { 3070 auto *CI = dyn_cast<CallInst>(Val); 3071 if (!CI || CI->use_empty()) 3072 return; 3073 3074 // Don't consider calls in other functions. 3075 if (CI->getFunction() != F) 3076 return; 3077 3078 Module *M = CI->getModule(); 3079 Function *Callee = CI->getCalledFunction(); 3080 LibFunc Func; 3081 if (!Callee || !TLI->getLibFunc(*Callee, Func) || 3082 !isLibFuncEmittable(M, TLI, Func) || 3083 !isTrigLibCall(CI)) 3084 return; 3085 3086 if (IsFloat) { 3087 if (Func == LibFunc_sinpif) 3088 SinCalls.push_back(CI); 3089 else if (Func == LibFunc_cospif) 3090 CosCalls.push_back(CI); 3091 else if (Func == LibFunc_sincospif_stret) 3092 SinCosCalls.push_back(CI); 3093 } else { 3094 if (Func == LibFunc_sinpi) 3095 SinCalls.push_back(CI); 3096 else if (Func == LibFunc_cospi) 3097 CosCalls.push_back(CI); 3098 else if (Func == LibFunc_sincospi_stret) 3099 SinCosCalls.push_back(CI); 3100 } 3101 } 3102 3103 /// Constant folds remquo 3104 Value *LibCallSimplifier::optimizeRemquo(CallInst *CI, IRBuilderBase &B) { 3105 const APFloat *X, *Y; 3106 if (!match(CI->getArgOperand(0), m_APFloat(X)) || 3107 !match(CI->getArgOperand(1), m_APFloat(Y))) 3108 return nullptr; 3109 3110 APFloat::opStatus Status; 3111 APFloat Quot = *X; 3112 Status = Quot.divide(*Y, APFloat::rmNearestTiesToEven); 3113 if (Status != APFloat::opOK && Status != APFloat::opInexact) 3114 return nullptr; 3115 APFloat Rem = *X; 3116 if (Rem.remainder(*Y) != APFloat::opOK) 3117 return nullptr; 3118 3119 // TODO: We can only keep at least the three of the last bits of x/y 3120 unsigned IntBW = TLI->getIntSize(); 3121 APSInt QuotInt(IntBW, /*isUnsigned=*/false); 3122 bool IsExact; 3123 Status = 3124 Quot.convertToInteger(QuotInt, APFloat::rmNearestTiesToEven, &IsExact); 3125 if (Status != APFloat::opOK && Status != APFloat::opInexact) 3126 return nullptr; 3127 3128 B.CreateAlignedStore( 3129 ConstantInt::get(B.getIntNTy(IntBW), QuotInt.getExtValue()), 3130 CI->getArgOperand(2), CI->getParamAlign(2)); 3131 return ConstantFP::get(CI->getType(), Rem); 3132 } 3133 3134 /// Constant folds fdim 3135 Value *LibCallSimplifier::optimizeFdim(CallInst *CI, IRBuilderBase &B) { 3136 // Cannot perform the fold unless the call has attribute memory(none) 3137 if (!CI->doesNotAccessMemory()) 3138 return nullptr; 3139 3140 // TODO : Handle undef values 3141 // Propagate poison if any 3142 if (isa<PoisonValue>(CI->getArgOperand(0))) 3143 return CI->getArgOperand(0); 3144 if (isa<PoisonValue>(CI->getArgOperand(1))) 3145 return CI->getArgOperand(1); 3146 3147 const APFloat *X, *Y; 3148 // Check if both values are constants 3149 if (!match(CI->getArgOperand(0), m_APFloat(X)) || 3150 !match(CI->getArgOperand(1), m_APFloat(Y))) 3151 return nullptr; 3152 3153 APFloat Difference = *X; 3154 Difference.subtract(*Y, RoundingMode::NearestTiesToEven); 3155 3156 APFloat MaxVal = 3157 maximum(Difference, APFloat::getZero(CI->getType()->getFltSemantics())); 3158 return ConstantFP::get(CI->getType(), MaxVal); 3159 } 3160 3161 //===----------------------------------------------------------------------===// 3162 // Integer Library Call Optimizations 3163 //===----------------------------------------------------------------------===// 3164 3165 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) { 3166 // All variants of ffs return int which need not be 32 bits wide. 3167 // ffs{,l,ll}(x) -> x != 0 ? (int)llvm.cttz(x)+1 : 0 3168 Type *RetType = CI->getType(); 3169 Value *Op = CI->getArgOperand(0); 3170 Type *ArgType = Op->getType(); 3171 Value *V = B.CreateIntrinsic(Intrinsic::cttz, {ArgType}, {Op, B.getTrue()}, 3172 nullptr, "cttz"); 3173 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 3174 V = B.CreateIntCast(V, RetType, false); 3175 3176 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 3177 return B.CreateSelect(Cond, V, ConstantInt::get(RetType, 0)); 3178 } 3179 3180 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) { 3181 // All variants of fls return int which need not be 32 bits wide. 3182 // fls{,l,ll}(x) -> (int)(sizeInBits(x) - llvm.ctlz(x, false)) 3183 Value *Op = CI->getArgOperand(0); 3184 Type *ArgType = Op->getType(); 3185 Value *V = B.CreateIntrinsic(Intrinsic::ctlz, {ArgType}, {Op, B.getFalse()}, 3186 nullptr, "ctlz"); 3187 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 3188 V); 3189 return B.CreateIntCast(V, CI->getType(), false); 3190 } 3191 3192 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) { 3193 // abs(x) -> x <s 0 ? -x : x 3194 // The negation has 'nsw' because abs of INT_MIN is undefined. 3195 Value *X = CI->getArgOperand(0); 3196 Value *IsNeg = B.CreateIsNeg(X); 3197 Value *NegX = B.CreateNSWNeg(X, "neg"); 3198 return B.CreateSelect(IsNeg, NegX, X); 3199 } 3200 3201 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) { 3202 // isdigit(c) -> (c-'0') <u 10 3203 Value *Op = CI->getArgOperand(0); 3204 Type *ArgType = Op->getType(); 3205 Op = B.CreateSub(Op, ConstantInt::get(ArgType, '0'), "isdigittmp"); 3206 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 10), "isdigit"); 3207 return B.CreateZExt(Op, CI->getType()); 3208 } 3209 3210 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) { 3211 // isascii(c) -> c <u 128 3212 Value *Op = CI->getArgOperand(0); 3213 Type *ArgType = Op->getType(); 3214 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 128), "isascii"); 3215 return B.CreateZExt(Op, CI->getType()); 3216 } 3217 3218 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) { 3219 // toascii(c) -> c & 0x7f 3220 return B.CreateAnd(CI->getArgOperand(0), 3221 ConstantInt::get(CI->getType(), 0x7F)); 3222 } 3223 3224 // Fold calls to atoi, atol, and atoll. 3225 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) { 3226 CI->addParamAttr(0, Attribute::NoCapture); 3227 3228 StringRef Str; 3229 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 3230 return nullptr; 3231 3232 return convertStrToInt(CI, Str, nullptr, 10, /*AsSigned=*/true, B); 3233 } 3234 3235 // Fold calls to strtol, strtoll, strtoul, and strtoull. 3236 Value *LibCallSimplifier::optimizeStrToInt(CallInst *CI, IRBuilderBase &B, 3237 bool AsSigned) { 3238 Value *EndPtr = CI->getArgOperand(1); 3239 if (isa<ConstantPointerNull>(EndPtr)) { 3240 // With a null EndPtr, this function won't capture the main argument. 3241 // It would be readonly too, except that it still may write to errno. 3242 CI->addParamAttr(0, Attribute::NoCapture); 3243 EndPtr = nullptr; 3244 } else if (!isKnownNonZero(EndPtr, DL)) 3245 return nullptr; 3246 3247 StringRef Str; 3248 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 3249 return nullptr; 3250 3251 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) { 3252 return convertStrToInt(CI, Str, EndPtr, CInt->getSExtValue(), AsSigned, B); 3253 } 3254 3255 return nullptr; 3256 } 3257 3258 //===----------------------------------------------------------------------===// 3259 // Formatting and IO Library Call Optimizations 3260 //===----------------------------------------------------------------------===// 3261 3262 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 3263 3264 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B, 3265 int StreamArg) { 3266 Function *Callee = CI->getCalledFunction(); 3267 // Error reporting calls should be cold, mark them as such. 3268 // This applies even to non-builtin calls: it is only a hint and applies to 3269 // functions that the frontend might not understand as builtins. 3270 3271 // This heuristic was suggested in: 3272 // Improving Static Branch Prediction in a Compiler 3273 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 3274 // Proceedings of PACT'98, Oct. 1998, IEEE 3275 if (!CI->hasFnAttr(Attribute::Cold) && 3276 isReportingError(Callee, CI, StreamArg)) { 3277 CI->addFnAttr(Attribute::Cold); 3278 } 3279 3280 return nullptr; 3281 } 3282 3283 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 3284 if (!Callee || !Callee->isDeclaration()) 3285 return false; 3286 3287 if (StreamArg < 0) 3288 return true; 3289 3290 // These functions might be considered cold, but only if their stream 3291 // argument is stderr. 3292 3293 if (StreamArg >= (int)CI->arg_size()) 3294 return false; 3295 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 3296 if (!LI) 3297 return false; 3298 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 3299 if (!GV || !GV->isDeclaration()) 3300 return false; 3301 return GV->getName() == "stderr"; 3302 } 3303 3304 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) { 3305 // Check for a fixed format string. 3306 StringRef FormatStr; 3307 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 3308 return nullptr; 3309 3310 // Empty format string -> noop. 3311 if (FormatStr.empty()) // Tolerate printf's declared void. 3312 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 3313 3314 // Do not do any of the following transformations if the printf return value 3315 // is used, in general the printf return value is not compatible with either 3316 // putchar() or puts(). 3317 if (!CI->use_empty()) 3318 return nullptr; 3319 3320 Type *IntTy = CI->getType(); 3321 // printf("x") -> putchar('x'), even for "%" and "%%". 3322 if (FormatStr.size() == 1 || FormatStr == "%%") { 3323 // Convert the character to unsigned char before passing it to putchar 3324 // to avoid host-specific sign extension in the IR. Putchar converts 3325 // it to unsigned char regardless. 3326 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)FormatStr[0]); 3327 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3328 } 3329 3330 // Try to remove call or emit putchar/puts. 3331 if (FormatStr == "%s" && CI->arg_size() > 1) { 3332 StringRef OperandStr; 3333 if (!getConstantStringInfo(CI->getOperand(1), OperandStr)) 3334 return nullptr; 3335 // printf("%s", "") --> NOP 3336 if (OperandStr.empty()) 3337 return (Value *)CI; 3338 // printf("%s", "a") --> putchar('a') 3339 if (OperandStr.size() == 1) { 3340 // Convert the character to unsigned char before passing it to putchar 3341 // to avoid host-specific sign extension in the IR. Putchar converts 3342 // it to unsigned char regardless. 3343 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)OperandStr[0]); 3344 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3345 } 3346 // printf("%s", str"\n") --> puts(str) 3347 if (OperandStr.back() == '\n') { 3348 OperandStr = OperandStr.drop_back(); 3349 Value *GV = B.CreateGlobalString(OperandStr, "str"); 3350 return copyFlags(*CI, emitPutS(GV, B, TLI)); 3351 } 3352 return nullptr; 3353 } 3354 3355 // printf("foo\n") --> puts("foo") 3356 if (FormatStr.back() == '\n' && 3357 !FormatStr.contains('%')) { // No format characters. 3358 // Create a string literal with no \n on it. We expect the constant merge 3359 // pass to be run after this pass, to merge duplicate strings. 3360 FormatStr = FormatStr.drop_back(); 3361 Value *GV = B.CreateGlobalString(FormatStr, "str"); 3362 return copyFlags(*CI, emitPutS(GV, B, TLI)); 3363 } 3364 3365 // Optimize specific format strings. 3366 // printf("%c", chr) --> putchar(chr) 3367 if (FormatStr == "%c" && CI->arg_size() > 1 && 3368 CI->getArgOperand(1)->getType()->isIntegerTy()) { 3369 // Convert the argument to the type expected by putchar, i.e., int, which 3370 // need not be 32 bits wide but which is the same as printf's return type. 3371 Value *IntChar = B.CreateIntCast(CI->getArgOperand(1), IntTy, false); 3372 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3373 } 3374 3375 // printf("%s\n", str) --> puts(str) 3376 if (FormatStr == "%s\n" && CI->arg_size() > 1 && 3377 CI->getArgOperand(1)->getType()->isPointerTy()) 3378 return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI)); 3379 return nullptr; 3380 } 3381 3382 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) { 3383 3384 Module *M = CI->getModule(); 3385 Function *Callee = CI->getCalledFunction(); 3386 FunctionType *FT = Callee->getFunctionType(); 3387 if (Value *V = optimizePrintFString(CI, B)) { 3388 return V; 3389 } 3390 3391 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3392 3393 // printf(format, ...) -> iprintf(format, ...) if no floating point 3394 // arguments. 3395 if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) && 3396 !callHasFloatingPointArgument(CI)) { 3397 FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT, 3398 Callee->getAttributes()); 3399 CallInst *New = cast<CallInst>(CI->clone()); 3400 New->setCalledFunction(IPrintFFn); 3401 B.Insert(New); 3402 return New; 3403 } 3404 3405 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point 3406 // arguments. 3407 if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) && 3408 !callHasFP128Argument(CI)) { 3409 auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT, 3410 Callee->getAttributes()); 3411 CallInst *New = cast<CallInst>(CI->clone()); 3412 New->setCalledFunction(SmallPrintFFn); 3413 B.Insert(New); 3414 return New; 3415 } 3416 3417 return nullptr; 3418 } 3419 3420 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, 3421 IRBuilderBase &B) { 3422 // Check for a fixed format string. 3423 StringRef FormatStr; 3424 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 3425 return nullptr; 3426 3427 // If we just have a format string (nothing else crazy) transform it. 3428 Value *Dest = CI->getArgOperand(0); 3429 if (CI->arg_size() == 2) { 3430 // Make sure there's no % in the constant array. We could try to handle 3431 // %% -> % in the future if we cared. 3432 if (FormatStr.contains('%')) 3433 return nullptr; // we found a format specifier, bail out. 3434 3435 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1) 3436 B.CreateMemCpy( 3437 Dest, Align(1), CI->getArgOperand(1), Align(1), 3438 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 3439 FormatStr.size() + 1)); // Copy the null byte. 3440 return ConstantInt::get(CI->getType(), FormatStr.size()); 3441 } 3442 3443 // The remaining optimizations require the format string to be "%s" or "%c" 3444 // and have an extra operand. 3445 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 3446 return nullptr; 3447 3448 // Decode the second character of the format string. 3449 if (FormatStr[1] == 'c') { 3450 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 3451 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 3452 return nullptr; 3453 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 3454 Value *Ptr = Dest; 3455 B.CreateStore(V, Ptr); 3456 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 3457 B.CreateStore(B.getInt8(0), Ptr); 3458 3459 return ConstantInt::get(CI->getType(), 1); 3460 } 3461 3462 if (FormatStr[1] == 's') { 3463 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str, 3464 // strlen(str)+1) 3465 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 3466 return nullptr; 3467 3468 if (CI->use_empty()) 3469 // sprintf(dest, "%s", str) -> strcpy(dest, str) 3470 return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI)); 3471 3472 uint64_t SrcLen = GetStringLength(CI->getArgOperand(2)); 3473 if (SrcLen) { 3474 B.CreateMemCpy( 3475 Dest, Align(1), CI->getArgOperand(2), Align(1), 3476 ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen)); 3477 // Returns total number of characters written without null-character. 3478 return ConstantInt::get(CI->getType(), SrcLen - 1); 3479 } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) { 3480 // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest 3481 Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest); 3482 return B.CreateIntCast(PtrDiff, CI->getType(), false); 3483 } 3484 3485 bool OptForSize = CI->getFunction()->hasOptSize() || 3486 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 3487 PGSOQueryType::IRPass); 3488 if (OptForSize) 3489 return nullptr; 3490 3491 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 3492 if (!Len) 3493 return nullptr; 3494 Value *IncLen = 3495 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 3496 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen); 3497 3498 // The sprintf result is the unincremented number of bytes in the string. 3499 return B.CreateIntCast(Len, CI->getType(), false); 3500 } 3501 return nullptr; 3502 } 3503 3504 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) { 3505 Module *M = CI->getModule(); 3506 Function *Callee = CI->getCalledFunction(); 3507 FunctionType *FT = Callee->getFunctionType(); 3508 if (Value *V = optimizeSPrintFString(CI, B)) { 3509 return V; 3510 } 3511 3512 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 3513 3514 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 3515 // point arguments. 3516 if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) && 3517 !callHasFloatingPointArgument(CI)) { 3518 FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf, 3519 FT, Callee->getAttributes()); 3520 CallInst *New = cast<CallInst>(CI->clone()); 3521 New->setCalledFunction(SIPrintFFn); 3522 B.Insert(New); 3523 return New; 3524 } 3525 3526 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit 3527 // floating point arguments. 3528 if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) && 3529 !callHasFP128Argument(CI)) { 3530 auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT, 3531 Callee->getAttributes()); 3532 CallInst *New = cast<CallInst>(CI->clone()); 3533 New->setCalledFunction(SmallSPrintFFn); 3534 B.Insert(New); 3535 return New; 3536 } 3537 3538 return nullptr; 3539 } 3540 3541 // Transform an snprintf call CI with the bound N to format the string Str 3542 // either to a call to memcpy, or to single character a store, or to nothing, 3543 // and fold the result to a constant. A nonnull StrArg refers to the string 3544 // argument being formatted. Otherwise the call is one with N < 2 and 3545 // the "%c" directive to format a single character. 3546 Value *LibCallSimplifier::emitSnPrintfMemCpy(CallInst *CI, Value *StrArg, 3547 StringRef Str, uint64_t N, 3548 IRBuilderBase &B) { 3549 assert(StrArg || (N < 2 && Str.size() == 1)); 3550 3551 unsigned IntBits = TLI->getIntSize(); 3552 uint64_t IntMax = maxIntN(IntBits); 3553 if (Str.size() > IntMax) 3554 // Bail if the string is longer than INT_MAX. POSIX requires 3555 // implementations to set errno to EOVERFLOW in this case, in 3556 // addition to when N is larger than that (checked by the caller). 3557 return nullptr; 3558 3559 Value *StrLen = ConstantInt::get(CI->getType(), Str.size()); 3560 if (N == 0) 3561 return StrLen; 3562 3563 // Set to the number of bytes to copy fron StrArg which is also 3564 // the offset of the terinating nul. 3565 uint64_t NCopy; 3566 if (N > Str.size()) 3567 // Copy the full string, including the terminating nul (which must 3568 // be present regardless of the bound). 3569 NCopy = Str.size() + 1; 3570 else 3571 NCopy = N - 1; 3572 3573 Value *DstArg = CI->getArgOperand(0); 3574 if (NCopy && StrArg) 3575 // Transform the call to lvm.memcpy(dst, fmt, N). 3576 copyFlags( 3577 *CI, 3578 B.CreateMemCpy( 3579 DstArg, Align(1), StrArg, Align(1), 3580 ConstantInt::get(DL.getIntPtrType(CI->getContext()), NCopy))); 3581 3582 if (N > Str.size()) 3583 // Return early when the whole format string, including the final nul, 3584 // has been copied. 3585 return StrLen; 3586 3587 // Otherwise, when truncating the string append a terminating nul. 3588 Type *Int8Ty = B.getInt8Ty(); 3589 Value *NulOff = B.getIntN(IntBits, NCopy); 3590 Value *DstEnd = B.CreateInBoundsGEP(Int8Ty, DstArg, NulOff, "endptr"); 3591 B.CreateStore(ConstantInt::get(Int8Ty, 0), DstEnd); 3592 return StrLen; 3593 } 3594 3595 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, 3596 IRBuilderBase &B) { 3597 // Check for size 3598 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 3599 if (!Size) 3600 return nullptr; 3601 3602 uint64_t N = Size->getZExtValue(); 3603 uint64_t IntMax = maxIntN(TLI->getIntSize()); 3604 if (N > IntMax) 3605 // Bail if the bound exceeds INT_MAX. POSIX requires implementations 3606 // to set errno to EOVERFLOW in this case. 3607 return nullptr; 3608 3609 Value *DstArg = CI->getArgOperand(0); 3610 Value *FmtArg = CI->getArgOperand(2); 3611 3612 // Check for a fixed format string. 3613 StringRef FormatStr; 3614 if (!getConstantStringInfo(FmtArg, FormatStr)) 3615 return nullptr; 3616 3617 // If we just have a format string (nothing else crazy) transform it. 3618 if (CI->arg_size() == 3) { 3619 if (FormatStr.contains('%')) 3620 // Bail if the format string contains a directive and there are 3621 // no arguments. We could handle "%%" in the future. 3622 return nullptr; 3623 3624 return emitSnPrintfMemCpy(CI, FmtArg, FormatStr, N, B); 3625 } 3626 3627 // The remaining optimizations require the format string to be "%s" or "%c" 3628 // and have an extra operand. 3629 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() != 4) 3630 return nullptr; 3631 3632 // Decode the second character of the format string. 3633 if (FormatStr[1] == 'c') { 3634 if (N <= 1) { 3635 // Use an arbitary string of length 1 to transform the call into 3636 // either a nul store (N == 1) or a no-op (N == 0) and fold it 3637 // to one. 3638 StringRef CharStr("*"); 3639 return emitSnPrintfMemCpy(CI, nullptr, CharStr, N, B); 3640 } 3641 3642 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 3643 if (!CI->getArgOperand(3)->getType()->isIntegerTy()) 3644 return nullptr; 3645 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char"); 3646 Value *Ptr = DstArg; 3647 B.CreateStore(V, Ptr); 3648 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 3649 B.CreateStore(B.getInt8(0), Ptr); 3650 return ConstantInt::get(CI->getType(), 1); 3651 } 3652 3653 if (FormatStr[1] != 's') 3654 return nullptr; 3655 3656 Value *StrArg = CI->getArgOperand(3); 3657 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1) 3658 StringRef Str; 3659 if (!getConstantStringInfo(StrArg, Str)) 3660 return nullptr; 3661 3662 return emitSnPrintfMemCpy(CI, StrArg, Str, N, B); 3663 } 3664 3665 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) { 3666 if (Value *V = optimizeSnPrintFString(CI, B)) { 3667 return V; 3668 } 3669 3670 if (isKnownNonZero(CI->getOperand(1), DL)) 3671 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3672 return nullptr; 3673 } 3674 3675 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, 3676 IRBuilderBase &B) { 3677 optimizeErrorReporting(CI, B, 0); 3678 3679 // All the optimizations depend on the format string. 3680 StringRef FormatStr; 3681 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 3682 return nullptr; 3683 3684 // Do not do any of the following transformations if the fprintf return 3685 // value is used, in general the fprintf return value is not compatible 3686 // with fwrite(), fputc() or fputs(). 3687 if (!CI->use_empty()) 3688 return nullptr; 3689 3690 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 3691 if (CI->arg_size() == 2) { 3692 // Could handle %% -> % if we cared. 3693 if (FormatStr.contains('%')) 3694 return nullptr; // We found a format specifier. 3695 3696 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 3697 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 3698 return copyFlags( 3699 *CI, emitFWrite(CI->getArgOperand(1), 3700 ConstantInt::get(SizeTTy, FormatStr.size()), 3701 CI->getArgOperand(0), B, DL, TLI)); 3702 } 3703 3704 // The remaining optimizations require the format string to be "%s" or "%c" 3705 // and have an extra operand. 3706 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 3707 return nullptr; 3708 3709 // Decode the second character of the format string. 3710 if (FormatStr[1] == 'c') { 3711 // fprintf(F, "%c", chr) --> fputc((int)chr, F) 3712 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 3713 return nullptr; 3714 Type *IntTy = B.getIntNTy(TLI->getIntSize()); 3715 Value *V = B.CreateIntCast(CI->getArgOperand(2), IntTy, /*isSigned*/ true, 3716 "chari"); 3717 return copyFlags(*CI, emitFPutC(V, CI->getArgOperand(0), B, TLI)); 3718 } 3719 3720 if (FormatStr[1] == 's') { 3721 // fprintf(F, "%s", str) --> fputs(str, F) 3722 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 3723 return nullptr; 3724 return copyFlags( 3725 *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI)); 3726 } 3727 return nullptr; 3728 } 3729 3730 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) { 3731 Module *M = CI->getModule(); 3732 Function *Callee = CI->getCalledFunction(); 3733 FunctionType *FT = Callee->getFunctionType(); 3734 if (Value *V = optimizeFPrintFString(CI, B)) { 3735 return V; 3736 } 3737 3738 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 3739 // floating point arguments. 3740 if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) && 3741 !callHasFloatingPointArgument(CI)) { 3742 FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf, 3743 FT, Callee->getAttributes()); 3744 CallInst *New = cast<CallInst>(CI->clone()); 3745 New->setCalledFunction(FIPrintFFn); 3746 B.Insert(New); 3747 return New; 3748 } 3749 3750 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no 3751 // 128-bit floating point arguments. 3752 if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) && 3753 !callHasFP128Argument(CI)) { 3754 auto SmallFPrintFFn = 3755 getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT, 3756 Callee->getAttributes()); 3757 CallInst *New = cast<CallInst>(CI->clone()); 3758 New->setCalledFunction(SmallFPrintFFn); 3759 B.Insert(New); 3760 return New; 3761 } 3762 3763 return nullptr; 3764 } 3765 3766 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) { 3767 optimizeErrorReporting(CI, B, 3); 3768 3769 // Get the element size and count. 3770 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 3771 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 3772 if (SizeC && CountC) { 3773 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 3774 3775 // If this is writing zero records, remove the call (it's a noop). 3776 if (Bytes == 0) 3777 return ConstantInt::get(CI->getType(), 0); 3778 3779 // If this is writing one byte, turn it into fputc. 3780 // This optimisation is only valid, if the return value is unused. 3781 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 3782 Value *Char = B.CreateLoad(B.getInt8Ty(), CI->getArgOperand(0), "char"); 3783 Type *IntTy = B.getIntNTy(TLI->getIntSize()); 3784 Value *Cast = B.CreateIntCast(Char, IntTy, /*isSigned*/ true, "chari"); 3785 Value *NewCI = emitFPutC(Cast, CI->getArgOperand(3), B, TLI); 3786 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 3787 } 3788 } 3789 3790 return nullptr; 3791 } 3792 3793 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) { 3794 optimizeErrorReporting(CI, B, 1); 3795 3796 // Don't rewrite fputs to fwrite when optimising for size because fwrite 3797 // requires more arguments and thus extra MOVs are required. 3798 bool OptForSize = CI->getFunction()->hasOptSize() || 3799 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 3800 PGSOQueryType::IRPass); 3801 if (OptForSize) 3802 return nullptr; 3803 3804 // We can't optimize if return value is used. 3805 if (!CI->use_empty()) 3806 return nullptr; 3807 3808 // fputs(s,F) --> fwrite(s,strlen(s),1,F) 3809 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 3810 if (!Len) 3811 return nullptr; 3812 3813 // Known to have no uses (see above). 3814 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 3815 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 3816 return copyFlags( 3817 *CI, 3818 emitFWrite(CI->getArgOperand(0), 3819 ConstantInt::get(SizeTTy, Len - 1), 3820 CI->getArgOperand(1), B, DL, TLI)); 3821 } 3822 3823 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) { 3824 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3825 if (!CI->use_empty()) 3826 return nullptr; 3827 3828 // Check for a constant string. 3829 // puts("") -> putchar('\n') 3830 StringRef Str; 3831 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) { 3832 // putchar takes an argument of the same type as puts returns, i.e., 3833 // int, which need not be 32 bits wide. 3834 Type *IntTy = CI->getType(); 3835 return copyFlags(*CI, emitPutChar(ConstantInt::get(IntTy, '\n'), B, TLI)); 3836 } 3837 3838 return nullptr; 3839 } 3840 3841 Value *LibCallSimplifier::optimizeExit(CallInst *CI) { 3842 3843 // Mark 'exit' as cold if its not exit(0) (success). 3844 const APInt *C; 3845 if (!CI->hasFnAttr(Attribute::Cold) && 3846 match(CI->getArgOperand(0), m_APInt(C)) && !C->isZero()) { 3847 CI->addFnAttr(Attribute::Cold); 3848 } 3849 return nullptr; 3850 } 3851 3852 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) { 3853 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n) 3854 return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1), 3855 CI->getArgOperand(0), Align(1), 3856 CI->getArgOperand(2))); 3857 } 3858 3859 bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) { 3860 SmallString<20> FloatFuncName = FuncName; 3861 FloatFuncName += 'f'; 3862 return isLibFuncEmittable(M, TLI, FloatFuncName); 3863 } 3864 3865 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 3866 IRBuilderBase &Builder) { 3867 Module *M = CI->getModule(); 3868 LibFunc Func; 3869 Function *Callee = CI->getCalledFunction(); 3870 3871 // Check for string/memory library functions. 3872 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 3873 // Make sure we never change the calling convention. 3874 assert( 3875 (ignoreCallingConv(Func) || 3876 TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) && 3877 "Optimizing string/memory libcall would change the calling convention"); 3878 switch (Func) { 3879 case LibFunc_strcat: 3880 return optimizeStrCat(CI, Builder); 3881 case LibFunc_strncat: 3882 return optimizeStrNCat(CI, Builder); 3883 case LibFunc_strchr: 3884 return optimizeStrChr(CI, Builder); 3885 case LibFunc_strrchr: 3886 return optimizeStrRChr(CI, Builder); 3887 case LibFunc_strcmp: 3888 return optimizeStrCmp(CI, Builder); 3889 case LibFunc_strncmp: 3890 return optimizeStrNCmp(CI, Builder); 3891 case LibFunc_strcpy: 3892 return optimizeStrCpy(CI, Builder); 3893 case LibFunc_stpcpy: 3894 return optimizeStpCpy(CI, Builder); 3895 case LibFunc_strlcpy: 3896 return optimizeStrLCpy(CI, Builder); 3897 case LibFunc_stpncpy: 3898 return optimizeStringNCpy(CI, /*RetEnd=*/true, Builder); 3899 case LibFunc_strncpy: 3900 return optimizeStringNCpy(CI, /*RetEnd=*/false, Builder); 3901 case LibFunc_strlen: 3902 return optimizeStrLen(CI, Builder); 3903 case LibFunc_strnlen: 3904 return optimizeStrNLen(CI, Builder); 3905 case LibFunc_strpbrk: 3906 return optimizeStrPBrk(CI, Builder); 3907 case LibFunc_strndup: 3908 return optimizeStrNDup(CI, Builder); 3909 case LibFunc_strtol: 3910 case LibFunc_strtod: 3911 case LibFunc_strtof: 3912 case LibFunc_strtoul: 3913 case LibFunc_strtoll: 3914 case LibFunc_strtold: 3915 case LibFunc_strtoull: 3916 return optimizeStrTo(CI, Builder); 3917 case LibFunc_strspn: 3918 return optimizeStrSpn(CI, Builder); 3919 case LibFunc_strcspn: 3920 return optimizeStrCSpn(CI, Builder); 3921 case LibFunc_strstr: 3922 return optimizeStrStr(CI, Builder); 3923 case LibFunc_memchr: 3924 return optimizeMemChr(CI, Builder); 3925 case LibFunc_memrchr: 3926 return optimizeMemRChr(CI, Builder); 3927 case LibFunc_bcmp: 3928 return optimizeBCmp(CI, Builder); 3929 case LibFunc_memcmp: 3930 return optimizeMemCmp(CI, Builder); 3931 case LibFunc_memcpy: 3932 return optimizeMemCpy(CI, Builder); 3933 case LibFunc_memccpy: 3934 return optimizeMemCCpy(CI, Builder); 3935 case LibFunc_mempcpy: 3936 return optimizeMemPCpy(CI, Builder); 3937 case LibFunc_memmove: 3938 return optimizeMemMove(CI, Builder); 3939 case LibFunc_memset: 3940 return optimizeMemSet(CI, Builder); 3941 case LibFunc_realloc: 3942 return optimizeRealloc(CI, Builder); 3943 case LibFunc_wcslen: 3944 return optimizeWcslen(CI, Builder); 3945 case LibFunc_bcopy: 3946 return optimizeBCopy(CI, Builder); 3947 case LibFunc_Znwm: 3948 case LibFunc_ZnwmRKSt9nothrow_t: 3949 case LibFunc_ZnwmSt11align_val_t: 3950 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t: 3951 case LibFunc_Znam: 3952 case LibFunc_ZnamRKSt9nothrow_t: 3953 case LibFunc_ZnamSt11align_val_t: 3954 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t: 3955 case LibFunc_Znwm12__hot_cold_t: 3956 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t: 3957 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t: 3958 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 3959 case LibFunc_Znam12__hot_cold_t: 3960 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t: 3961 case LibFunc_ZnamSt11align_val_t12__hot_cold_t: 3962 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 3963 case LibFunc_size_returning_new: 3964 case LibFunc_size_returning_new_hot_cold: 3965 case LibFunc_size_returning_new_aligned: 3966 case LibFunc_size_returning_new_aligned_hot_cold: 3967 return optimizeNew(CI, Builder, Func); 3968 default: 3969 break; 3970 } 3971 } 3972 return nullptr; 3973 } 3974 3975 /// Constant folding nan/nanf/nanl. 3976 static Value *optimizeNaN(CallInst *CI) { 3977 StringRef CharSeq; 3978 if (!getConstantStringInfo(CI->getArgOperand(0), CharSeq)) 3979 return nullptr; 3980 3981 APInt Fill; 3982 // Treat empty strings as if they were zero. 3983 if (CharSeq.empty()) 3984 Fill = APInt(32, 0); 3985 else if (CharSeq.getAsInteger(0, Fill)) 3986 return nullptr; 3987 3988 return ConstantFP::getQNaN(CI->getType(), /*Negative=*/false, &Fill); 3989 } 3990 3991 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 3992 LibFunc Func, 3993 IRBuilderBase &Builder) { 3994 const Module *M = CI->getModule(); 3995 3996 // Don't optimize calls that require strict floating point semantics. 3997 if (CI->isStrictFP()) 3998 return nullptr; 3999 4000 if (Value *V = optimizeSymmetric(CI, Func, Builder)) 4001 return V; 4002 4003 switch (Func) { 4004 case LibFunc_sinpif: 4005 case LibFunc_sinpi: 4006 return optimizeSinCosPi(CI, /*IsSin*/true, Builder); 4007 case LibFunc_cospif: 4008 case LibFunc_cospi: 4009 return optimizeSinCosPi(CI, /*IsSin*/false, Builder); 4010 case LibFunc_powf: 4011 case LibFunc_pow: 4012 case LibFunc_powl: 4013 return optimizePow(CI, Builder); 4014 case LibFunc_exp2l: 4015 case LibFunc_exp2: 4016 case LibFunc_exp2f: 4017 return optimizeExp2(CI, Builder); 4018 case LibFunc_fabsf: 4019 case LibFunc_fabs: 4020 case LibFunc_fabsl: 4021 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 4022 case LibFunc_sqrtf: 4023 case LibFunc_sqrt: 4024 case LibFunc_sqrtl: 4025 return optimizeSqrt(CI, Builder); 4026 case LibFunc_fmod: 4027 case LibFunc_fmodf: 4028 case LibFunc_fmodl: 4029 return optimizeFMod(CI, Builder); 4030 case LibFunc_logf: 4031 case LibFunc_log: 4032 case LibFunc_logl: 4033 case LibFunc_log10f: 4034 case LibFunc_log10: 4035 case LibFunc_log10l: 4036 case LibFunc_log1pf: 4037 case LibFunc_log1p: 4038 case LibFunc_log1pl: 4039 case LibFunc_log2f: 4040 case LibFunc_log2: 4041 case LibFunc_log2l: 4042 case LibFunc_logbf: 4043 case LibFunc_logb: 4044 case LibFunc_logbl: 4045 return optimizeLog(CI, Builder); 4046 case LibFunc_tan: 4047 case LibFunc_tanf: 4048 case LibFunc_tanl: 4049 case LibFunc_sinh: 4050 case LibFunc_sinhf: 4051 case LibFunc_sinhl: 4052 case LibFunc_asinh: 4053 case LibFunc_asinhf: 4054 case LibFunc_asinhl: 4055 case LibFunc_cosh: 4056 case LibFunc_coshf: 4057 case LibFunc_coshl: 4058 case LibFunc_atanh: 4059 case LibFunc_atanhf: 4060 case LibFunc_atanhl: 4061 return optimizeTrigInversionPairs(CI, Builder); 4062 case LibFunc_ceil: 4063 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 4064 case LibFunc_floor: 4065 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 4066 case LibFunc_round: 4067 return replaceUnaryCall(CI, Builder, Intrinsic::round); 4068 case LibFunc_roundeven: 4069 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven); 4070 case LibFunc_nearbyint: 4071 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 4072 case LibFunc_rint: 4073 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 4074 case LibFunc_trunc: 4075 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 4076 case LibFunc_acos: 4077 case LibFunc_acosh: 4078 case LibFunc_asin: 4079 case LibFunc_atan: 4080 case LibFunc_cbrt: 4081 case LibFunc_exp: 4082 case LibFunc_exp10: 4083 case LibFunc_expm1: 4084 case LibFunc_cos: 4085 case LibFunc_sin: 4086 case LibFunc_tanh: 4087 if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName())) 4088 return optimizeUnaryDoubleFP(CI, Builder, TLI, true); 4089 return nullptr; 4090 case LibFunc_copysign: 4091 if (hasFloatVersion(M, CI->getCalledFunction()->getName())) 4092 return optimizeBinaryDoubleFP(CI, Builder, TLI); 4093 return nullptr; 4094 case LibFunc_fdim: 4095 case LibFunc_fdimf: 4096 case LibFunc_fdiml: 4097 return optimizeFdim(CI, Builder); 4098 case LibFunc_fminf: 4099 case LibFunc_fmin: 4100 case LibFunc_fminl: 4101 case LibFunc_fmaxf: 4102 case LibFunc_fmax: 4103 case LibFunc_fmaxl: 4104 return optimizeFMinFMax(CI, Builder); 4105 case LibFunc_cabs: 4106 case LibFunc_cabsf: 4107 case LibFunc_cabsl: 4108 return optimizeCAbs(CI, Builder); 4109 case LibFunc_remquo: 4110 case LibFunc_remquof: 4111 case LibFunc_remquol: 4112 return optimizeRemquo(CI, Builder); 4113 case LibFunc_nan: 4114 case LibFunc_nanf: 4115 case LibFunc_nanl: 4116 return optimizeNaN(CI); 4117 default: 4118 return nullptr; 4119 } 4120 } 4121 4122 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) { 4123 Module *M = CI->getModule(); 4124 assert(!CI->isMustTailCall() && "These transforms aren't musttail safe."); 4125 4126 // TODO: Split out the code below that operates on FP calls so that 4127 // we can all non-FP calls with the StrictFP attribute to be 4128 // optimized. 4129 if (CI->isNoBuiltin()) 4130 return nullptr; 4131 4132 LibFunc Func; 4133 Function *Callee = CI->getCalledFunction(); 4134 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 4135 4136 SmallVector<OperandBundleDef, 2> OpBundles; 4137 CI->getOperandBundlesAsDefs(OpBundles); 4138 4139 IRBuilderBase::OperandBundlesGuard Guard(Builder); 4140 Builder.setDefaultOperandBundles(OpBundles); 4141 4142 // Command-line parameter overrides instruction attribute. 4143 // This can't be moved to optimizeFloatingPointLibCall() because it may be 4144 // used by the intrinsic optimizations. 4145 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 4146 UnsafeFPShrink = EnableUnsafeFPShrink; 4147 else if (isa<FPMathOperator>(CI) && CI->isFast()) 4148 UnsafeFPShrink = true; 4149 4150 // First, check for intrinsics. 4151 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 4152 if (!IsCallingConvC) 4153 return nullptr; 4154 // The FP intrinsics have corresponding constrained versions so we don't 4155 // need to check for the StrictFP attribute here. 4156 switch (II->getIntrinsicID()) { 4157 case Intrinsic::pow: 4158 return optimizePow(CI, Builder); 4159 case Intrinsic::exp2: 4160 return optimizeExp2(CI, Builder); 4161 case Intrinsic::log: 4162 case Intrinsic::log2: 4163 case Intrinsic::log10: 4164 return optimizeLog(CI, Builder); 4165 case Intrinsic::sqrt: 4166 return optimizeSqrt(CI, Builder); 4167 case Intrinsic::memset: 4168 return optimizeMemSet(CI, Builder); 4169 case Intrinsic::memcpy: 4170 return optimizeMemCpy(CI, Builder); 4171 case Intrinsic::memmove: 4172 return optimizeMemMove(CI, Builder); 4173 default: 4174 return nullptr; 4175 } 4176 } 4177 4178 // Also try to simplify calls to fortified library functions. 4179 if (Value *SimplifiedFortifiedCI = 4180 FortifiedSimplifier.optimizeCall(CI, Builder)) 4181 return SimplifiedFortifiedCI; 4182 4183 // Then check for known library functions. 4184 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 4185 // We never change the calling convention. 4186 if (!ignoreCallingConv(Func) && !IsCallingConvC) 4187 return nullptr; 4188 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 4189 return V; 4190 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 4191 return V; 4192 switch (Func) { 4193 case LibFunc_ffs: 4194 case LibFunc_ffsl: 4195 case LibFunc_ffsll: 4196 return optimizeFFS(CI, Builder); 4197 case LibFunc_fls: 4198 case LibFunc_flsl: 4199 case LibFunc_flsll: 4200 return optimizeFls(CI, Builder); 4201 case LibFunc_abs: 4202 case LibFunc_labs: 4203 case LibFunc_llabs: 4204 return optimizeAbs(CI, Builder); 4205 case LibFunc_isdigit: 4206 return optimizeIsDigit(CI, Builder); 4207 case LibFunc_isascii: 4208 return optimizeIsAscii(CI, Builder); 4209 case LibFunc_toascii: 4210 return optimizeToAscii(CI, Builder); 4211 case LibFunc_atoi: 4212 case LibFunc_atol: 4213 case LibFunc_atoll: 4214 return optimizeAtoi(CI, Builder); 4215 case LibFunc_strtol: 4216 case LibFunc_strtoll: 4217 return optimizeStrToInt(CI, Builder, /*AsSigned=*/true); 4218 case LibFunc_strtoul: 4219 case LibFunc_strtoull: 4220 return optimizeStrToInt(CI, Builder, /*AsSigned=*/false); 4221 case LibFunc_printf: 4222 return optimizePrintF(CI, Builder); 4223 case LibFunc_sprintf: 4224 return optimizeSPrintF(CI, Builder); 4225 case LibFunc_snprintf: 4226 return optimizeSnPrintF(CI, Builder); 4227 case LibFunc_fprintf: 4228 return optimizeFPrintF(CI, Builder); 4229 case LibFunc_fwrite: 4230 return optimizeFWrite(CI, Builder); 4231 case LibFunc_fputs: 4232 return optimizeFPuts(CI, Builder); 4233 case LibFunc_puts: 4234 return optimizePuts(CI, Builder); 4235 case LibFunc_perror: 4236 return optimizeErrorReporting(CI, Builder); 4237 case LibFunc_vfprintf: 4238 case LibFunc_fiprintf: 4239 return optimizeErrorReporting(CI, Builder, 0); 4240 case LibFunc_exit: 4241 case LibFunc_Exit: 4242 return optimizeExit(CI); 4243 default: 4244 return nullptr; 4245 } 4246 } 4247 return nullptr; 4248 } 4249 4250 LibCallSimplifier::LibCallSimplifier( 4251 const DataLayout &DL, const TargetLibraryInfo *TLI, DominatorTree *DT, 4252 DomConditionCache *DC, AssumptionCache *AC, OptimizationRemarkEmitter &ORE, 4253 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 4254 function_ref<void(Instruction *, Value *)> Replacer, 4255 function_ref<void(Instruction *)> Eraser) 4256 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), DT(DT), DC(DC), AC(AC), 4257 ORE(ORE), BFI(BFI), PSI(PSI), Replacer(Replacer), Eraser(Eraser) {} 4258 4259 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 4260 // Indirect through the replacer used in this instance. 4261 Replacer(I, With); 4262 } 4263 4264 void LibCallSimplifier::eraseFromParent(Instruction *I) { 4265 Eraser(I); 4266 } 4267 4268 // TODO: 4269 // Additional cases that we need to add to this file: 4270 // 4271 // cbrt: 4272 // * cbrt(expN(X)) -> expN(x/3) 4273 // * cbrt(sqrt(x)) -> pow(x,1/6) 4274 // * cbrt(cbrt(x)) -> pow(x,1/9) 4275 // 4276 // exp, expf, expl: 4277 // * exp(log(x)) -> x 4278 // 4279 // log, logf, logl: 4280 // * log(exp(x)) -> x 4281 // * log(exp(y)) -> y*log(e) 4282 // * log(exp10(y)) -> y*log(10) 4283 // * log(sqrt(x)) -> 0.5*log(x) 4284 // 4285 // pow, powf, powl: 4286 // * pow(sqrt(x),y) -> pow(x,y*0.5) 4287 // * pow(pow(x,y),z)-> pow(x,y*z) 4288 // 4289 // signbit: 4290 // * signbit(cnst) -> cnst' 4291 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 4292 // 4293 // sqrt, sqrtf, sqrtl: 4294 // * sqrt(expN(x)) -> expN(x*0.5) 4295 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 4296 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 4297 // 4298 4299 //===----------------------------------------------------------------------===// 4300 // Fortified Library Call Optimizations 4301 //===----------------------------------------------------------------------===// 4302 4303 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable( 4304 CallInst *CI, unsigned ObjSizeOp, std::optional<unsigned> SizeOp, 4305 std::optional<unsigned> StrOp, std::optional<unsigned> FlagOp) { 4306 // If this function takes a flag argument, the implementation may use it to 4307 // perform extra checks. Don't fold into the non-checking variant. 4308 if (FlagOp) { 4309 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp)); 4310 if (!Flag || !Flag->isZero()) 4311 return false; 4312 } 4313 4314 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp)) 4315 return true; 4316 4317 if (ConstantInt *ObjSizeCI = 4318 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 4319 if (ObjSizeCI->isMinusOne()) 4320 return true; 4321 // If the object size wasn't -1 (unknown), bail out if we were asked to. 4322 if (OnlyLowerUnknownSize) 4323 return false; 4324 if (StrOp) { 4325 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp)); 4326 // If the length is 0 we don't know how long it is and so we can't 4327 // remove the check. 4328 if (Len) 4329 annotateDereferenceableBytes(CI, *StrOp, Len); 4330 else 4331 return false; 4332 return ObjSizeCI->getZExtValue() >= Len; 4333 } 4334 4335 if (SizeOp) { 4336 if (ConstantInt *SizeCI = 4337 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp))) 4338 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 4339 } 4340 } 4341 return false; 4342 } 4343 4344 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 4345 IRBuilderBase &B) { 4346 if (isFortifiedCallFoldable(CI, 3, 2)) { 4347 CallInst *NewCI = 4348 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 4349 Align(1), CI->getArgOperand(2)); 4350 mergeAttributesAndFlags(NewCI, *CI); 4351 return CI->getArgOperand(0); 4352 } 4353 return nullptr; 4354 } 4355 4356 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 4357 IRBuilderBase &B) { 4358 if (isFortifiedCallFoldable(CI, 3, 2)) { 4359 CallInst *NewCI = 4360 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 4361 Align(1), CI->getArgOperand(2)); 4362 mergeAttributesAndFlags(NewCI, *CI); 4363 return CI->getArgOperand(0); 4364 } 4365 return nullptr; 4366 } 4367 4368 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 4369 IRBuilderBase &B) { 4370 if (isFortifiedCallFoldable(CI, 3, 2)) { 4371 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 4372 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, 4373 CI->getArgOperand(2), Align(1)); 4374 mergeAttributesAndFlags(NewCI, *CI); 4375 return CI->getArgOperand(0); 4376 } 4377 return nullptr; 4378 } 4379 4380 Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI, 4381 IRBuilderBase &B) { 4382 const DataLayout &DL = CI->getDataLayout(); 4383 if (isFortifiedCallFoldable(CI, 3, 2)) 4384 if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4385 CI->getArgOperand(2), B, DL, TLI)) { 4386 return mergeAttributesAndFlags(cast<CallInst>(Call), *CI); 4387 } 4388 return nullptr; 4389 } 4390 4391 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 4392 IRBuilderBase &B, 4393 LibFunc Func) { 4394 const DataLayout &DL = CI->getDataLayout(); 4395 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 4396 *ObjSize = CI->getArgOperand(2); 4397 4398 // __stpcpy_chk(x,x,...) -> x+strlen(x) 4399 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 4400 Value *StrLen = emitStrLen(Src, B, DL, TLI); 4401 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 4402 } 4403 4404 // If a) we don't have any length information, or b) we know this will 4405 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 4406 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 4407 // TODO: It might be nice to get a maximum length out of the possible 4408 // string lengths for varying. 4409 if (isFortifiedCallFoldable(CI, 2, std::nullopt, 1)) { 4410 if (Func == LibFunc_strcpy_chk) 4411 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI)); 4412 else 4413 return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI)); 4414 } 4415 4416 if (OnlyLowerUnknownSize) 4417 return nullptr; 4418 4419 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 4420 uint64_t Len = GetStringLength(Src); 4421 if (Len) 4422 annotateDereferenceableBytes(CI, 1, Len); 4423 else 4424 return nullptr; 4425 4426 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 4427 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 4428 Value *LenV = ConstantInt::get(SizeTTy, Len); 4429 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 4430 // If the function was an __stpcpy_chk, and we were able to fold it into 4431 // a __memcpy_chk, we still need to return the correct end pointer. 4432 if (Ret && Func == LibFunc_stpcpy_chk) 4433 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, 4434 ConstantInt::get(SizeTTy, Len - 1)); 4435 return copyFlags(*CI, cast<CallInst>(Ret)); 4436 } 4437 4438 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI, 4439 IRBuilderBase &B) { 4440 if (isFortifiedCallFoldable(CI, 1, std::nullopt, 0)) 4441 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, 4442 CI->getDataLayout(), TLI)); 4443 return nullptr; 4444 } 4445 4446 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 4447 IRBuilderBase &B, 4448 LibFunc Func) { 4449 if (isFortifiedCallFoldable(CI, 3, 2)) { 4450 if (Func == LibFunc_strncpy_chk) 4451 return copyFlags(*CI, 4452 emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4453 CI->getArgOperand(2), B, TLI)); 4454 else 4455 return copyFlags(*CI, 4456 emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4457 CI->getArgOperand(2), B, TLI)); 4458 } 4459 4460 return nullptr; 4461 } 4462 4463 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI, 4464 IRBuilderBase &B) { 4465 if (isFortifiedCallFoldable(CI, 4, 3)) 4466 return copyFlags( 4467 *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4468 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI)); 4469 4470 return nullptr; 4471 } 4472 4473 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI, 4474 IRBuilderBase &B) { 4475 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) { 4476 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5)); 4477 return copyFlags(*CI, 4478 emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 4479 CI->getArgOperand(4), VariadicArgs, B, TLI)); 4480 } 4481 4482 return nullptr; 4483 } 4484 4485 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI, 4486 IRBuilderBase &B) { 4487 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) { 4488 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4)); 4489 return copyFlags(*CI, 4490 emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 4491 VariadicArgs, B, TLI)); 4492 } 4493 4494 return nullptr; 4495 } 4496 4497 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI, 4498 IRBuilderBase &B) { 4499 if (isFortifiedCallFoldable(CI, 2)) 4500 return copyFlags( 4501 *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI)); 4502 4503 return nullptr; 4504 } 4505 4506 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI, 4507 IRBuilderBase &B) { 4508 if (isFortifiedCallFoldable(CI, 3)) 4509 return copyFlags(*CI, 4510 emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1), 4511 CI->getArgOperand(2), B, TLI)); 4512 4513 return nullptr; 4514 } 4515 4516 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI, 4517 IRBuilderBase &B) { 4518 if (isFortifiedCallFoldable(CI, 3)) 4519 return copyFlags(*CI, 4520 emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1), 4521 CI->getArgOperand(2), B, TLI)); 4522 4523 return nullptr; 4524 } 4525 4526 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI, 4527 IRBuilderBase &B) { 4528 if (isFortifiedCallFoldable(CI, 3)) 4529 return copyFlags(*CI, 4530 emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4531 CI->getArgOperand(2), B, TLI)); 4532 4533 return nullptr; 4534 } 4535 4536 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI, 4537 IRBuilderBase &B) { 4538 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) 4539 return copyFlags( 4540 *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 4541 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI)); 4542 4543 return nullptr; 4544 } 4545 4546 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI, 4547 IRBuilderBase &B) { 4548 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) 4549 return copyFlags(*CI, 4550 emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 4551 CI->getArgOperand(4), B, TLI)); 4552 4553 return nullptr; 4554 } 4555 4556 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI, 4557 IRBuilderBase &Builder) { 4558 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 4559 // Some clang users checked for _chk libcall availability using: 4560 // __has_builtin(__builtin___memcpy_chk) 4561 // When compiling with -fno-builtin, this is always true. 4562 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 4563 // end up with fortified libcalls, which isn't acceptable in a freestanding 4564 // environment which only provides their non-fortified counterparts. 4565 // 4566 // Until we change clang and/or teach external users to check for availability 4567 // differently, disregard the "nobuiltin" attribute and TLI::has. 4568 // 4569 // PR23093. 4570 4571 LibFunc Func; 4572 Function *Callee = CI->getCalledFunction(); 4573 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 4574 4575 SmallVector<OperandBundleDef, 2> OpBundles; 4576 CI->getOperandBundlesAsDefs(OpBundles); 4577 4578 IRBuilderBase::OperandBundlesGuard Guard(Builder); 4579 Builder.setDefaultOperandBundles(OpBundles); 4580 4581 // First, check that this is a known library functions and that the prototype 4582 // is correct. 4583 if (!TLI->getLibFunc(*Callee, Func)) 4584 return nullptr; 4585 4586 // We never change the calling convention. 4587 if (!ignoreCallingConv(Func) && !IsCallingConvC) 4588 return nullptr; 4589 4590 switch (Func) { 4591 case LibFunc_memcpy_chk: 4592 return optimizeMemCpyChk(CI, Builder); 4593 case LibFunc_mempcpy_chk: 4594 return optimizeMemPCpyChk(CI, Builder); 4595 case LibFunc_memmove_chk: 4596 return optimizeMemMoveChk(CI, Builder); 4597 case LibFunc_memset_chk: 4598 return optimizeMemSetChk(CI, Builder); 4599 case LibFunc_stpcpy_chk: 4600 case LibFunc_strcpy_chk: 4601 return optimizeStrpCpyChk(CI, Builder, Func); 4602 case LibFunc_strlen_chk: 4603 return optimizeStrLenChk(CI, Builder); 4604 case LibFunc_stpncpy_chk: 4605 case LibFunc_strncpy_chk: 4606 return optimizeStrpNCpyChk(CI, Builder, Func); 4607 case LibFunc_memccpy_chk: 4608 return optimizeMemCCpyChk(CI, Builder); 4609 case LibFunc_snprintf_chk: 4610 return optimizeSNPrintfChk(CI, Builder); 4611 case LibFunc_sprintf_chk: 4612 return optimizeSPrintfChk(CI, Builder); 4613 case LibFunc_strcat_chk: 4614 return optimizeStrCatChk(CI, Builder); 4615 case LibFunc_strlcat_chk: 4616 return optimizeStrLCat(CI, Builder); 4617 case LibFunc_strncat_chk: 4618 return optimizeStrNCatChk(CI, Builder); 4619 case LibFunc_strlcpy_chk: 4620 return optimizeStrLCpyChk(CI, Builder); 4621 case LibFunc_vsnprintf_chk: 4622 return optimizeVSNPrintfChk(CI, Builder); 4623 case LibFunc_vsprintf_chk: 4624 return optimizeVSPrintfChk(CI, Builder); 4625 default: 4626 break; 4627 } 4628 return nullptr; 4629 } 4630 4631 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 4632 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 4633 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 4634