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