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