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