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