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