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/Transforms/Utils/Local.h" 24 #include "llvm/Analysis/ValueTracking.h" 25 #include "llvm/Analysis/CaptureTracking.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/IRBuilder.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/Intrinsics.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/KnownBits.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Transforms/Utils/BuildLibCalls.h" 39 #include "llvm/Transforms/Utils/SizeOpts.h" 40 41 using namespace llvm; 42 using namespace PatternMatch; 43 44 static cl::opt<bool> 45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden, 46 cl::init(false), 47 cl::desc("Enable unsafe double to float " 48 "shrinking for math lib calls")); 49 50 //===----------------------------------------------------------------------===// 51 // Helper Functions 52 //===----------------------------------------------------------------------===// 53 54 static bool ignoreCallingConv(LibFunc Func) { 55 return Func == LibFunc_abs || Func == LibFunc_labs || 56 Func == LibFunc_llabs || Func == LibFunc_strlen; 57 } 58 59 static bool isCallingConvCCompatible(CallInst *CI) { 60 switch(CI->getCallingConv()) { 61 default: 62 return false; 63 case llvm::CallingConv::C: 64 return true; 65 case llvm::CallingConv::ARM_APCS: 66 case llvm::CallingConv::ARM_AAPCS: 67 case llvm::CallingConv::ARM_AAPCS_VFP: { 68 69 // The iOS ABI diverges from the standard in some cases, so for now don't 70 // try to simplify those calls. 71 if (Triple(CI->getModule()->getTargetTriple()).isiOS()) 72 return false; 73 74 auto *FuncTy = CI->getFunctionType(); 75 76 if (!FuncTy->getReturnType()->isPointerTy() && 77 !FuncTy->getReturnType()->isIntegerTy() && 78 !FuncTy->getReturnType()->isVoidTy()) 79 return false; 80 81 for (auto Param : FuncTy->params()) { 82 if (!Param->isPointerTy() && !Param->isIntegerTy()) 83 return false; 84 } 85 return true; 86 } 87 } 88 return false; 89 } 90 91 /// Return true if it is only used in equality comparisons with With. 92 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) { 93 for (User *U : V->users()) { 94 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 95 if (IC->isEquality() && IC->getOperand(1) == With) 96 continue; 97 // Unknown instruction. 98 return false; 99 } 100 return true; 101 } 102 103 static bool callHasFloatingPointArgument(const CallInst *CI) { 104 return any_of(CI->operands(), [](const Use &OI) { 105 return OI->getType()->isFloatingPointTy(); 106 }); 107 } 108 109 static bool callHasFP128Argument(const CallInst *CI) { 110 return any_of(CI->operands(), [](const Use &OI) { 111 return OI->getType()->isFP128Ty(); 112 }); 113 } 114 115 static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) { 116 if (Base < 2 || Base > 36) 117 // handle special zero base 118 if (Base != 0) 119 return nullptr; 120 121 char *End; 122 std::string nptr = Str.str(); 123 errno = 0; 124 long long int Result = strtoll(nptr.c_str(), &End, Base); 125 if (errno) 126 return nullptr; 127 128 // if we assume all possible target locales are ASCII supersets, 129 // then if strtoll successfully parses a number on the host, 130 // it will also successfully parse the same way on the target 131 if (*End != '\0') 132 return nullptr; 133 134 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result)) 135 return nullptr; 136 137 return ConstantInt::get(CI->getType(), Result); 138 } 139 140 static bool isOnlyUsedInComparisonWithZero(Value *V) { 141 for (User *U : V->users()) { 142 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 143 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 144 if (C->isNullValue()) 145 continue; 146 // Unknown instruction. 147 return false; 148 } 149 return true; 150 } 151 152 static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, 153 const DataLayout &DL) { 154 if (!isOnlyUsedInComparisonWithZero(CI)) 155 return false; 156 157 if (!isDereferenceableAndAlignedPointer(Str, Align(1), APInt(64, Len), DL)) 158 return false; 159 160 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory)) 161 return false; 162 163 return true; 164 } 165 166 static void annotateDereferenceableBytes(CallInst *CI, 167 ArrayRef<unsigned> ArgNos, 168 uint64_t DereferenceableBytes) { 169 const Function *F = CI->getCaller(); 170 if (!F) 171 return; 172 for (unsigned ArgNo : ArgNos) { 173 uint64_t DerefBytes = DereferenceableBytes; 174 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 175 if (!llvm::NullPointerIsDefined(F, AS) || 176 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 177 DerefBytes = std::max(CI->getDereferenceableOrNullBytes( 178 ArgNo + AttributeList::FirstArgIndex), 179 DereferenceableBytes); 180 181 if (CI->getDereferenceableBytes(ArgNo + AttributeList::FirstArgIndex) < 182 DerefBytes) { 183 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable); 184 if (!llvm::NullPointerIsDefined(F, AS) || 185 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 186 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull); 187 CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes( 188 CI->getContext(), DerefBytes)); 189 } 190 } 191 } 192 193 static void annotateNonNullBasedOnAccess(CallInst *CI, 194 ArrayRef<unsigned> ArgNos) { 195 Function *F = CI->getCaller(); 196 if (!F) 197 return; 198 199 for (unsigned ArgNo : ArgNos) { 200 if (CI->paramHasAttr(ArgNo, Attribute::NonNull)) 201 continue; 202 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 203 if (llvm::NullPointerIsDefined(F, AS)) 204 continue; 205 206 CI->addParamAttr(ArgNo, Attribute::NonNull); 207 annotateDereferenceableBytes(CI, ArgNo, 1); 208 } 209 } 210 211 static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos, 212 Value *Size, const DataLayout &DL) { 213 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) { 214 annotateNonNullBasedOnAccess(CI, ArgNos); 215 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue()); 216 } else if (isKnownNonZero(Size, DL)) { 217 annotateNonNullBasedOnAccess(CI, ArgNos); 218 const APInt *X, *Y; 219 uint64_t DerefMin = 1; 220 if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) { 221 DerefMin = std::min(X->getZExtValue(), Y->getZExtValue()); 222 annotateDereferenceableBytes(CI, ArgNos, DerefMin); 223 } 224 } 225 } 226 227 //===----------------------------------------------------------------------===// 228 // String and Memory Library Call Optimizations 229 //===----------------------------------------------------------------------===// 230 231 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilderBase &B) { 232 // Extract some information from the instruction 233 Value *Dst = CI->getArgOperand(0); 234 Value *Src = CI->getArgOperand(1); 235 annotateNonNullBasedOnAccess(CI, {0, 1}); 236 237 // See if we can get the length of the input string. 238 uint64_t Len = GetStringLength(Src); 239 if (Len) 240 annotateDereferenceableBytes(CI, 1, Len); 241 else 242 return nullptr; 243 --Len; // Unbias length. 244 245 // Handle the simple, do-nothing case: strcat(x, "") -> x 246 if (Len == 0) 247 return Dst; 248 249 return emitStrLenMemCpy(Src, Dst, Len, B); 250 } 251 252 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, 253 IRBuilderBase &B) { 254 // We need to find the end of the destination string. That's where the 255 // memory is to be moved to. We just generate a call to strlen. 256 Value *DstLen = emitStrLen(Dst, B, DL, TLI); 257 if (!DstLen) 258 return nullptr; 259 260 // Now that we have the destination's length, we must index into the 261 // destination's pointer to get the actual memcpy destination (end of 262 // the string .. we're concatenating). 263 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr"); 264 265 // We have enough information to now generate the memcpy call to do the 266 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 267 B.CreateMemCpy( 268 CpyDst, Align(1), Src, Align(1), 269 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1)); 270 return Dst; 271 } 272 273 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilderBase &B) { 274 // Extract some information from the instruction. 275 Value *Dst = CI->getArgOperand(0); 276 Value *Src = CI->getArgOperand(1); 277 Value *Size = CI->getArgOperand(2); 278 uint64_t Len; 279 annotateNonNullBasedOnAccess(CI, 0); 280 if (isKnownNonZero(Size, DL)) 281 annotateNonNullBasedOnAccess(CI, 1); 282 283 // We don't do anything if length is not constant. 284 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size); 285 if (LengthArg) { 286 Len = LengthArg->getZExtValue(); 287 // strncat(x, c, 0) -> x 288 if (!Len) 289 return Dst; 290 } else { 291 return nullptr; 292 } 293 294 // See if we can get the length of the input string. 295 uint64_t SrcLen = GetStringLength(Src); 296 if (SrcLen) { 297 annotateDereferenceableBytes(CI, 1, SrcLen); 298 --SrcLen; // Unbias length. 299 } else { 300 return nullptr; 301 } 302 303 // strncat(x, "", c) -> x 304 if (SrcLen == 0) 305 return Dst; 306 307 // We don't optimize this case. 308 if (Len < SrcLen) 309 return nullptr; 310 311 // strncat(x, s, c) -> strcat(x, s) 312 // s is constant so the strcat can be optimized further. 313 return emitStrLenMemCpy(Src, Dst, SrcLen, B); 314 } 315 316 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilderBase &B) { 317 Function *Callee = CI->getCalledFunction(); 318 FunctionType *FT = Callee->getFunctionType(); 319 Value *SrcStr = CI->getArgOperand(0); 320 annotateNonNullBasedOnAccess(CI, 0); 321 322 // If the second operand is non-constant, see if we can compute the length 323 // of the input string and turn this into memchr. 324 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 325 if (!CharC) { 326 uint64_t Len = GetStringLength(SrcStr); 327 if (Len) 328 annotateDereferenceableBytes(CI, 0, Len); 329 else 330 return nullptr; 331 if (!FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32. 332 return nullptr; 333 334 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul. 335 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 336 B, DL, TLI); 337 } 338 339 // Otherwise, the character is a constant, see if the first argument is 340 // a string literal. If so, we can constant fold. 341 StringRef Str; 342 if (!getConstantStringInfo(SrcStr, Str)) { 343 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p) 344 if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI)) 345 return B.CreateGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr"); 346 return nullptr; 347 } 348 349 // Compute the offset, make sure to handle the case when we're searching for 350 // zero (a weird way to spell strlen). 351 size_t I = (0xFF & CharC->getSExtValue()) == 0 352 ? Str.size() 353 : Str.find(CharC->getSExtValue()); 354 if (I == StringRef::npos) // Didn't find the char. strchr returns null. 355 return Constant::getNullValue(CI->getType()); 356 357 // strchr(s+n,c) -> gep(s+n+i,c) 358 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr"); 359 } 360 361 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilderBase &B) { 362 Value *SrcStr = CI->getArgOperand(0); 363 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 364 annotateNonNullBasedOnAccess(CI, 0); 365 366 // Cannot fold anything if we're not looking for a constant. 367 if (!CharC) 368 return nullptr; 369 370 StringRef Str; 371 if (!getConstantStringInfo(SrcStr, Str)) { 372 // strrchr(s, 0) -> strchr(s, 0) 373 if (CharC->isZero()) 374 return emitStrChr(SrcStr, '\0', B, TLI); 375 return nullptr; 376 } 377 378 // Compute the offset. 379 size_t I = (0xFF & CharC->getSExtValue()) == 0 380 ? Str.size() 381 : Str.rfind(CharC->getSExtValue()); 382 if (I == StringRef::npos) // Didn't find the char. Return null. 383 return Constant::getNullValue(CI->getType()); 384 385 // strrchr(s+n,c) -> gep(s+n+i,c) 386 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr"); 387 } 388 389 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) { 390 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 391 if (Str1P == Str2P) // strcmp(x,x) -> 0 392 return ConstantInt::get(CI->getType(), 0); 393 394 StringRef Str1, Str2; 395 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 396 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 397 398 // strcmp(x, y) -> cnst (if both x and y are constant strings) 399 if (HasStr1 && HasStr2) 400 return ConstantInt::get(CI->getType(), Str1.compare(Str2)); 401 402 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x 403 return B.CreateNeg(B.CreateZExt( 404 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 405 406 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 407 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 408 CI->getType()); 409 410 // strcmp(P, "x") -> memcmp(P, "x", 2) 411 uint64_t Len1 = GetStringLength(Str1P); 412 if (Len1) 413 annotateDereferenceableBytes(CI, 0, Len1); 414 uint64_t Len2 = GetStringLength(Str2P); 415 if (Len2) 416 annotateDereferenceableBytes(CI, 1, Len2); 417 418 if (Len1 && Len2) { 419 return emitMemCmp(Str1P, Str2P, 420 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 421 std::min(Len1, Len2)), 422 B, DL, TLI); 423 } 424 425 // strcmp to memcmp 426 if (!HasStr1 && HasStr2) { 427 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 428 return emitMemCmp( 429 Str1P, Str2P, 430 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL, 431 TLI); 432 } else if (HasStr1 && !HasStr2) { 433 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 434 return emitMemCmp( 435 Str1P, Str2P, 436 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL, 437 TLI); 438 } 439 440 annotateNonNullBasedOnAccess(CI, {0, 1}); 441 return nullptr; 442 } 443 444 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) { 445 Value *Str1P = CI->getArgOperand(0); 446 Value *Str2P = CI->getArgOperand(1); 447 Value *Size = CI->getArgOperand(2); 448 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 449 return ConstantInt::get(CI->getType(), 0); 450 451 if (isKnownNonZero(Size, DL)) 452 annotateNonNullBasedOnAccess(CI, {0, 1}); 453 // Get the length argument if it is constant. 454 uint64_t Length; 455 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size)) 456 Length = LengthArg->getZExtValue(); 457 else 458 return nullptr; 459 460 if (Length == 0) // strncmp(x,y,0) -> 0 461 return ConstantInt::get(CI->getType(), 0); 462 463 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1) 464 return emitMemCmp(Str1P, Str2P, Size, B, DL, TLI); 465 466 StringRef Str1, Str2; 467 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 468 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 469 470 // strncmp(x, y) -> cnst (if both x and y are constant strings) 471 if (HasStr1 && HasStr2) { 472 StringRef SubStr1 = Str1.substr(0, Length); 473 StringRef SubStr2 = Str2.substr(0, Length); 474 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2)); 475 } 476 477 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x 478 return B.CreateNeg(B.CreateZExt( 479 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 480 481 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 482 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 483 CI->getType()); 484 485 uint64_t Len1 = GetStringLength(Str1P); 486 if (Len1) 487 annotateDereferenceableBytes(CI, 0, Len1); 488 uint64_t Len2 = GetStringLength(Str2P); 489 if (Len2) 490 annotateDereferenceableBytes(CI, 1, Len2); 491 492 // strncmp to memcmp 493 if (!HasStr1 && HasStr2) { 494 Len2 = std::min(Len2, Length); 495 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 496 return emitMemCmp( 497 Str1P, Str2P, 498 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL, 499 TLI); 500 } else if (HasStr1 && !HasStr2) { 501 Len1 = std::min(Len1, Length); 502 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 503 return emitMemCmp( 504 Str1P, Str2P, 505 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL, 506 TLI); 507 } 508 509 return nullptr; 510 } 511 512 Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilderBase &B) { 513 Value *Src = CI->getArgOperand(0); 514 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 515 uint64_t SrcLen = GetStringLength(Src); 516 if (SrcLen && Size) { 517 annotateDereferenceableBytes(CI, 0, SrcLen); 518 if (SrcLen <= Size->getZExtValue() + 1) 519 return emitStrDup(Src, B, TLI); 520 } 521 522 return nullptr; 523 } 524 525 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilderBase &B) { 526 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 527 if (Dst == Src) // strcpy(x,x) -> x 528 return Src; 529 530 annotateNonNullBasedOnAccess(CI, {0, 1}); 531 // See if we can get the length of the input string. 532 uint64_t Len = GetStringLength(Src); 533 if (Len) 534 annotateDereferenceableBytes(CI, 1, Len); 535 else 536 return nullptr; 537 538 // We have enough information to now generate the memcpy call to do the 539 // copy for us. Make a memcpy to copy the nul byte with align = 1. 540 CallInst *NewCI = 541 B.CreateMemCpy(Dst, Align(1), Src, Align(1), 542 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len)); 543 NewCI->setAttributes(CI->getAttributes()); 544 return Dst; 545 } 546 547 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilderBase &B) { 548 Function *Callee = CI->getCalledFunction(); 549 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 550 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 551 Value *StrLen = emitStrLen(Src, B, DL, TLI); 552 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 553 } 554 555 // See if we can get the length of the input string. 556 uint64_t Len = GetStringLength(Src); 557 if (Len) 558 annotateDereferenceableBytes(CI, 1, Len); 559 else 560 return nullptr; 561 562 Type *PT = Callee->getFunctionType()->getParamType(0); 563 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len); 564 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst, 565 ConstantInt::get(DL.getIntPtrType(PT), Len - 1)); 566 567 // We have enough information to now generate the memcpy call to do the 568 // copy for us. Make a memcpy to copy the nul byte with align = 1. 569 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), LenV); 570 NewCI->setAttributes(CI->getAttributes()); 571 return DstEnd; 572 } 573 574 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilderBase &B) { 575 Function *Callee = CI->getCalledFunction(); 576 Value *Dst = CI->getArgOperand(0); 577 Value *Src = CI->getArgOperand(1); 578 Value *Size = CI->getArgOperand(2); 579 annotateNonNullBasedOnAccess(CI, 0); 580 if (isKnownNonZero(Size, DL)) 581 annotateNonNullBasedOnAccess(CI, 1); 582 583 uint64_t Len; 584 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size)) 585 Len = LengthArg->getZExtValue(); 586 else 587 return nullptr; 588 589 // strncpy(x, y, 0) -> x 590 if (Len == 0) 591 return Dst; 592 593 // See if we can get the length of the input string. 594 uint64_t SrcLen = GetStringLength(Src); 595 if (SrcLen) { 596 annotateDereferenceableBytes(CI, 1, SrcLen); 597 --SrcLen; // Unbias length. 598 } else { 599 return nullptr; 600 } 601 602 if (SrcLen == 0) { 603 // strncpy(x, "", y) -> memset(align 1 x, '\0', y) 604 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, Align(1)); 605 AttrBuilder ArgAttrs(CI->getAttributes().getParamAttributes(0)); 606 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes( 607 CI->getContext(), 0, ArgAttrs)); 608 return Dst; 609 } 610 611 // Let strncpy handle the zero padding 612 if (Len > SrcLen + 1) 613 return nullptr; 614 615 Type *PT = Callee->getFunctionType()->getParamType(0); 616 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant] 617 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), 618 ConstantInt::get(DL.getIntPtrType(PT), Len)); 619 NewCI->setAttributes(CI->getAttributes()); 620 return Dst; 621 } 622 623 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B, 624 unsigned CharSize) { 625 Value *Src = CI->getArgOperand(0); 626 627 // Constant folding: strlen("xyz") -> 3 628 if (uint64_t Len = GetStringLength(Src, CharSize)) 629 return ConstantInt::get(CI->getType(), Len - 1); 630 631 // If s is a constant pointer pointing to a string literal, we can fold 632 // strlen(s + x) to strlen(s) - x, when x is known to be in the range 633 // [0, strlen(s)] or the string has a single null terminator '\0' at the end. 634 // We only try to simplify strlen when the pointer s points to an array 635 // of i8. Otherwise, we would need to scale the offset x before doing the 636 // subtraction. This will make the optimization more complex, and it's not 637 // very useful because calling strlen for a pointer of other types is 638 // very uncommon. 639 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) { 640 if (!isGEPBasedOnPointerToString(GEP, CharSize)) 641 return nullptr; 642 643 ConstantDataArraySlice Slice; 644 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) { 645 uint64_t NullTermIdx; 646 if (Slice.Array == nullptr) { 647 NullTermIdx = 0; 648 } else { 649 NullTermIdx = ~((uint64_t)0); 650 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) { 651 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) { 652 NullTermIdx = I; 653 break; 654 } 655 } 656 // If the string does not have '\0', leave it to strlen to compute 657 // its length. 658 if (NullTermIdx == ~((uint64_t)0)) 659 return nullptr; 660 } 661 662 Value *Offset = GEP->getOperand(2); 663 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr); 664 Known.Zero.flipAllBits(); 665 uint64_t ArrSize = 666 cast<ArrayType>(GEP->getSourceElementType())->getNumElements(); 667 668 // KnownZero's bits are flipped, so zeros in KnownZero now represent 669 // bits known to be zeros in Offset, and ones in KnowZero represent 670 // bits unknown in Offset. Therefore, Offset is known to be in range 671 // [0, NullTermIdx] when the flipped KnownZero is non-negative and 672 // unsigned-less-than NullTermIdx. 673 // 674 // If Offset is not provably in the range [0, NullTermIdx], we can still 675 // optimize if we can prove that the program has undefined behavior when 676 // Offset is outside that range. That is the case when GEP->getOperand(0) 677 // is a pointer to an object whose memory extent is NullTermIdx+1. 678 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) || 679 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) && 680 NullTermIdx == ArrSize - 1)) { 681 Offset = B.CreateSExtOrTrunc(Offset, CI->getType()); 682 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx), 683 Offset); 684 } 685 } 686 687 return nullptr; 688 } 689 690 // strlen(x?"foo":"bars") --> x ? 3 : 4 691 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) { 692 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize); 693 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize); 694 if (LenTrue && LenFalse) { 695 ORE.emit([&]() { 696 return OptimizationRemark("instcombine", "simplify-libcalls", CI) 697 << "folded strlen(select) to select of constants"; 698 }); 699 return B.CreateSelect(SI->getCondition(), 700 ConstantInt::get(CI->getType(), LenTrue - 1), 701 ConstantInt::get(CI->getType(), LenFalse - 1)); 702 } 703 } 704 705 // strlen(x) != 0 --> *x != 0 706 // strlen(x) == 0 --> *x == 0 707 if (isOnlyUsedInZeroEqualityComparison(CI)) 708 return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"), 709 CI->getType()); 710 711 return nullptr; 712 } 713 714 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) { 715 if (Value *V = optimizeStringLength(CI, B, 8)) 716 return V; 717 annotateNonNullBasedOnAccess(CI, 0); 718 return nullptr; 719 } 720 721 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) { 722 Module &M = *CI->getModule(); 723 unsigned WCharSize = TLI->getWCharSize(M) * 8; 724 // We cannot perform this optimization without wchar_size metadata. 725 if (WCharSize == 0) 726 return nullptr; 727 728 return optimizeStringLength(CI, B, WCharSize); 729 } 730 731 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) { 732 StringRef S1, S2; 733 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 734 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 735 736 // strpbrk(s, "") -> nullptr 737 // strpbrk("", s) -> nullptr 738 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 739 return Constant::getNullValue(CI->getType()); 740 741 // Constant folding. 742 if (HasS1 && HasS2) { 743 size_t I = S1.find_first_of(S2); 744 if (I == StringRef::npos) // No match. 745 return Constant::getNullValue(CI->getType()); 746 747 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), 748 "strpbrk"); 749 } 750 751 // strpbrk(s, "a") -> strchr(s, 'a') 752 if (HasS2 && S2.size() == 1) 753 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI); 754 755 return nullptr; 756 } 757 758 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) { 759 Value *EndPtr = CI->getArgOperand(1); 760 if (isa<ConstantPointerNull>(EndPtr)) { 761 // With a null EndPtr, this function won't capture the main argument. 762 // It would be readonly too, except that it still may write to errno. 763 CI->addParamAttr(0, Attribute::NoCapture); 764 } 765 766 return nullptr; 767 } 768 769 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) { 770 StringRef S1, S2; 771 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 772 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 773 774 // strspn(s, "") -> 0 775 // strspn("", s) -> 0 776 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 777 return Constant::getNullValue(CI->getType()); 778 779 // Constant folding. 780 if (HasS1 && HasS2) { 781 size_t Pos = S1.find_first_not_of(S2); 782 if (Pos == StringRef::npos) 783 Pos = S1.size(); 784 return ConstantInt::get(CI->getType(), Pos); 785 } 786 787 return nullptr; 788 } 789 790 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) { 791 StringRef S1, S2; 792 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 793 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 794 795 // strcspn("", s) -> 0 796 if (HasS1 && S1.empty()) 797 return Constant::getNullValue(CI->getType()); 798 799 // Constant folding. 800 if (HasS1 && HasS2) { 801 size_t Pos = S1.find_first_of(S2); 802 if (Pos == StringRef::npos) 803 Pos = S1.size(); 804 return ConstantInt::get(CI->getType(), Pos); 805 } 806 807 // strcspn(s, "") -> strlen(s) 808 if (HasS2 && S2.empty()) 809 return emitStrLen(CI->getArgOperand(0), B, DL, TLI); 810 811 return nullptr; 812 } 813 814 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) { 815 // fold strstr(x, x) -> x. 816 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 817 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 818 819 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 820 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 821 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI); 822 if (!StrLen) 823 return nullptr; 824 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 825 StrLen, B, DL, TLI); 826 if (!StrNCmp) 827 return nullptr; 828 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) { 829 ICmpInst *Old = cast<ICmpInst>(*UI++); 830 Value *Cmp = 831 B.CreateICmp(Old->getPredicate(), StrNCmp, 832 ConstantInt::getNullValue(StrNCmp->getType()), "cmp"); 833 replaceAllUsesWith(Old, Cmp); 834 } 835 return CI; 836 } 837 838 // See if either input string is a constant string. 839 StringRef SearchStr, ToFindStr; 840 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 841 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 842 843 // fold strstr(x, "") -> x. 844 if (HasStr2 && ToFindStr.empty()) 845 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 846 847 // If both strings are known, constant fold it. 848 if (HasStr1 && HasStr2) { 849 size_t Offset = SearchStr.find(ToFindStr); 850 851 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 852 return Constant::getNullValue(CI->getType()); 853 854 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 855 Value *Result = castToCStr(CI->getArgOperand(0), B); 856 Result = 857 B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr"); 858 return B.CreateBitCast(Result, CI->getType()); 859 } 860 861 // fold strstr(x, "y") -> strchr(x, 'y'). 862 if (HasStr2 && ToFindStr.size() == 1) { 863 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI); 864 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr; 865 } 866 867 annotateNonNullBasedOnAccess(CI, {0, 1}); 868 return nullptr; 869 } 870 871 Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) { 872 if (isKnownNonZero(CI->getOperand(2), DL)) 873 annotateNonNullBasedOnAccess(CI, 0); 874 return nullptr; 875 } 876 877 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) { 878 Value *SrcStr = CI->getArgOperand(0); 879 Value *Size = CI->getArgOperand(2); 880 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 881 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 882 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 883 884 // memchr(x, y, 0) -> null 885 if (LenC) { 886 if (LenC->isZero()) 887 return Constant::getNullValue(CI->getType()); 888 } else { 889 // From now on we need at least constant length and string. 890 return nullptr; 891 } 892 893 StringRef Str; 894 if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false)) 895 return nullptr; 896 897 // Truncate the string to LenC. If Str is smaller than LenC we will still only 898 // scan the string, as reading past the end of it is undefined and we can just 899 // return null if we don't find the char. 900 Str = Str.substr(0, LenC->getZExtValue()); 901 902 // If the char is variable but the input str and length are not we can turn 903 // this memchr call into a simple bit field test. Of course this only works 904 // when the return value is only checked against null. 905 // 906 // It would be really nice to reuse switch lowering here but we can't change 907 // the CFG at this point. 908 // 909 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n'))) 910 // != 0 911 // after bounds check. 912 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) { 913 unsigned char Max = 914 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()), 915 reinterpret_cast<const unsigned char *>(Str.end())); 916 917 // Make sure the bit field we're about to create fits in a register on the 918 // target. 919 // FIXME: On a 64 bit architecture this prevents us from using the 920 // interesting range of alpha ascii chars. We could do better by emitting 921 // two bitfields or shifting the range by 64 if no lower chars are used. 922 if (!DL.fitsInLegalInteger(Max + 1)) 923 return nullptr; 924 925 // For the bit field use a power-of-2 type with at least 8 bits to avoid 926 // creating unnecessary illegal types. 927 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max)); 928 929 // Now build the bit field. 930 APInt Bitfield(Width, 0); 931 for (char C : Str) 932 Bitfield.setBit((unsigned char)C); 933 Value *BitfieldC = B.getInt(Bitfield); 934 935 // Adjust width of "C" to the bitfield width, then mask off the high bits. 936 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType()); 937 C = B.CreateAnd(C, B.getIntN(Width, 0xFF)); 938 939 // First check that the bit field access is within bounds. 940 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width), 941 "memchr.bounds"); 942 943 // Create code that checks if the given bit is set in the field. 944 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C); 945 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits"); 946 947 // Finally merge both checks and cast to pointer type. The inttoptr 948 // implicitly zexts the i1 to intptr type. 949 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType()); 950 } 951 952 // Check if all arguments are constants. If so, we can constant fold. 953 if (!CharC) 954 return nullptr; 955 956 // Compute the offset. 957 size_t I = Str.find(CharC->getSExtValue() & 0xFF); 958 if (I == StringRef::npos) // Didn't find the char. memchr returns null. 959 return Constant::getNullValue(CI->getType()); 960 961 // memchr(s+n,c,l) -> gep(s+n+i,c) 962 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr"); 963 } 964 965 static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS, 966 uint64_t Len, IRBuilderBase &B, 967 const DataLayout &DL) { 968 if (Len == 0) // memcmp(s1,s2,0) -> 0 969 return Constant::getNullValue(CI->getType()); 970 971 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 972 if (Len == 1) { 973 Value *LHSV = 974 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"), 975 CI->getType(), "lhsv"); 976 Value *RHSV = 977 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"), 978 CI->getType(), "rhsv"); 979 return B.CreateSub(LHSV, RHSV, "chardiff"); 980 } 981 982 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0 983 // TODO: The case where both inputs are constants does not need to be limited 984 // to legal integers or equality comparison. See block below this. 985 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) { 986 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8); 987 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType); 988 989 // First, see if we can fold either argument to a constant. 990 Value *LHSV = nullptr; 991 if (auto *LHSC = dyn_cast<Constant>(LHS)) { 992 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo()); 993 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL); 994 } 995 Value *RHSV = nullptr; 996 if (auto *RHSC = dyn_cast<Constant>(RHS)) { 997 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo()); 998 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL); 999 } 1000 1001 // Don't generate unaligned loads. If either source is constant data, 1002 // alignment doesn't matter for that source because there is no load. 1003 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) && 1004 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) { 1005 if (!LHSV) { 1006 Type *LHSPtrTy = 1007 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace()); 1008 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv"); 1009 } 1010 if (!RHSV) { 1011 Type *RHSPtrTy = 1012 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace()); 1013 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv"); 1014 } 1015 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp"); 1016 } 1017 } 1018 1019 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const). 1020 // TODO: This is limited to i8 arrays. 1021 StringRef LHSStr, RHSStr; 1022 if (getConstantStringInfo(LHS, LHSStr) && 1023 getConstantStringInfo(RHS, RHSStr)) { 1024 // Make sure we're not reading out-of-bounds memory. 1025 if (Len > LHSStr.size() || Len > RHSStr.size()) 1026 return nullptr; 1027 // Fold the memcmp and normalize the result. This way we get consistent 1028 // results across multiple platforms. 1029 uint64_t Ret = 0; 1030 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len); 1031 if (Cmp < 0) 1032 Ret = -1; 1033 else if (Cmp > 0) 1034 Ret = 1; 1035 return ConstantInt::get(CI->getType(), Ret); 1036 } 1037 1038 return nullptr; 1039 } 1040 1041 // Most simplifications for memcmp also apply to bcmp. 1042 Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI, 1043 IRBuilderBase &B) { 1044 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 1045 Value *Size = CI->getArgOperand(2); 1046 1047 if (LHS == RHS) // memcmp(s,s,x) -> 0 1048 return Constant::getNullValue(CI->getType()); 1049 1050 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1051 // Handle constant lengths. 1052 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1053 if (!LenC) 1054 return nullptr; 1055 1056 // memcmp(d,s,0) -> 0 1057 if (LenC->getZExtValue() == 0) 1058 return Constant::getNullValue(CI->getType()); 1059 1060 if (Value *Res = 1061 optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL)) 1062 return Res; 1063 return nullptr; 1064 } 1065 1066 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) { 1067 if (Value *V = optimizeMemCmpBCmpCommon(CI, B)) 1068 return V; 1069 1070 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0 1071 // bcmp can be more efficient than memcmp because it only has to know that 1072 // there is a difference, not how different one is to the other. 1073 if (TLI->has(LibFunc_bcmp) && isOnlyUsedInZeroEqualityComparison(CI)) { 1074 Value *LHS = CI->getArgOperand(0); 1075 Value *RHS = CI->getArgOperand(1); 1076 Value *Size = CI->getArgOperand(2); 1077 return emitBCmp(LHS, RHS, Size, B, DL, TLI); 1078 } 1079 1080 return nullptr; 1081 } 1082 1083 Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) { 1084 return optimizeMemCmpBCmpCommon(CI, B); 1085 } 1086 1087 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) { 1088 Value *Size = CI->getArgOperand(2); 1089 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1090 if (isa<IntrinsicInst>(CI)) 1091 return nullptr; 1092 1093 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n) 1094 CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1), 1095 CI->getArgOperand(1), Align(1), Size); 1096 NewCI->setAttributes(CI->getAttributes()); 1097 return CI->getArgOperand(0); 1098 } 1099 1100 Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) { 1101 Value *Dst = CI->getArgOperand(0); 1102 Value *Src = CI->getArgOperand(1); 1103 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 1104 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3)); 1105 StringRef SrcStr; 1106 if (CI->use_empty() && Dst == Src) 1107 return Dst; 1108 // memccpy(d, s, c, 0) -> nullptr 1109 if (N) { 1110 if (N->isNullValue()) 1111 return Constant::getNullValue(CI->getType()); 1112 if (!getConstantStringInfo(Src, SrcStr, /*Offset=*/0, 1113 /*TrimAtNul=*/false) || 1114 !StopChar) 1115 return nullptr; 1116 } else { 1117 return nullptr; 1118 } 1119 1120 // Wrap arg 'c' of type int to char 1121 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF); 1122 if (Pos == StringRef::npos) { 1123 if (N->getZExtValue() <= SrcStr.size()) { 1124 B.CreateMemCpy(Dst, Align(1), Src, Align(1), CI->getArgOperand(3)); 1125 return Constant::getNullValue(CI->getType()); 1126 } 1127 return nullptr; 1128 } 1129 1130 Value *NewN = 1131 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue())); 1132 // memccpy -> llvm.memcpy 1133 B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN); 1134 return Pos + 1 <= N->getZExtValue() 1135 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN) 1136 : Constant::getNullValue(CI->getType()); 1137 } 1138 1139 Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) { 1140 Value *Dst = CI->getArgOperand(0); 1141 Value *N = CI->getArgOperand(2); 1142 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n 1143 CallInst *NewCI = 1144 B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N); 1145 NewCI->setAttributes(CI->getAttributes()); 1146 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N); 1147 } 1148 1149 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) { 1150 Value *Size = CI->getArgOperand(2); 1151 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1152 if (isa<IntrinsicInst>(CI)) 1153 return nullptr; 1154 1155 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n) 1156 CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1), 1157 CI->getArgOperand(1), Align(1), Size); 1158 NewCI->setAttributes(CI->getAttributes()); 1159 return CI->getArgOperand(0); 1160 } 1161 1162 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n). 1163 Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilderBase &B) { 1164 // This has to be a memset of zeros (bzero). 1165 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1)); 1166 if (!FillValue || FillValue->getZExtValue() != 0) 1167 return nullptr; 1168 1169 // TODO: We should handle the case where the malloc has more than one use. 1170 // This is necessary to optimize common patterns such as when the result of 1171 // the malloc is checked against null or when a memset intrinsic is used in 1172 // place of a memset library call. 1173 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0)); 1174 if (!Malloc || !Malloc->hasOneUse()) 1175 return nullptr; 1176 1177 // Is the inner call really malloc()? 1178 Function *InnerCallee = Malloc->getCalledFunction(); 1179 if (!InnerCallee) 1180 return nullptr; 1181 1182 LibFunc Func; 1183 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) || 1184 Func != LibFunc_malloc) 1185 return nullptr; 1186 1187 // The memset must cover the same number of bytes that are malloc'd. 1188 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0)) 1189 return nullptr; 1190 1191 // Replace the malloc with a calloc. We need the data layout to know what the 1192 // actual size of a 'size_t' parameter is. 1193 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator()); 1194 const DataLayout &DL = Malloc->getModule()->getDataLayout(); 1195 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext()); 1196 if (Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1), 1197 Malloc->getArgOperand(0), 1198 Malloc->getAttributes(), B, *TLI)) { 1199 substituteInParent(Malloc, Calloc); 1200 return Calloc; 1201 } 1202 1203 return nullptr; 1204 } 1205 1206 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) { 1207 Value *Size = CI->getArgOperand(2); 1208 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1209 if (isa<IntrinsicInst>(CI)) 1210 return nullptr; 1211 1212 if (auto *Calloc = foldMallocMemset(CI, B)) 1213 return Calloc; 1214 1215 // memset(p, v, n) -> llvm.memset(align 1 p, v, n) 1216 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 1217 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1)); 1218 NewCI->setAttributes(CI->getAttributes()); 1219 return CI->getArgOperand(0); 1220 } 1221 1222 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) { 1223 if (isa<ConstantPointerNull>(CI->getArgOperand(0))) 1224 return emitMalloc(CI->getArgOperand(1), B, DL, TLI); 1225 1226 return nullptr; 1227 } 1228 1229 //===----------------------------------------------------------------------===// 1230 // Math Library Optimizations 1231 //===----------------------------------------------------------------------===// 1232 1233 // Replace a libcall \p CI with a call to intrinsic \p IID 1234 static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B, 1235 Intrinsic::ID IID) { 1236 // Propagate fast-math flags from the existing call to the new call. 1237 IRBuilderBase::FastMathFlagGuard Guard(B); 1238 B.setFastMathFlags(CI->getFastMathFlags()); 1239 1240 Module *M = CI->getModule(); 1241 Value *V = CI->getArgOperand(0); 1242 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType()); 1243 CallInst *NewCall = B.CreateCall(F, V); 1244 NewCall->takeName(CI); 1245 return NewCall; 1246 } 1247 1248 /// Return a variant of Val with float type. 1249 /// Currently this works in two cases: If Val is an FPExtension of a float 1250 /// value to something bigger, simply return the operand. 1251 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 1252 /// loss of precision do so. 1253 static Value *valueHasFloatPrecision(Value *Val) { 1254 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 1255 Value *Op = Cast->getOperand(0); 1256 if (Op->getType()->isFloatTy()) 1257 return Op; 1258 } 1259 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 1260 APFloat F = Const->getValueAPF(); 1261 bool losesInfo; 1262 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 1263 &losesInfo); 1264 if (!losesInfo) 1265 return ConstantFP::get(Const->getContext(), F); 1266 } 1267 return nullptr; 1268 } 1269 1270 /// Shrink double -> float functions. 1271 static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B, 1272 bool isBinary, bool isPrecise = false) { 1273 Function *CalleeFn = CI->getCalledFunction(); 1274 if (!CI->getType()->isDoubleTy() || !CalleeFn) 1275 return nullptr; 1276 1277 // If not all the uses of the function are converted to float, then bail out. 1278 // This matters if the precision of the result is more important than the 1279 // precision of the arguments. 1280 if (isPrecise) 1281 for (User *U : CI->users()) { 1282 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 1283 if (!Cast || !Cast->getType()->isFloatTy()) 1284 return nullptr; 1285 } 1286 1287 // If this is something like 'g((double) float)', convert to 'gf(float)'. 1288 Value *V[2]; 1289 V[0] = valueHasFloatPrecision(CI->getArgOperand(0)); 1290 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr; 1291 if (!V[0] || (isBinary && !V[1])) 1292 return nullptr; 1293 1294 // If call isn't an intrinsic, check that it isn't within a function with the 1295 // same name as the float version of this call, otherwise the result is an 1296 // infinite loop. For example, from MinGW-w64: 1297 // 1298 // float expf(float val) { return (float) exp((double) val); } 1299 StringRef CalleeName = CalleeFn->getName(); 1300 bool IsIntrinsic = CalleeFn->isIntrinsic(); 1301 if (!IsIntrinsic) { 1302 StringRef CallerName = CI->getFunction()->getName(); 1303 if (!CallerName.empty() && CallerName.back() == 'f' && 1304 CallerName.size() == (CalleeName.size() + 1) && 1305 CallerName.startswith(CalleeName)) 1306 return nullptr; 1307 } 1308 1309 // Propagate the math semantics from the current function to the new function. 1310 IRBuilderBase::FastMathFlagGuard Guard(B); 1311 B.setFastMathFlags(CI->getFastMathFlags()); 1312 1313 // g((double) float) -> (double) gf(float) 1314 Value *R; 1315 if (IsIntrinsic) { 1316 Module *M = CI->getModule(); 1317 Intrinsic::ID IID = CalleeFn->getIntrinsicID(); 1318 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy()); 1319 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]); 1320 } else { 1321 AttributeList CalleeAttrs = CalleeFn->getAttributes(); 1322 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeName, B, CalleeAttrs) 1323 : emitUnaryFloatFnCall(V[0], CalleeName, B, CalleeAttrs); 1324 } 1325 return B.CreateFPExt(R, B.getDoubleTy()); 1326 } 1327 1328 /// Shrink double -> float for unary functions. 1329 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1330 bool isPrecise = false) { 1331 return optimizeDoubleFP(CI, B, false, isPrecise); 1332 } 1333 1334 /// Shrink double -> float for binary functions. 1335 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1336 bool isPrecise = false) { 1337 return optimizeDoubleFP(CI, B, true, isPrecise); 1338 } 1339 1340 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1341 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) { 1342 if (!CI->isFast()) 1343 return nullptr; 1344 1345 // Propagate fast-math flags from the existing call to new instructions. 1346 IRBuilderBase::FastMathFlagGuard Guard(B); 1347 B.setFastMathFlags(CI->getFastMathFlags()); 1348 1349 Value *Real, *Imag; 1350 if (CI->getNumArgOperands() == 1) { 1351 Value *Op = CI->getArgOperand(0); 1352 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 1353 Real = B.CreateExtractValue(Op, 0, "real"); 1354 Imag = B.CreateExtractValue(Op, 1, "imag"); 1355 } else { 1356 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!"); 1357 Real = CI->getArgOperand(0); 1358 Imag = CI->getArgOperand(1); 1359 } 1360 1361 Value *RealReal = B.CreateFMul(Real, Real); 1362 Value *ImagImag = B.CreateFMul(Imag, Imag); 1363 1364 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt, 1365 CI->getType()); 1366 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs"); 1367 } 1368 1369 static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func, 1370 IRBuilderBase &B) { 1371 if (!isa<FPMathOperator>(Call)) 1372 return nullptr; 1373 1374 IRBuilderBase::FastMathFlagGuard Guard(B); 1375 B.setFastMathFlags(Call->getFastMathFlags()); 1376 1377 // TODO: Can this be shared to also handle LLVM intrinsics? 1378 Value *X; 1379 switch (Func) { 1380 case LibFunc_sin: 1381 case LibFunc_sinf: 1382 case LibFunc_sinl: 1383 case LibFunc_tan: 1384 case LibFunc_tanf: 1385 case LibFunc_tanl: 1386 // sin(-X) --> -sin(X) 1387 // tan(-X) --> -tan(X) 1388 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) 1389 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X)); 1390 break; 1391 case LibFunc_cos: 1392 case LibFunc_cosf: 1393 case LibFunc_cosl: 1394 // cos(-X) --> cos(X) 1395 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X)))) 1396 return B.CreateCall(Call->getCalledFunction(), X, "cos"); 1397 break; 1398 default: 1399 break; 1400 } 1401 return nullptr; 1402 } 1403 1404 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilderBase &B) { 1405 // Multiplications calculated using Addition Chains. 1406 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html 1407 1408 assert(Exp != 0 && "Incorrect exponent 0 not handled"); 1409 1410 if (InnerChain[Exp]) 1411 return InnerChain[Exp]; 1412 1413 static const unsigned AddChain[33][2] = { 1414 {0, 0}, // Unused. 1415 {0, 0}, // Unused (base case = pow1). 1416 {1, 1}, // Unused (pre-computed). 1417 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4}, 1418 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7}, 1419 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10}, 1420 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13}, 1421 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16}, 1422 }; 1423 1424 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B), 1425 getPow(InnerChain, AddChain[Exp][1], B)); 1426 return InnerChain[Exp]; 1427 } 1428 1429 // Return a properly extended 32-bit integer if the operation is an itofp. 1430 static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B) { 1431 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) { 1432 Value *Op = cast<Instruction>(I2F)->getOperand(0); 1433 // Make sure that the exponent fits inside an int32_t, 1434 // thus avoiding any range issues that FP has not. 1435 unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits(); 1436 if (BitWidth < 32 || 1437 (BitWidth == 32 && isa<SIToFPInst>(I2F))) 1438 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getInt32Ty()) 1439 : B.CreateZExt(Op, B.getInt32Ty()); 1440 } 1441 1442 return nullptr; 1443 } 1444 1445 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y); 1446 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x); 1447 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x). 1448 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) { 1449 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1450 AttributeList Attrs; // Attributes are only meaningful on the original call 1451 Module *Mod = Pow->getModule(); 1452 Type *Ty = Pow->getType(); 1453 bool Ignored; 1454 1455 // Evaluate special cases related to a nested function as the base. 1456 1457 // pow(exp(x), y) -> exp(x * y) 1458 // pow(exp2(x), y) -> exp2(x * y) 1459 // If exp{,2}() is used only once, it is better to fold two transcendental 1460 // math functions into one. If used again, exp{,2}() would still have to be 1461 // called with the original argument, then keep both original transcendental 1462 // functions. However, this transformation is only safe with fully relaxed 1463 // math semantics, since, besides rounding differences, it changes overflow 1464 // and underflow behavior quite dramatically. For example: 1465 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf 1466 // Whereas: 1467 // exp(1000 * 0.001) = exp(1) 1468 // TODO: Loosen the requirement for fully relaxed math semantics. 1469 // TODO: Handle exp10() when more targets have it available. 1470 CallInst *BaseFn = dyn_cast<CallInst>(Base); 1471 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) { 1472 LibFunc LibFn; 1473 1474 Function *CalleeFn = BaseFn->getCalledFunction(); 1475 if (CalleeFn && 1476 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) { 1477 StringRef ExpName; 1478 Intrinsic::ID ID; 1479 Value *ExpFn; 1480 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble; 1481 1482 switch (LibFn) { 1483 default: 1484 return nullptr; 1485 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl: 1486 ExpName = TLI->getName(LibFunc_exp); 1487 ID = Intrinsic::exp; 1488 LibFnFloat = LibFunc_expf; 1489 LibFnDouble = LibFunc_exp; 1490 LibFnLongDouble = LibFunc_expl; 1491 break; 1492 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l: 1493 ExpName = TLI->getName(LibFunc_exp2); 1494 ID = Intrinsic::exp2; 1495 LibFnFloat = LibFunc_exp2f; 1496 LibFnDouble = LibFunc_exp2; 1497 LibFnLongDouble = LibFunc_exp2l; 1498 break; 1499 } 1500 1501 // Create new exp{,2}() with the product as its argument. 1502 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul"); 1503 ExpFn = BaseFn->doesNotAccessMemory() 1504 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty), 1505 FMul, ExpName) 1506 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat, 1507 LibFnLongDouble, B, 1508 BaseFn->getAttributes()); 1509 1510 // Since the new exp{,2}() is different from the original one, dead code 1511 // elimination cannot be trusted to remove it, since it may have side 1512 // effects (e.g., errno). When the only consumer for the original 1513 // exp{,2}() is pow(), then it has to be explicitly erased. 1514 substituteInParent(BaseFn, ExpFn); 1515 return ExpFn; 1516 } 1517 } 1518 1519 // Evaluate special cases related to a constant base. 1520 1521 const APFloat *BaseF; 1522 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF))) 1523 return nullptr; 1524 1525 // pow(2.0, itofp(x)) -> ldexp(1.0, x) 1526 if (match(Base, m_SpecificFP(2.0)) && 1527 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) && 1528 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) { 1529 if (Value *ExpoI = getIntToFPVal(Expo, B)) 1530 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI, TLI, 1531 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl, 1532 B, Attrs); 1533 } 1534 1535 // pow(2.0 ** n, x) -> exp2(n * x) 1536 if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) { 1537 APFloat BaseR = APFloat(1.0); 1538 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored); 1539 BaseR = BaseR / *BaseF; 1540 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger(); 1541 const APFloat *NF = IsReciprocal ? &BaseR : BaseF; 1542 APSInt NI(64, false); 1543 if ((IsInteger || IsReciprocal) && 1544 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) == 1545 APFloat::opOK && 1546 NI > 1 && NI.isPowerOf2()) { 1547 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0); 1548 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul"); 1549 if (Pow->doesNotAccessMemory()) 1550 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty), 1551 FMul, "exp2"); 1552 else 1553 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f, 1554 LibFunc_exp2l, B, Attrs); 1555 } 1556 } 1557 1558 // pow(10.0, x) -> exp10(x) 1559 // TODO: There is no exp10() intrinsic yet, but some day there shall be one. 1560 if (match(Base, m_SpecificFP(10.0)) && 1561 hasFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) 1562 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f, 1563 LibFunc_exp10l, B, Attrs); 1564 1565 // pow(x, y) -> exp2(log2(x) * y) 1566 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() && 1567 !BaseF->isNegative()) { 1568 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN. 1569 // Luckily optimizePow has already handled the x == 1 case. 1570 assert(!match(Base, m_FPOne()) && 1571 "pow(1.0, y) should have been simplified earlier!"); 1572 1573 Value *Log = nullptr; 1574 if (Ty->isFloatTy()) 1575 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat())); 1576 else if (Ty->isDoubleTy()) 1577 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble())); 1578 1579 if (Log) { 1580 Value *FMul = B.CreateFMul(Log, Expo, "mul"); 1581 if (Pow->doesNotAccessMemory()) 1582 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty), 1583 FMul, "exp2"); 1584 else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) 1585 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f, 1586 LibFunc_exp2l, B, Attrs); 1587 } 1588 } 1589 1590 return nullptr; 1591 } 1592 1593 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, 1594 Module *M, IRBuilderBase &B, 1595 const TargetLibraryInfo *TLI) { 1596 // If errno is never set, then use the intrinsic for sqrt(). 1597 if (NoErrno) { 1598 Function *SqrtFn = 1599 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType()); 1600 return B.CreateCall(SqrtFn, V, "sqrt"); 1601 } 1602 1603 // Otherwise, use the libcall for sqrt(). 1604 if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl)) 1605 // TODO: We also should check that the target can in fact lower the sqrt() 1606 // libcall. We currently have no way to ask this question, so we ask if 1607 // the target has a sqrt() libcall, which is not exactly the same. 1608 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf, 1609 LibFunc_sqrtl, B, Attrs); 1610 1611 return nullptr; 1612 } 1613 1614 /// Use square root in place of pow(x, +/-0.5). 1615 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) { 1616 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1617 AttributeList Attrs; // Attributes are only meaningful on the original call 1618 Module *Mod = Pow->getModule(); 1619 Type *Ty = Pow->getType(); 1620 1621 const APFloat *ExpoF; 1622 if (!match(Expo, m_APFloat(ExpoF)) || 1623 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 1624 return nullptr; 1625 1626 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step, 1627 // so that requires fast-math-flags (afn or reassoc). 1628 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc())) 1629 return nullptr; 1630 1631 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI); 1632 if (!Sqrt) 1633 return nullptr; 1634 1635 // Handle signed zero base by expanding to fabs(sqrt(x)). 1636 if (!Pow->hasNoSignedZeros()) { 1637 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty); 1638 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs"); 1639 } 1640 1641 // Handle non finite base by expanding to 1642 // (x == -infinity ? +infinity : sqrt(x)). 1643 if (!Pow->hasNoInfs()) { 1644 Value *PosInf = ConstantFP::getInfinity(Ty), 1645 *NegInf = ConstantFP::getInfinity(Ty, true); 1646 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 1647 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 1648 } 1649 1650 // If the exponent is negative, then get the reciprocal. 1651 if (ExpoF->isNegative()) 1652 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 1653 1654 return Sqrt; 1655 } 1656 1657 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, 1658 IRBuilderBase &B) { 1659 Value *Args[] = {Base, Expo}; 1660 Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Base->getType()); 1661 return B.CreateCall(F, Args); 1662 } 1663 1664 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) { 1665 Value *Base = Pow->getArgOperand(0); 1666 Value *Expo = Pow->getArgOperand(1); 1667 Function *Callee = Pow->getCalledFunction(); 1668 StringRef Name = Callee->getName(); 1669 Type *Ty = Pow->getType(); 1670 Module *M = Pow->getModule(); 1671 Value *Shrunk = nullptr; 1672 bool AllowApprox = Pow->hasApproxFunc(); 1673 bool Ignored; 1674 1675 // Propagate the math semantics from the call to any created instructions. 1676 IRBuilderBase::FastMathFlagGuard Guard(B); 1677 B.setFastMathFlags(Pow->getFastMathFlags()); 1678 1679 // Shrink pow() to powf() if the arguments are single precision, 1680 // unless the result is expected to be double precision. 1681 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) && 1682 hasFloatVersion(Name)) 1683 Shrunk = optimizeBinaryDoubleFP(Pow, B, true); 1684 1685 // Evaluate special cases related to the base. 1686 1687 // pow(1.0, x) -> 1.0 1688 if (match(Base, m_FPOne())) 1689 return Base; 1690 1691 if (Value *Exp = replacePowWithExp(Pow, B)) 1692 return Exp; 1693 1694 // Evaluate special cases related to the exponent. 1695 1696 // pow(x, -1.0) -> 1.0 / x 1697 if (match(Expo, m_SpecificFP(-1.0))) 1698 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 1699 1700 // pow(x, +/-0.0) -> 1.0 1701 if (match(Expo, m_AnyZeroFP())) 1702 return ConstantFP::get(Ty, 1.0); 1703 1704 // pow(x, 1.0) -> x 1705 if (match(Expo, m_FPOne())) 1706 return Base; 1707 1708 // pow(x, 2.0) -> x * x 1709 if (match(Expo, m_SpecificFP(2.0))) 1710 return B.CreateFMul(Base, Base, "square"); 1711 1712 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 1713 return Sqrt; 1714 1715 // pow(x, n) -> x * x * x * ... 1716 const APFloat *ExpoF; 1717 if (AllowApprox && match(Expo, m_APFloat(ExpoF))) { 1718 // We limit to a max of 7 multiplications, thus the maximum exponent is 32. 1719 // If the exponent is an integer+0.5 we generate a call to sqrt and an 1720 // additional fmul. 1721 // TODO: This whole transformation should be backend specific (e.g. some 1722 // backends might prefer libcalls or the limit for the exponent might 1723 // be different) and it should also consider optimizing for size. 1724 APFloat LimF(ExpoF->getSemantics(), 33), 1725 ExpoA(abs(*ExpoF)); 1726 if (ExpoA < LimF) { 1727 // This transformation applies to integer or integer+0.5 exponents only. 1728 // For integer+0.5, we create a sqrt(Base) call. 1729 Value *Sqrt = nullptr; 1730 if (!ExpoA.isInteger()) { 1731 APFloat Expo2 = ExpoA; 1732 // To check if ExpoA is an integer + 0.5, we add it to itself. If there 1733 // is no floating point exception and the result is an integer, then 1734 // ExpoA == integer + 0.5 1735 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK) 1736 return nullptr; 1737 1738 if (!Expo2.isInteger()) 1739 return nullptr; 1740 1741 Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(), 1742 Pow->doesNotAccessMemory(), M, B, TLI); 1743 } 1744 1745 // We will memoize intermediate products of the Addition Chain. 1746 Value *InnerChain[33] = {nullptr}; 1747 InnerChain[1] = Base; 1748 InnerChain[2] = B.CreateFMul(Base, Base, "square"); 1749 1750 // We cannot readily convert a non-double type (like float) to a double. 1751 // So we first convert it to something which could be converted to double. 1752 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored); 1753 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B); 1754 1755 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x). 1756 if (Sqrt) 1757 FMul = B.CreateFMul(FMul, Sqrt); 1758 1759 // If the exponent is negative, then get the reciprocal. 1760 if (ExpoF->isNegative()) 1761 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal"); 1762 1763 return FMul; 1764 } 1765 1766 APSInt IntExpo(32, /*isUnsigned=*/false); 1767 // powf(x, n) -> powi(x, n) if n is a constant signed integer value 1768 if (ExpoF->isInteger() && 1769 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) == 1770 APFloat::opOK) { 1771 return createPowWithIntegerExponent( 1772 Base, ConstantInt::get(B.getInt32Ty(), IntExpo), M, B); 1773 } 1774 } 1775 1776 // powf(x, itofp(y)) -> powi(x, y) 1777 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) { 1778 if (Value *ExpoI = getIntToFPVal(Expo, B)) 1779 return createPowWithIntegerExponent(Base, ExpoI, M, B); 1780 } 1781 1782 return Shrunk; 1783 } 1784 1785 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) { 1786 Function *Callee = CI->getCalledFunction(); 1787 AttributeList Attrs; // Attributes are only meaningful on the original call 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, Attrs); 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; // Attributes are only meaningful on the original call 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 *>(FixedVectorType::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_roundeven: 2934 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven); 2935 case LibFunc_nearbyint: 2936 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 2937 case LibFunc_rint: 2938 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 2939 case LibFunc_trunc: 2940 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 2941 case LibFunc_acos: 2942 case LibFunc_acosh: 2943 case LibFunc_asin: 2944 case LibFunc_asinh: 2945 case LibFunc_atan: 2946 case LibFunc_atanh: 2947 case LibFunc_cbrt: 2948 case LibFunc_cosh: 2949 case LibFunc_exp: 2950 case LibFunc_exp10: 2951 case LibFunc_expm1: 2952 case LibFunc_cos: 2953 case LibFunc_sin: 2954 case LibFunc_sinh: 2955 case LibFunc_tanh: 2956 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName())) 2957 return optimizeUnaryDoubleFP(CI, Builder, true); 2958 return nullptr; 2959 case LibFunc_copysign: 2960 if (hasFloatVersion(CI->getCalledFunction()->getName())) 2961 return optimizeBinaryDoubleFP(CI, Builder); 2962 return nullptr; 2963 case LibFunc_fminf: 2964 case LibFunc_fmin: 2965 case LibFunc_fminl: 2966 case LibFunc_fmaxf: 2967 case LibFunc_fmax: 2968 case LibFunc_fmaxl: 2969 return optimizeFMinFMax(CI, Builder); 2970 case LibFunc_cabs: 2971 case LibFunc_cabsf: 2972 case LibFunc_cabsl: 2973 return optimizeCAbs(CI, Builder); 2974 default: 2975 return nullptr; 2976 } 2977 } 2978 2979 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) { 2980 // TODO: Split out the code below that operates on FP calls so that 2981 // we can all non-FP calls with the StrictFP attribute to be 2982 // optimized. 2983 if (CI->isNoBuiltin()) 2984 return nullptr; 2985 2986 LibFunc Func; 2987 Function *Callee = CI->getCalledFunction(); 2988 bool isCallingConvC = isCallingConvCCompatible(CI); 2989 2990 SmallVector<OperandBundleDef, 2> OpBundles; 2991 CI->getOperandBundlesAsDefs(OpBundles); 2992 2993 IRBuilderBase::OperandBundlesGuard Guard(Builder); 2994 Builder.setDefaultOperandBundles(OpBundles); 2995 2996 // Command-line parameter overrides instruction attribute. 2997 // This can't be moved to optimizeFloatingPointLibCall() because it may be 2998 // used by the intrinsic optimizations. 2999 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 3000 UnsafeFPShrink = EnableUnsafeFPShrink; 3001 else if (isa<FPMathOperator>(CI) && CI->isFast()) 3002 UnsafeFPShrink = true; 3003 3004 // First, check for intrinsics. 3005 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 3006 if (!isCallingConvC) 3007 return nullptr; 3008 // The FP intrinsics have corresponding constrained versions so we don't 3009 // need to check for the StrictFP attribute here. 3010 switch (II->getIntrinsicID()) { 3011 case Intrinsic::pow: 3012 return optimizePow(CI, Builder); 3013 case Intrinsic::exp2: 3014 return optimizeExp2(CI, Builder); 3015 case Intrinsic::log: 3016 case Intrinsic::log2: 3017 case Intrinsic::log10: 3018 return optimizeLog(CI, Builder); 3019 case Intrinsic::sqrt: 3020 return optimizeSqrt(CI, Builder); 3021 // TODO: Use foldMallocMemset() with memset intrinsic. 3022 case Intrinsic::memset: 3023 return optimizeMemSet(CI, Builder); 3024 case Intrinsic::memcpy: 3025 return optimizeMemCpy(CI, Builder); 3026 case Intrinsic::memmove: 3027 return optimizeMemMove(CI, Builder); 3028 default: 3029 return nullptr; 3030 } 3031 } 3032 3033 // Also try to simplify calls to fortified library functions. 3034 if (Value *SimplifiedFortifiedCI = 3035 FortifiedSimplifier.optimizeCall(CI, Builder)) { 3036 // Try to further simplify the result. 3037 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI); 3038 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) { 3039 // Ensure that SimplifiedCI's uses are complete, since some calls have 3040 // their uses analyzed. 3041 replaceAllUsesWith(CI, SimplifiedCI); 3042 3043 // Set insertion point to SimplifiedCI to guarantee we reach all uses 3044 // we might replace later on. 3045 IRBuilderBase::InsertPointGuard Guard(Builder); 3046 Builder.SetInsertPoint(SimplifiedCI); 3047 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) { 3048 // If we were able to further simplify, remove the now redundant call. 3049 substituteInParent(SimplifiedCI, V); 3050 return V; 3051 } 3052 } 3053 return SimplifiedFortifiedCI; 3054 } 3055 3056 // Then check for known library functions. 3057 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 3058 // We never change the calling convention. 3059 if (!ignoreCallingConv(Func) && !isCallingConvC) 3060 return nullptr; 3061 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 3062 return V; 3063 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 3064 return V; 3065 switch (Func) { 3066 case LibFunc_ffs: 3067 case LibFunc_ffsl: 3068 case LibFunc_ffsll: 3069 return optimizeFFS(CI, Builder); 3070 case LibFunc_fls: 3071 case LibFunc_flsl: 3072 case LibFunc_flsll: 3073 return optimizeFls(CI, Builder); 3074 case LibFunc_abs: 3075 case LibFunc_labs: 3076 case LibFunc_llabs: 3077 return optimizeAbs(CI, Builder); 3078 case LibFunc_isdigit: 3079 return optimizeIsDigit(CI, Builder); 3080 case LibFunc_isascii: 3081 return optimizeIsAscii(CI, Builder); 3082 case LibFunc_toascii: 3083 return optimizeToAscii(CI, Builder); 3084 case LibFunc_atoi: 3085 case LibFunc_atol: 3086 case LibFunc_atoll: 3087 return optimizeAtoi(CI, Builder); 3088 case LibFunc_strtol: 3089 case LibFunc_strtoll: 3090 return optimizeStrtol(CI, Builder); 3091 case LibFunc_printf: 3092 return optimizePrintF(CI, Builder); 3093 case LibFunc_sprintf: 3094 return optimizeSPrintF(CI, Builder); 3095 case LibFunc_snprintf: 3096 return optimizeSnPrintF(CI, Builder); 3097 case LibFunc_fprintf: 3098 return optimizeFPrintF(CI, Builder); 3099 case LibFunc_fwrite: 3100 return optimizeFWrite(CI, Builder); 3101 case LibFunc_fputs: 3102 return optimizeFPuts(CI, Builder); 3103 case LibFunc_puts: 3104 return optimizePuts(CI, Builder); 3105 case LibFunc_perror: 3106 return optimizeErrorReporting(CI, Builder); 3107 case LibFunc_vfprintf: 3108 case LibFunc_fiprintf: 3109 return optimizeErrorReporting(CI, Builder, 0); 3110 default: 3111 return nullptr; 3112 } 3113 } 3114 return nullptr; 3115 } 3116 3117 LibCallSimplifier::LibCallSimplifier( 3118 const DataLayout &DL, const TargetLibraryInfo *TLI, 3119 OptimizationRemarkEmitter &ORE, 3120 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 3121 function_ref<void(Instruction *, Value *)> Replacer, 3122 function_ref<void(Instruction *)> Eraser) 3123 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI), 3124 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {} 3125 3126 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 3127 // Indirect through the replacer used in this instance. 3128 Replacer(I, With); 3129 } 3130 3131 void LibCallSimplifier::eraseFromParent(Instruction *I) { 3132 Eraser(I); 3133 } 3134 3135 // TODO: 3136 // Additional cases that we need to add to this file: 3137 // 3138 // cbrt: 3139 // * cbrt(expN(X)) -> expN(x/3) 3140 // * cbrt(sqrt(x)) -> pow(x,1/6) 3141 // * cbrt(cbrt(x)) -> pow(x,1/9) 3142 // 3143 // exp, expf, expl: 3144 // * exp(log(x)) -> x 3145 // 3146 // log, logf, logl: 3147 // * log(exp(x)) -> x 3148 // * log(exp(y)) -> y*log(e) 3149 // * log(exp10(y)) -> y*log(10) 3150 // * log(sqrt(x)) -> 0.5*log(x) 3151 // 3152 // pow, powf, powl: 3153 // * pow(sqrt(x),y) -> pow(x,y*0.5) 3154 // * pow(pow(x,y),z)-> pow(x,y*z) 3155 // 3156 // signbit: 3157 // * signbit(cnst) -> cnst' 3158 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 3159 // 3160 // sqrt, sqrtf, sqrtl: 3161 // * sqrt(expN(x)) -> expN(x*0.5) 3162 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 3163 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 3164 // 3165 3166 //===----------------------------------------------------------------------===// 3167 // Fortified Library Call Optimizations 3168 //===----------------------------------------------------------------------===// 3169 3170 bool 3171 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI, 3172 unsigned ObjSizeOp, 3173 Optional<unsigned> SizeOp, 3174 Optional<unsigned> StrOp, 3175 Optional<unsigned> FlagOp) { 3176 // If this function takes a flag argument, the implementation may use it to 3177 // perform extra checks. Don't fold into the non-checking variant. 3178 if (FlagOp) { 3179 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp)); 3180 if (!Flag || !Flag->isZero()) 3181 return false; 3182 } 3183 3184 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp)) 3185 return true; 3186 3187 if (ConstantInt *ObjSizeCI = 3188 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 3189 if (ObjSizeCI->isMinusOne()) 3190 return true; 3191 // If the object size wasn't -1 (unknown), bail out if we were asked to. 3192 if (OnlyLowerUnknownSize) 3193 return false; 3194 if (StrOp) { 3195 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp)); 3196 // If the length is 0 we don't know how long it is and so we can't 3197 // remove the check. 3198 if (Len) 3199 annotateDereferenceableBytes(CI, *StrOp, Len); 3200 else 3201 return false; 3202 return ObjSizeCI->getZExtValue() >= Len; 3203 } 3204 3205 if (SizeOp) { 3206 if (ConstantInt *SizeCI = 3207 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp))) 3208 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 3209 } 3210 } 3211 return false; 3212 } 3213 3214 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 3215 IRBuilderBase &B) { 3216 if (isFortifiedCallFoldable(CI, 3, 2)) { 3217 CallInst *NewCI = 3218 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 3219 Align(1), CI->getArgOperand(2)); 3220 NewCI->setAttributes(CI->getAttributes()); 3221 return CI->getArgOperand(0); 3222 } 3223 return nullptr; 3224 } 3225 3226 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 3227 IRBuilderBase &B) { 3228 if (isFortifiedCallFoldable(CI, 3, 2)) { 3229 CallInst *NewCI = 3230 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 3231 Align(1), CI->getArgOperand(2)); 3232 NewCI->setAttributes(CI->getAttributes()); 3233 return CI->getArgOperand(0); 3234 } 3235 return nullptr; 3236 } 3237 3238 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 3239 IRBuilderBase &B) { 3240 // TODO: Try foldMallocMemset() here. 3241 3242 if (isFortifiedCallFoldable(CI, 3, 2)) { 3243 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 3244 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, 3245 CI->getArgOperand(2), Align(1)); 3246 NewCI->setAttributes(CI->getAttributes()); 3247 return CI->getArgOperand(0); 3248 } 3249 return nullptr; 3250 } 3251 3252 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 3253 IRBuilderBase &B, 3254 LibFunc Func) { 3255 const DataLayout &DL = CI->getModule()->getDataLayout(); 3256 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 3257 *ObjSize = CI->getArgOperand(2); 3258 3259 // __stpcpy_chk(x,x,...) -> x+strlen(x) 3260 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 3261 Value *StrLen = emitStrLen(Src, B, DL, TLI); 3262 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 3263 } 3264 3265 // If a) we don't have any length information, or b) we know this will 3266 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 3267 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 3268 // TODO: It might be nice to get a maximum length out of the possible 3269 // string lengths for varying. 3270 if (isFortifiedCallFoldable(CI, 2, None, 1)) { 3271 if (Func == LibFunc_strcpy_chk) 3272 return emitStrCpy(Dst, Src, B, TLI); 3273 else 3274 return emitStpCpy(Dst, Src, B, TLI); 3275 } 3276 3277 if (OnlyLowerUnknownSize) 3278 return nullptr; 3279 3280 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 3281 uint64_t Len = GetStringLength(Src); 3282 if (Len) 3283 annotateDereferenceableBytes(CI, 1, Len); 3284 else 3285 return nullptr; 3286 3287 Type *SizeTTy = DL.getIntPtrType(CI->getContext()); 3288 Value *LenV = ConstantInt::get(SizeTTy, Len); 3289 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 3290 // If the function was an __stpcpy_chk, and we were able to fold it into 3291 // a __memcpy_chk, we still need to return the correct end pointer. 3292 if (Ret && Func == LibFunc_stpcpy_chk) 3293 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1)); 3294 return Ret; 3295 } 3296 3297 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI, 3298 IRBuilderBase &B) { 3299 if (isFortifiedCallFoldable(CI, 1, None, 0)) 3300 return emitStrLen(CI->getArgOperand(0), B, CI->getModule()->getDataLayout(), 3301 TLI); 3302 return nullptr; 3303 } 3304 3305 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 3306 IRBuilderBase &B, 3307 LibFunc Func) { 3308 if (isFortifiedCallFoldable(CI, 3, 2)) { 3309 if (Func == LibFunc_strncpy_chk) 3310 return emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3311 CI->getArgOperand(2), B, TLI); 3312 else 3313 return emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3314 CI->getArgOperand(2), B, TLI); 3315 } 3316 3317 return nullptr; 3318 } 3319 3320 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI, 3321 IRBuilderBase &B) { 3322 if (isFortifiedCallFoldable(CI, 4, 3)) 3323 return emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3324 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI); 3325 3326 return nullptr; 3327 } 3328 3329 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI, 3330 IRBuilderBase &B) { 3331 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) { 3332 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 5, CI->arg_end()); 3333 return emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3334 CI->getArgOperand(4), VariadicArgs, B, TLI); 3335 } 3336 3337 return nullptr; 3338 } 3339 3340 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI, 3341 IRBuilderBase &B) { 3342 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) { 3343 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 4, CI->arg_end()); 3344 return emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), VariadicArgs, 3345 B, TLI); 3346 } 3347 3348 return nullptr; 3349 } 3350 3351 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI, 3352 IRBuilderBase &B) { 3353 if (isFortifiedCallFoldable(CI, 2)) 3354 return emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI); 3355 3356 return nullptr; 3357 } 3358 3359 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI, 3360 IRBuilderBase &B) { 3361 if (isFortifiedCallFoldable(CI, 3)) 3362 return emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1), 3363 CI->getArgOperand(2), B, TLI); 3364 3365 return nullptr; 3366 } 3367 3368 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI, 3369 IRBuilderBase &B) { 3370 if (isFortifiedCallFoldable(CI, 3)) 3371 return emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1), 3372 CI->getArgOperand(2), B, TLI); 3373 3374 return nullptr; 3375 } 3376 3377 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI, 3378 IRBuilderBase &B) { 3379 if (isFortifiedCallFoldable(CI, 3)) 3380 return emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3381 CI->getArgOperand(2), B, TLI); 3382 3383 return nullptr; 3384 } 3385 3386 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI, 3387 IRBuilderBase &B) { 3388 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) 3389 return emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3390 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI); 3391 3392 return nullptr; 3393 } 3394 3395 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI, 3396 IRBuilderBase &B) { 3397 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) 3398 return emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 3399 CI->getArgOperand(4), B, TLI); 3400 3401 return nullptr; 3402 } 3403 3404 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI, 3405 IRBuilderBase &Builder) { 3406 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 3407 // Some clang users checked for _chk libcall availability using: 3408 // __has_builtin(__builtin___memcpy_chk) 3409 // When compiling with -fno-builtin, this is always true. 3410 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 3411 // end up with fortified libcalls, which isn't acceptable in a freestanding 3412 // environment which only provides their non-fortified counterparts. 3413 // 3414 // Until we change clang and/or teach external users to check for availability 3415 // differently, disregard the "nobuiltin" attribute and TLI::has. 3416 // 3417 // PR23093. 3418 3419 LibFunc Func; 3420 Function *Callee = CI->getCalledFunction(); 3421 bool isCallingConvC = isCallingConvCCompatible(CI); 3422 3423 SmallVector<OperandBundleDef, 2> OpBundles; 3424 CI->getOperandBundlesAsDefs(OpBundles); 3425 3426 IRBuilderBase::OperandBundlesGuard Guard(Builder); 3427 Builder.setDefaultOperandBundles(OpBundles); 3428 3429 // First, check that this is a known library functions and that the prototype 3430 // is correct. 3431 if (!TLI->getLibFunc(*Callee, Func)) 3432 return nullptr; 3433 3434 // We never change the calling convention. 3435 if (!ignoreCallingConv(Func) && !isCallingConvC) 3436 return nullptr; 3437 3438 switch (Func) { 3439 case LibFunc_memcpy_chk: 3440 return optimizeMemCpyChk(CI, Builder); 3441 case LibFunc_memmove_chk: 3442 return optimizeMemMoveChk(CI, Builder); 3443 case LibFunc_memset_chk: 3444 return optimizeMemSetChk(CI, Builder); 3445 case LibFunc_stpcpy_chk: 3446 case LibFunc_strcpy_chk: 3447 return optimizeStrpCpyChk(CI, Builder, Func); 3448 case LibFunc_strlen_chk: 3449 return optimizeStrLenChk(CI, Builder); 3450 case LibFunc_stpncpy_chk: 3451 case LibFunc_strncpy_chk: 3452 return optimizeStrpNCpyChk(CI, Builder, Func); 3453 case LibFunc_memccpy_chk: 3454 return optimizeMemCCpyChk(CI, Builder); 3455 case LibFunc_snprintf_chk: 3456 return optimizeSNPrintfChk(CI, Builder); 3457 case LibFunc_sprintf_chk: 3458 return optimizeSPrintfChk(CI, Builder); 3459 case LibFunc_strcat_chk: 3460 return optimizeStrCatChk(CI, Builder); 3461 case LibFunc_strlcat_chk: 3462 return optimizeStrLCat(CI, Builder); 3463 case LibFunc_strncat_chk: 3464 return optimizeStrNCatChk(CI, Builder); 3465 case LibFunc_strlcpy_chk: 3466 return optimizeStrLCpyChk(CI, Builder); 3467 case LibFunc_vsnprintf_chk: 3468 return optimizeVSNPrintfChk(CI, Builder); 3469 case LibFunc_vsprintf_chk: 3470 return optimizeVSPrintfChk(CI, Builder); 3471 default: 3472 break; 3473 } 3474 return nullptr; 3475 } 3476 3477 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 3478 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 3479 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 3480