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