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