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( 921 SrcStr, "str", /*AddressSpace=*/DL.getDefaultGlobalsAddressSpace(), 922 /*M=*/nullptr, /*AddNull=*/false); 923 } 924 925 Type *PT = Callee->getFunctionType()->getParamType(0); 926 // st{p,r}ncpy(D, S, N) -> memcpy(align 1 D, align 1 S, N) when both 927 // S and N are constant. 928 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), 929 ConstantInt::get(DL.getIntPtrType(PT), N)); 930 mergeAttributesAndFlags(NewCI, *CI); 931 if (!RetEnd) 932 return Dst; 933 934 // stpncpy(D, S, N) returns the address of the first null in D if it writes 935 // one, otherwise D + N. 936 Value *Off = B.getInt64(std::min(SrcLen, N)); 937 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, Off, "endptr"); 938 } 939 940 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B, 941 unsigned CharSize, 942 Value *Bound) { 943 Value *Src = CI->getArgOperand(0); 944 Type *CharTy = B.getIntNTy(CharSize); 945 946 if (isOnlyUsedInZeroEqualityComparison(CI) && 947 (!Bound || isKnownNonZero(Bound, DL))) { 948 // Fold strlen: 949 // strlen(x) != 0 --> *x != 0 950 // strlen(x) == 0 --> *x == 0 951 // and likewise strnlen with constant N > 0: 952 // strnlen(x, N) != 0 --> *x != 0 953 // strnlen(x, N) == 0 --> *x == 0 954 return B.CreateZExt(B.CreateLoad(CharTy, Src, "char0"), 955 CI->getType()); 956 } 957 958 if (Bound) { 959 if (ConstantInt *BoundCst = dyn_cast<ConstantInt>(Bound)) { 960 if (BoundCst->isZero()) 961 // Fold strnlen(s, 0) -> 0 for any s, constant or otherwise. 962 return ConstantInt::get(CI->getType(), 0); 963 964 if (BoundCst->isOne()) { 965 // Fold strnlen(s, 1) -> *s ? 1 : 0 for any s. 966 Value *CharVal = B.CreateLoad(CharTy, Src, "strnlen.char0"); 967 Value *ZeroChar = ConstantInt::get(CharTy, 0); 968 Value *Cmp = B.CreateICmpNE(CharVal, ZeroChar, "strnlen.char0cmp"); 969 return B.CreateZExt(Cmp, CI->getType()); 970 } 971 } 972 } 973 974 if (uint64_t Len = GetStringLength(Src, CharSize)) { 975 Value *LenC = ConstantInt::get(CI->getType(), Len - 1); 976 // Fold strlen("xyz") -> 3 and strnlen("xyz", 2) -> 2 977 // and strnlen("xyz", Bound) -> min(3, Bound) for nonconstant Bound. 978 if (Bound) 979 return B.CreateBinaryIntrinsic(Intrinsic::umin, LenC, Bound); 980 return LenC; 981 } 982 983 if (Bound) 984 // Punt for strnlen for now. 985 return nullptr; 986 987 // If s is a constant pointer pointing to a string literal, we can fold 988 // strlen(s + x) to strlen(s) - x, when x is known to be in the range 989 // [0, strlen(s)] or the string has a single null terminator '\0' at the end. 990 // We only try to simplify strlen when the pointer s points to an array 991 // of CharSize elements. Otherwise, we would need to scale the offset x before 992 // doing the subtraction. This will make the optimization more complex, and 993 // it's not very useful because calling strlen for a pointer of other types is 994 // very uncommon. 995 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) { 996 // TODO: Handle subobjects. 997 if (!isGEPBasedOnPointerToString(GEP, CharSize)) 998 return nullptr; 999 1000 ConstantDataArraySlice Slice; 1001 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) { 1002 uint64_t NullTermIdx; 1003 if (Slice.Array == nullptr) { 1004 NullTermIdx = 0; 1005 } else { 1006 NullTermIdx = ~((uint64_t)0); 1007 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) { 1008 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) { 1009 NullTermIdx = I; 1010 break; 1011 } 1012 } 1013 // If the string does not have '\0', leave it to strlen to compute 1014 // its length. 1015 if (NullTermIdx == ~((uint64_t)0)) 1016 return nullptr; 1017 } 1018 1019 Value *Offset = GEP->getOperand(2); 1020 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr); 1021 uint64_t ArrSize = 1022 cast<ArrayType>(GEP->getSourceElementType())->getNumElements(); 1023 1024 // If Offset is not provably in the range [0, NullTermIdx], we can still 1025 // optimize if we can prove that the program has undefined behavior when 1026 // Offset is outside that range. That is the case when GEP->getOperand(0) 1027 // is a pointer to an object whose memory extent is NullTermIdx+1. 1028 if ((Known.isNonNegative() && Known.getMaxValue().ule(NullTermIdx)) || 1029 (isa<GlobalVariable>(GEP->getOperand(0)) && 1030 NullTermIdx == ArrSize - 1)) { 1031 Offset = B.CreateSExtOrTrunc(Offset, CI->getType()); 1032 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx), 1033 Offset); 1034 } 1035 } 1036 } 1037 1038 // strlen(x?"foo":"bars") --> x ? 3 : 4 1039 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) { 1040 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize); 1041 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize); 1042 if (LenTrue && LenFalse) { 1043 ORE.emit([&]() { 1044 return OptimizationRemark("instcombine", "simplify-libcalls", CI) 1045 << "folded strlen(select) to select of constants"; 1046 }); 1047 return B.CreateSelect(SI->getCondition(), 1048 ConstantInt::get(CI->getType(), LenTrue - 1), 1049 ConstantInt::get(CI->getType(), LenFalse - 1)); 1050 } 1051 } 1052 1053 return nullptr; 1054 } 1055 1056 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) { 1057 if (Value *V = optimizeStringLength(CI, B, 8)) 1058 return V; 1059 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1060 return nullptr; 1061 } 1062 1063 Value *LibCallSimplifier::optimizeStrNLen(CallInst *CI, IRBuilderBase &B) { 1064 Value *Bound = CI->getArgOperand(1); 1065 if (Value *V = optimizeStringLength(CI, B, 8, Bound)) 1066 return V; 1067 1068 if (isKnownNonZero(Bound, DL)) 1069 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1070 return nullptr; 1071 } 1072 1073 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) { 1074 Module &M = *CI->getModule(); 1075 unsigned WCharSize = TLI->getWCharSize(M) * 8; 1076 // We cannot perform this optimization without wchar_size metadata. 1077 if (WCharSize == 0) 1078 return nullptr; 1079 1080 return optimizeStringLength(CI, B, WCharSize); 1081 } 1082 1083 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) { 1084 StringRef S1, S2; 1085 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1086 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1087 1088 // strpbrk(s, "") -> nullptr 1089 // strpbrk("", s) -> nullptr 1090 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 1091 return Constant::getNullValue(CI->getType()); 1092 1093 // Constant folding. 1094 if (HasS1 && HasS2) { 1095 size_t I = S1.find_first_of(S2); 1096 if (I == StringRef::npos) // No match. 1097 return Constant::getNullValue(CI->getType()); 1098 1099 return B.CreateInBoundsGEP(B.getInt8Ty(), CI->getArgOperand(0), 1100 B.getInt64(I), "strpbrk"); 1101 } 1102 1103 // strpbrk(s, "a") -> strchr(s, 'a') 1104 if (HasS2 && S2.size() == 1) 1105 return copyFlags(*CI, emitStrChr(CI->getArgOperand(0), S2[0], B, TLI)); 1106 1107 return nullptr; 1108 } 1109 1110 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) { 1111 Value *EndPtr = CI->getArgOperand(1); 1112 if (isa<ConstantPointerNull>(EndPtr)) { 1113 // With a null EndPtr, this function won't capture the main argument. 1114 // It would be readonly too, except that it still may write to errno. 1115 CI->addParamAttr(0, Attribute::NoCapture); 1116 } 1117 1118 return nullptr; 1119 } 1120 1121 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) { 1122 StringRef S1, S2; 1123 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1124 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1125 1126 // strspn(s, "") -> 0 1127 // strspn("", s) -> 0 1128 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 1129 return Constant::getNullValue(CI->getType()); 1130 1131 // Constant folding. 1132 if (HasS1 && HasS2) { 1133 size_t Pos = S1.find_first_not_of(S2); 1134 if (Pos == StringRef::npos) 1135 Pos = S1.size(); 1136 return ConstantInt::get(CI->getType(), Pos); 1137 } 1138 1139 return nullptr; 1140 } 1141 1142 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) { 1143 StringRef S1, S2; 1144 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1145 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1146 1147 // strcspn("", s) -> 0 1148 if (HasS1 && S1.empty()) 1149 return Constant::getNullValue(CI->getType()); 1150 1151 // Constant folding. 1152 if (HasS1 && HasS2) { 1153 size_t Pos = S1.find_first_of(S2); 1154 if (Pos == StringRef::npos) 1155 Pos = S1.size(); 1156 return ConstantInt::get(CI->getType(), Pos); 1157 } 1158 1159 // strcspn(s, "") -> strlen(s) 1160 if (HasS2 && S2.empty()) 1161 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, DL, TLI)); 1162 1163 return nullptr; 1164 } 1165 1166 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) { 1167 // fold strstr(x, x) -> x. 1168 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 1169 return CI->getArgOperand(0); 1170 1171 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 1172 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 1173 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI); 1174 if (!StrLen) 1175 return nullptr; 1176 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 1177 StrLen, B, DL, TLI); 1178 if (!StrNCmp) 1179 return nullptr; 1180 for (User *U : llvm::make_early_inc_range(CI->users())) { 1181 ICmpInst *Old = cast<ICmpInst>(U); 1182 Value *Cmp = 1183 B.CreateICmp(Old->getPredicate(), StrNCmp, 1184 ConstantInt::getNullValue(StrNCmp->getType()), "cmp"); 1185 replaceAllUsesWith(Old, Cmp); 1186 } 1187 return CI; 1188 } 1189 1190 // See if either input string is a constant string. 1191 StringRef SearchStr, ToFindStr; 1192 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 1193 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 1194 1195 // fold strstr(x, "") -> x. 1196 if (HasStr2 && ToFindStr.empty()) 1197 return CI->getArgOperand(0); 1198 1199 // If both strings are known, constant fold it. 1200 if (HasStr1 && HasStr2) { 1201 size_t Offset = SearchStr.find(ToFindStr); 1202 1203 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 1204 return Constant::getNullValue(CI->getType()); 1205 1206 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 1207 return B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), CI->getArgOperand(0), 1208 Offset, "strstr"); 1209 } 1210 1211 // fold strstr(x, "y") -> strchr(x, 'y'). 1212 if (HasStr2 && ToFindStr.size() == 1) { 1213 return emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI); 1214 } 1215 1216 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 1217 return nullptr; 1218 } 1219 1220 Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) { 1221 Value *SrcStr = CI->getArgOperand(0); 1222 Value *Size = CI->getArgOperand(2); 1223 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1224 Value *CharVal = CI->getArgOperand(1); 1225 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1226 Value *NullPtr = Constant::getNullValue(CI->getType()); 1227 1228 if (LenC) { 1229 if (LenC->isZero()) 1230 // Fold memrchr(x, y, 0) --> null. 1231 return NullPtr; 1232 1233 if (LenC->isOne()) { 1234 // Fold memrchr(x, y, 1) --> *x == y ? x : null for any x and y, 1235 // constant or otherwise. 1236 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memrchr.char0"); 1237 // Slice off the character's high end bits. 1238 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1239 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memrchr.char0cmp"); 1240 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memrchr.sel"); 1241 } 1242 } 1243 1244 StringRef Str; 1245 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false)) 1246 return nullptr; 1247 1248 if (Str.size() == 0) 1249 // If the array is empty fold memrchr(A, C, N) to null for any value 1250 // of C and N on the basis that the only valid value of N is zero 1251 // (otherwise the call is undefined). 1252 return NullPtr; 1253 1254 uint64_t EndOff = UINT64_MAX; 1255 if (LenC) { 1256 EndOff = LenC->getZExtValue(); 1257 if (Str.size() < EndOff) 1258 // Punt out-of-bounds accesses to sanitizers and/or libc. 1259 return nullptr; 1260 } 1261 1262 if (ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal)) { 1263 // Fold memrchr(S, C, N) for a constant C. 1264 size_t Pos = Str.rfind(CharC->getZExtValue(), EndOff); 1265 if (Pos == StringRef::npos) 1266 // When the character is not in the source array fold the result 1267 // to null regardless of Size. 1268 return NullPtr; 1269 1270 if (LenC) 1271 // Fold memrchr(s, c, N) --> s + Pos for constant N > Pos. 1272 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos)); 1273 1274 if (Str.find(Str[Pos]) == Pos) { 1275 // When there is just a single occurrence of C in S, i.e., the one 1276 // in Str[Pos], fold 1277 // memrchr(s, c, N) --> N <= Pos ? null : s + Pos 1278 // for nonconstant N. 1279 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos), 1280 "memrchr.cmp"); 1281 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, 1282 B.getInt64(Pos), "memrchr.ptr_plus"); 1283 return B.CreateSelect(Cmp, NullPtr, SrcPlus, "memrchr.sel"); 1284 } 1285 } 1286 1287 // Truncate the string to search at most EndOff characters. 1288 Str = Str.substr(0, EndOff); 1289 if (Str.find_first_not_of(Str[0]) != StringRef::npos) 1290 return nullptr; 1291 1292 // If the source array consists of all equal characters, then for any 1293 // C and N (whether in bounds or not), fold memrchr(S, C, N) to 1294 // N != 0 && *S == C ? S + N - 1 : null 1295 Type *SizeTy = Size->getType(); 1296 Type *Int8Ty = B.getInt8Ty(); 1297 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1298 // Slice off the sought character's high end bits. 1299 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1300 Value *CEqS0 = B.CreateICmpEQ(ConstantInt::get(Int8Ty, Str[0]), CharVal); 1301 Value *And = B.CreateLogicalAnd(NNeZ, CEqS0); 1302 Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1)); 1303 Value *SrcPlus = 1304 B.CreateInBoundsGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus"); 1305 return B.CreateSelect(And, SrcPlus, NullPtr, "memrchr.sel"); 1306 } 1307 1308 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) { 1309 Value *SrcStr = CI->getArgOperand(0); 1310 Value *Size = CI->getArgOperand(2); 1311 1312 if (isKnownNonZero(Size, DL)) { 1313 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1314 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 1315 return memChrToCharCompare(CI, Size, B, DL); 1316 } 1317 1318 Value *CharVal = CI->getArgOperand(1); 1319 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 1320 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1321 Value *NullPtr = Constant::getNullValue(CI->getType()); 1322 1323 // memchr(x, y, 0) -> null 1324 if (LenC) { 1325 if (LenC->isZero()) 1326 return NullPtr; 1327 1328 if (LenC->isOne()) { 1329 // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y, 1330 // constant or otherwise. 1331 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0"); 1332 // Slice off the character's high end bits. 1333 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1334 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp"); 1335 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memchr.sel"); 1336 } 1337 } 1338 1339 StringRef Str; 1340 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false)) 1341 return nullptr; 1342 1343 if (CharC) { 1344 size_t Pos = Str.find(CharC->getZExtValue()); 1345 if (Pos == StringRef::npos) 1346 // When the character is not in the source array fold the result 1347 // to null regardless of Size. 1348 return NullPtr; 1349 1350 // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos 1351 // When the constant Size is less than or equal to the character 1352 // position also fold the result to null. 1353 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos), 1354 "memchr.cmp"); 1355 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos), 1356 "memchr.ptr"); 1357 return B.CreateSelect(Cmp, NullPtr, SrcPlus); 1358 } 1359 1360 if (Str.size() == 0) 1361 // If the array is empty fold memchr(A, C, N) to null for any value 1362 // of C and N on the basis that the only valid value of N is zero 1363 // (otherwise the call is undefined). 1364 return NullPtr; 1365 1366 if (LenC) 1367 Str = substr(Str, LenC->getZExtValue()); 1368 1369 size_t Pos = Str.find_first_not_of(Str[0]); 1370 if (Pos == StringRef::npos 1371 || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) { 1372 // If the source array consists of at most two consecutive sequences 1373 // of the same characters, then for any C and N (whether in bounds or 1374 // not), fold memchr(S, C, N) to 1375 // N != 0 && *S == C ? S : null 1376 // or for the two sequences to: 1377 // N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null) 1378 // ^Sel2 ^Sel1 are denoted above. 1379 // The latter makes it also possible to fold strchr() calls with strings 1380 // of the same characters. 1381 Type *SizeTy = Size->getType(); 1382 Type *Int8Ty = B.getInt8Ty(); 1383 1384 // Slice off the sought character's high end bits. 1385 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1386 1387 Value *Sel1 = NullPtr; 1388 if (Pos != StringRef::npos) { 1389 // Handle two consecutive sequences of the same characters. 1390 Value *PosVal = ConstantInt::get(SizeTy, Pos); 1391 Value *StrPos = ConstantInt::get(Int8Ty, Str[Pos]); 1392 Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos); 1393 Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal); 1394 Value *And = B.CreateAnd(CEqSPos, NGtPos); 1395 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal); 1396 Sel1 = B.CreateSelect(And, SrcPlus, NullPtr, "memchr.sel1"); 1397 } 1398 1399 Value *Str0 = ConstantInt::get(Int8Ty, Str[0]); 1400 Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal); 1401 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1402 Value *And = B.CreateAnd(NNeZ, CEqS0); 1403 return B.CreateSelect(And, SrcStr, Sel1, "memchr.sel2"); 1404 } 1405 1406 if (!LenC) { 1407 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 1408 // S is dereferenceable so it's safe to load from it and fold 1409 // memchr(S, C, N) == S to N && *S == C for any C and N. 1410 // TODO: This is safe even for nonconstant S. 1411 return memChrToCharCompare(CI, Size, B, DL); 1412 1413 // From now on we need a constant length and constant array. 1414 return nullptr; 1415 } 1416 1417 bool OptForSize = 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(0)->getType(), 1728 CI->getArgOperand(1), B, DL, TLI)); 1729 1730 return nullptr; 1731 } 1732 1733 // When enabled, replace operator new() calls marked with a hot or cold memprof 1734 // attribute with an operator new() call that takes a __hot_cold_t parameter. 1735 // Currently this is supported by the open source version of tcmalloc, see: 1736 // https://github.com/google/tcmalloc/blob/master/tcmalloc/new_extension.h 1737 Value *LibCallSimplifier::optimizeNew(CallInst *CI, IRBuilderBase &B, 1738 LibFunc &Func) { 1739 if (!OptimizeHotColdNew) 1740 return nullptr; 1741 1742 uint8_t HotCold; 1743 if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "cold") 1744 HotCold = ColdNewHintValue; 1745 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == 1746 "notcold") 1747 HotCold = NotColdNewHintValue; 1748 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "hot") 1749 HotCold = HotNewHintValue; 1750 else 1751 return nullptr; 1752 1753 // For calls that already pass a hot/cold hint, only update the hint if 1754 // directed by OptimizeExistingHotColdNew. For other calls to new, add a hint 1755 // if cold or hot, and leave as-is for default handling if "notcold" aka warm. 1756 // Note that in cases where we decide it is "notcold", it might be slightly 1757 // better to replace the hinted call with a non hinted call, to avoid the 1758 // extra parameter and the if condition check of the hint value in the 1759 // allocator. This can be considered in the future. 1760 switch (Func) { 1761 case LibFunc_Znwm12__hot_cold_t: 1762 if (OptimizeExistingHotColdNew) 1763 return emitHotColdNew(CI->getType(), CI->getArgOperand(0), B, TLI, 1764 LibFunc_Znwm12__hot_cold_t, HotCold); 1765 break; 1766 case LibFunc_Znwm: 1767 if (HotCold != NotColdNewHintValue) 1768 return emitHotColdNew(CI->getType(), CI->getArgOperand(0), B, TLI, 1769 LibFunc_Znwm12__hot_cold_t, HotCold); 1770 break; 1771 case LibFunc_Znam12__hot_cold_t: 1772 if (OptimizeExistingHotColdNew) 1773 return emitHotColdNew(CI->getType(), CI->getArgOperand(0), B, TLI, 1774 LibFunc_Znam12__hot_cold_t, HotCold); 1775 break; 1776 case LibFunc_Znam: 1777 if (HotCold != NotColdNewHintValue) 1778 return emitHotColdNew(CI->getType(), CI->getArgOperand(0), B, TLI, 1779 LibFunc_Znam12__hot_cold_t, HotCold); 1780 break; 1781 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t: 1782 if (OptimizeExistingHotColdNew) 1783 return emitHotColdNewNoThrow( 1784 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1785 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold); 1786 break; 1787 case LibFunc_ZnwmRKSt9nothrow_t: 1788 if (HotCold != NotColdNewHintValue) 1789 return emitHotColdNewNoThrow( 1790 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1791 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold); 1792 break; 1793 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t: 1794 if (OptimizeExistingHotColdNew) 1795 return emitHotColdNewNoThrow( 1796 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1797 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold); 1798 break; 1799 case LibFunc_ZnamRKSt9nothrow_t: 1800 if (HotCold != NotColdNewHintValue) 1801 return emitHotColdNewNoThrow( 1802 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1803 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold); 1804 break; 1805 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t: 1806 if (OptimizeExistingHotColdNew) 1807 return emitHotColdNewAligned( 1808 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1809 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold); 1810 break; 1811 case LibFunc_ZnwmSt11align_val_t: 1812 if (HotCold != NotColdNewHintValue) 1813 return emitHotColdNewAligned( 1814 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1815 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold); 1816 break; 1817 case LibFunc_ZnamSt11align_val_t12__hot_cold_t: 1818 if (OptimizeExistingHotColdNew) 1819 return emitHotColdNewAligned( 1820 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1821 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold); 1822 break; 1823 case LibFunc_ZnamSt11align_val_t: 1824 if (HotCold != NotColdNewHintValue) 1825 return emitHotColdNewAligned( 1826 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1827 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold); 1828 break; 1829 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 1830 if (OptimizeExistingHotColdNew) 1831 return emitHotColdNewAlignedNoThrow( 1832 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), 1833 CI->getArgOperand(2), B, TLI, 1834 LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t, HotCold); 1835 break; 1836 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t: 1837 if (HotCold != NotColdNewHintValue) 1838 return emitHotColdNewAlignedNoThrow( 1839 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), 1840 CI->getArgOperand(2), B, TLI, 1841 LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t, HotCold); 1842 break; 1843 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 1844 if (OptimizeExistingHotColdNew) 1845 return emitHotColdNewAlignedNoThrow( 1846 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), 1847 CI->getArgOperand(2), B, TLI, 1848 LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t, HotCold); 1849 break; 1850 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t: 1851 if (HotCold != NotColdNewHintValue) 1852 return emitHotColdNewAlignedNoThrow( 1853 CI->getType(), CI->getArgOperand(0), CI->getArgOperand(1), 1854 CI->getArgOperand(2), B, TLI, 1855 LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t, HotCold); 1856 break; 1857 case LibFunc_size_returning_new: 1858 if (HotCold != NotColdNewHintValue) 1859 return emitHotColdSizeReturningNew( 1860 CI->getType()->getStructElementType(0), CI->getArgOperand(0), B, TLI, 1861 LibFunc_size_returning_new_hot_cold, HotCold); 1862 break; 1863 case LibFunc_size_returning_new_hot_cold: 1864 if (OptimizeExistingHotColdNew) 1865 return emitHotColdSizeReturningNew( 1866 CI->getType()->getStructElementType(0), CI->getArgOperand(0), B, TLI, 1867 LibFunc_size_returning_new_hot_cold, HotCold); 1868 break; 1869 case LibFunc_size_returning_new_aligned: 1870 if (HotCold != NotColdNewHintValue) 1871 return emitHotColdSizeReturningNewAligned( 1872 CI->getType()->getStructElementType(0), CI->getArgOperand(0), 1873 CI->getArgOperand(1), B, TLI, 1874 LibFunc_size_returning_new_aligned_hot_cold, HotCold); 1875 break; 1876 case LibFunc_size_returning_new_aligned_hot_cold: 1877 if (OptimizeExistingHotColdNew) 1878 return emitHotColdSizeReturningNewAligned( 1879 CI->getType()->getStructElementType(0), CI->getArgOperand(0), 1880 CI->getArgOperand(1), B, TLI, 1881 LibFunc_size_returning_new_aligned_hot_cold, HotCold); 1882 break; 1883 default: 1884 return nullptr; 1885 } 1886 return nullptr; 1887 } 1888 1889 //===----------------------------------------------------------------------===// 1890 // Math Library Optimizations 1891 //===----------------------------------------------------------------------===// 1892 1893 // Replace a libcall \p CI with a call to intrinsic \p IID 1894 static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B, 1895 Intrinsic::ID IID) { 1896 CallInst *NewCall = B.CreateUnaryIntrinsic(IID, CI->getArgOperand(0), CI); 1897 NewCall->takeName(CI); 1898 return copyFlags(*CI, NewCall); 1899 } 1900 1901 /// Return a variant of Val with float type. 1902 /// Currently this works in two cases: If Val is an FPExtension of a float 1903 /// value to something bigger, simply return the operand. 1904 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 1905 /// loss of precision do so. 1906 static Value *valueHasFloatPrecision(Value *Val) { 1907 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 1908 Value *Op = Cast->getOperand(0); 1909 if (Op->getType()->isFloatTy()) 1910 return Op; 1911 } 1912 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 1913 APFloat F = Const->getValueAPF(); 1914 bool losesInfo; 1915 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 1916 &losesInfo); 1917 if (!losesInfo) 1918 return ConstantFP::get(Const->getContext(), F); 1919 } 1920 return nullptr; 1921 } 1922 1923 /// Shrink double -> float functions. 1924 static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B, 1925 bool isBinary, const TargetLibraryInfo *TLI, 1926 bool isPrecise = false) { 1927 Function *CalleeFn = CI->getCalledFunction(); 1928 if (!CI->getType()->isDoubleTy() || !CalleeFn) 1929 return nullptr; 1930 1931 // If not all the uses of the function are converted to float, then bail out. 1932 // This matters if the precision of the result is more important than the 1933 // precision of the arguments. 1934 if (isPrecise) 1935 for (User *U : CI->users()) { 1936 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 1937 if (!Cast || !Cast->getType()->isFloatTy()) 1938 return nullptr; 1939 } 1940 1941 // If this is something like 'g((double) float)', convert to 'gf(float)'. 1942 Value *V[2]; 1943 V[0] = valueHasFloatPrecision(CI->getArgOperand(0)); 1944 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr; 1945 if (!V[0] || (isBinary && !V[1])) 1946 return nullptr; 1947 1948 // If call isn't an intrinsic, check that it isn't within a function with the 1949 // same name as the float version of this call, otherwise the result is an 1950 // infinite loop. For example, from MinGW-w64: 1951 // 1952 // float expf(float val) { return (float) exp((double) val); } 1953 StringRef CalleeName = CalleeFn->getName(); 1954 bool IsIntrinsic = CalleeFn->isIntrinsic(); 1955 if (!IsIntrinsic) { 1956 StringRef CallerName = CI->getFunction()->getName(); 1957 if (!CallerName.empty() && CallerName.back() == 'f' && 1958 CallerName.size() == (CalleeName.size() + 1) && 1959 CallerName.starts_with(CalleeName)) 1960 return nullptr; 1961 } 1962 1963 // Propagate the math semantics from the current function to the new function. 1964 IRBuilderBase::FastMathFlagGuard Guard(B); 1965 B.setFastMathFlags(CI->getFastMathFlags()); 1966 1967 // g((double) float) -> (double) gf(float) 1968 Value *R; 1969 if (IsIntrinsic) { 1970 Intrinsic::ID IID = CalleeFn->getIntrinsicID(); 1971 R = isBinary ? B.CreateIntrinsic(IID, B.getFloatTy(), V) 1972 : B.CreateIntrinsic(IID, B.getFloatTy(), V[0]); 1973 } else { 1974 AttributeList CalleeAttrs = CalleeFn->getAttributes(); 1975 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B, 1976 CalleeAttrs) 1977 : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CalleeAttrs); 1978 } 1979 return B.CreateFPExt(R, B.getDoubleTy()); 1980 } 1981 1982 /// Shrink double -> float for unary functions. 1983 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1984 const TargetLibraryInfo *TLI, 1985 bool isPrecise = false) { 1986 return optimizeDoubleFP(CI, B, false, TLI, isPrecise); 1987 } 1988 1989 /// Shrink double -> float for binary functions. 1990 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1991 const TargetLibraryInfo *TLI, 1992 bool isPrecise = false) { 1993 return optimizeDoubleFP(CI, B, true, TLI, isPrecise); 1994 } 1995 1996 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1997 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) { 1998 Value *Real, *Imag; 1999 2000 if (CI->arg_size() == 1) { 2001 2002 if (!CI->isFast()) 2003 return nullptr; 2004 2005 Value *Op = CI->getArgOperand(0); 2006 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 2007 2008 Real = B.CreateExtractValue(Op, 0, "real"); 2009 Imag = B.CreateExtractValue(Op, 1, "imag"); 2010 2011 } else { 2012 assert(CI->arg_size() == 2 && "Unexpected signature for cabs!"); 2013 2014 Real = CI->getArgOperand(0); 2015 Imag = CI->getArgOperand(1); 2016 2017 // if real or imaginary part is zero, simplify to abs(cimag(z)) 2018 // or abs(creal(z)) 2019 Value *AbsOp = nullptr; 2020 if (ConstantFP *ConstReal = dyn_cast<ConstantFP>(Real)) { 2021 if (ConstReal->isZero()) 2022 AbsOp = Imag; 2023 2024 } else if (ConstantFP *ConstImag = dyn_cast<ConstantFP>(Imag)) { 2025 if (ConstImag->isZero()) 2026 AbsOp = Real; 2027 } 2028 2029 if (AbsOp) { 2030 IRBuilderBase::FastMathFlagGuard Guard(B); 2031 B.setFastMathFlags(CI->getFastMathFlags()); 2032 2033 return copyFlags( 2034 *CI, B.CreateUnaryIntrinsic(Intrinsic::fabs, AbsOp, nullptr, "cabs")); 2035 } 2036 2037 if (!CI->isFast()) 2038 return nullptr; 2039 } 2040 2041 // Propagate fast-math flags from the existing call to new instructions. 2042 IRBuilderBase::FastMathFlagGuard Guard(B); 2043 B.setFastMathFlags(CI->getFastMathFlags()); 2044 2045 Value *RealReal = B.CreateFMul(Real, Real); 2046 Value *ImagImag = B.CreateFMul(Imag, Imag); 2047 2048 return copyFlags(*CI, B.CreateUnaryIntrinsic(Intrinsic::sqrt, 2049 B.CreateFAdd(RealReal, ImagImag), 2050 nullptr, "cabs")); 2051 } 2052 2053 // Return a properly extended integer (DstWidth bits wide) if the operation is 2054 // an itofp. 2055 static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) { 2056 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) { 2057 Value *Op = cast<Instruction>(I2F)->getOperand(0); 2058 // Make sure that the exponent fits inside an "int" of size DstWidth, 2059 // thus avoiding any range issues that FP has not. 2060 unsigned BitWidth = Op->getType()->getScalarSizeInBits(); 2061 if (BitWidth < DstWidth || (BitWidth == DstWidth && isa<SIToFPInst>(I2F))) { 2062 Type *IntTy = Op->getType()->getWithNewBitWidth(DstWidth); 2063 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, IntTy) 2064 : B.CreateZExt(Op, IntTy); 2065 } 2066 } 2067 2068 return nullptr; 2069 } 2070 2071 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y); 2072 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x); 2073 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x). 2074 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) { 2075 Module *M = Pow->getModule(); 2076 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 2077 Type *Ty = Pow->getType(); 2078 bool Ignored; 2079 2080 // Evaluate special cases related to a nested function as the base. 2081 2082 // pow(exp(x), y) -> exp(x * y) 2083 // pow(exp2(x), y) -> exp2(x * y) 2084 // If exp{,2}() is used only once, it is better to fold two transcendental 2085 // math functions into one. If used again, exp{,2}() would still have to be 2086 // called with the original argument, then keep both original transcendental 2087 // functions. However, this transformation is only safe with fully relaxed 2088 // math semantics, since, besides rounding differences, it changes overflow 2089 // and underflow behavior quite dramatically. For example: 2090 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf 2091 // Whereas: 2092 // exp(1000 * 0.001) = exp(1) 2093 // TODO: Loosen the requirement for fully relaxed math semantics. 2094 // TODO: Handle exp10() when more targets have it available. 2095 CallInst *BaseFn = dyn_cast<CallInst>(Base); 2096 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) { 2097 LibFunc LibFn; 2098 2099 Function *CalleeFn = BaseFn->getCalledFunction(); 2100 if (CalleeFn && TLI->getLibFunc(CalleeFn->getName(), LibFn) && 2101 isLibFuncEmittable(M, TLI, LibFn)) { 2102 StringRef ExpName; 2103 Intrinsic::ID ID; 2104 Value *ExpFn; 2105 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble; 2106 2107 switch (LibFn) { 2108 default: 2109 return nullptr; 2110 case LibFunc_expf: 2111 case LibFunc_exp: 2112 case LibFunc_expl: 2113 ExpName = TLI->getName(LibFunc_exp); 2114 ID = Intrinsic::exp; 2115 LibFnFloat = LibFunc_expf; 2116 LibFnDouble = LibFunc_exp; 2117 LibFnLongDouble = LibFunc_expl; 2118 break; 2119 case LibFunc_exp2f: 2120 case LibFunc_exp2: 2121 case LibFunc_exp2l: 2122 ExpName = TLI->getName(LibFunc_exp2); 2123 ID = Intrinsic::exp2; 2124 LibFnFloat = LibFunc_exp2f; 2125 LibFnDouble = LibFunc_exp2; 2126 LibFnLongDouble = LibFunc_exp2l; 2127 break; 2128 } 2129 2130 // Create new exp{,2}() with the product as its argument. 2131 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul"); 2132 ExpFn = BaseFn->doesNotAccessMemory() 2133 ? B.CreateUnaryIntrinsic(ID, FMul, nullptr, ExpName) 2134 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat, 2135 LibFnLongDouble, B, 2136 BaseFn->getAttributes()); 2137 2138 // Since the new exp{,2}() is different from the original one, dead code 2139 // elimination cannot be trusted to remove it, since it may have side 2140 // effects (e.g., errno). When the only consumer for the original 2141 // exp{,2}() is pow(), then it has to be explicitly erased. 2142 substituteInParent(BaseFn, ExpFn); 2143 return ExpFn; 2144 } 2145 } 2146 2147 // Evaluate special cases related to a constant base. 2148 2149 const APFloat *BaseF; 2150 if (!match(Base, m_APFloat(BaseF))) 2151 return nullptr; 2152 2153 AttributeList NoAttrs; // Attributes are only meaningful on the original call 2154 2155 const bool UseIntrinsic = Pow->doesNotAccessMemory(); 2156 2157 // pow(2.0, itofp(x)) -> ldexp(1.0, x) 2158 if ((UseIntrinsic || !Ty->isVectorTy()) && BaseF->isExactlyValue(2.0) && 2159 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) && 2160 (UseIntrinsic || 2161 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) { 2162 2163 // TODO: Shouldn't really need to depend on getIntToFPVal for intrinsic. Can 2164 // just directly use the original integer type. 2165 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) { 2166 Constant *One = ConstantFP::get(Ty, 1.0); 2167 2168 if (UseIntrinsic) { 2169 return copyFlags(*Pow, B.CreateIntrinsic(Intrinsic::ldexp, 2170 {Ty, ExpoI->getType()}, 2171 {One, ExpoI}, Pow, "exp2")); 2172 } 2173 2174 return copyFlags(*Pow, emitBinaryFloatFnCall( 2175 One, ExpoI, TLI, LibFunc_ldexp, LibFunc_ldexpf, 2176 LibFunc_ldexpl, B, NoAttrs)); 2177 } 2178 } 2179 2180 // pow(2.0 ** n, x) -> exp2(n * x) 2181 if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) { 2182 APFloat BaseR = APFloat(1.0); 2183 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored); 2184 BaseR = BaseR / *BaseF; 2185 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger(); 2186 const APFloat *NF = IsReciprocal ? &BaseR : BaseF; 2187 APSInt NI(64, false); 2188 if ((IsInteger || IsReciprocal) && 2189 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) == 2190 APFloat::opOK && 2191 NI > 1 && NI.isPowerOf2()) { 2192 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0); 2193 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul"); 2194 if (Pow->doesNotAccessMemory()) 2195 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul, 2196 nullptr, "exp2")); 2197 else 2198 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 2199 LibFunc_exp2f, 2200 LibFunc_exp2l, B, NoAttrs)); 2201 } 2202 } 2203 2204 // pow(10.0, x) -> exp10(x) 2205 if (BaseF->isExactlyValue(10.0) && 2206 hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) { 2207 2208 if (Pow->doesNotAccessMemory()) { 2209 CallInst *NewExp10 = 2210 B.CreateIntrinsic(Intrinsic::exp10, {Ty}, {Expo}, Pow, "exp10"); 2211 return copyFlags(*Pow, NewExp10); 2212 } 2213 2214 return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, 2215 LibFunc_exp10f, LibFunc_exp10l, 2216 B, NoAttrs)); 2217 } 2218 2219 // pow(x, y) -> exp2(log2(x) * y) 2220 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() && 2221 !BaseF->isNegative()) { 2222 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN. 2223 // Luckily optimizePow has already handled the x == 1 case. 2224 assert(!match(Base, m_FPOne()) && 2225 "pow(1.0, y) should have been simplified earlier!"); 2226 2227 Value *Log = nullptr; 2228 if (Ty->isFloatTy()) 2229 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat())); 2230 else if (Ty->isDoubleTy()) 2231 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble())); 2232 2233 if (Log) { 2234 Value *FMul = B.CreateFMul(Log, Expo, "mul"); 2235 if (Pow->doesNotAccessMemory()) 2236 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul, 2237 nullptr, "exp2")); 2238 else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, 2239 LibFunc_exp2l)) 2240 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 2241 LibFunc_exp2f, 2242 LibFunc_exp2l, B, NoAttrs)); 2243 } 2244 } 2245 2246 return nullptr; 2247 } 2248 2249 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, 2250 Module *M, IRBuilderBase &B, 2251 const TargetLibraryInfo *TLI) { 2252 // If errno is never set, then use the intrinsic for sqrt(). 2253 if (NoErrno) 2254 return B.CreateUnaryIntrinsic(Intrinsic::sqrt, V, nullptr, "sqrt"); 2255 2256 // Otherwise, use the libcall for sqrt(). 2257 if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, 2258 LibFunc_sqrtl)) 2259 // TODO: We also should check that the target can in fact lower the sqrt() 2260 // libcall. We currently have no way to ask this question, so we ask if 2261 // the target has a sqrt() libcall, which is not exactly the same. 2262 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf, 2263 LibFunc_sqrtl, B, Attrs); 2264 2265 return nullptr; 2266 } 2267 2268 /// Use square root in place of pow(x, +/-0.5). 2269 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) { 2270 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 2271 Module *Mod = Pow->getModule(); 2272 Type *Ty = Pow->getType(); 2273 2274 const APFloat *ExpoF; 2275 if (!match(Expo, m_APFloat(ExpoF)) || 2276 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 2277 return nullptr; 2278 2279 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step, 2280 // so that requires fast-math-flags (afn or reassoc). 2281 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc())) 2282 return nullptr; 2283 2284 // If we have a pow() library call (accesses memory) and we can't guarantee 2285 // that the base is not an infinity, give up: 2286 // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting 2287 // errno), but sqrt(-Inf) is required by various standards to set errno. 2288 if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() && 2289 !isKnownNeverInfinity( 2290 Base, 0, SimplifyQuery(DL, TLI, DT, AC, Pow, true, true, DC))) 2291 return nullptr; 2292 2293 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), Mod, B, 2294 TLI); 2295 if (!Sqrt) 2296 return nullptr; 2297 2298 // Handle signed zero base by expanding to fabs(sqrt(x)). 2299 if (!Pow->hasNoSignedZeros()) 2300 Sqrt = B.CreateUnaryIntrinsic(Intrinsic::fabs, Sqrt, nullptr, "abs"); 2301 2302 Sqrt = copyFlags(*Pow, Sqrt); 2303 2304 // Handle non finite base by expanding to 2305 // (x == -infinity ? +infinity : sqrt(x)). 2306 if (!Pow->hasNoInfs()) { 2307 Value *PosInf = ConstantFP::getInfinity(Ty), 2308 *NegInf = ConstantFP::getInfinity(Ty, true); 2309 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 2310 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 2311 } 2312 2313 // If the exponent is negative, then get the reciprocal. 2314 if (ExpoF->isNegative()) 2315 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 2316 2317 return Sqrt; 2318 } 2319 2320 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, 2321 IRBuilderBase &B) { 2322 Value *Args[] = {Base, Expo}; 2323 Type *Types[] = {Base->getType(), Expo->getType()}; 2324 return B.CreateIntrinsic(Intrinsic::powi, Types, Args); 2325 } 2326 2327 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) { 2328 Value *Base = Pow->getArgOperand(0); 2329 Value *Expo = Pow->getArgOperand(1); 2330 Function *Callee = Pow->getCalledFunction(); 2331 StringRef Name = Callee->getName(); 2332 Type *Ty = Pow->getType(); 2333 Module *M = Pow->getModule(); 2334 bool AllowApprox = Pow->hasApproxFunc(); 2335 bool Ignored; 2336 2337 // Propagate the math semantics from the call to any created instructions. 2338 IRBuilderBase::FastMathFlagGuard Guard(B); 2339 B.setFastMathFlags(Pow->getFastMathFlags()); 2340 // Evaluate special cases related to the base. 2341 2342 // pow(1.0, x) -> 1.0 2343 if (match(Base, m_FPOne())) 2344 return Base; 2345 2346 if (Value *Exp = replacePowWithExp(Pow, B)) 2347 return Exp; 2348 2349 // Evaluate special cases related to the exponent. 2350 2351 // pow(x, -1.0) -> 1.0 / x 2352 if (match(Expo, m_SpecificFP(-1.0))) 2353 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 2354 2355 // pow(x, +/-0.0) -> 1.0 2356 if (match(Expo, m_AnyZeroFP())) 2357 return ConstantFP::get(Ty, 1.0); 2358 2359 // pow(x, 1.0) -> x 2360 if (match(Expo, m_FPOne())) 2361 return Base; 2362 2363 // pow(x, 2.0) -> x * x 2364 if (match(Expo, m_SpecificFP(2.0))) 2365 return B.CreateFMul(Base, Base, "square"); 2366 2367 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 2368 return Sqrt; 2369 2370 // If we can approximate pow: 2371 // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction 2372 // pow(x, n) -> powi(x, n) if n is a constant signed integer value 2373 const APFloat *ExpoF; 2374 if (AllowApprox && match(Expo, m_APFloat(ExpoF)) && 2375 !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) { 2376 APFloat ExpoA(abs(*ExpoF)); 2377 APFloat ExpoI(*ExpoF); 2378 Value *Sqrt = nullptr; 2379 if (!ExpoA.isInteger()) { 2380 APFloat Expo2 = ExpoA; 2381 // To check if ExpoA is an integer + 0.5, we add it to itself. If there 2382 // is no floating point exception and the result is an integer, then 2383 // ExpoA == integer + 0.5 2384 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK) 2385 return nullptr; 2386 2387 if (!Expo2.isInteger()) 2388 return nullptr; 2389 2390 if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) != 2391 APFloat::opInexact) 2392 return nullptr; 2393 if (!ExpoI.isInteger()) 2394 return nullptr; 2395 ExpoF = &ExpoI; 2396 2397 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), M, 2398 B, TLI); 2399 if (!Sqrt) 2400 return nullptr; 2401 } 2402 2403 // 0.5 fraction is now optionally handled. 2404 // Do pow -> powi for remaining integer exponent 2405 APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false); 2406 if (ExpoF->isInteger() && 2407 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) == 2408 APFloat::opOK) { 2409 Value *PowI = copyFlags( 2410 *Pow, 2411 createPowWithIntegerExponent( 2412 Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo), 2413 M, B)); 2414 2415 if (PowI && Sqrt) 2416 return B.CreateFMul(PowI, Sqrt); 2417 2418 return PowI; 2419 } 2420 } 2421 2422 // powf(x, itofp(y)) -> powi(x, y) 2423 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) { 2424 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) 2425 return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B)); 2426 } 2427 2428 // Shrink pow() to powf() if the arguments are single precision, 2429 // unless the result is expected to be double precision. 2430 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) && 2431 hasFloatVersion(M, Name)) { 2432 if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true)) 2433 return Shrunk; 2434 } 2435 2436 return nullptr; 2437 } 2438 2439 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) { 2440 Module *M = CI->getModule(); 2441 Function *Callee = CI->getCalledFunction(); 2442 StringRef Name = Callee->getName(); 2443 Value *Ret = nullptr; 2444 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) && 2445 hasFloatVersion(M, Name)) 2446 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2447 2448 // If we have an llvm.exp2 intrinsic, emit the llvm.ldexp intrinsic. If we 2449 // have the libcall, emit the libcall. 2450 // 2451 // TODO: In principle we should be able to just always use the intrinsic for 2452 // any doesNotAccessMemory callsite. 2453 2454 const bool UseIntrinsic = Callee->isIntrinsic(); 2455 // Bail out for vectors because the code below only expects scalars. 2456 Type *Ty = CI->getType(); 2457 if (!UseIntrinsic && Ty->isVectorTy()) 2458 return Ret; 2459 2460 // exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize 2461 // exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize 2462 Value *Op = CI->getArgOperand(0); 2463 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) && 2464 (UseIntrinsic || 2465 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) { 2466 if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize())) { 2467 Constant *One = ConstantFP::get(Ty, 1.0); 2468 2469 if (UseIntrinsic) { 2470 return copyFlags(*CI, B.CreateIntrinsic(Intrinsic::ldexp, 2471 {Ty, Exp->getType()}, 2472 {One, Exp}, CI)); 2473 } 2474 2475 IRBuilderBase::FastMathFlagGuard Guard(B); 2476 B.setFastMathFlags(CI->getFastMathFlags()); 2477 return copyFlags(*CI, emitBinaryFloatFnCall( 2478 One, Exp, TLI, LibFunc_ldexp, LibFunc_ldexpf, 2479 LibFunc_ldexpl, B, AttributeList())); 2480 } 2481 } 2482 2483 return Ret; 2484 } 2485 2486 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) { 2487 Module *M = CI->getModule(); 2488 2489 // If we can shrink the call to a float function rather than a double 2490 // function, do that first. 2491 Function *Callee = CI->getCalledFunction(); 2492 StringRef Name = Callee->getName(); 2493 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(M, Name)) 2494 if (Value *Ret = optimizeBinaryDoubleFP(CI, B, TLI)) 2495 return Ret; 2496 2497 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to 2498 // the intrinsics for improved optimization (for example, vectorization). 2499 // No-signed-zeros is implied by the definitions of fmax/fmin themselves. 2500 // From the C standard draft WG14/N1256: 2501 // "Ideally, fmax would be sensitive to the sign of zero, for example 2502 // fmax(-0.0, +0.0) would return +0; however, implementation in software 2503 // might be impractical." 2504 IRBuilderBase::FastMathFlagGuard Guard(B); 2505 FastMathFlags FMF = CI->getFastMathFlags(); 2506 FMF.setNoSignedZeros(); 2507 B.setFastMathFlags(FMF); 2508 2509 Intrinsic::ID IID = Callee->getName().starts_with("fmin") ? Intrinsic::minnum 2510 : Intrinsic::maxnum; 2511 return copyFlags(*CI, B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0), 2512 CI->getArgOperand(1))); 2513 } 2514 2515 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) { 2516 Function *LogFn = Log->getCalledFunction(); 2517 StringRef LogNm = LogFn->getName(); 2518 Intrinsic::ID LogID = LogFn->getIntrinsicID(); 2519 Module *Mod = Log->getModule(); 2520 Type *Ty = Log->getType(); 2521 2522 if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm)) 2523 if (Value *Ret = optimizeUnaryDoubleFP(Log, B, TLI, true)) 2524 return Ret; 2525 2526 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb; 2527 2528 // This is only applicable to log(), log2(), log10(). 2529 if (TLI->getLibFunc(LogNm, LogLb)) { 2530 switch (LogLb) { 2531 case LibFunc_logf: 2532 LogID = Intrinsic::log; 2533 ExpLb = LibFunc_expf; 2534 Exp2Lb = LibFunc_exp2f; 2535 Exp10Lb = LibFunc_exp10f; 2536 PowLb = LibFunc_powf; 2537 break; 2538 case LibFunc_log: 2539 LogID = Intrinsic::log; 2540 ExpLb = LibFunc_exp; 2541 Exp2Lb = LibFunc_exp2; 2542 Exp10Lb = LibFunc_exp10; 2543 PowLb = LibFunc_pow; 2544 break; 2545 case LibFunc_logl: 2546 LogID = Intrinsic::log; 2547 ExpLb = LibFunc_expl; 2548 Exp2Lb = LibFunc_exp2l; 2549 Exp10Lb = LibFunc_exp10l; 2550 PowLb = LibFunc_powl; 2551 break; 2552 case LibFunc_log2f: 2553 LogID = Intrinsic::log2; 2554 ExpLb = LibFunc_expf; 2555 Exp2Lb = LibFunc_exp2f; 2556 Exp10Lb = LibFunc_exp10f; 2557 PowLb = LibFunc_powf; 2558 break; 2559 case LibFunc_log2: 2560 LogID = Intrinsic::log2; 2561 ExpLb = LibFunc_exp; 2562 Exp2Lb = LibFunc_exp2; 2563 Exp10Lb = LibFunc_exp10; 2564 PowLb = LibFunc_pow; 2565 break; 2566 case LibFunc_log2l: 2567 LogID = Intrinsic::log2; 2568 ExpLb = LibFunc_expl; 2569 Exp2Lb = LibFunc_exp2l; 2570 Exp10Lb = LibFunc_exp10l; 2571 PowLb = LibFunc_powl; 2572 break; 2573 case LibFunc_log10f: 2574 LogID = Intrinsic::log10; 2575 ExpLb = LibFunc_expf; 2576 Exp2Lb = LibFunc_exp2f; 2577 Exp10Lb = LibFunc_exp10f; 2578 PowLb = LibFunc_powf; 2579 break; 2580 case LibFunc_log10: 2581 LogID = Intrinsic::log10; 2582 ExpLb = LibFunc_exp; 2583 Exp2Lb = LibFunc_exp2; 2584 Exp10Lb = LibFunc_exp10; 2585 PowLb = LibFunc_pow; 2586 break; 2587 case LibFunc_log10l: 2588 LogID = Intrinsic::log10; 2589 ExpLb = LibFunc_expl; 2590 Exp2Lb = LibFunc_exp2l; 2591 Exp10Lb = LibFunc_exp10l; 2592 PowLb = LibFunc_powl; 2593 break; 2594 default: 2595 return nullptr; 2596 } 2597 2598 // Convert libcall to intrinsic if the value is known > 0. 2599 bool IsKnownNoErrno = Log->hasNoNaNs() && Log->hasNoInfs(); 2600 if (!IsKnownNoErrno) { 2601 SimplifyQuery SQ(DL, TLI, DT, AC, Log, true, true, DC); 2602 KnownFPClass Known = computeKnownFPClass( 2603 Log->getOperand(0), 2604 KnownFPClass::OrderedLessThanZeroMask | fcSubnormal, 2605 /*Depth=*/0, SQ); 2606 Function *F = Log->getParent()->getParent(); 2607 IsKnownNoErrno = Known.cannotBeOrderedLessThanZero() && 2608 Known.isKnownNeverLogicalZero(*F, Ty); 2609 } 2610 if (IsKnownNoErrno) { 2611 auto *NewLog = B.CreateUnaryIntrinsic(LogID, Log->getArgOperand(0), Log); 2612 NewLog->copyMetadata(*Log); 2613 return copyFlags(*Log, NewLog); 2614 } 2615 } else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 || 2616 LogID == Intrinsic::log10) { 2617 if (Ty->getScalarType()->isFloatTy()) { 2618 ExpLb = LibFunc_expf; 2619 Exp2Lb = LibFunc_exp2f; 2620 Exp10Lb = LibFunc_exp10f; 2621 PowLb = LibFunc_powf; 2622 } else if (Ty->getScalarType()->isDoubleTy()) { 2623 ExpLb = LibFunc_exp; 2624 Exp2Lb = LibFunc_exp2; 2625 Exp10Lb = LibFunc_exp10; 2626 PowLb = LibFunc_pow; 2627 } else 2628 return nullptr; 2629 } else 2630 return nullptr; 2631 2632 // The earlier call must also be 'fast' in order to do these transforms. 2633 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0)); 2634 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse()) 2635 return nullptr; 2636 2637 IRBuilderBase::FastMathFlagGuard Guard(B); 2638 B.setFastMathFlags(FastMathFlags::getFast()); 2639 2640 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 2641 LibFunc ArgLb = NotLibFunc; 2642 TLI->getLibFunc(*Arg, ArgLb); 2643 2644 // log(pow(x,y)) -> y*log(x) 2645 AttributeList NoAttrs; 2646 if (ArgLb == PowLb || ArgID == Intrinsic::pow || ArgID == Intrinsic::powi) { 2647 Value *LogX = 2648 Log->doesNotAccessMemory() 2649 ? B.CreateUnaryIntrinsic(LogID, Arg->getOperand(0), nullptr, "log") 2650 : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, NoAttrs); 2651 Value *Y = Arg->getArgOperand(1); 2652 // Cast exponent to FP if integer. 2653 if (ArgID == Intrinsic::powi) 2654 Y = B.CreateSIToFP(Y, Ty, "cast"); 2655 Value *MulY = B.CreateFMul(Y, LogX, "mul"); 2656 // Since pow() may have side effects, e.g. errno, 2657 // dead code elimination may not be trusted to remove it. 2658 substituteInParent(Arg, MulY); 2659 return MulY; 2660 } 2661 2662 // log(exp{,2,10}(y)) -> y*log({e,2,10}) 2663 // TODO: There is no exp10() intrinsic yet. 2664 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb || 2665 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) { 2666 Constant *Eul; 2667 if (ArgLb == ExpLb || ArgID == Intrinsic::exp) 2668 // FIXME: Add more precise value of e for long double. 2669 Eul = ConstantFP::get(Log->getType(), numbers::e); 2670 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2) 2671 Eul = ConstantFP::get(Log->getType(), 2.0); 2672 else 2673 Eul = ConstantFP::get(Log->getType(), 10.0); 2674 Value *LogE = Log->doesNotAccessMemory() 2675 ? B.CreateUnaryIntrinsic(LogID, Eul, nullptr, "log") 2676 : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, NoAttrs); 2677 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul"); 2678 // Since exp() may have side effects, e.g. errno, 2679 // dead code elimination may not be trusted to remove it. 2680 substituteInParent(Arg, MulY); 2681 return MulY; 2682 } 2683 2684 return nullptr; 2685 } 2686 2687 // sqrt(exp(X)) -> exp(X * 0.5) 2688 Value *LibCallSimplifier::mergeSqrtToExp(CallInst *CI, IRBuilderBase &B) { 2689 if (!CI->hasAllowReassoc()) 2690 return nullptr; 2691 2692 Function *SqrtFn = CI->getCalledFunction(); 2693 CallInst *Arg = dyn_cast<CallInst>(CI->getArgOperand(0)); 2694 if (!Arg || !Arg->hasAllowReassoc() || !Arg->hasOneUse()) 2695 return nullptr; 2696 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 2697 LibFunc ArgLb = NotLibFunc; 2698 TLI->getLibFunc(*Arg, ArgLb); 2699 2700 LibFunc SqrtLb, ExpLb, Exp2Lb, Exp10Lb; 2701 2702 if (TLI->getLibFunc(SqrtFn->getName(), SqrtLb)) 2703 switch (SqrtLb) { 2704 case LibFunc_sqrtf: 2705 ExpLb = LibFunc_expf; 2706 Exp2Lb = LibFunc_exp2f; 2707 Exp10Lb = LibFunc_exp10f; 2708 break; 2709 case LibFunc_sqrt: 2710 ExpLb = LibFunc_exp; 2711 Exp2Lb = LibFunc_exp2; 2712 Exp10Lb = LibFunc_exp10; 2713 break; 2714 case LibFunc_sqrtl: 2715 ExpLb = LibFunc_expl; 2716 Exp2Lb = LibFunc_exp2l; 2717 Exp10Lb = LibFunc_exp10l; 2718 break; 2719 default: 2720 return nullptr; 2721 } 2722 else if (SqrtFn->getIntrinsicID() == Intrinsic::sqrt) { 2723 if (CI->getType()->getScalarType()->isFloatTy()) { 2724 ExpLb = LibFunc_expf; 2725 Exp2Lb = LibFunc_exp2f; 2726 Exp10Lb = LibFunc_exp10f; 2727 } else if (CI->getType()->getScalarType()->isDoubleTy()) { 2728 ExpLb = LibFunc_exp; 2729 Exp2Lb = LibFunc_exp2; 2730 Exp10Lb = LibFunc_exp10; 2731 } else 2732 return nullptr; 2733 } else 2734 return nullptr; 2735 2736 if (ArgLb != ExpLb && ArgLb != Exp2Lb && ArgLb != Exp10Lb && 2737 ArgID != Intrinsic::exp && ArgID != Intrinsic::exp2) 2738 return nullptr; 2739 2740 IRBuilderBase::InsertPointGuard Guard(B); 2741 B.SetInsertPoint(Arg); 2742 auto *ExpOperand = Arg->getOperand(0); 2743 auto *FMul = 2744 B.CreateFMulFMF(ExpOperand, ConstantFP::get(ExpOperand->getType(), 0.5), 2745 CI, "merged.sqrt"); 2746 2747 Arg->setOperand(0, FMul); 2748 return Arg; 2749 } 2750 2751 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) { 2752 Module *M = CI->getModule(); 2753 Function *Callee = CI->getCalledFunction(); 2754 Value *Ret = nullptr; 2755 // TODO: Once we have a way (other than checking for the existince of the 2756 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 2757 // condition below. 2758 if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) && 2759 (Callee->getName() == "sqrt" || 2760 Callee->getIntrinsicID() == Intrinsic::sqrt)) 2761 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2762 2763 if (Value *Opt = mergeSqrtToExp(CI, B)) 2764 return Opt; 2765 2766 if (!CI->isFast()) 2767 return Ret; 2768 2769 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 2770 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 2771 return Ret; 2772 2773 // We're looking for a repeated factor in a multiplication tree, 2774 // so we can do this fold: sqrt(x * x) -> fabs(x); 2775 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 2776 Value *Op0 = I->getOperand(0); 2777 Value *Op1 = I->getOperand(1); 2778 Value *RepeatOp = nullptr; 2779 Value *OtherOp = nullptr; 2780 if (Op0 == Op1) { 2781 // Simple match: the operands of the multiply are identical. 2782 RepeatOp = Op0; 2783 } else { 2784 // Look for a more complicated pattern: one of the operands is itself 2785 // a multiply, so search for a common factor in that multiply. 2786 // Note: We don't bother looking any deeper than this first level or for 2787 // variations of this pattern because instcombine's visitFMUL and/or the 2788 // reassociation pass should give us this form. 2789 Value *MulOp; 2790 if (match(Op0, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) && 2791 cast<Instruction>(Op0)->isFast()) { 2792 // Pattern: sqrt((x * x) * z) 2793 RepeatOp = MulOp; 2794 OtherOp = Op1; 2795 } else if (match(Op1, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) && 2796 cast<Instruction>(Op1)->isFast()) { 2797 // Pattern: sqrt(z * (x * x)) 2798 RepeatOp = MulOp; 2799 OtherOp = Op0; 2800 } 2801 } 2802 if (!RepeatOp) 2803 return Ret; 2804 2805 // Fast math flags for any created instructions should match the sqrt 2806 // and multiply. 2807 IRBuilderBase::FastMathFlagGuard Guard(B); 2808 B.setFastMathFlags(I->getFastMathFlags()); 2809 2810 // If we found a repeated factor, hoist it out of the square root and 2811 // replace it with the fabs of that factor. 2812 Value *FabsCall = 2813 B.CreateUnaryIntrinsic(Intrinsic::fabs, RepeatOp, nullptr, "fabs"); 2814 if (OtherOp) { 2815 // If we found a non-repeated factor, we still need to get its square 2816 // root. We then multiply that by the value that was simplified out 2817 // of the square root calculation. 2818 Value *SqrtCall = 2819 B.CreateUnaryIntrinsic(Intrinsic::sqrt, OtherOp, nullptr, "sqrt"); 2820 return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall)); 2821 } 2822 return copyFlags(*CI, FabsCall); 2823 } 2824 2825 Value *LibCallSimplifier::optimizeFMod(CallInst *CI, IRBuilderBase &B) { 2826 2827 // fmod(x,y) can set errno if y == 0 or x == +/-inf, and returns Nan in those 2828 // case. If we know those do not happen, then we can convert the fmod into 2829 // frem. 2830 bool IsNoNan = CI->hasNoNaNs(); 2831 if (!IsNoNan) { 2832 SimplifyQuery SQ(DL, TLI, DT, AC, CI, true, true, DC); 2833 KnownFPClass Known0 = computeKnownFPClass(CI->getOperand(0), fcInf, 2834 /*Depth=*/0, SQ); 2835 if (Known0.isKnownNeverInfinity()) { 2836 KnownFPClass Known1 = 2837 computeKnownFPClass(CI->getOperand(1), fcZero | fcSubnormal, 2838 /*Depth=*/0, SQ); 2839 Function *F = CI->getParent()->getParent(); 2840 IsNoNan = Known1.isKnownNeverLogicalZero(*F, CI->getType()); 2841 } 2842 } 2843 2844 if (IsNoNan) { 2845 Value *FRem = B.CreateFRemFMF(CI->getOperand(0), CI->getOperand(1), CI); 2846 if (auto *FRemI = dyn_cast<Instruction>(FRem)) 2847 FRemI->setHasNoNaNs(true); 2848 return FRem; 2849 } 2850 return nullptr; 2851 } 2852 2853 Value *LibCallSimplifier::optimizeTrigInversionPairs(CallInst *CI, 2854 IRBuilderBase &B) { 2855 Module *M = CI->getModule(); 2856 Function *Callee = CI->getCalledFunction(); 2857 Value *Ret = nullptr; 2858 StringRef Name = Callee->getName(); 2859 if (UnsafeFPShrink && 2860 (Name == "tan" || Name == "atanh" || Name == "sinh" || Name == "cosh" || 2861 Name == "asinh") && 2862 hasFloatVersion(M, Name)) 2863 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2864 2865 Value *Op1 = CI->getArgOperand(0); 2866 auto *OpC = dyn_cast<CallInst>(Op1); 2867 if (!OpC) 2868 return Ret; 2869 2870 // Both calls must be 'fast' in order to remove them. 2871 if (!CI->isFast() || !OpC->isFast()) 2872 return Ret; 2873 2874 // tan(atan(x)) -> x 2875 // atanh(tanh(x)) -> x 2876 // sinh(asinh(x)) -> x 2877 // asinh(sinh(x)) -> x 2878 // cosh(acosh(x)) -> x 2879 LibFunc Func; 2880 Function *F = OpC->getCalledFunction(); 2881 if (F && TLI->getLibFunc(F->getName(), Func) && 2882 isLibFuncEmittable(M, TLI, Func)) { 2883 LibFunc inverseFunc = llvm::StringSwitch<LibFunc>(Callee->getName()) 2884 .Case("tan", LibFunc_atan) 2885 .Case("atanh", LibFunc_tanh) 2886 .Case("sinh", LibFunc_asinh) 2887 .Case("cosh", LibFunc_acosh) 2888 .Case("tanf", LibFunc_atanf) 2889 .Case("atanhf", LibFunc_tanhf) 2890 .Case("sinhf", LibFunc_asinhf) 2891 .Case("coshf", LibFunc_acoshf) 2892 .Case("tanl", LibFunc_atanl) 2893 .Case("atanhl", LibFunc_tanhl) 2894 .Case("sinhl", LibFunc_asinhl) 2895 .Case("coshl", LibFunc_acoshl) 2896 .Case("asinh", LibFunc_sinh) 2897 .Case("asinhf", LibFunc_sinhf) 2898 .Case("asinhl", LibFunc_sinhl) 2899 .Default(NumLibFuncs); // Used as error value 2900 if (Func == inverseFunc) 2901 Ret = OpC->getArgOperand(0); 2902 } 2903 return Ret; 2904 } 2905 2906 static bool isTrigLibCall(CallInst *CI) { 2907 // We can only hope to do anything useful if we can ignore things like errno 2908 // and floating-point exceptions. 2909 // We already checked the prototype. 2910 return CI->doesNotThrow() && CI->doesNotAccessMemory(); 2911 } 2912 2913 static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg, 2914 bool UseFloat, Value *&Sin, Value *&Cos, 2915 Value *&SinCos, const TargetLibraryInfo *TLI) { 2916 Module *M = OrigCallee->getParent(); 2917 Type *ArgTy = Arg->getType(); 2918 Type *ResTy; 2919 StringRef Name; 2920 2921 Triple T(OrigCallee->getParent()->getTargetTriple()); 2922 if (UseFloat) { 2923 Name = "__sincospif_stret"; 2924 2925 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 2926 // x86_64 can't use {float, float} since that would be returned in both 2927 // xmm0 and xmm1, which isn't what a real struct would do. 2928 ResTy = T.getArch() == Triple::x86_64 2929 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2)) 2930 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 2931 } else { 2932 Name = "__sincospi_stret"; 2933 ResTy = StructType::get(ArgTy, ArgTy); 2934 } 2935 2936 if (!isLibFuncEmittable(M, TLI, Name)) 2937 return false; 2938 LibFunc TheLibFunc; 2939 TLI->getLibFunc(Name, TheLibFunc); 2940 FunctionCallee Callee = getOrInsertLibFunc( 2941 M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy); 2942 2943 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 2944 // If the argument is an instruction, it must dominate all uses so put our 2945 // sincos call there. 2946 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 2947 } else { 2948 // Otherwise (e.g. for a constant) the beginning of the function is as 2949 // good a place as any. 2950 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 2951 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 2952 } 2953 2954 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 2955 2956 if (SinCos->getType()->isStructTy()) { 2957 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 2958 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 2959 } else { 2960 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 2961 "sinpi"); 2962 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 2963 "cospi"); 2964 } 2965 2966 return true; 2967 } 2968 2969 static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven, 2970 IRBuilderBase &B) { 2971 Value *X; 2972 Value *Src = CI->getArgOperand(0); 2973 2974 if (match(Src, m_OneUse(m_FNeg(m_Value(X))))) { 2975 IRBuilderBase::FastMathFlagGuard Guard(B); 2976 B.setFastMathFlags(CI->getFastMathFlags()); 2977 2978 auto *CallInst = copyFlags(*CI, B.CreateCall(CI->getCalledFunction(), {X})); 2979 if (IsEven) { 2980 // Even function: f(-x) = f(x) 2981 return CallInst; 2982 } 2983 // Odd function: f(-x) = -f(x) 2984 return B.CreateFNeg(CallInst); 2985 } 2986 2987 // Even function: f(abs(x)) = f(x), f(copysign(x, y)) = f(x) 2988 if (IsEven && (match(Src, m_FAbs(m_Value(X))) || 2989 match(Src, m_CopySign(m_Value(X), m_Value())))) { 2990 IRBuilderBase::FastMathFlagGuard Guard(B); 2991 B.setFastMathFlags(CI->getFastMathFlags()); 2992 2993 auto *CallInst = copyFlags(*CI, B.CreateCall(CI->getCalledFunction(), {X})); 2994 return CallInst; 2995 } 2996 2997 return nullptr; 2998 } 2999 3000 Value *LibCallSimplifier::optimizeSymmetric(CallInst *CI, LibFunc Func, 3001 IRBuilderBase &B) { 3002 switch (Func) { 3003 case LibFunc_cos: 3004 case LibFunc_cosf: 3005 case LibFunc_cosl: 3006 return optimizeSymmetricCall(CI, /*IsEven*/ true, B); 3007 3008 case LibFunc_sin: 3009 case LibFunc_sinf: 3010 case LibFunc_sinl: 3011 3012 case LibFunc_tan: 3013 case LibFunc_tanf: 3014 case LibFunc_tanl: 3015 3016 case LibFunc_erf: 3017 case LibFunc_erff: 3018 case LibFunc_erfl: 3019 return optimizeSymmetricCall(CI, /*IsEven*/ false, B); 3020 3021 default: 3022 return nullptr; 3023 } 3024 } 3025 3026 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, bool IsSin, IRBuilderBase &B) { 3027 // Make sure the prototype is as expected, otherwise the rest of the 3028 // function is probably invalid and likely to abort. 3029 if (!isTrigLibCall(CI)) 3030 return nullptr; 3031 3032 Value *Arg = CI->getArgOperand(0); 3033 SmallVector<CallInst *, 1> SinCalls; 3034 SmallVector<CallInst *, 1> CosCalls; 3035 SmallVector<CallInst *, 1> SinCosCalls; 3036 3037 bool IsFloat = Arg->getType()->isFloatTy(); 3038 3039 // Look for all compatible sinpi, cospi and sincospi calls with the same 3040 // argument. If there are enough (in some sense) we can make the 3041 // substitution. 3042 Function *F = CI->getFunction(); 3043 for (User *U : Arg->users()) 3044 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 3045 3046 // It's only worthwhile if both sinpi and cospi are actually used. 3047 if (SinCalls.empty() || CosCalls.empty()) 3048 return nullptr; 3049 3050 Value *Sin, *Cos, *SinCos; 3051 if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, 3052 SinCos, TLI)) 3053 return nullptr; 3054 3055 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 3056 Value *Res) { 3057 for (CallInst *C : Calls) 3058 replaceAllUsesWith(C, Res); 3059 }; 3060 3061 replaceTrigInsts(SinCalls, Sin); 3062 replaceTrigInsts(CosCalls, Cos); 3063 replaceTrigInsts(SinCosCalls, SinCos); 3064 3065 return IsSin ? Sin : Cos; 3066 } 3067 3068 void LibCallSimplifier::classifyArgUse( 3069 Value *Val, Function *F, bool IsFloat, 3070 SmallVectorImpl<CallInst *> &SinCalls, 3071 SmallVectorImpl<CallInst *> &CosCalls, 3072 SmallVectorImpl<CallInst *> &SinCosCalls) { 3073 auto *CI = dyn_cast<CallInst>(Val); 3074 if (!CI || CI->use_empty()) 3075 return; 3076 3077 // Don't consider calls in other functions. 3078 if (CI->getFunction() != F) 3079 return; 3080 3081 Module *M = CI->getModule(); 3082 Function *Callee = CI->getCalledFunction(); 3083 LibFunc Func; 3084 if (!Callee || !TLI->getLibFunc(*Callee, Func) || 3085 !isLibFuncEmittable(M, TLI, Func) || 3086 !isTrigLibCall(CI)) 3087 return; 3088 3089 if (IsFloat) { 3090 if (Func == LibFunc_sinpif) 3091 SinCalls.push_back(CI); 3092 else if (Func == LibFunc_cospif) 3093 CosCalls.push_back(CI); 3094 else if (Func == LibFunc_sincospif_stret) 3095 SinCosCalls.push_back(CI); 3096 } else { 3097 if (Func == LibFunc_sinpi) 3098 SinCalls.push_back(CI); 3099 else if (Func == LibFunc_cospi) 3100 CosCalls.push_back(CI); 3101 else if (Func == LibFunc_sincospi_stret) 3102 SinCosCalls.push_back(CI); 3103 } 3104 } 3105 3106 /// Constant folds remquo 3107 Value *LibCallSimplifier::optimizeRemquo(CallInst *CI, IRBuilderBase &B) { 3108 const APFloat *X, *Y; 3109 if (!match(CI->getArgOperand(0), m_APFloat(X)) || 3110 !match(CI->getArgOperand(1), m_APFloat(Y))) 3111 return nullptr; 3112 3113 APFloat::opStatus Status; 3114 APFloat Quot = *X; 3115 Status = Quot.divide(*Y, APFloat::rmNearestTiesToEven); 3116 if (Status != APFloat::opOK && Status != APFloat::opInexact) 3117 return nullptr; 3118 APFloat Rem = *X; 3119 if (Rem.remainder(*Y) != APFloat::opOK) 3120 return nullptr; 3121 3122 // TODO: We can only keep at least the three of the last bits of x/y 3123 unsigned IntBW = TLI->getIntSize(); 3124 APSInt QuotInt(IntBW, /*isUnsigned=*/false); 3125 bool IsExact; 3126 Status = 3127 Quot.convertToInteger(QuotInt, APFloat::rmNearestTiesToEven, &IsExact); 3128 if (Status != APFloat::opOK && Status != APFloat::opInexact) 3129 return nullptr; 3130 3131 B.CreateAlignedStore( 3132 ConstantInt::get(B.getIntNTy(IntBW), QuotInt.getExtValue()), 3133 CI->getArgOperand(2), CI->getParamAlign(2)); 3134 return ConstantFP::get(CI->getType(), Rem); 3135 } 3136 3137 /// Constant folds fdim 3138 Value *LibCallSimplifier::optimizeFdim(CallInst *CI, IRBuilderBase &B) { 3139 // Cannot perform the fold unless the call has attribute memory(none) 3140 if (!CI->doesNotAccessMemory()) 3141 return nullptr; 3142 3143 // TODO : Handle undef values 3144 // Propagate poison if any 3145 if (isa<PoisonValue>(CI->getArgOperand(0))) 3146 return CI->getArgOperand(0); 3147 if (isa<PoisonValue>(CI->getArgOperand(1))) 3148 return CI->getArgOperand(1); 3149 3150 const APFloat *X, *Y; 3151 // Check if both values are constants 3152 if (!match(CI->getArgOperand(0), m_APFloat(X)) || 3153 !match(CI->getArgOperand(1), m_APFloat(Y))) 3154 return nullptr; 3155 3156 APFloat Difference = *X; 3157 Difference.subtract(*Y, RoundingMode::NearestTiesToEven); 3158 3159 APFloat MaxVal = 3160 maximum(Difference, APFloat::getZero(CI->getType()->getFltSemantics())); 3161 return ConstantFP::get(CI->getType(), MaxVal); 3162 } 3163 3164 //===----------------------------------------------------------------------===// 3165 // Integer Library Call Optimizations 3166 //===----------------------------------------------------------------------===// 3167 3168 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) { 3169 // All variants of ffs return int which need not be 32 bits wide. 3170 // ffs{,l,ll}(x) -> x != 0 ? (int)llvm.cttz(x)+1 : 0 3171 Type *RetType = CI->getType(); 3172 Value *Op = CI->getArgOperand(0); 3173 Type *ArgType = Op->getType(); 3174 Value *V = B.CreateIntrinsic(Intrinsic::cttz, {ArgType}, {Op, B.getTrue()}, 3175 nullptr, "cttz"); 3176 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 3177 V = B.CreateIntCast(V, RetType, false); 3178 3179 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 3180 return B.CreateSelect(Cond, V, ConstantInt::get(RetType, 0)); 3181 } 3182 3183 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) { 3184 // All variants of fls return int which need not be 32 bits wide. 3185 // fls{,l,ll}(x) -> (int)(sizeInBits(x) - llvm.ctlz(x, false)) 3186 Value *Op = CI->getArgOperand(0); 3187 Type *ArgType = Op->getType(); 3188 Value *V = B.CreateIntrinsic(Intrinsic::ctlz, {ArgType}, {Op, B.getFalse()}, 3189 nullptr, "ctlz"); 3190 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 3191 V); 3192 return B.CreateIntCast(V, CI->getType(), false); 3193 } 3194 3195 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) { 3196 // abs(x) -> x <s 0 ? -x : x 3197 // The negation has 'nsw' because abs of INT_MIN is undefined. 3198 Value *X = CI->getArgOperand(0); 3199 Value *IsNeg = B.CreateIsNeg(X); 3200 Value *NegX = B.CreateNSWNeg(X, "neg"); 3201 return B.CreateSelect(IsNeg, NegX, X); 3202 } 3203 3204 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) { 3205 // isdigit(c) -> (c-'0') <u 10 3206 Value *Op = CI->getArgOperand(0); 3207 Type *ArgType = Op->getType(); 3208 Op = B.CreateSub(Op, ConstantInt::get(ArgType, '0'), "isdigittmp"); 3209 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 10), "isdigit"); 3210 return B.CreateZExt(Op, CI->getType()); 3211 } 3212 3213 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) { 3214 // isascii(c) -> c <u 128 3215 Value *Op = CI->getArgOperand(0); 3216 Type *ArgType = Op->getType(); 3217 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 128), "isascii"); 3218 return B.CreateZExt(Op, CI->getType()); 3219 } 3220 3221 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) { 3222 // toascii(c) -> c & 0x7f 3223 return B.CreateAnd(CI->getArgOperand(0), 3224 ConstantInt::get(CI->getType(), 0x7F)); 3225 } 3226 3227 // Fold calls to atoi, atol, and atoll. 3228 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) { 3229 CI->addParamAttr(0, Attribute::NoCapture); 3230 3231 StringRef Str; 3232 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 3233 return nullptr; 3234 3235 return convertStrToInt(CI, Str, nullptr, 10, /*AsSigned=*/true, B); 3236 } 3237 3238 // Fold calls to strtol, strtoll, strtoul, and strtoull. 3239 Value *LibCallSimplifier::optimizeStrToInt(CallInst *CI, IRBuilderBase &B, 3240 bool AsSigned) { 3241 Value *EndPtr = CI->getArgOperand(1); 3242 if (isa<ConstantPointerNull>(EndPtr)) { 3243 // With a null EndPtr, this function won't capture the main argument. 3244 // It would be readonly too, except that it still may write to errno. 3245 CI->addParamAttr(0, Attribute::NoCapture); 3246 EndPtr = nullptr; 3247 } else if (!isKnownNonZero(EndPtr, DL)) 3248 return nullptr; 3249 3250 StringRef Str; 3251 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 3252 return nullptr; 3253 3254 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) { 3255 return convertStrToInt(CI, Str, EndPtr, CInt->getSExtValue(), AsSigned, B); 3256 } 3257 3258 return nullptr; 3259 } 3260 3261 //===----------------------------------------------------------------------===// 3262 // Formatting and IO Library Call Optimizations 3263 //===----------------------------------------------------------------------===// 3264 3265 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 3266 3267 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B, 3268 int StreamArg) { 3269 Function *Callee = CI->getCalledFunction(); 3270 // Error reporting calls should be cold, mark them as such. 3271 // This applies even to non-builtin calls: it is only a hint and applies to 3272 // functions that the frontend might not understand as builtins. 3273 3274 // This heuristic was suggested in: 3275 // Improving Static Branch Prediction in a Compiler 3276 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 3277 // Proceedings of PACT'98, Oct. 1998, IEEE 3278 if (!CI->hasFnAttr(Attribute::Cold) && 3279 isReportingError(Callee, CI, StreamArg)) { 3280 CI->addFnAttr(Attribute::Cold); 3281 } 3282 3283 return nullptr; 3284 } 3285 3286 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 3287 if (!Callee || !Callee->isDeclaration()) 3288 return false; 3289 3290 if (StreamArg < 0) 3291 return true; 3292 3293 // These functions might be considered cold, but only if their stream 3294 // argument is stderr. 3295 3296 if (StreamArg >= (int)CI->arg_size()) 3297 return false; 3298 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 3299 if (!LI) 3300 return false; 3301 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 3302 if (!GV || !GV->isDeclaration()) 3303 return false; 3304 return GV->getName() == "stderr"; 3305 } 3306 3307 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) { 3308 // Check for a fixed format string. 3309 StringRef FormatStr; 3310 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 3311 return nullptr; 3312 3313 // Empty format string -> noop. 3314 if (FormatStr.empty()) // Tolerate printf's declared void. 3315 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 3316 3317 // Do not do any of the following transformations if the printf return value 3318 // is used, in general the printf return value is not compatible with either 3319 // putchar() or puts(). 3320 if (!CI->use_empty()) 3321 return nullptr; 3322 3323 Type *IntTy = CI->getType(); 3324 // printf("x") -> putchar('x'), even for "%" and "%%". 3325 if (FormatStr.size() == 1 || FormatStr == "%%") { 3326 // Convert the character to unsigned char before passing it to putchar 3327 // to avoid host-specific sign extension in the IR. Putchar converts 3328 // it to unsigned char regardless. 3329 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)FormatStr[0]); 3330 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3331 } 3332 3333 // Try to remove call or emit putchar/puts. 3334 if (FormatStr == "%s" && CI->arg_size() > 1) { 3335 StringRef OperandStr; 3336 if (!getConstantStringInfo(CI->getOperand(1), OperandStr)) 3337 return nullptr; 3338 // printf("%s", "") --> NOP 3339 if (OperandStr.empty()) 3340 return (Value *)CI; 3341 // printf("%s", "a") --> putchar('a') 3342 if (OperandStr.size() == 1) { 3343 // Convert the character to unsigned char before passing it to putchar 3344 // to avoid host-specific sign extension in the IR. Putchar converts 3345 // it to unsigned char regardless. 3346 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)OperandStr[0]); 3347 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3348 } 3349 // printf("%s", str"\n") --> puts(str) 3350 if (OperandStr.back() == '\n') { 3351 OperandStr = OperandStr.drop_back(); 3352 Value *GV = B.CreateGlobalString(OperandStr, "str", 3353 DL.getDefaultGlobalsAddressSpace()); 3354 return copyFlags(*CI, emitPutS(GV, B, TLI)); 3355 } 3356 return nullptr; 3357 } 3358 3359 // printf("foo\n") --> puts("foo") 3360 if (FormatStr.back() == '\n' && 3361 !FormatStr.contains('%')) { // No format characters. 3362 // Create a string literal with no \n on it. We expect the constant merge 3363 // pass to be run after this pass, to merge duplicate strings. 3364 FormatStr = FormatStr.drop_back(); 3365 Value *GV = B.CreateGlobalString(FormatStr, "str", 3366 DL.getDefaultGlobalsAddressSpace()); 3367 return copyFlags(*CI, emitPutS(GV, B, TLI)); 3368 } 3369 3370 // Optimize specific format strings. 3371 // printf("%c", chr) --> putchar(chr) 3372 if (FormatStr == "%c" && CI->arg_size() > 1 && 3373 CI->getArgOperand(1)->getType()->isIntegerTy()) { 3374 // Convert the argument to the type expected by putchar, i.e., int, which 3375 // need not be 32 bits wide but which is the same as printf's return type. 3376 Value *IntChar = B.CreateIntCast(CI->getArgOperand(1), IntTy, false); 3377 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3378 } 3379 3380 // printf("%s\n", str) --> puts(str) 3381 if (FormatStr == "%s\n" && CI->arg_size() > 1 && 3382 CI->getArgOperand(1)->getType()->isPointerTy()) 3383 return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI)); 3384 return nullptr; 3385 } 3386 3387 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) { 3388 3389 Module *M = CI->getModule(); 3390 Function *Callee = CI->getCalledFunction(); 3391 FunctionType *FT = Callee->getFunctionType(); 3392 if (Value *V = optimizePrintFString(CI, B)) { 3393 return V; 3394 } 3395 3396 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3397 3398 // printf(format, ...) -> iprintf(format, ...) if no floating point 3399 // arguments. 3400 if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) && 3401 !callHasFloatingPointArgument(CI)) { 3402 FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT, 3403 Callee->getAttributes()); 3404 CallInst *New = cast<CallInst>(CI->clone()); 3405 New->setCalledFunction(IPrintFFn); 3406 B.Insert(New); 3407 return New; 3408 } 3409 3410 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point 3411 // arguments. 3412 if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) && 3413 !callHasFP128Argument(CI)) { 3414 auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT, 3415 Callee->getAttributes()); 3416 CallInst *New = cast<CallInst>(CI->clone()); 3417 New->setCalledFunction(SmallPrintFFn); 3418 B.Insert(New); 3419 return New; 3420 } 3421 3422 return nullptr; 3423 } 3424 3425 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, 3426 IRBuilderBase &B) { 3427 // Check for a fixed format string. 3428 StringRef FormatStr; 3429 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 3430 return nullptr; 3431 3432 // If we just have a format string (nothing else crazy) transform it. 3433 Value *Dest = CI->getArgOperand(0); 3434 if (CI->arg_size() == 2) { 3435 // Make sure there's no % in the constant array. We could try to handle 3436 // %% -> % in the future if we cared. 3437 if (FormatStr.contains('%')) 3438 return nullptr; // we found a format specifier, bail out. 3439 3440 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1) 3441 B.CreateMemCpy( 3442 Dest, Align(1), CI->getArgOperand(1), Align(1), 3443 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 3444 FormatStr.size() + 1)); // Copy the null byte. 3445 return ConstantInt::get(CI->getType(), FormatStr.size()); 3446 } 3447 3448 // The remaining optimizations require the format string to be "%s" or "%c" 3449 // and have an extra operand. 3450 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 3451 return nullptr; 3452 3453 // Decode the second character of the format string. 3454 if (FormatStr[1] == 'c') { 3455 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 3456 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 3457 return nullptr; 3458 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 3459 Value *Ptr = Dest; 3460 B.CreateStore(V, Ptr); 3461 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 3462 B.CreateStore(B.getInt8(0), Ptr); 3463 3464 return ConstantInt::get(CI->getType(), 1); 3465 } 3466 3467 if (FormatStr[1] == 's') { 3468 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str, 3469 // strlen(str)+1) 3470 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 3471 return nullptr; 3472 3473 if (CI->use_empty()) 3474 // sprintf(dest, "%s", str) -> strcpy(dest, str) 3475 return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI)); 3476 3477 uint64_t SrcLen = GetStringLength(CI->getArgOperand(2)); 3478 if (SrcLen) { 3479 B.CreateMemCpy( 3480 Dest, Align(1), CI->getArgOperand(2), Align(1), 3481 ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen)); 3482 // Returns total number of characters written without null-character. 3483 return ConstantInt::get(CI->getType(), SrcLen - 1); 3484 } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) { 3485 // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest 3486 Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest); 3487 return B.CreateIntCast(PtrDiff, CI->getType(), false); 3488 } 3489 3490 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 3491 PGSOQueryType::IRPass)) 3492 return nullptr; 3493 3494 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 3495 if (!Len) 3496 return nullptr; 3497 Value *IncLen = 3498 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 3499 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen); 3500 3501 // The sprintf result is the unincremented number of bytes in the string. 3502 return B.CreateIntCast(Len, CI->getType(), false); 3503 } 3504 return nullptr; 3505 } 3506 3507 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) { 3508 Module *M = CI->getModule(); 3509 Function *Callee = CI->getCalledFunction(); 3510 FunctionType *FT = Callee->getFunctionType(); 3511 if (Value *V = optimizeSPrintFString(CI, B)) { 3512 return V; 3513 } 3514 3515 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 3516 3517 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 3518 // point arguments. 3519 if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) && 3520 !callHasFloatingPointArgument(CI)) { 3521 FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf, 3522 FT, Callee->getAttributes()); 3523 CallInst *New = cast<CallInst>(CI->clone()); 3524 New->setCalledFunction(SIPrintFFn); 3525 B.Insert(New); 3526 return New; 3527 } 3528 3529 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit 3530 // floating point arguments. 3531 if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) && 3532 !callHasFP128Argument(CI)) { 3533 auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT, 3534 Callee->getAttributes()); 3535 CallInst *New = cast<CallInst>(CI->clone()); 3536 New->setCalledFunction(SmallSPrintFFn); 3537 B.Insert(New); 3538 return New; 3539 } 3540 3541 return nullptr; 3542 } 3543 3544 // Transform an snprintf call CI with the bound N to format the string Str 3545 // either to a call to memcpy, or to single character a store, or to nothing, 3546 // and fold the result to a constant. A nonnull StrArg refers to the string 3547 // argument being formatted. Otherwise the call is one with N < 2 and 3548 // the "%c" directive to format a single character. 3549 Value *LibCallSimplifier::emitSnPrintfMemCpy(CallInst *CI, Value *StrArg, 3550 StringRef Str, uint64_t N, 3551 IRBuilderBase &B) { 3552 assert(StrArg || (N < 2 && Str.size() == 1)); 3553 3554 unsigned IntBits = TLI->getIntSize(); 3555 uint64_t IntMax = maxIntN(IntBits); 3556 if (Str.size() > IntMax) 3557 // Bail if the string is longer than INT_MAX. POSIX requires 3558 // implementations to set errno to EOVERFLOW in this case, in 3559 // addition to when N is larger than that (checked by the caller). 3560 return nullptr; 3561 3562 Value *StrLen = ConstantInt::get(CI->getType(), Str.size()); 3563 if (N == 0) 3564 return StrLen; 3565 3566 // Set to the number of bytes to copy fron StrArg which is also 3567 // the offset of the terinating nul. 3568 uint64_t NCopy; 3569 if (N > Str.size()) 3570 // Copy the full string, including the terminating nul (which must 3571 // be present regardless of the bound). 3572 NCopy = Str.size() + 1; 3573 else 3574 NCopy = N - 1; 3575 3576 Value *DstArg = CI->getArgOperand(0); 3577 if (NCopy && StrArg) 3578 // Transform the call to lvm.memcpy(dst, fmt, N). 3579 copyFlags( 3580 *CI, 3581 B.CreateMemCpy( 3582 DstArg, Align(1), StrArg, Align(1), 3583 ConstantInt::get(DL.getIntPtrType(CI->getContext()), NCopy))); 3584 3585 if (N > Str.size()) 3586 // Return early when the whole format string, including the final nul, 3587 // has been copied. 3588 return StrLen; 3589 3590 // Otherwise, when truncating the string append a terminating nul. 3591 Type *Int8Ty = B.getInt8Ty(); 3592 Value *NulOff = B.getIntN(IntBits, NCopy); 3593 Value *DstEnd = B.CreateInBoundsGEP(Int8Ty, DstArg, NulOff, "endptr"); 3594 B.CreateStore(ConstantInt::get(Int8Ty, 0), DstEnd); 3595 return StrLen; 3596 } 3597 3598 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, 3599 IRBuilderBase &B) { 3600 // Check for size 3601 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 3602 if (!Size) 3603 return nullptr; 3604 3605 uint64_t N = Size->getZExtValue(); 3606 uint64_t IntMax = maxIntN(TLI->getIntSize()); 3607 if (N > IntMax) 3608 // Bail if the bound exceeds INT_MAX. POSIX requires implementations 3609 // to set errno to EOVERFLOW in this case. 3610 return nullptr; 3611 3612 Value *DstArg = CI->getArgOperand(0); 3613 Value *FmtArg = CI->getArgOperand(2); 3614 3615 // Check for a fixed format string. 3616 StringRef FormatStr; 3617 if (!getConstantStringInfo(FmtArg, FormatStr)) 3618 return nullptr; 3619 3620 // If we just have a format string (nothing else crazy) transform it. 3621 if (CI->arg_size() == 3) { 3622 if (FormatStr.contains('%')) 3623 // Bail if the format string contains a directive and there are 3624 // no arguments. We could handle "%%" in the future. 3625 return nullptr; 3626 3627 return emitSnPrintfMemCpy(CI, FmtArg, FormatStr, N, B); 3628 } 3629 3630 // The remaining optimizations require the format string to be "%s" or "%c" 3631 // and have an extra operand. 3632 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() != 4) 3633 return nullptr; 3634 3635 // Decode the second character of the format string. 3636 if (FormatStr[1] == 'c') { 3637 if (N <= 1) { 3638 // Use an arbitary string of length 1 to transform the call into 3639 // either a nul store (N == 1) or a no-op (N == 0) and fold it 3640 // to one. 3641 StringRef CharStr("*"); 3642 return emitSnPrintfMemCpy(CI, nullptr, CharStr, N, B); 3643 } 3644 3645 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 3646 if (!CI->getArgOperand(3)->getType()->isIntegerTy()) 3647 return nullptr; 3648 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char"); 3649 Value *Ptr = DstArg; 3650 B.CreateStore(V, Ptr); 3651 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 3652 B.CreateStore(B.getInt8(0), Ptr); 3653 return ConstantInt::get(CI->getType(), 1); 3654 } 3655 3656 if (FormatStr[1] != 's') 3657 return nullptr; 3658 3659 Value *StrArg = CI->getArgOperand(3); 3660 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1) 3661 StringRef Str; 3662 if (!getConstantStringInfo(StrArg, Str)) 3663 return nullptr; 3664 3665 return emitSnPrintfMemCpy(CI, StrArg, Str, N, B); 3666 } 3667 3668 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) { 3669 if (Value *V = optimizeSnPrintFString(CI, B)) { 3670 return V; 3671 } 3672 3673 if (isKnownNonZero(CI->getOperand(1), DL)) 3674 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3675 return nullptr; 3676 } 3677 3678 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, 3679 IRBuilderBase &B) { 3680 optimizeErrorReporting(CI, B, 0); 3681 3682 // All the optimizations depend on the format string. 3683 StringRef FormatStr; 3684 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 3685 return nullptr; 3686 3687 // Do not do any of the following transformations if the fprintf return 3688 // value is used, in general the fprintf return value is not compatible 3689 // with fwrite(), fputc() or fputs(). 3690 if (!CI->use_empty()) 3691 return nullptr; 3692 3693 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 3694 if (CI->arg_size() == 2) { 3695 // Could handle %% -> % if we cared. 3696 if (FormatStr.contains('%')) 3697 return nullptr; // We found a format specifier. 3698 3699 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 3700 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 3701 return copyFlags( 3702 *CI, emitFWrite(CI->getArgOperand(1), 3703 ConstantInt::get(SizeTTy, FormatStr.size()), 3704 CI->getArgOperand(0), B, DL, TLI)); 3705 } 3706 3707 // The remaining optimizations require the format string to be "%s" or "%c" 3708 // and have an extra operand. 3709 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 3710 return nullptr; 3711 3712 // Decode the second character of the format string. 3713 if (FormatStr[1] == 'c') { 3714 // fprintf(F, "%c", chr) --> fputc((int)chr, F) 3715 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 3716 return nullptr; 3717 Type *IntTy = B.getIntNTy(TLI->getIntSize()); 3718 Value *V = B.CreateIntCast(CI->getArgOperand(2), IntTy, /*isSigned*/ true, 3719 "chari"); 3720 return copyFlags(*CI, emitFPutC(V, CI->getArgOperand(0), B, TLI)); 3721 } 3722 3723 if (FormatStr[1] == 's') { 3724 // fprintf(F, "%s", str) --> fputs(str, F) 3725 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 3726 return nullptr; 3727 return copyFlags( 3728 *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI)); 3729 } 3730 return nullptr; 3731 } 3732 3733 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) { 3734 Module *M = CI->getModule(); 3735 Function *Callee = CI->getCalledFunction(); 3736 FunctionType *FT = Callee->getFunctionType(); 3737 if (Value *V = optimizeFPrintFString(CI, B)) { 3738 return V; 3739 } 3740 3741 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 3742 // floating point arguments. 3743 if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) && 3744 !callHasFloatingPointArgument(CI)) { 3745 FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf, 3746 FT, Callee->getAttributes()); 3747 CallInst *New = cast<CallInst>(CI->clone()); 3748 New->setCalledFunction(FIPrintFFn); 3749 B.Insert(New); 3750 return New; 3751 } 3752 3753 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no 3754 // 128-bit floating point arguments. 3755 if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) && 3756 !callHasFP128Argument(CI)) { 3757 auto SmallFPrintFFn = 3758 getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT, 3759 Callee->getAttributes()); 3760 CallInst *New = cast<CallInst>(CI->clone()); 3761 New->setCalledFunction(SmallFPrintFFn); 3762 B.Insert(New); 3763 return New; 3764 } 3765 3766 return nullptr; 3767 } 3768 3769 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) { 3770 optimizeErrorReporting(CI, B, 3); 3771 3772 // Get the element size and count. 3773 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 3774 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 3775 if (SizeC && CountC) { 3776 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 3777 3778 // If this is writing zero records, remove the call (it's a noop). 3779 if (Bytes == 0) 3780 return ConstantInt::get(CI->getType(), 0); 3781 3782 // If this is writing one byte, turn it into fputc. 3783 // This optimisation is only valid, if the return value is unused. 3784 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 3785 Value *Char = B.CreateLoad(B.getInt8Ty(), CI->getArgOperand(0), "char"); 3786 Type *IntTy = B.getIntNTy(TLI->getIntSize()); 3787 Value *Cast = B.CreateIntCast(Char, IntTy, /*isSigned*/ true, "chari"); 3788 Value *NewCI = emitFPutC(Cast, CI->getArgOperand(3), B, TLI); 3789 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 3790 } 3791 } 3792 3793 return nullptr; 3794 } 3795 3796 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) { 3797 optimizeErrorReporting(CI, B, 1); 3798 3799 // Don't rewrite fputs to fwrite when optimising for size because fwrite 3800 // requires more arguments and thus extra MOVs are required. 3801 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 3802 PGSOQueryType::IRPass)) 3803 return nullptr; 3804 3805 // We can't optimize if return value is used. 3806 if (!CI->use_empty()) 3807 return nullptr; 3808 3809 // fputs(s,F) --> fwrite(s,strlen(s),1,F) 3810 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 3811 if (!Len) 3812 return nullptr; 3813 3814 // Known to have no uses (see above). 3815 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 3816 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 3817 return copyFlags( 3818 *CI, 3819 emitFWrite(CI->getArgOperand(0), 3820 ConstantInt::get(SizeTTy, Len - 1), 3821 CI->getArgOperand(1), B, DL, TLI)); 3822 } 3823 3824 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) { 3825 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3826 if (!CI->use_empty()) 3827 return nullptr; 3828 3829 // Check for a constant string. 3830 // puts("") -> putchar('\n') 3831 StringRef Str; 3832 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) { 3833 // putchar takes an argument of the same type as puts returns, i.e., 3834 // int, which need not be 32 bits wide. 3835 Type *IntTy = CI->getType(); 3836 return copyFlags(*CI, emitPutChar(ConstantInt::get(IntTy, '\n'), B, TLI)); 3837 } 3838 3839 return nullptr; 3840 } 3841 3842 Value *LibCallSimplifier::optimizeExit(CallInst *CI) { 3843 3844 // Mark 'exit' as cold if its not exit(0) (success). 3845 const APInt *C; 3846 if (!CI->hasFnAttr(Attribute::Cold) && 3847 match(CI->getArgOperand(0), m_APInt(C)) && !C->isZero()) { 3848 CI->addFnAttr(Attribute::Cold); 3849 } 3850 return nullptr; 3851 } 3852 3853 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) { 3854 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n) 3855 return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1), 3856 CI->getArgOperand(0), Align(1), 3857 CI->getArgOperand(2))); 3858 } 3859 3860 bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) { 3861 SmallString<20> FloatFuncName = FuncName; 3862 FloatFuncName += 'f'; 3863 return isLibFuncEmittable(M, TLI, FloatFuncName); 3864 } 3865 3866 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 3867 IRBuilderBase &Builder) { 3868 Module *M = CI->getModule(); 3869 LibFunc Func; 3870 Function *Callee = CI->getCalledFunction(); 3871 3872 // Check for string/memory library functions. 3873 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 3874 // Make sure we never change the calling convention. 3875 assert( 3876 (ignoreCallingConv(Func) || 3877 TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) && 3878 "Optimizing string/memory libcall would change the calling convention"); 3879 switch (Func) { 3880 case LibFunc_strcat: 3881 return optimizeStrCat(CI, Builder); 3882 case LibFunc_strncat: 3883 return optimizeStrNCat(CI, Builder); 3884 case LibFunc_strchr: 3885 return optimizeStrChr(CI, Builder); 3886 case LibFunc_strrchr: 3887 return optimizeStrRChr(CI, Builder); 3888 case LibFunc_strcmp: 3889 return optimizeStrCmp(CI, Builder); 3890 case LibFunc_strncmp: 3891 return optimizeStrNCmp(CI, Builder); 3892 case LibFunc_strcpy: 3893 return optimizeStrCpy(CI, Builder); 3894 case LibFunc_stpcpy: 3895 return optimizeStpCpy(CI, Builder); 3896 case LibFunc_strlcpy: 3897 return optimizeStrLCpy(CI, Builder); 3898 case LibFunc_stpncpy: 3899 return optimizeStringNCpy(CI, /*RetEnd=*/true, Builder); 3900 case LibFunc_strncpy: 3901 return optimizeStringNCpy(CI, /*RetEnd=*/false, Builder); 3902 case LibFunc_strlen: 3903 return optimizeStrLen(CI, Builder); 3904 case LibFunc_strnlen: 3905 return optimizeStrNLen(CI, Builder); 3906 case LibFunc_strpbrk: 3907 return optimizeStrPBrk(CI, Builder); 3908 case LibFunc_strndup: 3909 return optimizeStrNDup(CI, Builder); 3910 case LibFunc_strtol: 3911 case LibFunc_strtod: 3912 case LibFunc_strtof: 3913 case LibFunc_strtoul: 3914 case LibFunc_strtoll: 3915 case LibFunc_strtold: 3916 case LibFunc_strtoull: 3917 return optimizeStrTo(CI, Builder); 3918 case LibFunc_strspn: 3919 return optimizeStrSpn(CI, Builder); 3920 case LibFunc_strcspn: 3921 return optimizeStrCSpn(CI, Builder); 3922 case LibFunc_strstr: 3923 return optimizeStrStr(CI, Builder); 3924 case LibFunc_memchr: 3925 return optimizeMemChr(CI, Builder); 3926 case LibFunc_memrchr: 3927 return optimizeMemRChr(CI, Builder); 3928 case LibFunc_bcmp: 3929 return optimizeBCmp(CI, Builder); 3930 case LibFunc_memcmp: 3931 return optimizeMemCmp(CI, Builder); 3932 case LibFunc_memcpy: 3933 return optimizeMemCpy(CI, Builder); 3934 case LibFunc_memccpy: 3935 return optimizeMemCCpy(CI, Builder); 3936 case LibFunc_mempcpy: 3937 return optimizeMemPCpy(CI, Builder); 3938 case LibFunc_memmove: 3939 return optimizeMemMove(CI, Builder); 3940 case LibFunc_memset: 3941 return optimizeMemSet(CI, Builder); 3942 case LibFunc_realloc: 3943 return optimizeRealloc(CI, Builder); 3944 case LibFunc_wcslen: 3945 return optimizeWcslen(CI, Builder); 3946 case LibFunc_bcopy: 3947 return optimizeBCopy(CI, Builder); 3948 case LibFunc_Znwm: 3949 case LibFunc_ZnwmRKSt9nothrow_t: 3950 case LibFunc_ZnwmSt11align_val_t: 3951 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t: 3952 case LibFunc_Znam: 3953 case LibFunc_ZnamRKSt9nothrow_t: 3954 case LibFunc_ZnamSt11align_val_t: 3955 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t: 3956 case LibFunc_Znwm12__hot_cold_t: 3957 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t: 3958 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t: 3959 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 3960 case LibFunc_Znam12__hot_cold_t: 3961 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t: 3962 case LibFunc_ZnamSt11align_val_t12__hot_cold_t: 3963 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 3964 case LibFunc_size_returning_new: 3965 case LibFunc_size_returning_new_hot_cold: 3966 case LibFunc_size_returning_new_aligned: 3967 case LibFunc_size_returning_new_aligned_hot_cold: 3968 return optimizeNew(CI, Builder, Func); 3969 default: 3970 break; 3971 } 3972 } 3973 return nullptr; 3974 } 3975 3976 /// Constant folding nan/nanf/nanl. 3977 static Value *optimizeNaN(CallInst *CI) { 3978 StringRef CharSeq; 3979 if (!getConstantStringInfo(CI->getArgOperand(0), CharSeq)) 3980 return nullptr; 3981 3982 APInt Fill; 3983 // Treat empty strings as if they were zero. 3984 if (CharSeq.empty()) 3985 Fill = APInt(32, 0); 3986 else if (CharSeq.getAsInteger(0, Fill)) 3987 return nullptr; 3988 3989 return ConstantFP::getQNaN(CI->getType(), /*Negative=*/false, &Fill); 3990 } 3991 3992 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 3993 LibFunc Func, 3994 IRBuilderBase &Builder) { 3995 const Module *M = CI->getModule(); 3996 3997 // Don't optimize calls that require strict floating point semantics. 3998 if (CI->isStrictFP()) 3999 return nullptr; 4000 4001 if (Value *V = optimizeSymmetric(CI, Func, Builder)) 4002 return V; 4003 4004 switch (Func) { 4005 case LibFunc_sinpif: 4006 case LibFunc_sinpi: 4007 return optimizeSinCosPi(CI, /*IsSin*/true, Builder); 4008 case LibFunc_cospif: 4009 case LibFunc_cospi: 4010 return optimizeSinCosPi(CI, /*IsSin*/false, Builder); 4011 case LibFunc_powf: 4012 case LibFunc_pow: 4013 case LibFunc_powl: 4014 return optimizePow(CI, Builder); 4015 case LibFunc_exp2l: 4016 case LibFunc_exp2: 4017 case LibFunc_exp2f: 4018 return optimizeExp2(CI, Builder); 4019 case LibFunc_fabsf: 4020 case LibFunc_fabs: 4021 case LibFunc_fabsl: 4022 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 4023 case LibFunc_sqrtf: 4024 case LibFunc_sqrt: 4025 case LibFunc_sqrtl: 4026 return optimizeSqrt(CI, Builder); 4027 case LibFunc_fmod: 4028 case LibFunc_fmodf: 4029 case LibFunc_fmodl: 4030 return optimizeFMod(CI, Builder); 4031 case LibFunc_logf: 4032 case LibFunc_log: 4033 case LibFunc_logl: 4034 case LibFunc_log10f: 4035 case LibFunc_log10: 4036 case LibFunc_log10l: 4037 case LibFunc_log1pf: 4038 case LibFunc_log1p: 4039 case LibFunc_log1pl: 4040 case LibFunc_log2f: 4041 case LibFunc_log2: 4042 case LibFunc_log2l: 4043 case LibFunc_logbf: 4044 case LibFunc_logb: 4045 case LibFunc_logbl: 4046 return optimizeLog(CI, Builder); 4047 case LibFunc_tan: 4048 case LibFunc_tanf: 4049 case LibFunc_tanl: 4050 case LibFunc_sinh: 4051 case LibFunc_sinhf: 4052 case LibFunc_sinhl: 4053 case LibFunc_asinh: 4054 case LibFunc_asinhf: 4055 case LibFunc_asinhl: 4056 case LibFunc_cosh: 4057 case LibFunc_coshf: 4058 case LibFunc_coshl: 4059 case LibFunc_atanh: 4060 case LibFunc_atanhf: 4061 case LibFunc_atanhl: 4062 return optimizeTrigInversionPairs(CI, Builder); 4063 case LibFunc_ceil: 4064 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 4065 case LibFunc_floor: 4066 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 4067 case LibFunc_round: 4068 return replaceUnaryCall(CI, Builder, Intrinsic::round); 4069 case LibFunc_roundeven: 4070 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven); 4071 case LibFunc_nearbyint: 4072 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 4073 case LibFunc_rint: 4074 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 4075 case LibFunc_trunc: 4076 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 4077 case LibFunc_acos: 4078 case LibFunc_acosh: 4079 case LibFunc_asin: 4080 case LibFunc_atan: 4081 case LibFunc_cbrt: 4082 case LibFunc_exp: 4083 case LibFunc_exp10: 4084 case LibFunc_expm1: 4085 case LibFunc_cos: 4086 case LibFunc_sin: 4087 case LibFunc_tanh: 4088 if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName())) 4089 return optimizeUnaryDoubleFP(CI, Builder, TLI, true); 4090 return nullptr; 4091 case LibFunc_copysign: 4092 if (hasFloatVersion(M, CI->getCalledFunction()->getName())) 4093 return optimizeBinaryDoubleFP(CI, Builder, TLI); 4094 return nullptr; 4095 case LibFunc_fdim: 4096 case LibFunc_fdimf: 4097 case LibFunc_fdiml: 4098 return optimizeFdim(CI, Builder); 4099 case LibFunc_fminf: 4100 case LibFunc_fmin: 4101 case LibFunc_fminl: 4102 case LibFunc_fmaxf: 4103 case LibFunc_fmax: 4104 case LibFunc_fmaxl: 4105 return optimizeFMinFMax(CI, Builder); 4106 case LibFunc_cabs: 4107 case LibFunc_cabsf: 4108 case LibFunc_cabsl: 4109 return optimizeCAbs(CI, Builder); 4110 case LibFunc_remquo: 4111 case LibFunc_remquof: 4112 case LibFunc_remquol: 4113 return optimizeRemquo(CI, Builder); 4114 case LibFunc_nan: 4115 case LibFunc_nanf: 4116 case LibFunc_nanl: 4117 return optimizeNaN(CI); 4118 default: 4119 return nullptr; 4120 } 4121 } 4122 4123 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) { 4124 Module *M = CI->getModule(); 4125 assert(!CI->isMustTailCall() && "These transforms aren't musttail safe."); 4126 4127 // TODO: Split out the code below that operates on FP calls so that 4128 // we can all non-FP calls with the StrictFP attribute to be 4129 // optimized. 4130 if (CI->isNoBuiltin()) 4131 return nullptr; 4132 4133 LibFunc Func; 4134 Function *Callee = CI->getCalledFunction(); 4135 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 4136 4137 SmallVector<OperandBundleDef, 2> OpBundles; 4138 CI->getOperandBundlesAsDefs(OpBundles); 4139 4140 IRBuilderBase::OperandBundlesGuard Guard(Builder); 4141 Builder.setDefaultOperandBundles(OpBundles); 4142 4143 // Command-line parameter overrides instruction attribute. 4144 // This can't be moved to optimizeFloatingPointLibCall() because it may be 4145 // used by the intrinsic optimizations. 4146 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 4147 UnsafeFPShrink = EnableUnsafeFPShrink; 4148 else if (isa<FPMathOperator>(CI) && CI->isFast()) 4149 UnsafeFPShrink = true; 4150 4151 // First, check for intrinsics. 4152 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 4153 if (!IsCallingConvC) 4154 return nullptr; 4155 // The FP intrinsics have corresponding constrained versions so we don't 4156 // need to check for the StrictFP attribute here. 4157 switch (II->getIntrinsicID()) { 4158 case Intrinsic::pow: 4159 return optimizePow(CI, Builder); 4160 case Intrinsic::exp2: 4161 return optimizeExp2(CI, Builder); 4162 case Intrinsic::log: 4163 case Intrinsic::log2: 4164 case Intrinsic::log10: 4165 return optimizeLog(CI, Builder); 4166 case Intrinsic::sqrt: 4167 return optimizeSqrt(CI, Builder); 4168 case Intrinsic::memset: 4169 return optimizeMemSet(CI, Builder); 4170 case Intrinsic::memcpy: 4171 return optimizeMemCpy(CI, Builder); 4172 case Intrinsic::memmove: 4173 return optimizeMemMove(CI, Builder); 4174 default: 4175 return nullptr; 4176 } 4177 } 4178 4179 // Also try to simplify calls to fortified library functions. 4180 if (Value *SimplifiedFortifiedCI = 4181 FortifiedSimplifier.optimizeCall(CI, Builder)) 4182 return SimplifiedFortifiedCI; 4183 4184 // Then check for known library functions. 4185 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 4186 // We never change the calling convention. 4187 if (!ignoreCallingConv(Func) && !IsCallingConvC) 4188 return nullptr; 4189 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 4190 return V; 4191 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 4192 return V; 4193 switch (Func) { 4194 case LibFunc_ffs: 4195 case LibFunc_ffsl: 4196 case LibFunc_ffsll: 4197 return optimizeFFS(CI, Builder); 4198 case LibFunc_fls: 4199 case LibFunc_flsl: 4200 case LibFunc_flsll: 4201 return optimizeFls(CI, Builder); 4202 case LibFunc_abs: 4203 case LibFunc_labs: 4204 case LibFunc_llabs: 4205 return optimizeAbs(CI, Builder); 4206 case LibFunc_isdigit: 4207 return optimizeIsDigit(CI, Builder); 4208 case LibFunc_isascii: 4209 return optimizeIsAscii(CI, Builder); 4210 case LibFunc_toascii: 4211 return optimizeToAscii(CI, Builder); 4212 case LibFunc_atoi: 4213 case LibFunc_atol: 4214 case LibFunc_atoll: 4215 return optimizeAtoi(CI, Builder); 4216 case LibFunc_strtol: 4217 case LibFunc_strtoll: 4218 return optimizeStrToInt(CI, Builder, /*AsSigned=*/true); 4219 case LibFunc_strtoul: 4220 case LibFunc_strtoull: 4221 return optimizeStrToInt(CI, Builder, /*AsSigned=*/false); 4222 case LibFunc_printf: 4223 return optimizePrintF(CI, Builder); 4224 case LibFunc_sprintf: 4225 return optimizeSPrintF(CI, Builder); 4226 case LibFunc_snprintf: 4227 return optimizeSnPrintF(CI, Builder); 4228 case LibFunc_fprintf: 4229 return optimizeFPrintF(CI, Builder); 4230 case LibFunc_fwrite: 4231 return optimizeFWrite(CI, Builder); 4232 case LibFunc_fputs: 4233 return optimizeFPuts(CI, Builder); 4234 case LibFunc_puts: 4235 return optimizePuts(CI, Builder); 4236 case LibFunc_perror: 4237 return optimizeErrorReporting(CI, Builder); 4238 case LibFunc_vfprintf: 4239 case LibFunc_fiprintf: 4240 return optimizeErrorReporting(CI, Builder, 0); 4241 case LibFunc_exit: 4242 case LibFunc_Exit: 4243 return optimizeExit(CI); 4244 default: 4245 return nullptr; 4246 } 4247 } 4248 return nullptr; 4249 } 4250 4251 LibCallSimplifier::LibCallSimplifier( 4252 const DataLayout &DL, const TargetLibraryInfo *TLI, DominatorTree *DT, 4253 DomConditionCache *DC, AssumptionCache *AC, OptimizationRemarkEmitter &ORE, 4254 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 4255 function_ref<void(Instruction *, Value *)> Replacer, 4256 function_ref<void(Instruction *)> Eraser) 4257 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), DT(DT), DC(DC), AC(AC), 4258 ORE(ORE), BFI(BFI), PSI(PSI), Replacer(Replacer), Eraser(Eraser) {} 4259 4260 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 4261 // Indirect through the replacer used in this instance. 4262 Replacer(I, With); 4263 } 4264 4265 void LibCallSimplifier::eraseFromParent(Instruction *I) { 4266 Eraser(I); 4267 } 4268 4269 // TODO: 4270 // Additional cases that we need to add to this file: 4271 // 4272 // cbrt: 4273 // * cbrt(expN(X)) -> expN(x/3) 4274 // * cbrt(sqrt(x)) -> pow(x,1/6) 4275 // * cbrt(cbrt(x)) -> pow(x,1/9) 4276 // 4277 // exp, expf, expl: 4278 // * exp(log(x)) -> x 4279 // 4280 // log, logf, logl: 4281 // * log(exp(x)) -> x 4282 // * log(exp(y)) -> y*log(e) 4283 // * log(exp10(y)) -> y*log(10) 4284 // * log(sqrt(x)) -> 0.5*log(x) 4285 // 4286 // pow, powf, powl: 4287 // * pow(sqrt(x),y) -> pow(x,y*0.5) 4288 // * pow(pow(x,y),z)-> pow(x,y*z) 4289 // 4290 // signbit: 4291 // * signbit(cnst) -> cnst' 4292 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 4293 // 4294 // sqrt, sqrtf, sqrtl: 4295 // * sqrt(expN(x)) -> expN(x*0.5) 4296 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 4297 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 4298 // 4299 4300 //===----------------------------------------------------------------------===// 4301 // Fortified Library Call Optimizations 4302 //===----------------------------------------------------------------------===// 4303 4304 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable( 4305 CallInst *CI, unsigned ObjSizeOp, std::optional<unsigned> SizeOp, 4306 std::optional<unsigned> StrOp, std::optional<unsigned> FlagOp) { 4307 // If this function takes a flag argument, the implementation may use it to 4308 // perform extra checks. Don't fold into the non-checking variant. 4309 if (FlagOp) { 4310 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp)); 4311 if (!Flag || !Flag->isZero()) 4312 return false; 4313 } 4314 4315 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp)) 4316 return true; 4317 4318 if (ConstantInt *ObjSizeCI = 4319 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 4320 if (ObjSizeCI->isMinusOne()) 4321 return true; 4322 // If the object size wasn't -1 (unknown), bail out if we were asked to. 4323 if (OnlyLowerUnknownSize) 4324 return false; 4325 if (StrOp) { 4326 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp)); 4327 // If the length is 0 we don't know how long it is and so we can't 4328 // remove the check. 4329 if (Len) 4330 annotateDereferenceableBytes(CI, *StrOp, Len); 4331 else 4332 return false; 4333 return ObjSizeCI->getZExtValue() >= Len; 4334 } 4335 4336 if (SizeOp) { 4337 if (ConstantInt *SizeCI = 4338 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp))) 4339 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 4340 } 4341 } 4342 return false; 4343 } 4344 4345 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 4346 IRBuilderBase &B) { 4347 if (isFortifiedCallFoldable(CI, 3, 2)) { 4348 CallInst *NewCI = 4349 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 4350 Align(1), CI->getArgOperand(2)); 4351 mergeAttributesAndFlags(NewCI, *CI); 4352 return CI->getArgOperand(0); 4353 } 4354 return nullptr; 4355 } 4356 4357 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 4358 IRBuilderBase &B) { 4359 if (isFortifiedCallFoldable(CI, 3, 2)) { 4360 CallInst *NewCI = 4361 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 4362 Align(1), CI->getArgOperand(2)); 4363 mergeAttributesAndFlags(NewCI, *CI); 4364 return CI->getArgOperand(0); 4365 } 4366 return nullptr; 4367 } 4368 4369 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 4370 IRBuilderBase &B) { 4371 if (isFortifiedCallFoldable(CI, 3, 2)) { 4372 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 4373 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, 4374 CI->getArgOperand(2), Align(1)); 4375 mergeAttributesAndFlags(NewCI, *CI); 4376 return CI->getArgOperand(0); 4377 } 4378 return nullptr; 4379 } 4380 4381 Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI, 4382 IRBuilderBase &B) { 4383 const DataLayout &DL = CI->getDataLayout(); 4384 if (isFortifiedCallFoldable(CI, 3, 2)) 4385 if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4386 CI->getArgOperand(2), B, DL, TLI)) { 4387 return mergeAttributesAndFlags(cast<CallInst>(Call), *CI); 4388 } 4389 return nullptr; 4390 } 4391 4392 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 4393 IRBuilderBase &B, 4394 LibFunc Func) { 4395 const DataLayout &DL = CI->getDataLayout(); 4396 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 4397 *ObjSize = CI->getArgOperand(2); 4398 4399 // __stpcpy_chk(x,x,...) -> x+strlen(x) 4400 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 4401 Value *StrLen = emitStrLen(Src, B, DL, TLI); 4402 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 4403 } 4404 4405 // If a) we don't have any length information, or b) we know this will 4406 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 4407 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 4408 // TODO: It might be nice to get a maximum length out of the possible 4409 // string lengths for varying. 4410 if (isFortifiedCallFoldable(CI, 2, std::nullopt, 1)) { 4411 if (Func == LibFunc_strcpy_chk) 4412 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI)); 4413 else 4414 return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI)); 4415 } 4416 4417 if (OnlyLowerUnknownSize) 4418 return nullptr; 4419 4420 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 4421 uint64_t Len = GetStringLength(Src); 4422 if (Len) 4423 annotateDereferenceableBytes(CI, 1, Len); 4424 else 4425 return nullptr; 4426 4427 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 4428 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 4429 Value *LenV = ConstantInt::get(SizeTTy, Len); 4430 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 4431 // If the function was an __stpcpy_chk, and we were able to fold it into 4432 // a __memcpy_chk, we still need to return the correct end pointer. 4433 if (Ret && Func == LibFunc_stpcpy_chk) 4434 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, 4435 ConstantInt::get(SizeTTy, Len - 1)); 4436 return copyFlags(*CI, cast<CallInst>(Ret)); 4437 } 4438 4439 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI, 4440 IRBuilderBase &B) { 4441 if (isFortifiedCallFoldable(CI, 1, std::nullopt, 0)) 4442 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, 4443 CI->getDataLayout(), TLI)); 4444 return nullptr; 4445 } 4446 4447 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 4448 IRBuilderBase &B, 4449 LibFunc Func) { 4450 if (isFortifiedCallFoldable(CI, 3, 2)) { 4451 if (Func == LibFunc_strncpy_chk) 4452 return copyFlags(*CI, 4453 emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4454 CI->getArgOperand(2), B, TLI)); 4455 else 4456 return copyFlags(*CI, 4457 emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4458 CI->getArgOperand(2), B, TLI)); 4459 } 4460 4461 return nullptr; 4462 } 4463 4464 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI, 4465 IRBuilderBase &B) { 4466 if (isFortifiedCallFoldable(CI, 4, 3)) 4467 return copyFlags( 4468 *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4469 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI)); 4470 4471 return nullptr; 4472 } 4473 4474 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI, 4475 IRBuilderBase &B) { 4476 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) { 4477 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5)); 4478 return copyFlags(*CI, 4479 emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 4480 CI->getArgOperand(4), VariadicArgs, B, TLI)); 4481 } 4482 4483 return nullptr; 4484 } 4485 4486 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI, 4487 IRBuilderBase &B) { 4488 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) { 4489 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4)); 4490 return copyFlags(*CI, 4491 emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 4492 VariadicArgs, B, TLI)); 4493 } 4494 4495 return nullptr; 4496 } 4497 4498 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI, 4499 IRBuilderBase &B) { 4500 if (isFortifiedCallFoldable(CI, 2)) 4501 return copyFlags( 4502 *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI)); 4503 4504 return nullptr; 4505 } 4506 4507 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI, 4508 IRBuilderBase &B) { 4509 if (isFortifiedCallFoldable(CI, 3)) 4510 return copyFlags(*CI, 4511 emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1), 4512 CI->getArgOperand(2), B, TLI)); 4513 4514 return nullptr; 4515 } 4516 4517 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI, 4518 IRBuilderBase &B) { 4519 if (isFortifiedCallFoldable(CI, 3)) 4520 return copyFlags(*CI, 4521 emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1), 4522 CI->getArgOperand(2), B, TLI)); 4523 4524 return nullptr; 4525 } 4526 4527 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI, 4528 IRBuilderBase &B) { 4529 if (isFortifiedCallFoldable(CI, 3)) 4530 return copyFlags(*CI, 4531 emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4532 CI->getArgOperand(2), B, TLI)); 4533 4534 return nullptr; 4535 } 4536 4537 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI, 4538 IRBuilderBase &B) { 4539 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) 4540 return copyFlags( 4541 *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 4542 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI)); 4543 4544 return nullptr; 4545 } 4546 4547 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI, 4548 IRBuilderBase &B) { 4549 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) 4550 return copyFlags(*CI, 4551 emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 4552 CI->getArgOperand(4), B, TLI)); 4553 4554 return nullptr; 4555 } 4556 4557 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI, 4558 IRBuilderBase &Builder) { 4559 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 4560 // Some clang users checked for _chk libcall availability using: 4561 // __has_builtin(__builtin___memcpy_chk) 4562 // When compiling with -fno-builtin, this is always true. 4563 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 4564 // end up with fortified libcalls, which isn't acceptable in a freestanding 4565 // environment which only provides their non-fortified counterparts. 4566 // 4567 // Until we change clang and/or teach external users to check for availability 4568 // differently, disregard the "nobuiltin" attribute and TLI::has. 4569 // 4570 // PR23093. 4571 4572 LibFunc Func; 4573 Function *Callee = CI->getCalledFunction(); 4574 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 4575 4576 SmallVector<OperandBundleDef, 2> OpBundles; 4577 CI->getOperandBundlesAsDefs(OpBundles); 4578 4579 IRBuilderBase::OperandBundlesGuard Guard(Builder); 4580 Builder.setDefaultOperandBundles(OpBundles); 4581 4582 // First, check that this is a known library functions and that the prototype 4583 // is correct. 4584 if (!TLI->getLibFunc(*Callee, Func)) 4585 return nullptr; 4586 4587 // We never change the calling convention. 4588 if (!ignoreCallingConv(Func) && !IsCallingConvC) 4589 return nullptr; 4590 4591 switch (Func) { 4592 case LibFunc_memcpy_chk: 4593 return optimizeMemCpyChk(CI, Builder); 4594 case LibFunc_mempcpy_chk: 4595 return optimizeMemPCpyChk(CI, Builder); 4596 case LibFunc_memmove_chk: 4597 return optimizeMemMoveChk(CI, Builder); 4598 case LibFunc_memset_chk: 4599 return optimizeMemSetChk(CI, Builder); 4600 case LibFunc_stpcpy_chk: 4601 case LibFunc_strcpy_chk: 4602 return optimizeStrpCpyChk(CI, Builder, Func); 4603 case LibFunc_strlen_chk: 4604 return optimizeStrLenChk(CI, Builder); 4605 case LibFunc_stpncpy_chk: 4606 case LibFunc_strncpy_chk: 4607 return optimizeStrpNCpyChk(CI, Builder, Func); 4608 case LibFunc_memccpy_chk: 4609 return optimizeMemCCpyChk(CI, Builder); 4610 case LibFunc_snprintf_chk: 4611 return optimizeSNPrintfChk(CI, Builder); 4612 case LibFunc_sprintf_chk: 4613 return optimizeSPrintfChk(CI, Builder); 4614 case LibFunc_strcat_chk: 4615 return optimizeStrCatChk(CI, Builder); 4616 case LibFunc_strlcat_chk: 4617 return optimizeStrLCat(CI, Builder); 4618 case LibFunc_strncat_chk: 4619 return optimizeStrNCatChk(CI, Builder); 4620 case LibFunc_strlcpy_chk: 4621 return optimizeStrLCpyChk(CI, Builder); 4622 case LibFunc_vsnprintf_chk: 4623 return optimizeVSNPrintfChk(CI, Builder); 4624 case LibFunc_vsprintf_chk: 4625 return optimizeVSPrintfChk(CI, Builder); 4626 default: 4627 break; 4628 } 4629 return nullptr; 4630 } 4631 4632 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 4633 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 4634 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 4635