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