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