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(Str[Pos]) == Pos) { 981 // When there is just a single occurrence of C in S, i.e., the one 982 // in Str[Pos], fold 983 // memrchr(s, c, N) --> N <= Pos ? null : s + Pos 984 // for nonconstant N. 985 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), 986 Pos), 987 "memrchr.cmp"); 988 Value *SrcPlus = B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos), 989 "memrchr.ptr_plus"); 990 return B.CreateSelect(Cmp, NullPtr, SrcPlus, "memrchr.sel"); 991 } 992 } 993 994 // Truncate the string to search at most EndOff characters. 995 Str = Str.substr(0, EndOff); 996 if (Str.find_first_not_of(Str[0]) != StringRef::npos) 997 return nullptr; 998 999 // If the source array consists of all equal characters, then for any 1000 // C and N (whether in bounds or not), fold memrchr(S, C, N) to 1001 // N != 0 && *S == C ? S + N - 1 : null 1002 Type *SizeTy = Size->getType(); 1003 Type *Int8Ty = B.getInt8Ty(); 1004 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1005 // Slice off the sought character's high end bits. 1006 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1007 Value *CEqS0 = B.CreateICmpEQ(ConstantInt::get(Int8Ty, Str[0]), CharVal); 1008 Value *And = B.CreateLogicalAnd(NNeZ, CEqS0); 1009 Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1)); 1010 Value *SrcPlus = B.CreateGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus"); 1011 return B.CreateSelect(And, SrcPlus, NullPtr, "memrchr.sel"); 1012 } 1013 1014 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) { 1015 Value *SrcStr = CI->getArgOperand(0); 1016 Value *Size = CI->getArgOperand(2); 1017 if (isKnownNonZero(Size, DL)) 1018 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1019 1020 Value *CharVal = CI->getArgOperand(1); 1021 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 1022 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1023 Value *NullPtr = Constant::getNullValue(CI->getType()); 1024 1025 // memchr(x, y, 0) -> null 1026 if (LenC) { 1027 if (LenC->isZero()) 1028 return NullPtr; 1029 1030 if (LenC->isOne()) { 1031 // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y, 1032 // constant or otherwise. 1033 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0"); 1034 // Slice off the character's high end bits. 1035 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1036 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp"); 1037 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memchr.sel"); 1038 } 1039 } 1040 1041 StringRef Str; 1042 if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false)) 1043 return nullptr; 1044 1045 if (CharC) { 1046 size_t Pos = Str.find(CharC->getZExtValue()); 1047 if (Pos == StringRef::npos) 1048 // When the character is not in the source array fold the result 1049 // to null regardless of Size. 1050 return NullPtr; 1051 1052 // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos 1053 // When the constant Size is less than or equal to the character 1054 // position also fold the result to null. 1055 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos), 1056 "memchr.cmp"); 1057 Value *SrcPlus = 1058 B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos), "memchr.ptr"); 1059 return B.CreateSelect(Cmp, NullPtr, SrcPlus); 1060 } 1061 1062 if (Str.size() == 0) 1063 // If the array is empty fold memchr(A, C, N) to null for any value 1064 // of C and N on the basis that the only valid value of N is zero 1065 // (otherwise the call is undefined). 1066 return NullPtr; 1067 1068 if (LenC) 1069 Str = substr(Str, LenC->getZExtValue()); 1070 1071 size_t Pos = Str.find_first_not_of(Str[0]); 1072 if (Pos == StringRef::npos 1073 || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) { 1074 // If the source array consists of at most two consecutive sequences 1075 // of the same characters, then for any C and N (whether in bounds or 1076 // not), fold memchr(S, C, N) to 1077 // N != 0 && *S == C ? S : null 1078 // or for the two sequences to: 1079 // N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null) 1080 // ^Sel2 ^Sel1 are denoted above. 1081 // The latter makes it also possible to fold strchr() calls with strings 1082 // of the same characters. 1083 Type *SizeTy = Size->getType(); 1084 Type *Int8Ty = B.getInt8Ty(); 1085 1086 // Slice off the sought character's high end bits. 1087 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1088 1089 Value *Sel1 = NullPtr; 1090 if (Pos != StringRef::npos) { 1091 // Handle two consecutive sequences of the same characters. 1092 Value *PosVal = ConstantInt::get(SizeTy, Pos); 1093 Value *StrPos = ConstantInt::get(Int8Ty, Str[Pos]); 1094 Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos); 1095 Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal); 1096 Value *And = B.CreateAnd(CEqSPos, NGtPos); 1097 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal); 1098 Sel1 = B.CreateSelect(And, SrcPlus, NullPtr, "memchr.sel1"); 1099 } 1100 1101 Value *Str0 = ConstantInt::get(Int8Ty, Str[0]); 1102 Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal); 1103 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1104 Value *And = B.CreateAnd(NNeZ, CEqS0); 1105 return B.CreateSelect(And, SrcStr, Sel1, "memchr.sel2"); 1106 } 1107 1108 if (!LenC) 1109 // From now on we need a constant length and constant array. 1110 return nullptr; 1111 1112 // If the char is variable but the input str and length are not we can turn 1113 // this memchr call into a simple bit field test. Of course this only works 1114 // when the return value is only checked against null. 1115 // 1116 // It would be really nice to reuse switch lowering here but we can't change 1117 // the CFG at this point. 1118 // 1119 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n'))) 1120 // != 0 1121 // after bounds check. 1122 if (Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI)) 1123 return nullptr; 1124 1125 unsigned char Max = 1126 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()), 1127 reinterpret_cast<const unsigned char *>(Str.end())); 1128 1129 // Make sure the bit field we're about to create fits in a register on the 1130 // target. 1131 // FIXME: On a 64 bit architecture this prevents us from using the 1132 // interesting range of alpha ascii chars. We could do better by emitting 1133 // two bitfields or shifting the range by 64 if no lower chars are used. 1134 if (!DL.fitsInLegalInteger(Max + 1)) 1135 return nullptr; 1136 1137 // For the bit field use a power-of-2 type with at least 8 bits to avoid 1138 // creating unnecessary illegal types. 1139 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max)); 1140 1141 // Now build the bit field. 1142 APInt Bitfield(Width, 0); 1143 for (char C : Str) 1144 Bitfield.setBit((unsigned char)C); 1145 Value *BitfieldC = B.getInt(Bitfield); 1146 1147 // Adjust width of "C" to the bitfield width, then mask off the high bits. 1148 Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType()); 1149 C = B.CreateAnd(C, B.getIntN(Width, 0xFF)); 1150 1151 // First check that the bit field access is within bounds. 1152 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width), 1153 "memchr.bounds"); 1154 1155 // Create code that checks if the given bit is set in the field. 1156 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C); 1157 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits"); 1158 1159 // Finally merge both checks and cast to pointer type. The inttoptr 1160 // implicitly zexts the i1 to intptr type. 1161 return B.CreateIntToPtr(B.CreateLogicalAnd(Bounds, Bits, "memchr"), 1162 CI->getType()); 1163 } 1164 1165 // Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant 1166 // arrays LHS and RHS and nonconstant Size. 1167 static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS, 1168 Value *Size, bool StrNCmp, 1169 IRBuilderBase &B, const DataLayout &DL) { 1170 if (LHS == RHS) // memcmp(s,s,x) -> 0 1171 return Constant::getNullValue(CI->getType()); 1172 1173 StringRef LStr, RStr; 1174 if (!getConstantStringInfo(LHS, LStr, 0, /*TrimAtNul=*/false) || 1175 !getConstantStringInfo(RHS, RStr, 0, /*TrimAtNul=*/false)) 1176 return nullptr; 1177 1178 // If the contents of both constant arrays are known, fold a call to 1179 // memcmp(A, B, N) to 1180 // N <= Pos ? 0 : (A < B ? -1 : B < A ? +1 : 0) 1181 // where Pos is the first mismatch between A and B, determined below. 1182 1183 uint64_t Pos = 0; 1184 Value *Zero = ConstantInt::get(CI->getType(), 0); 1185 for (uint64_t MinSize = std::min(LStr.size(), RStr.size()); ; ++Pos) { 1186 if (Pos == MinSize || 1187 (StrNCmp && (LStr[Pos] == '\0' && RStr[Pos] == '\0'))) { 1188 // One array is a leading part of the other of equal or greater 1189 // size, or for strncmp, the arrays are equal strings. 1190 // Fold the result to zero. Size is assumed to be in bounds, since 1191 // otherwise the call would be undefined. 1192 return Zero; 1193 } 1194 1195 if (LStr[Pos] != RStr[Pos]) 1196 break; 1197 } 1198 1199 // Normalize the result. 1200 typedef unsigned char UChar; 1201 int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1; 1202 Value *MaxSize = ConstantInt::get(Size->getType(), Pos); 1203 Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize); 1204 Value *Res = ConstantInt::get(CI->getType(), IRes); 1205 return B.CreateSelect(Cmp, Zero, Res); 1206 } 1207 1208 // Optimize a memcmp call CI with constant size Len. 1209 static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS, 1210 uint64_t Len, IRBuilderBase &B, 1211 const DataLayout &DL) { 1212 if (Len == 0) // memcmp(s1,s2,0) -> 0 1213 return Constant::getNullValue(CI->getType()); 1214 1215 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 1216 if (Len == 1) { 1217 Value *LHSV = 1218 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"), 1219 CI->getType(), "lhsv"); 1220 Value *RHSV = 1221 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"), 1222 CI->getType(), "rhsv"); 1223 return B.CreateSub(LHSV, RHSV, "chardiff"); 1224 } 1225 1226 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0 1227 // TODO: The case where both inputs are constants does not need to be limited 1228 // to legal integers or equality comparison. See block below this. 1229 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) { 1230 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8); 1231 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType); 1232 1233 // First, see if we can fold either argument to a constant. 1234 Value *LHSV = nullptr; 1235 if (auto *LHSC = dyn_cast<Constant>(LHS)) { 1236 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo()); 1237 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL); 1238 } 1239 Value *RHSV = nullptr; 1240 if (auto *RHSC = dyn_cast<Constant>(RHS)) { 1241 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo()); 1242 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL); 1243 } 1244 1245 // Don't generate unaligned loads. If either source is constant data, 1246 // alignment doesn't matter for that source because there is no load. 1247 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) && 1248 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) { 1249 if (!LHSV) { 1250 Type *LHSPtrTy = 1251 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace()); 1252 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv"); 1253 } 1254 if (!RHSV) { 1255 Type *RHSPtrTy = 1256 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace()); 1257 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv"); 1258 } 1259 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp"); 1260 } 1261 } 1262 1263 return nullptr; 1264 } 1265 1266 // Most simplifications for memcmp also apply to bcmp. 1267 Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI, 1268 IRBuilderBase &B) { 1269 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 1270 Value *Size = CI->getArgOperand(2); 1271 1272 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1273 1274 if (Value *Res = optimizeMemCmpVarSize(CI, LHS, RHS, Size, false, B, DL)) 1275 return Res; 1276 1277 // Handle constant Size. 1278 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1279 if (!LenC) 1280 return nullptr; 1281 1282 return optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL); 1283 } 1284 1285 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) { 1286 Module *M = CI->getModule(); 1287 if (Value *V = optimizeMemCmpBCmpCommon(CI, B)) 1288 return V; 1289 1290 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0 1291 // bcmp can be more efficient than memcmp because it only has to know that 1292 // there is a difference, not how different one is to the other. 1293 if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) && 1294 isOnlyUsedInZeroEqualityComparison(CI)) { 1295 Value *LHS = CI->getArgOperand(0); 1296 Value *RHS = CI->getArgOperand(1); 1297 Value *Size = CI->getArgOperand(2); 1298 return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI)); 1299 } 1300 1301 return nullptr; 1302 } 1303 1304 Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) { 1305 return optimizeMemCmpBCmpCommon(CI, B); 1306 } 1307 1308 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) { 1309 Value *Size = CI->getArgOperand(2); 1310 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1311 if (isa<IntrinsicInst>(CI)) 1312 return nullptr; 1313 1314 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n) 1315 CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1), 1316 CI->getArgOperand(1), Align(1), Size); 1317 NewCI->setAttributes(CI->getAttributes()); 1318 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 1319 copyFlags(*CI, NewCI); 1320 return CI->getArgOperand(0); 1321 } 1322 1323 Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) { 1324 Value *Dst = CI->getArgOperand(0); 1325 Value *Src = CI->getArgOperand(1); 1326 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 1327 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3)); 1328 StringRef SrcStr; 1329 if (CI->use_empty() && Dst == Src) 1330 return Dst; 1331 // memccpy(d, s, c, 0) -> nullptr 1332 if (N) { 1333 if (N->isNullValue()) 1334 return Constant::getNullValue(CI->getType()); 1335 if (!getConstantStringInfo(Src, SrcStr, /*Offset=*/0, 1336 /*TrimAtNul=*/false) || 1337 // TODO: Handle zeroinitializer. 1338 !StopChar) 1339 return nullptr; 1340 } else { 1341 return nullptr; 1342 } 1343 1344 // Wrap arg 'c' of type int to char 1345 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF); 1346 if (Pos == StringRef::npos) { 1347 if (N->getZExtValue() <= SrcStr.size()) { 1348 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), 1349 CI->getArgOperand(3))); 1350 return Constant::getNullValue(CI->getType()); 1351 } 1352 return nullptr; 1353 } 1354 1355 Value *NewN = 1356 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue())); 1357 // memccpy -> llvm.memcpy 1358 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN)); 1359 return Pos + 1 <= N->getZExtValue() 1360 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN) 1361 : Constant::getNullValue(CI->getType()); 1362 } 1363 1364 Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) { 1365 Value *Dst = CI->getArgOperand(0); 1366 Value *N = CI->getArgOperand(2); 1367 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n 1368 CallInst *NewCI = 1369 B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N); 1370 // Propagate attributes, but memcpy has no return value, so make sure that 1371 // any return attributes are compliant. 1372 // TODO: Attach return value attributes to the 1st operand to preserve them? 1373 NewCI->setAttributes(CI->getAttributes()); 1374 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 1375 copyFlags(*CI, NewCI); 1376 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N); 1377 } 1378 1379 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) { 1380 Value *Size = CI->getArgOperand(2); 1381 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1382 if (isa<IntrinsicInst>(CI)) 1383 return nullptr; 1384 1385 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n) 1386 CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1), 1387 CI->getArgOperand(1), Align(1), Size); 1388 NewCI->setAttributes(CI->getAttributes()); 1389 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 1390 copyFlags(*CI, NewCI); 1391 return CI->getArgOperand(0); 1392 } 1393 1394 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) { 1395 Value *Size = CI->getArgOperand(2); 1396 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1397 if (isa<IntrinsicInst>(CI)) 1398 return nullptr; 1399 1400 // memset(p, v, n) -> llvm.memset(align 1 p, v, n) 1401 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 1402 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1)); 1403 NewCI->setAttributes(CI->getAttributes()); 1404 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 1405 copyFlags(*CI, NewCI); 1406 return CI->getArgOperand(0); 1407 } 1408 1409 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) { 1410 if (isa<ConstantPointerNull>(CI->getArgOperand(0))) 1411 return copyFlags(*CI, emitMalloc(CI->getArgOperand(1), B, DL, TLI)); 1412 1413 return nullptr; 1414 } 1415 1416 //===----------------------------------------------------------------------===// 1417 // Math Library Optimizations 1418 //===----------------------------------------------------------------------===// 1419 1420 // Replace a libcall \p CI with a call to intrinsic \p IID 1421 static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B, 1422 Intrinsic::ID IID) { 1423 // Propagate fast-math flags from the existing call to the new call. 1424 IRBuilderBase::FastMathFlagGuard Guard(B); 1425 B.setFastMathFlags(CI->getFastMathFlags()); 1426 1427 Module *M = CI->getModule(); 1428 Value *V = CI->getArgOperand(0); 1429 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType()); 1430 CallInst *NewCall = B.CreateCall(F, V); 1431 NewCall->takeName(CI); 1432 return copyFlags(*CI, NewCall); 1433 } 1434 1435 /// Return a variant of Val with float type. 1436 /// Currently this works in two cases: If Val is an FPExtension of a float 1437 /// value to something bigger, simply return the operand. 1438 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 1439 /// loss of precision do so. 1440 static Value *valueHasFloatPrecision(Value *Val) { 1441 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 1442 Value *Op = Cast->getOperand(0); 1443 if (Op->getType()->isFloatTy()) 1444 return Op; 1445 } 1446 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 1447 APFloat F = Const->getValueAPF(); 1448 bool losesInfo; 1449 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 1450 &losesInfo); 1451 if (!losesInfo) 1452 return ConstantFP::get(Const->getContext(), F); 1453 } 1454 return nullptr; 1455 } 1456 1457 /// Shrink double -> float functions. 1458 static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B, 1459 bool isBinary, const TargetLibraryInfo *TLI, 1460 bool isPrecise = false) { 1461 Function *CalleeFn = CI->getCalledFunction(); 1462 if (!CI->getType()->isDoubleTy() || !CalleeFn) 1463 return nullptr; 1464 1465 // If not all the uses of the function are converted to float, then bail out. 1466 // This matters if the precision of the result is more important than the 1467 // precision of the arguments. 1468 if (isPrecise) 1469 for (User *U : CI->users()) { 1470 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 1471 if (!Cast || !Cast->getType()->isFloatTy()) 1472 return nullptr; 1473 } 1474 1475 // If this is something like 'g((double) float)', convert to 'gf(float)'. 1476 Value *V[2]; 1477 V[0] = valueHasFloatPrecision(CI->getArgOperand(0)); 1478 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr; 1479 if (!V[0] || (isBinary && !V[1])) 1480 return nullptr; 1481 1482 // If call isn't an intrinsic, check that it isn't within a function with the 1483 // same name as the float version of this call, otherwise the result is an 1484 // infinite loop. For example, from MinGW-w64: 1485 // 1486 // float expf(float val) { return (float) exp((double) val); } 1487 StringRef CalleeName = CalleeFn->getName(); 1488 bool IsIntrinsic = CalleeFn->isIntrinsic(); 1489 if (!IsIntrinsic) { 1490 StringRef CallerName = CI->getFunction()->getName(); 1491 if (!CallerName.empty() && CallerName.back() == 'f' && 1492 CallerName.size() == (CalleeName.size() + 1) && 1493 CallerName.startswith(CalleeName)) 1494 return nullptr; 1495 } 1496 1497 // Propagate the math semantics from the current function to the new function. 1498 IRBuilderBase::FastMathFlagGuard Guard(B); 1499 B.setFastMathFlags(CI->getFastMathFlags()); 1500 1501 // g((double) float) -> (double) gf(float) 1502 Value *R; 1503 if (IsIntrinsic) { 1504 Module *M = CI->getModule(); 1505 Intrinsic::ID IID = CalleeFn->getIntrinsicID(); 1506 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy()); 1507 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]); 1508 } else { 1509 AttributeList CalleeAttrs = CalleeFn->getAttributes(); 1510 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B, 1511 CalleeAttrs) 1512 : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CalleeAttrs); 1513 } 1514 return B.CreateFPExt(R, B.getDoubleTy()); 1515 } 1516 1517 /// Shrink double -> float for unary functions. 1518 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1519 const TargetLibraryInfo *TLI, 1520 bool isPrecise = false) { 1521 return optimizeDoubleFP(CI, B, false, TLI, isPrecise); 1522 } 1523 1524 /// Shrink double -> float for binary functions. 1525 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1526 const TargetLibraryInfo *TLI, 1527 bool isPrecise = false) { 1528 return optimizeDoubleFP(CI, B, true, TLI, isPrecise); 1529 } 1530 1531 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1532 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) { 1533 if (!CI->isFast()) 1534 return nullptr; 1535 1536 // Propagate fast-math flags from the existing call to new instructions. 1537 IRBuilderBase::FastMathFlagGuard Guard(B); 1538 B.setFastMathFlags(CI->getFastMathFlags()); 1539 1540 Value *Real, *Imag; 1541 if (CI->arg_size() == 1) { 1542 Value *Op = CI->getArgOperand(0); 1543 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 1544 Real = B.CreateExtractValue(Op, 0, "real"); 1545 Imag = B.CreateExtractValue(Op, 1, "imag"); 1546 } else { 1547 assert(CI->arg_size() == 2 && "Unexpected signature for cabs!"); 1548 Real = CI->getArgOperand(0); 1549 Imag = CI->getArgOperand(1); 1550 } 1551 1552 Value *RealReal = B.CreateFMul(Real, Real); 1553 Value *ImagImag = B.CreateFMul(Imag, Imag); 1554 1555 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt, 1556 CI->getType()); 1557 return copyFlags( 1558 *CI, B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs")); 1559 } 1560 1561 static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func, 1562 IRBuilderBase &B) { 1563 if (!isa<FPMathOperator>(Call)) 1564 return nullptr; 1565 1566 IRBuilderBase::FastMathFlagGuard Guard(B); 1567 B.setFastMathFlags(Call->getFastMathFlags()); 1568 1569 // TODO: Can this be shared to also handle LLVM intrinsics? 1570 Value *X; 1571 switch (Func) { 1572 case LibFunc_sin: 1573 case LibFunc_sinf: 1574 case LibFunc_sinl: 1575 case LibFunc_tan: 1576 case LibFunc_tanf: 1577 case LibFunc_tanl: 1578 // sin(-X) --> -sin(X) 1579 // tan(-X) --> -tan(X) 1580 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) 1581 return B.CreateFNeg( 1582 copyFlags(*Call, B.CreateCall(Call->getCalledFunction(), X))); 1583 break; 1584 case LibFunc_cos: 1585 case LibFunc_cosf: 1586 case LibFunc_cosl: 1587 // cos(-X) --> cos(X) 1588 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X)))) 1589 return copyFlags(*Call, 1590 B.CreateCall(Call->getCalledFunction(), X, "cos")); 1591 break; 1592 default: 1593 break; 1594 } 1595 return nullptr; 1596 } 1597 1598 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilderBase &B) { 1599 // Multiplications calculated using Addition Chains. 1600 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html 1601 1602 assert(Exp != 0 && "Incorrect exponent 0 not handled"); 1603 1604 if (InnerChain[Exp]) 1605 return InnerChain[Exp]; 1606 1607 static const unsigned AddChain[33][2] = { 1608 {0, 0}, // Unused. 1609 {0, 0}, // Unused (base case = pow1). 1610 {1, 1}, // Unused (pre-computed). 1611 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4}, 1612 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7}, 1613 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10}, 1614 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13}, 1615 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16}, 1616 }; 1617 1618 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B), 1619 getPow(InnerChain, AddChain[Exp][1], B)); 1620 return InnerChain[Exp]; 1621 } 1622 1623 // Return a properly extended integer (DstWidth bits wide) if the operation is 1624 // an itofp. 1625 static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) { 1626 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) { 1627 Value *Op = cast<Instruction>(I2F)->getOperand(0); 1628 // Make sure that the exponent fits inside an "int" of size DstWidth, 1629 // thus avoiding any range issues that FP has not. 1630 unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits(); 1631 if (BitWidth < DstWidth || 1632 (BitWidth == DstWidth && isa<SIToFPInst>(I2F))) 1633 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getIntNTy(DstWidth)) 1634 : B.CreateZExt(Op, B.getIntNTy(DstWidth)); 1635 } 1636 1637 return nullptr; 1638 } 1639 1640 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y); 1641 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x); 1642 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x). 1643 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) { 1644 Module *M = Pow->getModule(); 1645 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1646 AttributeList Attrs; // Attributes are only meaningful on the original call 1647 Module *Mod = Pow->getModule(); 1648 Type *Ty = Pow->getType(); 1649 bool Ignored; 1650 1651 // Evaluate special cases related to a nested function as the base. 1652 1653 // pow(exp(x), y) -> exp(x * y) 1654 // pow(exp2(x), y) -> exp2(x * y) 1655 // If exp{,2}() is used only once, it is better to fold two transcendental 1656 // math functions into one. If used again, exp{,2}() would still have to be 1657 // called with the original argument, then keep both original transcendental 1658 // functions. However, this transformation is only safe with fully relaxed 1659 // math semantics, since, besides rounding differences, it changes overflow 1660 // and underflow behavior quite dramatically. For example: 1661 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf 1662 // Whereas: 1663 // exp(1000 * 0.001) = exp(1) 1664 // TODO: Loosen the requirement for fully relaxed math semantics. 1665 // TODO: Handle exp10() when more targets have it available. 1666 CallInst *BaseFn = dyn_cast<CallInst>(Base); 1667 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) { 1668 LibFunc LibFn; 1669 1670 Function *CalleeFn = BaseFn->getCalledFunction(); 1671 if (CalleeFn && 1672 TLI->getLibFunc(CalleeFn->getName(), LibFn) && 1673 isLibFuncEmittable(M, TLI, LibFn)) { 1674 StringRef ExpName; 1675 Intrinsic::ID ID; 1676 Value *ExpFn; 1677 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble; 1678 1679 switch (LibFn) { 1680 default: 1681 return nullptr; 1682 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl: 1683 ExpName = TLI->getName(LibFunc_exp); 1684 ID = Intrinsic::exp; 1685 LibFnFloat = LibFunc_expf; 1686 LibFnDouble = LibFunc_exp; 1687 LibFnLongDouble = LibFunc_expl; 1688 break; 1689 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l: 1690 ExpName = TLI->getName(LibFunc_exp2); 1691 ID = Intrinsic::exp2; 1692 LibFnFloat = LibFunc_exp2f; 1693 LibFnDouble = LibFunc_exp2; 1694 LibFnLongDouble = LibFunc_exp2l; 1695 break; 1696 } 1697 1698 // Create new exp{,2}() with the product as its argument. 1699 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul"); 1700 ExpFn = BaseFn->doesNotAccessMemory() 1701 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty), 1702 FMul, ExpName) 1703 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat, 1704 LibFnLongDouble, B, 1705 BaseFn->getAttributes()); 1706 1707 // Since the new exp{,2}() is different from the original one, dead code 1708 // elimination cannot be trusted to remove it, since it may have side 1709 // effects (e.g., errno). When the only consumer for the original 1710 // exp{,2}() is pow(), then it has to be explicitly erased. 1711 substituteInParent(BaseFn, ExpFn); 1712 return ExpFn; 1713 } 1714 } 1715 1716 // Evaluate special cases related to a constant base. 1717 1718 const APFloat *BaseF; 1719 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF))) 1720 return nullptr; 1721 1722 // pow(2.0, itofp(x)) -> ldexp(1.0, x) 1723 if (match(Base, m_SpecificFP(2.0)) && 1724 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) && 1725 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) { 1726 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) 1727 return copyFlags(*Pow, 1728 emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI, 1729 TLI, LibFunc_ldexp, LibFunc_ldexpf, 1730 LibFunc_ldexpl, B, Attrs)); 1731 } 1732 1733 // pow(2.0 ** n, x) -> exp2(n * x) 1734 if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) { 1735 APFloat BaseR = APFloat(1.0); 1736 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored); 1737 BaseR = BaseR / *BaseF; 1738 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger(); 1739 const APFloat *NF = IsReciprocal ? &BaseR : BaseF; 1740 APSInt NI(64, false); 1741 if ((IsInteger || IsReciprocal) && 1742 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) == 1743 APFloat::opOK && 1744 NI > 1 && NI.isPowerOf2()) { 1745 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0); 1746 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul"); 1747 if (Pow->doesNotAccessMemory()) 1748 return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration( 1749 Mod, Intrinsic::exp2, Ty), 1750 FMul, "exp2")); 1751 else 1752 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 1753 LibFunc_exp2f, 1754 LibFunc_exp2l, B, Attrs)); 1755 } 1756 } 1757 1758 // pow(10.0, x) -> exp10(x) 1759 // TODO: There is no exp10() intrinsic yet, but some day there shall be one. 1760 if (match(Base, m_SpecificFP(10.0)) && 1761 hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) 1762 return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, 1763 LibFunc_exp10f, LibFunc_exp10l, 1764 B, Attrs)); 1765 1766 // pow(x, y) -> exp2(log2(x) * y) 1767 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() && 1768 !BaseF->isNegative()) { 1769 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN. 1770 // Luckily optimizePow has already handled the x == 1 case. 1771 assert(!match(Base, m_FPOne()) && 1772 "pow(1.0, y) should have been simplified earlier!"); 1773 1774 Value *Log = nullptr; 1775 if (Ty->isFloatTy()) 1776 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat())); 1777 else if (Ty->isDoubleTy()) 1778 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble())); 1779 1780 if (Log) { 1781 Value *FMul = B.CreateFMul(Log, Expo, "mul"); 1782 if (Pow->doesNotAccessMemory()) 1783 return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration( 1784 Mod, Intrinsic::exp2, Ty), 1785 FMul, "exp2")); 1786 else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, 1787 LibFunc_exp2l)) 1788 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 1789 LibFunc_exp2f, 1790 LibFunc_exp2l, B, Attrs)); 1791 } 1792 } 1793 1794 return nullptr; 1795 } 1796 1797 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, 1798 Module *M, IRBuilderBase &B, 1799 const TargetLibraryInfo *TLI) { 1800 // If errno is never set, then use the intrinsic for sqrt(). 1801 if (NoErrno) { 1802 Function *SqrtFn = 1803 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType()); 1804 return B.CreateCall(SqrtFn, V, "sqrt"); 1805 } 1806 1807 // Otherwise, use the libcall for sqrt(). 1808 if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, 1809 LibFunc_sqrtl)) 1810 // TODO: We also should check that the target can in fact lower the sqrt() 1811 // libcall. We currently have no way to ask this question, so we ask if 1812 // the target has a sqrt() libcall, which is not exactly the same. 1813 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf, 1814 LibFunc_sqrtl, B, Attrs); 1815 1816 return nullptr; 1817 } 1818 1819 /// Use square root in place of pow(x, +/-0.5). 1820 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) { 1821 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1822 AttributeList Attrs; // Attributes are only meaningful on the original call 1823 Module *Mod = Pow->getModule(); 1824 Type *Ty = Pow->getType(); 1825 1826 const APFloat *ExpoF; 1827 if (!match(Expo, m_APFloat(ExpoF)) || 1828 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 1829 return nullptr; 1830 1831 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step, 1832 // so that requires fast-math-flags (afn or reassoc). 1833 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc())) 1834 return nullptr; 1835 1836 // If we have a pow() library call (accesses memory) and we can't guarantee 1837 // that the base is not an infinity, give up: 1838 // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting 1839 // errno), but sqrt(-Inf) is required by various standards to set errno. 1840 if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() && 1841 !isKnownNeverInfinity(Base, TLI)) 1842 return nullptr; 1843 1844 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI); 1845 if (!Sqrt) 1846 return nullptr; 1847 1848 // Handle signed zero base by expanding to fabs(sqrt(x)). 1849 if (!Pow->hasNoSignedZeros()) { 1850 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty); 1851 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs"); 1852 } 1853 1854 Sqrt = copyFlags(*Pow, Sqrt); 1855 1856 // Handle non finite base by expanding to 1857 // (x == -infinity ? +infinity : sqrt(x)). 1858 if (!Pow->hasNoInfs()) { 1859 Value *PosInf = ConstantFP::getInfinity(Ty), 1860 *NegInf = ConstantFP::getInfinity(Ty, true); 1861 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 1862 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 1863 } 1864 1865 // If the exponent is negative, then get the reciprocal. 1866 if (ExpoF->isNegative()) 1867 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 1868 1869 return Sqrt; 1870 } 1871 1872 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, 1873 IRBuilderBase &B) { 1874 Value *Args[] = {Base, Expo}; 1875 Type *Types[] = {Base->getType(), Expo->getType()}; 1876 Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Types); 1877 return B.CreateCall(F, Args); 1878 } 1879 1880 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) { 1881 Value *Base = Pow->getArgOperand(0); 1882 Value *Expo = Pow->getArgOperand(1); 1883 Function *Callee = Pow->getCalledFunction(); 1884 StringRef Name = Callee->getName(); 1885 Type *Ty = Pow->getType(); 1886 Module *M = Pow->getModule(); 1887 bool AllowApprox = Pow->hasApproxFunc(); 1888 bool Ignored; 1889 1890 // Propagate the math semantics from the call to any created instructions. 1891 IRBuilderBase::FastMathFlagGuard Guard(B); 1892 B.setFastMathFlags(Pow->getFastMathFlags()); 1893 // Evaluate special cases related to the base. 1894 1895 // pow(1.0, x) -> 1.0 1896 if (match(Base, m_FPOne())) 1897 return Base; 1898 1899 if (Value *Exp = replacePowWithExp(Pow, B)) 1900 return Exp; 1901 1902 // Evaluate special cases related to the exponent. 1903 1904 // pow(x, -1.0) -> 1.0 / x 1905 if (match(Expo, m_SpecificFP(-1.0))) 1906 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 1907 1908 // pow(x, +/-0.0) -> 1.0 1909 if (match(Expo, m_AnyZeroFP())) 1910 return ConstantFP::get(Ty, 1.0); 1911 1912 // pow(x, 1.0) -> x 1913 if (match(Expo, m_FPOne())) 1914 return Base; 1915 1916 // pow(x, 2.0) -> x * x 1917 if (match(Expo, m_SpecificFP(2.0))) 1918 return B.CreateFMul(Base, Base, "square"); 1919 1920 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 1921 return Sqrt; 1922 1923 // pow(x, n) -> x * x * x * ... 1924 const APFloat *ExpoF; 1925 if (AllowApprox && match(Expo, m_APFloat(ExpoF)) && 1926 !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) { 1927 // We limit to a max of 7 multiplications, thus the maximum exponent is 32. 1928 // If the exponent is an integer+0.5 we generate a call to sqrt and an 1929 // additional fmul. 1930 // TODO: This whole transformation should be backend specific (e.g. some 1931 // backends might prefer libcalls or the limit for the exponent might 1932 // be different) and it should also consider optimizing for size. 1933 APFloat LimF(ExpoF->getSemantics(), 33), 1934 ExpoA(abs(*ExpoF)); 1935 if (ExpoA < LimF) { 1936 // This transformation applies to integer or integer+0.5 exponents only. 1937 // For integer+0.5, we create a sqrt(Base) call. 1938 Value *Sqrt = nullptr; 1939 if (!ExpoA.isInteger()) { 1940 APFloat Expo2 = ExpoA; 1941 // To check if ExpoA is an integer + 0.5, we add it to itself. If there 1942 // is no floating point exception and the result is an integer, then 1943 // ExpoA == integer + 0.5 1944 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK) 1945 return nullptr; 1946 1947 if (!Expo2.isInteger()) 1948 return nullptr; 1949 1950 Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(), 1951 Pow->doesNotAccessMemory(), M, B, TLI); 1952 if (!Sqrt) 1953 return nullptr; 1954 } 1955 1956 // We will memoize intermediate products of the Addition Chain. 1957 Value *InnerChain[33] = {nullptr}; 1958 InnerChain[1] = Base; 1959 InnerChain[2] = B.CreateFMul(Base, Base, "square"); 1960 1961 // We cannot readily convert a non-double type (like float) to a double. 1962 // So we first convert it to something which could be converted to double. 1963 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored); 1964 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B); 1965 1966 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x). 1967 if (Sqrt) 1968 FMul = B.CreateFMul(FMul, Sqrt); 1969 1970 // If the exponent is negative, then get the reciprocal. 1971 if (ExpoF->isNegative()) 1972 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal"); 1973 1974 return FMul; 1975 } 1976 1977 APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false); 1978 // powf(x, n) -> powi(x, n) if n is a constant signed integer value 1979 if (ExpoF->isInteger() && 1980 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) == 1981 APFloat::opOK) { 1982 return copyFlags( 1983 *Pow, 1984 createPowWithIntegerExponent( 1985 Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo), 1986 M, B)); 1987 } 1988 } 1989 1990 // powf(x, itofp(y)) -> powi(x, y) 1991 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) { 1992 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) 1993 return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B)); 1994 } 1995 1996 // Shrink pow() to powf() if the arguments are single precision, 1997 // unless the result is expected to be double precision. 1998 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) && 1999 hasFloatVersion(M, Name)) { 2000 if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true)) 2001 return Shrunk; 2002 } 2003 2004 return nullptr; 2005 } 2006 2007 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) { 2008 Module *M = CI->getModule(); 2009 Function *Callee = CI->getCalledFunction(); 2010 AttributeList Attrs; // Attributes are only meaningful on the original call 2011 StringRef Name = Callee->getName(); 2012 Value *Ret = nullptr; 2013 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) && 2014 hasFloatVersion(M, Name)) 2015 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2016 2017 Type *Ty = CI->getType(); 2018 Value *Op = CI->getArgOperand(0); 2019 2020 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize 2021 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize 2022 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) && 2023 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) { 2024 if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize())) 2025 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI, 2026 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl, 2027 B, Attrs); 2028 } 2029 2030 return Ret; 2031 } 2032 2033 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) { 2034 Module *M = CI->getModule(); 2035 2036 // If we can shrink the call to a float function rather than a double 2037 // function, do that first. 2038 Function *Callee = CI->getCalledFunction(); 2039 StringRef Name = Callee->getName(); 2040 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(M, Name)) 2041 if (Value *Ret = optimizeBinaryDoubleFP(CI, B, TLI)) 2042 return Ret; 2043 2044 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to 2045 // the intrinsics for improved optimization (for example, vectorization). 2046 // No-signed-zeros is implied by the definitions of fmax/fmin themselves. 2047 // From the C standard draft WG14/N1256: 2048 // "Ideally, fmax would be sensitive to the sign of zero, for example 2049 // fmax(-0.0, +0.0) would return +0; however, implementation in software 2050 // might be impractical." 2051 IRBuilderBase::FastMathFlagGuard Guard(B); 2052 FastMathFlags FMF = CI->getFastMathFlags(); 2053 FMF.setNoSignedZeros(); 2054 B.setFastMathFlags(FMF); 2055 2056 Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum 2057 : Intrinsic::maxnum; 2058 Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType()); 2059 return copyFlags( 2060 *CI, B.CreateCall(F, {CI->getArgOperand(0), CI->getArgOperand(1)})); 2061 } 2062 2063 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) { 2064 Function *LogFn = Log->getCalledFunction(); 2065 AttributeList Attrs; // Attributes are only meaningful on the original call 2066 StringRef LogNm = LogFn->getName(); 2067 Intrinsic::ID LogID = LogFn->getIntrinsicID(); 2068 Module *Mod = Log->getModule(); 2069 Type *Ty = Log->getType(); 2070 Value *Ret = nullptr; 2071 2072 if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm)) 2073 Ret = optimizeUnaryDoubleFP(Log, B, TLI, true); 2074 2075 // The earlier call must also be 'fast' in order to do these transforms. 2076 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0)); 2077 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse()) 2078 return Ret; 2079 2080 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb; 2081 2082 // This is only applicable to log(), log2(), log10(). 2083 if (TLI->getLibFunc(LogNm, LogLb)) 2084 switch (LogLb) { 2085 case LibFunc_logf: 2086 LogID = Intrinsic::log; 2087 ExpLb = LibFunc_expf; 2088 Exp2Lb = LibFunc_exp2f; 2089 Exp10Lb = LibFunc_exp10f; 2090 PowLb = LibFunc_powf; 2091 break; 2092 case LibFunc_log: 2093 LogID = Intrinsic::log; 2094 ExpLb = LibFunc_exp; 2095 Exp2Lb = LibFunc_exp2; 2096 Exp10Lb = LibFunc_exp10; 2097 PowLb = LibFunc_pow; 2098 break; 2099 case LibFunc_logl: 2100 LogID = Intrinsic::log; 2101 ExpLb = LibFunc_expl; 2102 Exp2Lb = LibFunc_exp2l; 2103 Exp10Lb = LibFunc_exp10l; 2104 PowLb = LibFunc_powl; 2105 break; 2106 case LibFunc_log2f: 2107 LogID = Intrinsic::log2; 2108 ExpLb = LibFunc_expf; 2109 Exp2Lb = LibFunc_exp2f; 2110 Exp10Lb = LibFunc_exp10f; 2111 PowLb = LibFunc_powf; 2112 break; 2113 case LibFunc_log2: 2114 LogID = Intrinsic::log2; 2115 ExpLb = LibFunc_exp; 2116 Exp2Lb = LibFunc_exp2; 2117 Exp10Lb = LibFunc_exp10; 2118 PowLb = LibFunc_pow; 2119 break; 2120 case LibFunc_log2l: 2121 LogID = Intrinsic::log2; 2122 ExpLb = LibFunc_expl; 2123 Exp2Lb = LibFunc_exp2l; 2124 Exp10Lb = LibFunc_exp10l; 2125 PowLb = LibFunc_powl; 2126 break; 2127 case LibFunc_log10f: 2128 LogID = Intrinsic::log10; 2129 ExpLb = LibFunc_expf; 2130 Exp2Lb = LibFunc_exp2f; 2131 Exp10Lb = LibFunc_exp10f; 2132 PowLb = LibFunc_powf; 2133 break; 2134 case LibFunc_log10: 2135 LogID = Intrinsic::log10; 2136 ExpLb = LibFunc_exp; 2137 Exp2Lb = LibFunc_exp2; 2138 Exp10Lb = LibFunc_exp10; 2139 PowLb = LibFunc_pow; 2140 break; 2141 case LibFunc_log10l: 2142 LogID = Intrinsic::log10; 2143 ExpLb = LibFunc_expl; 2144 Exp2Lb = LibFunc_exp2l; 2145 Exp10Lb = LibFunc_exp10l; 2146 PowLb = LibFunc_powl; 2147 break; 2148 default: 2149 return Ret; 2150 } 2151 else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 || 2152 LogID == Intrinsic::log10) { 2153 if (Ty->getScalarType()->isFloatTy()) { 2154 ExpLb = LibFunc_expf; 2155 Exp2Lb = LibFunc_exp2f; 2156 Exp10Lb = LibFunc_exp10f; 2157 PowLb = LibFunc_powf; 2158 } else if (Ty->getScalarType()->isDoubleTy()) { 2159 ExpLb = LibFunc_exp; 2160 Exp2Lb = LibFunc_exp2; 2161 Exp10Lb = LibFunc_exp10; 2162 PowLb = LibFunc_pow; 2163 } else 2164 return Ret; 2165 } else 2166 return Ret; 2167 2168 IRBuilderBase::FastMathFlagGuard Guard(B); 2169 B.setFastMathFlags(FastMathFlags::getFast()); 2170 2171 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 2172 LibFunc ArgLb = NotLibFunc; 2173 TLI->getLibFunc(*Arg, ArgLb); 2174 2175 // log(pow(x,y)) -> y*log(x) 2176 if (ArgLb == PowLb || ArgID == Intrinsic::pow) { 2177 Value *LogX = 2178 Log->doesNotAccessMemory() 2179 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty), 2180 Arg->getOperand(0), "log") 2181 : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, Attrs); 2182 Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul"); 2183 // Since pow() may have side effects, e.g. errno, 2184 // dead code elimination may not be trusted to remove it. 2185 substituteInParent(Arg, MulY); 2186 return MulY; 2187 } 2188 2189 // log(exp{,2,10}(y)) -> y*log({e,2,10}) 2190 // TODO: There is no exp10() intrinsic yet. 2191 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb || 2192 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) { 2193 Constant *Eul; 2194 if (ArgLb == ExpLb || ArgID == Intrinsic::exp) 2195 // FIXME: Add more precise value of e for long double. 2196 Eul = ConstantFP::get(Log->getType(), numbers::e); 2197 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2) 2198 Eul = ConstantFP::get(Log->getType(), 2.0); 2199 else 2200 Eul = ConstantFP::get(Log->getType(), 10.0); 2201 Value *LogE = Log->doesNotAccessMemory() 2202 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty), 2203 Eul, "log") 2204 : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, Attrs); 2205 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul"); 2206 // Since exp() may have side effects, e.g. errno, 2207 // dead code elimination may not be trusted to remove it. 2208 substituteInParent(Arg, MulY); 2209 return MulY; 2210 } 2211 2212 return Ret; 2213 } 2214 2215 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) { 2216 Module *M = CI->getModule(); 2217 Function *Callee = CI->getCalledFunction(); 2218 Value *Ret = nullptr; 2219 // TODO: Once we have a way (other than checking for the existince of the 2220 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 2221 // condition below. 2222 if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) && 2223 (Callee->getName() == "sqrt" || 2224 Callee->getIntrinsicID() == Intrinsic::sqrt)) 2225 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2226 2227 if (!CI->isFast()) 2228 return Ret; 2229 2230 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 2231 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 2232 return Ret; 2233 2234 // We're looking for a repeated factor in a multiplication tree, 2235 // so we can do this fold: sqrt(x * x) -> fabs(x); 2236 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 2237 Value *Op0 = I->getOperand(0); 2238 Value *Op1 = I->getOperand(1); 2239 Value *RepeatOp = nullptr; 2240 Value *OtherOp = nullptr; 2241 if (Op0 == Op1) { 2242 // Simple match: the operands of the multiply are identical. 2243 RepeatOp = Op0; 2244 } else { 2245 // Look for a more complicated pattern: one of the operands is itself 2246 // a multiply, so search for a common factor in that multiply. 2247 // Note: We don't bother looking any deeper than this first level or for 2248 // variations of this pattern because instcombine's visitFMUL and/or the 2249 // reassociation pass should give us this form. 2250 Value *OtherMul0, *OtherMul1; 2251 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) { 2252 // Pattern: sqrt((x * y) * z) 2253 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) { 2254 // Matched: sqrt((x * x) * z) 2255 RepeatOp = OtherMul0; 2256 OtherOp = Op1; 2257 } 2258 } 2259 } 2260 if (!RepeatOp) 2261 return Ret; 2262 2263 // Fast math flags for any created instructions should match the sqrt 2264 // and multiply. 2265 IRBuilderBase::FastMathFlagGuard Guard(B); 2266 B.setFastMathFlags(I->getFastMathFlags()); 2267 2268 // If we found a repeated factor, hoist it out of the square root and 2269 // replace it with the fabs of that factor. 2270 Type *ArgType = I->getType(); 2271 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType); 2272 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs"); 2273 if (OtherOp) { 2274 // If we found a non-repeated factor, we still need to get its square 2275 // root. We then multiply that by the value that was simplified out 2276 // of the square root calculation. 2277 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType); 2278 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt"); 2279 return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall)); 2280 } 2281 return copyFlags(*CI, FabsCall); 2282 } 2283 2284 // TODO: Generalize to handle any trig function and its inverse. 2285 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilderBase &B) { 2286 Module *M = CI->getModule(); 2287 Function *Callee = CI->getCalledFunction(); 2288 Value *Ret = nullptr; 2289 StringRef Name = Callee->getName(); 2290 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(M, Name)) 2291 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2292 2293 Value *Op1 = CI->getArgOperand(0); 2294 auto *OpC = dyn_cast<CallInst>(Op1); 2295 if (!OpC) 2296 return Ret; 2297 2298 // Both calls must be 'fast' in order to remove them. 2299 if (!CI->isFast() || !OpC->isFast()) 2300 return Ret; 2301 2302 // tan(atan(x)) -> x 2303 // tanf(atanf(x)) -> x 2304 // tanl(atanl(x)) -> x 2305 LibFunc Func; 2306 Function *F = OpC->getCalledFunction(); 2307 if (F && TLI->getLibFunc(F->getName(), Func) && 2308 isLibFuncEmittable(M, TLI, Func) && 2309 ((Func == LibFunc_atan && Callee->getName() == "tan") || 2310 (Func == LibFunc_atanf && Callee->getName() == "tanf") || 2311 (Func == LibFunc_atanl && Callee->getName() == "tanl"))) 2312 Ret = OpC->getArgOperand(0); 2313 return Ret; 2314 } 2315 2316 static bool isTrigLibCall(CallInst *CI) { 2317 // We can only hope to do anything useful if we can ignore things like errno 2318 // and floating-point exceptions. 2319 // We already checked the prototype. 2320 return CI->hasFnAttr(Attribute::NoUnwind) && 2321 CI->hasFnAttr(Attribute::ReadNone); 2322 } 2323 2324 static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg, 2325 bool UseFloat, Value *&Sin, Value *&Cos, 2326 Value *&SinCos, const TargetLibraryInfo *TLI) { 2327 Module *M = OrigCallee->getParent(); 2328 Type *ArgTy = Arg->getType(); 2329 Type *ResTy; 2330 StringRef Name; 2331 2332 Triple T(OrigCallee->getParent()->getTargetTriple()); 2333 if (UseFloat) { 2334 Name = "__sincospif_stret"; 2335 2336 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 2337 // x86_64 can't use {float, float} since that would be returned in both 2338 // xmm0 and xmm1, which isn't what a real struct would do. 2339 ResTy = T.getArch() == Triple::x86_64 2340 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2)) 2341 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 2342 } else { 2343 Name = "__sincospi_stret"; 2344 ResTy = StructType::get(ArgTy, ArgTy); 2345 } 2346 2347 if (!isLibFuncEmittable(M, TLI, Name)) 2348 return false; 2349 LibFunc TheLibFunc; 2350 TLI->getLibFunc(Name, TheLibFunc); 2351 FunctionCallee Callee = getOrInsertLibFunc( 2352 M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy); 2353 2354 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 2355 // If the argument is an instruction, it must dominate all uses so put our 2356 // sincos call there. 2357 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 2358 } else { 2359 // Otherwise (e.g. for a constant) the beginning of the function is as 2360 // good a place as any. 2361 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 2362 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 2363 } 2364 2365 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 2366 2367 if (SinCos->getType()->isStructTy()) { 2368 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 2369 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 2370 } else { 2371 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 2372 "sinpi"); 2373 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 2374 "cospi"); 2375 } 2376 2377 return true; 2378 } 2379 2380 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilderBase &B) { 2381 // Make sure the prototype is as expected, otherwise the rest of the 2382 // function is probably invalid and likely to abort. 2383 if (!isTrigLibCall(CI)) 2384 return nullptr; 2385 2386 Value *Arg = CI->getArgOperand(0); 2387 SmallVector<CallInst *, 1> SinCalls; 2388 SmallVector<CallInst *, 1> CosCalls; 2389 SmallVector<CallInst *, 1> SinCosCalls; 2390 2391 bool IsFloat = Arg->getType()->isFloatTy(); 2392 2393 // Look for all compatible sinpi, cospi and sincospi calls with the same 2394 // argument. If there are enough (in some sense) we can make the 2395 // substitution. 2396 Function *F = CI->getFunction(); 2397 for (User *U : Arg->users()) 2398 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 2399 2400 // It's only worthwhile if both sinpi and cospi are actually used. 2401 if (SinCalls.empty() || CosCalls.empty()) 2402 return nullptr; 2403 2404 Value *Sin, *Cos, *SinCos; 2405 if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, 2406 SinCos, TLI)) 2407 return nullptr; 2408 2409 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 2410 Value *Res) { 2411 for (CallInst *C : Calls) 2412 replaceAllUsesWith(C, Res); 2413 }; 2414 2415 replaceTrigInsts(SinCalls, Sin); 2416 replaceTrigInsts(CosCalls, Cos); 2417 replaceTrigInsts(SinCosCalls, SinCos); 2418 2419 return nullptr; 2420 } 2421 2422 void LibCallSimplifier::classifyArgUse( 2423 Value *Val, Function *F, bool IsFloat, 2424 SmallVectorImpl<CallInst *> &SinCalls, 2425 SmallVectorImpl<CallInst *> &CosCalls, 2426 SmallVectorImpl<CallInst *> &SinCosCalls) { 2427 CallInst *CI = dyn_cast<CallInst>(Val); 2428 Module *M = CI->getModule(); 2429 2430 if (!CI || CI->use_empty()) 2431 return; 2432 2433 // Don't consider calls in other functions. 2434 if (CI->getFunction() != F) 2435 return; 2436 2437 Function *Callee = CI->getCalledFunction(); 2438 LibFunc Func; 2439 if (!Callee || !TLI->getLibFunc(*Callee, Func) || 2440 !isLibFuncEmittable(M, TLI, Func) || 2441 !isTrigLibCall(CI)) 2442 return; 2443 2444 if (IsFloat) { 2445 if (Func == LibFunc_sinpif) 2446 SinCalls.push_back(CI); 2447 else if (Func == LibFunc_cospif) 2448 CosCalls.push_back(CI); 2449 else if (Func == LibFunc_sincospif_stret) 2450 SinCosCalls.push_back(CI); 2451 } else { 2452 if (Func == LibFunc_sinpi) 2453 SinCalls.push_back(CI); 2454 else if (Func == LibFunc_cospi) 2455 CosCalls.push_back(CI); 2456 else if (Func == LibFunc_sincospi_stret) 2457 SinCosCalls.push_back(CI); 2458 } 2459 } 2460 2461 //===----------------------------------------------------------------------===// 2462 // Integer Library Call Optimizations 2463 //===----------------------------------------------------------------------===// 2464 2465 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) { 2466 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 2467 Value *Op = CI->getArgOperand(0); 2468 Type *ArgType = Op->getType(); 2469 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 2470 Intrinsic::cttz, ArgType); 2471 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz"); 2472 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 2473 V = B.CreateIntCast(V, B.getInt32Ty(), false); 2474 2475 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 2476 return B.CreateSelect(Cond, V, B.getInt32(0)); 2477 } 2478 2479 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) { 2480 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false)) 2481 Value *Op = CI->getArgOperand(0); 2482 Type *ArgType = Op->getType(); 2483 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 2484 Intrinsic::ctlz, ArgType); 2485 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz"); 2486 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 2487 V); 2488 return B.CreateIntCast(V, CI->getType(), false); 2489 } 2490 2491 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) { 2492 // abs(x) -> x <s 0 ? -x : x 2493 // The negation has 'nsw' because abs of INT_MIN is undefined. 2494 Value *X = CI->getArgOperand(0); 2495 Value *IsNeg = B.CreateIsNeg(X); 2496 Value *NegX = B.CreateNSWNeg(X, "neg"); 2497 return B.CreateSelect(IsNeg, NegX, X); 2498 } 2499 2500 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) { 2501 // isdigit(c) -> (c-'0') <u 10 2502 Value *Op = CI->getArgOperand(0); 2503 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp"); 2504 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit"); 2505 return B.CreateZExt(Op, CI->getType()); 2506 } 2507 2508 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) { 2509 // isascii(c) -> c <u 128 2510 Value *Op = CI->getArgOperand(0); 2511 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii"); 2512 return B.CreateZExt(Op, CI->getType()); 2513 } 2514 2515 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) { 2516 // toascii(c) -> c & 0x7f 2517 return B.CreateAnd(CI->getArgOperand(0), 2518 ConstantInt::get(CI->getType(), 0x7F)); 2519 } 2520 2521 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) { 2522 StringRef Str; 2523 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2524 return nullptr; 2525 2526 return convertStrToNumber(CI, Str, 10); 2527 } 2528 2529 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilderBase &B) { 2530 StringRef Str; 2531 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2532 return nullptr; 2533 2534 if (!isa<ConstantPointerNull>(CI->getArgOperand(1))) 2535 return nullptr; 2536 2537 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) { 2538 return convertStrToNumber(CI, Str, CInt->getSExtValue()); 2539 } 2540 2541 return nullptr; 2542 } 2543 2544 //===----------------------------------------------------------------------===// 2545 // Formatting and IO Library Call Optimizations 2546 //===----------------------------------------------------------------------===// 2547 2548 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 2549 2550 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B, 2551 int StreamArg) { 2552 Function *Callee = CI->getCalledFunction(); 2553 // Error reporting calls should be cold, mark them as such. 2554 // This applies even to non-builtin calls: it is only a hint and applies to 2555 // functions that the frontend might not understand as builtins. 2556 2557 // This heuristic was suggested in: 2558 // Improving Static Branch Prediction in a Compiler 2559 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 2560 // Proceedings of PACT'98, Oct. 1998, IEEE 2561 if (!CI->hasFnAttr(Attribute::Cold) && 2562 isReportingError(Callee, CI, StreamArg)) { 2563 CI->addFnAttr(Attribute::Cold); 2564 } 2565 2566 return nullptr; 2567 } 2568 2569 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 2570 if (!Callee || !Callee->isDeclaration()) 2571 return false; 2572 2573 if (StreamArg < 0) 2574 return true; 2575 2576 // These functions might be considered cold, but only if their stream 2577 // argument is stderr. 2578 2579 if (StreamArg >= (int)CI->arg_size()) 2580 return false; 2581 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 2582 if (!LI) 2583 return false; 2584 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 2585 if (!GV || !GV->isDeclaration()) 2586 return false; 2587 return GV->getName() == "stderr"; 2588 } 2589 2590 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) { 2591 // Check for a fixed format string. 2592 StringRef FormatStr; 2593 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 2594 return nullptr; 2595 2596 // Empty format string -> noop. 2597 if (FormatStr.empty()) // Tolerate printf's declared void. 2598 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 2599 2600 // Do not do any of the following transformations if the printf return value 2601 // is used, in general the printf return value is not compatible with either 2602 // putchar() or puts(). 2603 if (!CI->use_empty()) 2604 return nullptr; 2605 2606 // printf("x") -> putchar('x'), even for "%" and "%%". 2607 if (FormatStr.size() == 1 || FormatStr == "%%") 2608 return copyFlags(*CI, emitPutChar(B.getInt32(FormatStr[0]), B, TLI)); 2609 2610 // Try to remove call or emit putchar/puts. 2611 if (FormatStr == "%s" && CI->arg_size() > 1) { 2612 StringRef OperandStr; 2613 if (!getConstantStringInfo(CI->getOperand(1), OperandStr)) 2614 return nullptr; 2615 // printf("%s", "") --> NOP 2616 if (OperandStr.empty()) 2617 return (Value *)CI; 2618 // printf("%s", "a") --> putchar('a') 2619 if (OperandStr.size() == 1) 2620 return copyFlags(*CI, emitPutChar(B.getInt32(OperandStr[0]), B, TLI)); 2621 // printf("%s", str"\n") --> puts(str) 2622 if (OperandStr.back() == '\n') { 2623 OperandStr = OperandStr.drop_back(); 2624 Value *GV = B.CreateGlobalString(OperandStr, "str"); 2625 return copyFlags(*CI, emitPutS(GV, B, TLI)); 2626 } 2627 return nullptr; 2628 } 2629 2630 // printf("foo\n") --> puts("foo") 2631 if (FormatStr.back() == '\n' && 2632 !FormatStr.contains('%')) { // No format characters. 2633 // Create a string literal with no \n on it. We expect the constant merge 2634 // pass to be run after this pass, to merge duplicate strings. 2635 FormatStr = FormatStr.drop_back(); 2636 Value *GV = B.CreateGlobalString(FormatStr, "str"); 2637 return copyFlags(*CI, emitPutS(GV, B, TLI)); 2638 } 2639 2640 // Optimize specific format strings. 2641 // printf("%c", chr) --> putchar(chr) 2642 if (FormatStr == "%c" && CI->arg_size() > 1 && 2643 CI->getArgOperand(1)->getType()->isIntegerTy()) 2644 return copyFlags(*CI, emitPutChar(CI->getArgOperand(1), B, TLI)); 2645 2646 // printf("%s\n", str) --> puts(str) 2647 if (FormatStr == "%s\n" && CI->arg_size() > 1 && 2648 CI->getArgOperand(1)->getType()->isPointerTy()) 2649 return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI)); 2650 return nullptr; 2651 } 2652 2653 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) { 2654 2655 Module *M = CI->getModule(); 2656 Function *Callee = CI->getCalledFunction(); 2657 FunctionType *FT = Callee->getFunctionType(); 2658 if (Value *V = optimizePrintFString(CI, B)) { 2659 return V; 2660 } 2661 2662 // printf(format, ...) -> iprintf(format, ...) if no floating point 2663 // arguments. 2664 if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) && 2665 !callHasFloatingPointArgument(CI)) { 2666 FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT, 2667 Callee->getAttributes()); 2668 CallInst *New = cast<CallInst>(CI->clone()); 2669 New->setCalledFunction(IPrintFFn); 2670 B.Insert(New); 2671 return New; 2672 } 2673 2674 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point 2675 // arguments. 2676 if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) && 2677 !callHasFP128Argument(CI)) { 2678 auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT, 2679 Callee->getAttributes()); 2680 CallInst *New = cast<CallInst>(CI->clone()); 2681 New->setCalledFunction(SmallPrintFFn); 2682 B.Insert(New); 2683 return New; 2684 } 2685 2686 annotateNonNullNoUndefBasedOnAccess(CI, 0); 2687 return nullptr; 2688 } 2689 2690 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, 2691 IRBuilderBase &B) { 2692 // Check for a fixed format string. 2693 StringRef FormatStr; 2694 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 2695 return nullptr; 2696 2697 // If we just have a format string (nothing else crazy) transform it. 2698 Value *Dest = CI->getArgOperand(0); 2699 if (CI->arg_size() == 2) { 2700 // Make sure there's no % in the constant array. We could try to handle 2701 // %% -> % in the future if we cared. 2702 if (FormatStr.contains('%')) 2703 return nullptr; // we found a format specifier, bail out. 2704 2705 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1) 2706 B.CreateMemCpy( 2707 Dest, Align(1), CI->getArgOperand(1), Align(1), 2708 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2709 FormatStr.size() + 1)); // Copy the null byte. 2710 return ConstantInt::get(CI->getType(), FormatStr.size()); 2711 } 2712 2713 // The remaining optimizations require the format string to be "%s" or "%c" 2714 // and have an extra operand. 2715 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 2716 return nullptr; 2717 2718 // Decode the second character of the format string. 2719 if (FormatStr[1] == 'c') { 2720 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 2721 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 2722 return nullptr; 2723 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 2724 Value *Ptr = castToCStr(Dest, B); 2725 B.CreateStore(V, Ptr); 2726 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 2727 B.CreateStore(B.getInt8(0), Ptr); 2728 2729 return ConstantInt::get(CI->getType(), 1); 2730 } 2731 2732 if (FormatStr[1] == 's') { 2733 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str, 2734 // strlen(str)+1) 2735 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2736 return nullptr; 2737 2738 if (CI->use_empty()) 2739 // sprintf(dest, "%s", str) -> strcpy(dest, str) 2740 return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI)); 2741 2742 uint64_t SrcLen = GetStringLength(CI->getArgOperand(2)); 2743 if (SrcLen) { 2744 B.CreateMemCpy( 2745 Dest, Align(1), CI->getArgOperand(2), Align(1), 2746 ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen)); 2747 // Returns total number of characters written without null-character. 2748 return ConstantInt::get(CI->getType(), SrcLen - 1); 2749 } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) { 2750 // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest 2751 // Handle mismatched pointer types (goes away with typeless pointers?). 2752 V = B.CreatePointerCast(V, B.getInt8PtrTy()); 2753 Dest = B.CreatePointerCast(Dest, B.getInt8PtrTy()); 2754 Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest); 2755 return B.CreateIntCast(PtrDiff, CI->getType(), false); 2756 } 2757 2758 bool OptForSize = CI->getFunction()->hasOptSize() || 2759 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 2760 PGSOQueryType::IRPass); 2761 if (OptForSize) 2762 return nullptr; 2763 2764 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 2765 if (!Len) 2766 return nullptr; 2767 Value *IncLen = 2768 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 2769 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen); 2770 2771 // The sprintf result is the unincremented number of bytes in the string. 2772 return B.CreateIntCast(Len, CI->getType(), false); 2773 } 2774 return nullptr; 2775 } 2776 2777 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) { 2778 Module *M = CI->getModule(); 2779 Function *Callee = CI->getCalledFunction(); 2780 FunctionType *FT = Callee->getFunctionType(); 2781 if (Value *V = optimizeSPrintFString(CI, B)) { 2782 return V; 2783 } 2784 2785 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 2786 // point arguments. 2787 if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) && 2788 !callHasFloatingPointArgument(CI)) { 2789 FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf, 2790 FT, Callee->getAttributes()); 2791 CallInst *New = cast<CallInst>(CI->clone()); 2792 New->setCalledFunction(SIPrintFFn); 2793 B.Insert(New); 2794 return New; 2795 } 2796 2797 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit 2798 // floating point arguments. 2799 if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) && 2800 !callHasFP128Argument(CI)) { 2801 auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT, 2802 Callee->getAttributes()); 2803 CallInst *New = cast<CallInst>(CI->clone()); 2804 New->setCalledFunction(SmallSPrintFFn); 2805 B.Insert(New); 2806 return New; 2807 } 2808 2809 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 2810 return nullptr; 2811 } 2812 2813 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, 2814 IRBuilderBase &B) { 2815 // Check for size 2816 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2817 if (!Size) 2818 return nullptr; 2819 2820 uint64_t N = Size->getZExtValue(); 2821 // Check for a fixed format string. 2822 StringRef FormatStr; 2823 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr)) 2824 return nullptr; 2825 2826 // If we just have a format string (nothing else crazy) transform it. 2827 if (CI->arg_size() == 3) { 2828 // Make sure there's no % in the constant array. We could try to handle 2829 // %% -> % in the future if we cared. 2830 if (FormatStr.contains('%')) 2831 return nullptr; // we found a format specifier, bail out. 2832 2833 if (N == 0) 2834 return ConstantInt::get(CI->getType(), FormatStr.size()); 2835 else if (N < FormatStr.size() + 1) 2836 return nullptr; 2837 2838 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt, 2839 // strlen(fmt)+1) 2840 copyFlags( 2841 *CI, 2842 B.CreateMemCpy( 2843 CI->getArgOperand(0), Align(1), CI->getArgOperand(2), Align(1), 2844 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2845 FormatStr.size() + 1))); // Copy the null byte. 2846 return ConstantInt::get(CI->getType(), FormatStr.size()); 2847 } 2848 2849 // The remaining optimizations require the format string to be "%s" or "%c" 2850 // and have an extra operand. 2851 if (FormatStr.size() == 2 && FormatStr[0] == '%' && CI->arg_size() == 4) { 2852 2853 // Decode the second character of the format string. 2854 if (FormatStr[1] == 'c') { 2855 if (N == 0) 2856 return ConstantInt::get(CI->getType(), 1); 2857 else if (N == 1) 2858 return nullptr; 2859 2860 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 2861 if (!CI->getArgOperand(3)->getType()->isIntegerTy()) 2862 return nullptr; 2863 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char"); 2864 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 2865 B.CreateStore(V, Ptr); 2866 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 2867 B.CreateStore(B.getInt8(0), Ptr); 2868 2869 return ConstantInt::get(CI->getType(), 1); 2870 } 2871 2872 if (FormatStr[1] == 's') { 2873 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1) 2874 StringRef Str; 2875 if (!getConstantStringInfo(CI->getArgOperand(3), Str)) 2876 return nullptr; 2877 2878 if (N == 0) 2879 return ConstantInt::get(CI->getType(), Str.size()); 2880 else if (N < Str.size() + 1) 2881 return nullptr; 2882 2883 copyFlags( 2884 *CI, B.CreateMemCpy(CI->getArgOperand(0), Align(1), 2885 CI->getArgOperand(3), Align(1), 2886 ConstantInt::get(CI->getType(), Str.size() + 1))); 2887 2888 // The snprintf result is the unincremented number of bytes in the string. 2889 return ConstantInt::get(CI->getType(), Str.size()); 2890 } 2891 } 2892 return nullptr; 2893 } 2894 2895 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) { 2896 if (Value *V = optimizeSnPrintFString(CI, B)) { 2897 return V; 2898 } 2899 2900 if (isKnownNonZero(CI->getOperand(1), DL)) 2901 annotateNonNullNoUndefBasedOnAccess(CI, 0); 2902 return nullptr; 2903 } 2904 2905 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, 2906 IRBuilderBase &B) { 2907 optimizeErrorReporting(CI, B, 0); 2908 2909 // All the optimizations depend on the format string. 2910 StringRef FormatStr; 2911 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 2912 return nullptr; 2913 2914 // Do not do any of the following transformations if the fprintf return 2915 // value is used, in general the fprintf return value is not compatible 2916 // with fwrite(), fputc() or fputs(). 2917 if (!CI->use_empty()) 2918 return nullptr; 2919 2920 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 2921 if (CI->arg_size() == 2) { 2922 // Could handle %% -> % if we cared. 2923 if (FormatStr.contains('%')) 2924 return nullptr; // We found a format specifier. 2925 2926 return copyFlags( 2927 *CI, emitFWrite(CI->getArgOperand(1), 2928 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2929 FormatStr.size()), 2930 CI->getArgOperand(0), B, DL, TLI)); 2931 } 2932 2933 // The remaining optimizations require the format string to be "%s" or "%c" 2934 // and have an extra operand. 2935 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 2936 return nullptr; 2937 2938 // Decode the second character of the format string. 2939 if (FormatStr[1] == 'c') { 2940 // fprintf(F, "%c", chr) --> fputc(chr, F) 2941 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 2942 return nullptr; 2943 return copyFlags( 2944 *CI, emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI)); 2945 } 2946 2947 if (FormatStr[1] == 's') { 2948 // fprintf(F, "%s", str) --> fputs(str, F) 2949 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2950 return nullptr; 2951 return copyFlags( 2952 *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI)); 2953 } 2954 return nullptr; 2955 } 2956 2957 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) { 2958 Module *M = CI->getModule(); 2959 Function *Callee = CI->getCalledFunction(); 2960 FunctionType *FT = Callee->getFunctionType(); 2961 if (Value *V = optimizeFPrintFString(CI, B)) { 2962 return V; 2963 } 2964 2965 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 2966 // floating point arguments. 2967 if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) && 2968 !callHasFloatingPointArgument(CI)) { 2969 FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf, 2970 FT, Callee->getAttributes()); 2971 CallInst *New = cast<CallInst>(CI->clone()); 2972 New->setCalledFunction(FIPrintFFn); 2973 B.Insert(New); 2974 return New; 2975 } 2976 2977 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no 2978 // 128-bit floating point arguments. 2979 if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) && 2980 !callHasFP128Argument(CI)) { 2981 auto SmallFPrintFFn = 2982 getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT, 2983 Callee->getAttributes()); 2984 CallInst *New = cast<CallInst>(CI->clone()); 2985 New->setCalledFunction(SmallFPrintFFn); 2986 B.Insert(New); 2987 return New; 2988 } 2989 2990 return nullptr; 2991 } 2992 2993 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) { 2994 optimizeErrorReporting(CI, B, 3); 2995 2996 // Get the element size and count. 2997 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2998 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 2999 if (SizeC && CountC) { 3000 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 3001 3002 // If this is writing zero records, remove the call (it's a noop). 3003 if (Bytes == 0) 3004 return ConstantInt::get(CI->getType(), 0); 3005 3006 // If this is writing one byte, turn it into fputc. 3007 // This optimisation is only valid, if the return value is unused. 3008 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 3009 Value *Char = B.CreateLoad(B.getInt8Ty(), 3010 castToCStr(CI->getArgOperand(0), B), "char"); 3011 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI); 3012 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 3013 } 3014 } 3015 3016 return nullptr; 3017 } 3018 3019 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) { 3020 optimizeErrorReporting(CI, B, 1); 3021 3022 // Don't rewrite fputs to fwrite when optimising for size because fwrite 3023 // requires more arguments and thus extra MOVs are required. 3024 bool OptForSize = CI->getFunction()->hasOptSize() || 3025 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 3026 PGSOQueryType::IRPass); 3027 if (OptForSize) 3028 return nullptr; 3029 3030 // We can't optimize if return value is used. 3031 if (!CI->use_empty()) 3032 return nullptr; 3033 3034 // fputs(s,F) --> fwrite(s,strlen(s),1,F) 3035 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 3036 if (!Len) 3037 return nullptr; 3038 3039 // Known to have no uses (see above). 3040 return copyFlags( 3041 *CI, 3042 emitFWrite(CI->getArgOperand(0), 3043 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1), 3044 CI->getArgOperand(1), B, DL, TLI)); 3045 } 3046 3047 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) { 3048 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3049 if (!CI->use_empty()) 3050 return nullptr; 3051 3052 // Check for a constant string. 3053 // puts("") -> putchar('\n') 3054 StringRef Str; 3055 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) 3056 return copyFlags(*CI, emitPutChar(B.getInt32('\n'), B, TLI)); 3057 3058 return nullptr; 3059 } 3060 3061 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) { 3062 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n) 3063 return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1), 3064 CI->getArgOperand(0), Align(1), 3065 CI->getArgOperand(2))); 3066 } 3067 3068 bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) { 3069 SmallString<20> FloatFuncName = FuncName; 3070 FloatFuncName += 'f'; 3071 return isLibFuncEmittable(M, TLI, FloatFuncName); 3072 } 3073 3074 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 3075 IRBuilderBase &Builder) { 3076 Module *M = CI->getModule(); 3077 LibFunc Func; 3078 Function *Callee = CI->getCalledFunction(); 3079 // Check for string/memory library functions. 3080 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 3081 // Make sure we never change the calling convention. 3082 assert( 3083 (ignoreCallingConv(Func) || 3084 TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) && 3085 "Optimizing string/memory libcall would change the calling convention"); 3086 switch (Func) { 3087 case LibFunc_strcat: 3088 return optimizeStrCat(CI, Builder); 3089 case LibFunc_strncat: 3090 return optimizeStrNCat(CI, Builder); 3091 case LibFunc_strchr: 3092 return optimizeStrChr(CI, Builder); 3093 case LibFunc_strrchr: 3094 return optimizeStrRChr(CI, Builder); 3095 case LibFunc_strcmp: 3096 return optimizeStrCmp(CI, Builder); 3097 case LibFunc_strncmp: 3098 return optimizeStrNCmp(CI, Builder); 3099 case LibFunc_strcpy: 3100 return optimizeStrCpy(CI, Builder); 3101 case LibFunc_stpcpy: 3102 return optimizeStpCpy(CI, Builder); 3103 case LibFunc_strncpy: 3104 return optimizeStrNCpy(CI, Builder); 3105 case LibFunc_strlen: 3106 return optimizeStrLen(CI, Builder); 3107 case LibFunc_strnlen: 3108 return optimizeStrNLen(CI, Builder); 3109 case LibFunc_strpbrk: 3110 return optimizeStrPBrk(CI, Builder); 3111 case LibFunc_strndup: 3112 return optimizeStrNDup(CI, Builder); 3113 case LibFunc_strtol: 3114 case LibFunc_strtod: 3115 case LibFunc_strtof: 3116 case LibFunc_strtoul: 3117 case LibFunc_strtoll: 3118 case LibFunc_strtold: 3119 case LibFunc_strtoull: 3120 return optimizeStrTo(CI, Builder); 3121 case LibFunc_strspn: 3122 return optimizeStrSpn(CI, Builder); 3123 case LibFunc_strcspn: 3124 return optimizeStrCSpn(CI, Builder); 3125 case LibFunc_strstr: 3126 return optimizeStrStr(CI, Builder); 3127 case LibFunc_memchr: 3128 return optimizeMemChr(CI, Builder); 3129 case LibFunc_memrchr: 3130 return optimizeMemRChr(CI, Builder); 3131 case LibFunc_bcmp: 3132 return optimizeBCmp(CI, Builder); 3133 case LibFunc_memcmp: 3134 return optimizeMemCmp(CI, Builder); 3135 case LibFunc_memcpy: 3136 return optimizeMemCpy(CI, Builder); 3137 case LibFunc_memccpy: 3138 return optimizeMemCCpy(CI, Builder); 3139 case LibFunc_mempcpy: 3140 return optimizeMemPCpy(CI, Builder); 3141 case LibFunc_memmove: 3142 return optimizeMemMove(CI, Builder); 3143 case LibFunc_memset: 3144 return optimizeMemSet(CI, Builder); 3145 case LibFunc_realloc: 3146 return optimizeRealloc(CI, Builder); 3147 case LibFunc_wcslen: 3148 return optimizeWcslen(CI, Builder); 3149 case LibFunc_bcopy: 3150 return optimizeBCopy(CI, Builder); 3151 default: 3152 break; 3153 } 3154 } 3155 return nullptr; 3156 } 3157 3158 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 3159 LibFunc Func, 3160 IRBuilderBase &Builder) { 3161 const Module *M = CI->getModule(); 3162 3163 // Don't optimize calls that require strict floating point semantics. 3164 if (CI->isStrictFP()) 3165 return nullptr; 3166 3167 if (Value *V = optimizeTrigReflections(CI, Func, Builder)) 3168 return V; 3169 3170 switch (Func) { 3171 case LibFunc_sinpif: 3172 case LibFunc_sinpi: 3173 case LibFunc_cospif: 3174 case LibFunc_cospi: 3175 return optimizeSinCosPi(CI, Builder); 3176 case LibFunc_powf: 3177 case LibFunc_pow: 3178 case LibFunc_powl: 3179 return optimizePow(CI, Builder); 3180 case LibFunc_exp2l: 3181 case LibFunc_exp2: 3182 case LibFunc_exp2f: 3183 return optimizeExp2(CI, Builder); 3184 case LibFunc_fabsf: 3185 case LibFunc_fabs: 3186 case LibFunc_fabsl: 3187 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 3188 case LibFunc_sqrtf: 3189 case LibFunc_sqrt: 3190 case LibFunc_sqrtl: 3191 return optimizeSqrt(CI, Builder); 3192 case LibFunc_logf: 3193 case LibFunc_log: 3194 case LibFunc_logl: 3195 case LibFunc_log10f: 3196 case LibFunc_log10: 3197 case LibFunc_log10l: 3198 case LibFunc_log1pf: 3199 case LibFunc_log1p: 3200 case LibFunc_log1pl: 3201 case LibFunc_log2f: 3202 case LibFunc_log2: 3203 case LibFunc_log2l: 3204 case LibFunc_logbf: 3205 case LibFunc_logb: 3206 case LibFunc_logbl: 3207 return optimizeLog(CI, Builder); 3208 case LibFunc_tan: 3209 case LibFunc_tanf: 3210 case LibFunc_tanl: 3211 return optimizeTan(CI, Builder); 3212 case LibFunc_ceil: 3213 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 3214 case LibFunc_floor: 3215 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 3216 case LibFunc_round: 3217 return replaceUnaryCall(CI, Builder, Intrinsic::round); 3218 case LibFunc_roundeven: 3219 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven); 3220 case LibFunc_nearbyint: 3221 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 3222 case LibFunc_rint: 3223 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 3224 case LibFunc_trunc: 3225 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 3226 case LibFunc_acos: 3227 case LibFunc_acosh: 3228 case LibFunc_asin: 3229 case LibFunc_asinh: 3230 case LibFunc_atan: 3231 case LibFunc_atanh: 3232 case LibFunc_cbrt: 3233 case LibFunc_cosh: 3234 case LibFunc_exp: 3235 case LibFunc_exp10: 3236 case LibFunc_expm1: 3237 case LibFunc_cos: 3238 case LibFunc_sin: 3239 case LibFunc_sinh: 3240 case LibFunc_tanh: 3241 if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName())) 3242 return optimizeUnaryDoubleFP(CI, Builder, TLI, true); 3243 return nullptr; 3244 case LibFunc_copysign: 3245 if (hasFloatVersion(M, CI->getCalledFunction()->getName())) 3246 return optimizeBinaryDoubleFP(CI, Builder, TLI); 3247 return nullptr; 3248 case LibFunc_fminf: 3249 case LibFunc_fmin: 3250 case LibFunc_fminl: 3251 case LibFunc_fmaxf: 3252 case LibFunc_fmax: 3253 case LibFunc_fmaxl: 3254 return optimizeFMinFMax(CI, Builder); 3255 case LibFunc_cabs: 3256 case LibFunc_cabsf: 3257 case LibFunc_cabsl: 3258 return optimizeCAbs(CI, Builder); 3259 default: 3260 return nullptr; 3261 } 3262 } 3263 3264 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) { 3265 Module *M = CI->getModule(); 3266 assert(!CI->isMustTailCall() && "These transforms aren't musttail safe."); 3267 3268 // TODO: Split out the code below that operates on FP calls so that 3269 // we can all non-FP calls with the StrictFP attribute to be 3270 // optimized. 3271 if (CI->isNoBuiltin()) 3272 return nullptr; 3273 3274 LibFunc Func; 3275 Function *Callee = CI->getCalledFunction(); 3276 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 3277 3278 SmallVector<OperandBundleDef, 2> OpBundles; 3279 CI->getOperandBundlesAsDefs(OpBundles); 3280 3281 IRBuilderBase::OperandBundlesGuard Guard(Builder); 3282 Builder.setDefaultOperandBundles(OpBundles); 3283 3284 // Command-line parameter overrides instruction attribute. 3285 // This can't be moved to optimizeFloatingPointLibCall() because it may be 3286 // used by the intrinsic optimizations. 3287 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 3288 UnsafeFPShrink = EnableUnsafeFPShrink; 3289 else if (isa<FPMathOperator>(CI) && CI->isFast()) 3290 UnsafeFPShrink = true; 3291 3292 // First, check for intrinsics. 3293 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 3294 if (!IsCallingConvC) 3295 return nullptr; 3296 // The FP intrinsics have corresponding constrained versions so we don't 3297 // need to check for the StrictFP attribute here. 3298 switch (II->getIntrinsicID()) { 3299 case Intrinsic::pow: 3300 return optimizePow(CI, Builder); 3301 case Intrinsic::exp2: 3302 return optimizeExp2(CI, Builder); 3303 case Intrinsic::log: 3304 case Intrinsic::log2: 3305 case Intrinsic::log10: 3306 return optimizeLog(CI, Builder); 3307 case Intrinsic::sqrt: 3308 return optimizeSqrt(CI, Builder); 3309 case Intrinsic::memset: 3310 return optimizeMemSet(CI, Builder); 3311 case Intrinsic::memcpy: 3312 return optimizeMemCpy(CI, Builder); 3313 case Intrinsic::memmove: 3314 return optimizeMemMove(CI, Builder); 3315 default: 3316 return nullptr; 3317 } 3318 } 3319 3320 // Also try to simplify calls to fortified library functions. 3321 if (Value *SimplifiedFortifiedCI = 3322 FortifiedSimplifier.optimizeCall(CI, Builder)) { 3323 // Try to further simplify the result. 3324 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI); 3325 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) { 3326 // Ensure that SimplifiedCI's uses are complete, since some calls have 3327 // their uses analyzed. 3328 replaceAllUsesWith(CI, SimplifiedCI); 3329 3330 // Set insertion point to SimplifiedCI to guarantee we reach all uses 3331 // we might replace later on. 3332 IRBuilderBase::InsertPointGuard Guard(Builder); 3333 Builder.SetInsertPoint(SimplifiedCI); 3334 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) { 3335 // If we were able to further simplify, remove the now redundant call. 3336 substituteInParent(SimplifiedCI, V); 3337 return V; 3338 } 3339 } 3340 return SimplifiedFortifiedCI; 3341 } 3342 3343 // Then check for known library functions. 3344 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 3345 // We never change the calling convention. 3346 if (!ignoreCallingConv(Func) && !IsCallingConvC) 3347 return nullptr; 3348 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 3349 return V; 3350 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 3351 return V; 3352 switch (Func) { 3353 case LibFunc_ffs: 3354 case LibFunc_ffsl: 3355 case LibFunc_ffsll: 3356 return optimizeFFS(CI, Builder); 3357 case LibFunc_fls: 3358 case LibFunc_flsl: 3359 case LibFunc_flsll: 3360 return optimizeFls(CI, Builder); 3361 case LibFunc_abs: 3362 case LibFunc_labs: 3363 case LibFunc_llabs: 3364 return optimizeAbs(CI, Builder); 3365 case LibFunc_isdigit: 3366 return optimizeIsDigit(CI, Builder); 3367 case LibFunc_isascii: 3368 return optimizeIsAscii(CI, Builder); 3369 case LibFunc_toascii: 3370 return optimizeToAscii(CI, Builder); 3371 case LibFunc_atoi: 3372 case LibFunc_atol: 3373 case LibFunc_atoll: 3374 return optimizeAtoi(CI, Builder); 3375 case LibFunc_strtol: 3376 case LibFunc_strtoll: 3377 return optimizeStrtol(CI, Builder); 3378 case LibFunc_printf: 3379 return optimizePrintF(CI, Builder); 3380 case LibFunc_sprintf: 3381 return optimizeSPrintF(CI, Builder); 3382 case LibFunc_snprintf: 3383 return optimizeSnPrintF(CI, Builder); 3384 case LibFunc_fprintf: 3385 return optimizeFPrintF(CI, Builder); 3386 case LibFunc_fwrite: 3387 return optimizeFWrite(CI, Builder); 3388 case LibFunc_fputs: 3389 return optimizeFPuts(CI, Builder); 3390 case LibFunc_puts: 3391 return optimizePuts(CI, Builder); 3392 case LibFunc_perror: 3393 return optimizeErrorReporting(CI, Builder); 3394 case LibFunc_vfprintf: 3395 case LibFunc_fiprintf: 3396 return optimizeErrorReporting(CI, Builder, 0); 3397 default: 3398 return nullptr; 3399 } 3400 } 3401 return nullptr; 3402 } 3403 3404 LibCallSimplifier::LibCallSimplifier( 3405 const DataLayout &DL, const TargetLibraryInfo *TLI, 3406 OptimizationRemarkEmitter &ORE, 3407 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 3408 function_ref<void(Instruction *, Value *)> Replacer, 3409 function_ref<void(Instruction *)> Eraser) 3410 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI), 3411 Replacer(Replacer), Eraser(Eraser) {} 3412 3413 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 3414 // Indirect through the replacer used in this instance. 3415 Replacer(I, With); 3416 } 3417 3418 void LibCallSimplifier::eraseFromParent(Instruction *I) { 3419 Eraser(I); 3420 } 3421 3422 // TODO: 3423 // Additional cases that we need to add to this file: 3424 // 3425 // cbrt: 3426 // * cbrt(expN(X)) -> expN(x/3) 3427 // * cbrt(sqrt(x)) -> pow(x,1/6) 3428 // * cbrt(cbrt(x)) -> pow(x,1/9) 3429 // 3430 // exp, expf, expl: 3431 // * exp(log(x)) -> x 3432 // 3433 // log, logf, logl: 3434 // * log(exp(x)) -> x 3435 // * log(exp(y)) -> y*log(e) 3436 // * log(exp10(y)) -> y*log(10) 3437 // * log(sqrt(x)) -> 0.5*log(x) 3438 // 3439 // pow, powf, powl: 3440 // * pow(sqrt(x),y) -> pow(x,y*0.5) 3441 // * pow(pow(x,y),z)-> pow(x,y*z) 3442 // 3443 // signbit: 3444 // * signbit(cnst) -> cnst' 3445 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 3446 // 3447 // sqrt, sqrtf, sqrtl: 3448 // * sqrt(expN(x)) -> expN(x*0.5) 3449 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 3450 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 3451 // 3452 3453 //===----------------------------------------------------------------------===// 3454 // Fortified Library Call Optimizations 3455 //===----------------------------------------------------------------------===// 3456 3457 bool 3458 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI, 3459 unsigned ObjSizeOp, 3460 Optional<unsigned> SizeOp, 3461 Optional<unsigned> StrOp, 3462 Optional<unsigned> FlagOp) { 3463 // If this function takes a flag argument, the implementation may use it to 3464 // perform extra checks. Don't fold into the non-checking variant. 3465 if (FlagOp) { 3466 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp)); 3467 if (!Flag || !Flag->isZero()) 3468 return false; 3469 } 3470 3471 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp)) 3472 return true; 3473 3474 if (ConstantInt *ObjSizeCI = 3475 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 3476 if (ObjSizeCI->isMinusOne()) 3477 return true; 3478 // If the object size wasn't -1 (unknown), bail out if we were asked to. 3479 if (OnlyLowerUnknownSize) 3480 return false; 3481 if (StrOp) { 3482 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp)); 3483 // If the length is 0 we don't know how long it is and so we can't 3484 // remove the check. 3485 if (Len) 3486 annotateDereferenceableBytes(CI, *StrOp, Len); 3487 else 3488 return false; 3489 return ObjSizeCI->getZExtValue() >= Len; 3490 } 3491 3492 if (SizeOp) { 3493 if (ConstantInt *SizeCI = 3494 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp))) 3495 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 3496 } 3497 } 3498 return false; 3499 } 3500 3501 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 3502 IRBuilderBase &B) { 3503 if (isFortifiedCallFoldable(CI, 3, 2)) { 3504 CallInst *NewCI = 3505 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 3506 Align(1), CI->getArgOperand(2)); 3507 NewCI->setAttributes(CI->getAttributes()); 3508 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 3509 copyFlags(*CI, NewCI); 3510 return CI->getArgOperand(0); 3511 } 3512 return nullptr; 3513 } 3514 3515 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 3516 IRBuilderBase &B) { 3517 if (isFortifiedCallFoldable(CI, 3, 2)) { 3518 CallInst *NewCI = 3519 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 3520 Align(1), CI->getArgOperand(2)); 3521 NewCI->setAttributes(CI->getAttributes()); 3522 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 3523 copyFlags(*CI, NewCI); 3524 return CI->getArgOperand(0); 3525 } 3526 return nullptr; 3527 } 3528 3529 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 3530 IRBuilderBase &B) { 3531 if (isFortifiedCallFoldable(CI, 3, 2)) { 3532 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 3533 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, 3534 CI->getArgOperand(2), Align(1)); 3535 NewCI->setAttributes(CI->getAttributes()); 3536 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 3537 copyFlags(*CI, NewCI); 3538 return CI->getArgOperand(0); 3539 } 3540 return nullptr; 3541 } 3542 3543 Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI, 3544 IRBuilderBase &B) { 3545 const DataLayout &DL = CI->getModule()->getDataLayout(); 3546 if (isFortifiedCallFoldable(CI, 3, 2)) 3547 if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3548 CI->getArgOperand(2), B, DL, TLI)) { 3549 CallInst *NewCI = cast<CallInst>(Call); 3550 NewCI->setAttributes(CI->getAttributes()); 3551 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 3552 return copyFlags(*CI, NewCI); 3553 } 3554 return nullptr; 3555 } 3556 3557 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 3558 IRBuilderBase &B, 3559 LibFunc Func) { 3560 const DataLayout &DL = CI->getModule()->getDataLayout(); 3561 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 3562 *ObjSize = CI->getArgOperand(2); 3563 3564 // __stpcpy_chk(x,x,...) -> x+strlen(x) 3565 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 3566 Value *StrLen = emitStrLen(Src, B, DL, TLI); 3567 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 3568 } 3569 3570 // If a) we don't have any length information, or b) we know this will 3571 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 3572 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 3573 // TODO: It might be nice to get a maximum length out of the possible 3574 // string lengths for varying. 3575 if (isFortifiedCallFoldable(CI, 2, None, 1)) { 3576 if (Func == LibFunc_strcpy_chk) 3577 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI)); 3578 else 3579 return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI)); 3580 } 3581 3582 if (OnlyLowerUnknownSize) 3583 return nullptr; 3584 3585 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 3586 uint64_t Len = GetStringLength(Src); 3587 if (Len) 3588 annotateDereferenceableBytes(CI, 1, Len); 3589 else 3590 return nullptr; 3591 3592 // FIXME: There is really no guarantee that sizeof(size_t) is equal to 3593 // sizeof(int*) for every target. So the assumption used here to derive the 3594 // SizeTBits based on the size of an integer pointer in address space zero 3595 // isn't always valid. 3596 Type *SizeTTy = DL.getIntPtrType(CI->getContext(), /*AddressSpace=*/0); 3597 Value *LenV = ConstantInt::get(SizeTTy, Len); 3598 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 3599 // If the function was an __stpcpy_chk, and we were able to fold it into 3600 // a __memcpy_chk, we still need to return the correct end pointer. 3601 if (Ret && Func == LibFunc_stpcpy_chk) 3602 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1)); 3603 return copyFlags(*CI, cast<CallInst>(Ret)); 3604 } 3605 3606 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI, 3607 IRBuilderBase &B) { 3608 if (isFortifiedCallFoldable(CI, 1, None, 0)) 3609 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, 3610 CI->getModule()->getDataLayout(), TLI)); 3611 return nullptr; 3612 } 3613 3614 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 3615 IRBuilderBase &B, 3616 LibFunc Func) { 3617 if (isFortifiedCallFoldable(CI, 3, 2)) { 3618 if (Func == LibFunc_strncpy_chk) 3619 return copyFlags(*CI, 3620 emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3621 CI->getArgOperand(2), B, TLI)); 3622 else 3623 return copyFlags(*CI, 3624 emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3625 CI->getArgOperand(2), B, TLI)); 3626 } 3627 3628 return nullptr; 3629 } 3630 3631 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI, 3632 IRBuilderBase &B) { 3633 if (isFortifiedCallFoldable(CI, 4, 3)) 3634 return copyFlags( 3635 *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3636 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI)); 3637 3638 return nullptr; 3639 } 3640 3641 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI, 3642 IRBuilderBase &B) { 3643 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) { 3644 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5)); 3645 return copyFlags(*CI, 3646 emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3647 CI->getArgOperand(4), VariadicArgs, B, TLI)); 3648 } 3649 3650 return nullptr; 3651 } 3652 3653 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI, 3654 IRBuilderBase &B) { 3655 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) { 3656 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4)); 3657 return copyFlags(*CI, 3658 emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 3659 VariadicArgs, B, TLI)); 3660 } 3661 3662 return nullptr; 3663 } 3664 3665 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI, 3666 IRBuilderBase &B) { 3667 if (isFortifiedCallFoldable(CI, 2)) 3668 return copyFlags( 3669 *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI)); 3670 3671 return nullptr; 3672 } 3673 3674 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI, 3675 IRBuilderBase &B) { 3676 if (isFortifiedCallFoldable(CI, 3)) 3677 return copyFlags(*CI, 3678 emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1), 3679 CI->getArgOperand(2), B, TLI)); 3680 3681 return nullptr; 3682 } 3683 3684 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI, 3685 IRBuilderBase &B) { 3686 if (isFortifiedCallFoldable(CI, 3)) 3687 return copyFlags(*CI, 3688 emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1), 3689 CI->getArgOperand(2), B, TLI)); 3690 3691 return nullptr; 3692 } 3693 3694 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI, 3695 IRBuilderBase &B) { 3696 if (isFortifiedCallFoldable(CI, 3)) 3697 return copyFlags(*CI, 3698 emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3699 CI->getArgOperand(2), B, TLI)); 3700 3701 return nullptr; 3702 } 3703 3704 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI, 3705 IRBuilderBase &B) { 3706 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) 3707 return copyFlags( 3708 *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3709 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI)); 3710 3711 return nullptr; 3712 } 3713 3714 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI, 3715 IRBuilderBase &B) { 3716 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) 3717 return copyFlags(*CI, 3718 emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 3719 CI->getArgOperand(4), B, TLI)); 3720 3721 return nullptr; 3722 } 3723 3724 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI, 3725 IRBuilderBase &Builder) { 3726 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 3727 // Some clang users checked for _chk libcall availability using: 3728 // __has_builtin(__builtin___memcpy_chk) 3729 // When compiling with -fno-builtin, this is always true. 3730 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 3731 // end up with fortified libcalls, which isn't acceptable in a freestanding 3732 // environment which only provides their non-fortified counterparts. 3733 // 3734 // Until we change clang and/or teach external users to check for availability 3735 // differently, disregard the "nobuiltin" attribute and TLI::has. 3736 // 3737 // PR23093. 3738 3739 LibFunc Func; 3740 Function *Callee = CI->getCalledFunction(); 3741 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 3742 3743 SmallVector<OperandBundleDef, 2> OpBundles; 3744 CI->getOperandBundlesAsDefs(OpBundles); 3745 3746 IRBuilderBase::OperandBundlesGuard Guard(Builder); 3747 Builder.setDefaultOperandBundles(OpBundles); 3748 3749 // First, check that this is a known library functions and that the prototype 3750 // is correct. 3751 if (!TLI->getLibFunc(*Callee, Func)) 3752 return nullptr; 3753 3754 // We never change the calling convention. 3755 if (!ignoreCallingConv(Func) && !IsCallingConvC) 3756 return nullptr; 3757 3758 switch (Func) { 3759 case LibFunc_memcpy_chk: 3760 return optimizeMemCpyChk(CI, Builder); 3761 case LibFunc_mempcpy_chk: 3762 return optimizeMemPCpyChk(CI, Builder); 3763 case LibFunc_memmove_chk: 3764 return optimizeMemMoveChk(CI, Builder); 3765 case LibFunc_memset_chk: 3766 return optimizeMemSetChk(CI, Builder); 3767 case LibFunc_stpcpy_chk: 3768 case LibFunc_strcpy_chk: 3769 return optimizeStrpCpyChk(CI, Builder, Func); 3770 case LibFunc_strlen_chk: 3771 return optimizeStrLenChk(CI, Builder); 3772 case LibFunc_stpncpy_chk: 3773 case LibFunc_strncpy_chk: 3774 return optimizeStrpNCpyChk(CI, Builder, Func); 3775 case LibFunc_memccpy_chk: 3776 return optimizeMemCCpyChk(CI, Builder); 3777 case LibFunc_snprintf_chk: 3778 return optimizeSNPrintfChk(CI, Builder); 3779 case LibFunc_sprintf_chk: 3780 return optimizeSPrintfChk(CI, Builder); 3781 case LibFunc_strcat_chk: 3782 return optimizeStrCatChk(CI, Builder); 3783 case LibFunc_strlcat_chk: 3784 return optimizeStrLCat(CI, Builder); 3785 case LibFunc_strncat_chk: 3786 return optimizeStrNCatChk(CI, Builder); 3787 case LibFunc_strlcpy_chk: 3788 return optimizeStrLCpyChk(CI, Builder); 3789 case LibFunc_vsnprintf_chk: 3790 return optimizeVSNPrintfChk(CI, Builder); 3791 case LibFunc_vsprintf_chk: 3792 return optimizeVSPrintfChk(CI, Builder); 3793 default: 3794 break; 3795 } 3796 return nullptr; 3797 } 3798 3799 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 3800 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 3801 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 3802