LLVM 24.0.0git
SimplifyLibCalls.cpp
Go to the documentation of this file.
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 be used by other passes to do simplifications.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APSInt.h"
20#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Module.h"
42
43#include <cmath>
44
45using namespace llvm;
46using namespace PatternMatch;
47
48static cl::opt<bool>
49 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
50 cl::init(false),
51 cl::desc("Enable unsafe double to float "
52 "shrinking for math lib calls"));
53
54// Enable conversion of operator new calls with a MemProf hot or cold hint
55// to an operator new call that takes a hot/cold hint. Off by default since
56// not all allocators currently support this extension.
57static cl::opt<bool>
58 OptimizeHotColdNew("optimize-hot-cold-new", cl::Hidden, cl::init(false),
59 cl::desc("Enable hot/cold operator new library calls"));
61 "optimize-existing-hot-cold-new", cl::Hidden, cl::init(false),
63 "Enable optimization of existing hot/cold operator new library calls"));
65 "optimize-nobuiltin-hot-cold-new-new", cl::Hidden, cl::init(false),
66 cl::desc("Enable transformation of nobuiltin operator new library calls"));
67
68namespace {
69
70// Specialized parser to ensure the hint is an 8 bit value (we can't specify
71// uint8_t to opt<> as that is interpreted to mean that we are passing a char
72// option with a specific set of values.
73struct HotColdHintParser : public cl::parser<unsigned> {
74 HotColdHintParser(cl::Option &O) : cl::parser<unsigned>(O) {}
75
76 bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) {
77 if (Arg.getAsInteger(0, Value))
78 return O.error("'" + Arg + "' value invalid for uint argument!");
79
80 if (Value > 255)
81 return O.error("'" + Arg + "' value must be in the range [0, 255]!");
82
83 return false;
84 }
85};
86
87} // end anonymous namespace
88
89// Hot/cold operator new takes an 8 bit hotness hint, where 0 is the coldest
90// and 255 is the hottest. Default to 1 value away from the coldest and hottest
91// hints, so that the compiler hinted allocations are slightly less strong than
92// manually inserted hints at the two extremes.
94 "cold-new-hint-value", cl::Hidden, cl::init(1),
95 cl::desc("Value to pass to hot/cold operator new for cold allocation"));
97 NotColdNewHintValue("notcold-new-hint-value", cl::Hidden, cl::init(128),
98 cl::desc("Value to pass to hot/cold operator new for "
99 "notcold (warm) allocation"));
101 "hot-new-hint-value", cl::Hidden, cl::init(254),
102 cl::desc("Value to pass to hot/cold operator new for hot allocation"));
104 "ambiguous-new-hint-value", cl::Hidden, cl::init(222),
105 cl::desc(
106 "Value to pass to hot/cold operator new for ambiguous allocation"));
107
108//===----------------------------------------------------------------------===//
109// Helper Functions
110//===----------------------------------------------------------------------===//
111
112static bool ignoreCallingConv(LibFunc Func) {
113 return Func == LibFunc_abs || Func == LibFunc_labs ||
114 Func == LibFunc_llabs || Func == LibFunc_strlen;
115}
116
117/// Return true if it is only used in equality comparisons with With.
119 for (User *U : V->users()) {
120 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
121 if (IC->isEquality() && IC->getOperand(1) == With)
122 continue;
123 // Unknown instruction.
124 return false;
125 }
126 return true;
127}
128
130 return any_of(CI->operands(), [](const Use &OI) {
131 return OI->getType()->isFloatingPointTy();
132 });
133}
134
135static bool callHasFP128Argument(const CallInst *CI) {
136 return any_of(CI->operands(), [](const Use &OI) {
137 return OI->getType()->isFP128Ty();
138 });
139}
140
141// Convert the entire string Str representing an integer in Base, up to
142// the terminating nul if present, to a constant according to the rules
143// of strtoul[l] or, when AsSigned is set, of strtol[l]. On success
144// return the result, otherwise null.
145// The function assumes the string is encoded in ASCII and carefully
146// avoids converting sequences (including "") that the corresponding
147// library call might fail and set errno for.
148static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
149 uint64_t Base, bool AsSigned, IRBuilderBase &B) {
150 if (Base < 2 || Base > 36)
151 if (Base != 0)
152 // Fail for an invalid base (required by POSIX).
153 return nullptr;
154
155 // Current offset into the original string to reflect in EndPtr.
156 size_t Offset = 0;
157 // Strip leading whitespace.
158 for ( ; Offset != Str.size(); ++Offset)
159 if (!isSpace((unsigned char)Str[Offset])) {
160 Str = Str.substr(Offset);
161 break;
162 }
163
164 if (Str.empty())
165 // Fail for empty subject sequences (POSIX allows but doesn't require
166 // strtol[l]/strtoul[l] to fail with EINVAL).
167 return nullptr;
168
169 // Strip but remember the sign.
170 bool Negate = Str[0] == '-';
171 if (Str[0] == '-' || Str[0] == '+') {
172 Str = Str.drop_front();
173 if (Str.empty())
174 // Fail for a sign with nothing after it.
175 return nullptr;
176 ++Offset;
177 }
178
179 // Set Max to the absolute value of the minimum (for signed), or
180 // to the maximum (for unsigned) value representable in the type.
181 Type *RetTy = CI->getType();
182 unsigned NBits = RetTy->getPrimitiveSizeInBits();
183 uint64_t Max = AsSigned && Negate ? 1 : 0;
184 Max += AsSigned ? maxIntN(NBits) : maxUIntN(NBits);
185
186 // Autodetect Base if it's zero and consume the "0x" prefix.
187 if (Str.size() > 1) {
188 if (Str[0] == '0') {
189 if (toUpper((unsigned char)Str[1]) == 'X') {
190 if (Str.size() == 2 || (Base && Base != 16))
191 // Fail if Base doesn't allow the "0x" prefix or for the prefix
192 // alone that implementations like BSD set errno to EINVAL for.
193 return nullptr;
194
195 Str = Str.drop_front(2);
196 Offset += 2;
197 Base = 16;
198 }
199 else if (Base == 0)
200 Base = 8;
201 } else if (Base == 0)
202 Base = 10;
203 }
204 else if (Base == 0)
205 Base = 10;
206
207 // Convert the rest of the subject sequence, not including the sign,
208 // to its uint64_t representation (this assumes the source character
209 // set is ASCII).
210 uint64_t Result = 0;
211 for (unsigned i = 0; i != Str.size(); ++i) {
212 unsigned char DigVal = Str[i];
213 if (isDigit(DigVal))
214 DigVal = DigVal - '0';
215 else {
216 DigVal = toUpper(DigVal);
217 if (isAlpha(DigVal))
218 DigVal = DigVal - 'A' + 10;
219 else
220 return nullptr;
221 }
222
223 if (DigVal >= Base)
224 // Fail if the digit is not valid in the Base.
225 return nullptr;
226
227 // Add the digit and fail if the result is not representable in
228 // the (unsigned form of the) destination type.
229 bool VFlow;
230 Result = SaturatingMultiplyAdd(Result, Base, (uint64_t)DigVal, &VFlow);
231 if (VFlow || Result > Max)
232 return nullptr;
233 }
234
235 if (EndPtr) {
236 // Store the pointer to the end.
237 Value *Off = B.getInt64(Offset + Str.size());
238 Value *StrBeg = CI->getArgOperand(0);
239 Value *StrEnd = B.CreateInBoundsGEP(B.getInt8Ty(), StrBeg, Off, "endptr");
240 B.CreateStore(StrEnd, EndPtr);
241 }
242
243 if (Negate) {
244 // Unsigned negation doesn't overflow.
245 Result = -Result;
246 // For unsigned numbers, discard sign bits.
247 if (!AsSigned)
248 Result &= maxUIntN(NBits);
249 }
250
251 return ConstantInt::get(RetTy, Result, AsSigned);
252}
253
255 for (User *U : V->users()) {
256 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
257 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
258 if (C->isNullValue())
259 continue;
260 // Unknown instruction.
261 return false;
262 }
263 return true;
264}
265
266static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
267 const SimplifyQuery &SQ) {
269 return false;
270
271 if (!isDereferenceablePointer(Str, APInt(64, Len), SQ))
272 return false;
273
274 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
275 return false;
276
277 return true;
278}
279
281 ArrayRef<unsigned> ArgNos,
282 uint64_t DereferenceableBytes) {
283 const Function *F = CI->getCaller();
284 if (!F)
285 return;
286 for (unsigned ArgNo : ArgNos) {
287 uint64_t DerefBytes = DereferenceableBytes;
288 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
289 if (!llvm::NullPointerIsDefined(F, AS) ||
290 CI->paramHasAttr(ArgNo, Attribute::NonNull))
291 DerefBytes = std::max(CI->getParamDereferenceableOrNullBytes(ArgNo),
292 DereferenceableBytes);
293
294 if (CI->getParamDereferenceableBytes(ArgNo) < DerefBytes) {
295 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable);
296 if (!llvm::NullPointerIsDefined(F, AS) ||
297 CI->paramHasAttr(ArgNo, Attribute::NonNull))
298 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull);
300 CI->getContext(), DerefBytes));
301 }
302 }
303}
304
306 ArrayRef<unsigned> ArgNos) {
307 Function *F = CI->getCaller();
308 if (!F)
309 return;
310
311 for (unsigned ArgNo : ArgNos) {
312 if (!CI->paramHasAttr(ArgNo, Attribute::NoUndef))
313 CI->addParamAttr(ArgNo, Attribute::NoUndef);
314
315 if (!CI->paramHasAttr(ArgNo, Attribute::NonNull)) {
316 unsigned AS =
319 continue;
320 CI->addParamAttr(ArgNo, Attribute::NonNull);
321 }
322
323 annotateDereferenceableBytes(CI, ArgNo, 1);
324 }
325}
326
328 Value *Size, const DataLayout &DL) {
331 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue());
332 } else if (isKnownNonZero(Size, DL)) {
334 uint64_t X, Y;
335 uint64_t DerefMin = 1;
337 DerefMin = std::min(X, Y);
338 annotateDereferenceableBytes(CI, ArgNos, DerefMin);
339 }
340 }
341}
342
343// Copy CallInst "flags" like musttail, notail, and tail. Return New param for
344// easier chaining. Calls to emit* and B.createCall should probably be wrapped
345// in this function when New is created to replace Old. Callers should take
346// care to check Old.isMustTailCall() if they aren't replacing Old directly
347// with New.
348static Value *copyFlags(const CallInst &Old, Value *New) {
349 assert(!Old.isMustTailCall() && "do not copy musttail call flags");
350 assert(!Old.isNoTailCall() && "do not copy notail call flags");
351 if (auto *NewCI = dyn_cast_or_null<CallInst>(New))
352 NewCI->setTailCallKind(Old.getTailCallKind());
353 return New;
354}
355
356static Value *mergeAttributesAndFlags(CallInst *NewCI, const CallInst &Old) {
357 NewCI->setAttributes(AttributeList::get(
358 NewCI->getContext(), {NewCI->getAttributes(), Old.getAttributes()}));
359 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(
360 NewCI->getType(), NewCI->getRetAttributes()));
361 for (unsigned I = 0; I < NewCI->arg_size(); ++I)
362 NewCI->removeParamAttrs(
363 I, AttributeFuncs::typeIncompatible(NewCI->getArgOperand(I)->getType(),
364 NewCI->getParamAttributes(I)));
365
366 return copyFlags(Old, NewCI);
367}
368
369// Helper to avoid truncating the length if size_t is 32-bits.
371 return Len >= Str.size() ? Str : Str.substr(0, Len);
372}
373
374//===----------------------------------------------------------------------===//
375// String and Memory Library Call Optimizations
376//===----------------------------------------------------------------------===//
377
378Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilderBase &B) {
379 // Extract some information from the instruction
380 Value *Dst = CI->getArgOperand(0);
381 Value *Src = CI->getArgOperand(1);
383
384 // See if we can get the length of the input string.
385 uint64_t Len = GetStringLength(Src);
386 if (Len)
388 else
389 return nullptr;
390 --Len; // Unbias length.
391
392 // Handle the simple, do-nothing case: strcat(x, "") -> x
393 if (Len == 0)
394 return Dst;
395
396 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, Len, B));
397}
398
399Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
400 IRBuilderBase &B) {
401 // We need to find the end of the destination string. That's where the
402 // memory is to be moved to. We just generate a call to strlen.
403 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
404 if (!DstLen)
405 return nullptr;
406
407 // Now that we have the destination's length, we must index into the
408 // destination's pointer to get the actual memcpy destination (end of
409 // the string .. we're concatenating).
410 Value *CpyDst = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
411
412 // We have enough information to now generate the memcpy call to do the
413 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
414 B.CreateMemCpy(CpyDst, Align(1), Src, Align(1),
415 TLI->getAsSizeT(Len + 1, *B.GetInsertBlock()->getModule()));
416 return Dst;
417}
418
419Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilderBase &B) {
420 // Extract some information from the instruction.
421 Value *Dst = CI->getArgOperand(0);
422 Value *Src = CI->getArgOperand(1);
423 Value *Size = CI->getArgOperand(2);
424 uint64_t Len;
426 if (isKnownNonZero(Size, DL))
428
429 // We don't do anything if length is not constant.
430 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size);
431 if (LengthArg) {
432 Len = LengthArg->getZExtValue();
433 // strncat(x, c, 0) -> x
434 if (!Len)
435 return Dst;
436 } else {
437 return nullptr;
438 }
439
440 // See if we can get the length of the input string.
441 uint64_t SrcLen = GetStringLength(Src);
442 if (SrcLen) {
443 annotateDereferenceableBytes(CI, 1, SrcLen);
444 --SrcLen; // Unbias length.
445 } else {
446 return nullptr;
447 }
448
449 // strncat(x, "", c) -> x
450 if (SrcLen == 0)
451 return Dst;
452
453 // We don't optimize this case.
454 if (Len < SrcLen)
455 return nullptr;
456
457 // strncat(x, s, c) -> strcat(x, s)
458 // s is constant so the strcat can be optimized further.
459 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, SrcLen, B));
460}
461
462// Helper to transform memchr(S, C, N) == S to N && *S == C and, when
463// NBytes is null, strchr(S, C) to *S == C. A precondition of the function
464// is that either S is dereferenceable or the value of N is nonzero.
466 IRBuilderBase &B, const DataLayout &DL)
467{
468 Value *Src = CI->getArgOperand(0);
469 Value *CharVal = CI->getArgOperand(1);
470
471 // Fold memchr(A, C, N) == A to N && *A == C.
472 Type *CharTy = B.getInt8Ty();
473 Value *Char0 = B.CreateLoad(CharTy, Src);
474 CharVal = B.CreateTrunc(CharVal, CharTy);
475 Value *Cmp = B.CreateICmpEQ(Char0, CharVal, "char0cmp");
476
477 if (NBytes) {
478 Value *Zero = ConstantInt::get(NBytes->getType(), 0);
479 Value *And = B.CreateICmpNE(NBytes, Zero);
480 Cmp = B.CreateLogicalAnd(And, Cmp);
481 }
482
483 Value *NullPtr = Constant::getNullValue(CI->getType());
484 return B.CreateSelect(Cmp, Src, NullPtr);
485}
486
487Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilderBase &B) {
488 Value *SrcStr = CI->getArgOperand(0);
489 Value *CharVal = CI->getArgOperand(1);
491
492 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
493 return memChrToCharCompare(CI, nullptr, B, DL);
494
495 // If the second operand is non-constant, see if we can compute the length
496 // of the input string and turn this into memchr.
497 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
498 if (!CharC) {
499 uint64_t Len = GetStringLength(SrcStr);
500 if (Len)
502 else
503 return nullptr;
504
506 FunctionType *FT = Callee->getFunctionType();
507 unsigned IntBits = TLI->getIntSize();
508 if (!FT->getParamType(1)->isIntegerTy(IntBits)) // memchr needs 'int'.
509 return nullptr;
510
511 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
512 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
513 return copyFlags(*CI,
514 emitMemChr(SrcStr, CharVal, // include nul.
515 ConstantInt::get(SizeTTy, Len), B,
516 DL, TLI));
517 }
518
519 if (CharC->isZero()) {
520 Value *NullPtr = Constant::getNullValue(CI->getType());
521 if (isOnlyUsedInEqualityComparison(CI, NullPtr))
522 // Pre-empt the transformation to strlen below and fold
523 // strchr(A, '\0') == null to false.
524 return B.CreateIntToPtr(B.getTrue(), CI->getType());
525 }
526
527 // Otherwise, the character is a constant, see if the first argument is
528 // a string literal. If so, we can constant fold.
529 StringRef Str;
530 if (!getConstantStringInfo(SrcStr, Str)) {
531 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
532 if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI))
533 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr");
534 return nullptr;
535 }
536
537 // Compute the offset, make sure to handle the case when we're searching for
538 // zero (a weird way to spell strlen).
539 size_t I = (0xFF & CharC->getSExtValue()) == 0
540 ? Str.size()
541 : Str.find(CharC->getSExtValue());
542 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
543 return Constant::getNullValue(CI->getType());
544
545 // strchr(s+n,c) -> gep(s+n+i,c)
546 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
547}
548
549Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilderBase &B) {
550 Value *SrcStr = CI->getArgOperand(0);
551 Value *CharVal = CI->getArgOperand(1);
552 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
554
555 StringRef Str;
556 if (!getConstantStringInfo(SrcStr, Str)) {
557 // strrchr(s, 0) -> strchr(s, 0)
558 if (CharC && CharC->isZero())
559 return copyFlags(*CI, emitStrChr(SrcStr, '\0', B, TLI));
560 return nullptr;
561 }
562
563 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
564 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
565
566 // Try to expand strrchr to the memrchr nonstandard extension if it's
567 // available, or simply fail otherwise.
568 uint64_t NBytes = Str.size() + 1; // Include the terminating nul.
569 Value *Size = ConstantInt::get(SizeTTy, NBytes);
570 return copyFlags(*CI, emitMemRChr(SrcStr, CharVal, Size, B, DL, TLI));
571}
572
573Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) {
574 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
575 if (Str1P == Str2P) // strcmp(x,x) -> 0
576 return ConstantInt::get(CI->getType(), 0);
577
578 StringRef Str1, Str2;
579 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
580 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
581
582 // strcmp(x, y) -> cnst (if both x and y are constant strings)
583 if (HasStr1 && HasStr2)
584 return ConstantInt::getSigned(CI->getType(),
585 std::clamp(Str1.compare(Str2), -1, 1));
586
587 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
588 return B.CreateNeg(B.CreateZExt(
589 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
590
591 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
592 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
593 CI->getType());
594
595 // strcmp(P, "x") -> memcmp(P, "x", 2)
596 uint64_t Len1 = GetStringLength(Str1P);
597 if (Len1)
598 annotateDereferenceableBytes(CI, 0, Len1);
599 uint64_t Len2 = GetStringLength(Str2P);
600 if (Len2)
601 annotateDereferenceableBytes(CI, 1, Len2);
602
603 if (Len1 && Len2) {
604 return copyFlags(
605 *CI, emitMemCmp(Str1P, Str2P,
606 TLI->getAsSizeT(std::min(Len1, Len2), *CI->getModule()),
607 B, DL, TLI));
608 }
609
610 // strcmp to memcmp
611 SimplifyQuery SQ(DL, TLI, DT, AC, CI);
612 if (!HasStr1 && HasStr2) {
613 if (canTransformToMemCmp(CI, Str1P, Len2, SQ))
614 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
615 TLI->getAsSizeT(Len2, *CI->getModule()),
616 B, DL, TLI));
617 } else if (HasStr1 && !HasStr2) {
618 if (canTransformToMemCmp(CI, Str2P, Len1, SQ))
619 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
620 TLI->getAsSizeT(Len1, *CI->getModule()),
621 B, DL, TLI));
622 }
623
625 return nullptr;
626}
627
628// Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant
629// arrays LHS and RHS and nonconstant Size.
631 Value *Size, bool StrNCmp,
632 IRBuilderBase &B, const DataLayout &DL);
633
634Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) {
635 Value *Str1P = CI->getArgOperand(0);
636 Value *Str2P = CI->getArgOperand(1);
637 Value *Size = CI->getArgOperand(2);
638 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
639 return ConstantInt::get(CI->getType(), 0);
640
641 if (isKnownNonZero(Size, DL))
643 // Get the length argument if it is constant.
644 uint64_t Length;
645 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
646 Length = LengthArg->getZExtValue();
647 else
648 return optimizeMemCmpVarSize(CI, Str1P, Str2P, Size, true, B, DL);
649
650 if (Length == 0) // strncmp(x,y,0) -> 0
651 return ConstantInt::get(CI->getType(), 0);
652
653 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
654 return copyFlags(*CI, emitMemCmp(Str1P, Str2P, Size, B, DL, TLI));
655
656 StringRef Str1, Str2;
657 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
658 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
659
660 // strncmp(x, y) -> cnst (if both x and y are constant strings)
661 if (HasStr1 && HasStr2) {
662 // Avoid truncating the 64-bit Length to 32 bits in ILP32.
663 StringRef SubStr1 = substr(Str1, Length);
664 StringRef SubStr2 = substr(Str2, Length);
665 return ConstantInt::getSigned(CI->getType(),
666 std::clamp(SubStr1.compare(SubStr2), -1, 1));
667 }
668
669 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
670 return B.CreateNeg(B.CreateZExt(
671 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
672
673 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
674 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
675 CI->getType());
676
677 uint64_t Len1 = GetStringLength(Str1P);
678 if (Len1)
679 annotateDereferenceableBytes(CI, 0, Len1);
680 uint64_t Len2 = GetStringLength(Str2P);
681 if (Len2)
682 annotateDereferenceableBytes(CI, 1, Len2);
683
684 // strncmp to memcmp
685 if (!HasStr1 && HasStr2) {
686 Len2 = std::min(Len2, Length);
687 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
688 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
689 TLI->getAsSizeT(Len2, *CI->getModule()),
690 B, DL, TLI));
691 } else if (HasStr1 && !HasStr2) {
692 Len1 = std::min(Len1, Length);
693 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
694 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
695 TLI->getAsSizeT(Len1, *CI->getModule()),
696 B, DL, TLI));
697 }
698
699 return nullptr;
700}
701
702Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilderBase &B) {
703 Value *Src = CI->getArgOperand(0);
704 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
705 uint64_t SrcLen = GetStringLength(Src);
706 if (SrcLen && Size) {
707 annotateDereferenceableBytes(CI, 0, SrcLen);
708 if (SrcLen <= Size->getZExtValue() + 1)
709 return copyFlags(*CI, emitStrDup(Src, B, TLI));
710 }
711
712 return nullptr;
713}
714
715Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilderBase &B) {
716 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
717 if (Dst == Src) // strcpy(x,x) -> x
718 return Src;
719
721 // See if we can get the length of the input string.
722 uint64_t Len = GetStringLength(Src);
723 if (Len)
725 else
726 return nullptr;
727
728 // We have enough information to now generate the memcpy call to do the
729 // copy for us. Make a memcpy to copy the nul byte with align = 1.
730 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
731 TLI->getAsSizeT(Len, *CI->getModule()));
732 mergeAttributesAndFlags(NewCI, *CI);
733 return Dst;
734}
735
736Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilderBase &B) {
737 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
738
739 // stpcpy(d,s) -> strcpy(d,s) if the result is not used.
740 if (CI->use_empty())
741 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
742
743 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
744 Value *StrLen = emitStrLen(Src, B, DL, TLI);
745 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
746 }
747
748 // See if we can get the length of the input string.
749 uint64_t Len = GetStringLength(Src);
750 if (Len)
752 else
753 return nullptr;
754
755 Value *LenV = TLI->getAsSizeT(Len, *CI->getModule());
756 Value *DstEnd = B.CreateInBoundsGEP(
757 B.getInt8Ty(), Dst, TLI->getAsSizeT(Len - 1, *CI->getModule()));
758
759 // We have enough information to now generate the memcpy call to do the
760 // copy for us. Make a memcpy to copy the nul byte with align = 1.
761 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), LenV);
762 mergeAttributesAndFlags(NewCI, *CI);
763 return DstEnd;
764}
765
766// Optimize a call to size_t strlcpy(char*, const char*, size_t).
767
768Value *LibCallSimplifier::optimizeStrLCpy(CallInst *CI, IRBuilderBase &B) {
769 Value *Size = CI->getArgOperand(2);
770 if (isKnownNonZero(Size, DL))
771 // Like snprintf, the function stores into the destination only when
772 // the size argument is nonzero.
774 // The function reads the source argument regardless of Size (it returns
775 // its length).
777
778 uint64_t NBytes;
779 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size))
780 NBytes = SizeC->getZExtValue();
781 else
782 return nullptr;
783
784 Value *Dst = CI->getArgOperand(0);
785 Value *Src = CI->getArgOperand(1);
786 if (NBytes <= 1) {
787 if (NBytes == 1)
788 // For a call to strlcpy(D, S, 1) first store a nul in *D.
789 B.CreateStore(B.getInt8(0), Dst);
790
791 // Transform strlcpy(D, S, 0) to a call to strlen(S).
792 return copyFlags(*CI, emitStrLen(Src, B, DL, TLI));
793 }
794
795 // Try to determine the length of the source, substituting its size
796 // when it's not nul-terminated (as it's required to be) to avoid
797 // reading past its end.
798 StringRef Str;
799 if (!getConstantStringInfo(Src, Str, /*TrimAtNul=*/false))
800 return nullptr;
801
802 uint64_t SrcLen = Str.find('\0');
803 // Set if the terminating nul should be copied by the call to memcpy
804 // below.
805 bool NulTerm = SrcLen < NBytes;
806
807 if (NulTerm)
808 // Overwrite NBytes with the number of bytes to copy, including
809 // the terminating nul.
810 NBytes = SrcLen + 1;
811 else {
812 // Set the length of the source for the function to return to its
813 // size, and cap NBytes at the same.
814 SrcLen = std::min(SrcLen, uint64_t(Str.size()));
815 NBytes = std::min(NBytes - 1, SrcLen);
816 }
817
818 if (SrcLen == 0) {
819 // Transform strlcpy(D, "", N) to (*D = '\0, 0).
820 B.CreateStore(B.getInt8(0), Dst);
821 return ConstantInt::get(CI->getType(), 0);
822 }
823
824 // Transform strlcpy(D, S, N) to memcpy(D, S, N') where N' is the lower
825 // bound on strlen(S) + 1 and N, optionally followed by a nul store to
826 // D[N' - 1] if necessary.
827 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
828 TLI->getAsSizeT(NBytes, *CI->getModule()));
829 mergeAttributesAndFlags(NewCI, *CI);
830
831 if (!NulTerm) {
832 Value *EndOff = ConstantInt::get(CI->getType(), NBytes);
833 Value *EndPtr = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, EndOff);
834 B.CreateStore(B.getInt8(0), EndPtr);
835 }
836
837 // Like snprintf, strlcpy returns the number of nonzero bytes that would
838 // have been copied if the bound had been sufficiently big (which in this
839 // case is strlen(Src)).
840 return ConstantInt::get(CI->getType(), SrcLen);
841}
842
843// Optimize a call CI to either stpncpy when RetEnd is true, or to strncpy
844// otherwise.
845Value *LibCallSimplifier::optimizeStringNCpy(CallInst *CI, bool RetEnd,
846 IRBuilderBase &B) {
847 Value *Dst = CI->getArgOperand(0);
848 Value *Src = CI->getArgOperand(1);
849 Value *Size = CI->getArgOperand(2);
850
851 if (isKnownNonZero(Size, DL)) {
852 // Both st{p,r}ncpy(D, S, N) access the source and destination arrays
853 // only when N is nonzero.
856 }
857
858 // If the "bound" argument is known set N to it. Otherwise set it to
859 // UINT64_MAX and handle it later.
860 uint64_t N = UINT64_MAX;
861 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size))
862 N = SizeC->getZExtValue();
863
864 if (N == 0)
865 // Fold st{p,r}ncpy(D, S, 0) to D.
866 return Dst;
867
868 if (N == 1) {
869 Type *CharTy = B.getInt8Ty();
870 Value *CharVal = B.CreateLoad(CharTy, Src, "stxncpy.char0");
871 B.CreateStore(CharVal, Dst);
872 if (!RetEnd)
873 // Transform strncpy(D, S, 1) to return (*D = *S), D.
874 return Dst;
875
876 // Transform stpncpy(D, S, 1) to return (*D = *S) ? D + 1 : D.
877 Value *ZeroChar = ConstantInt::get(CharTy, 0);
878 Value *Cmp = B.CreateICmpEQ(CharVal, ZeroChar, "stpncpy.char0cmp");
879
880 Value *Off1 = B.getInt32(1);
881 Value *EndPtr = B.CreateInBoundsGEP(CharTy, Dst, Off1, "stpncpy.end");
882 return B.CreateSelect(Cmp, Dst, EndPtr, "stpncpy.sel");
883 }
884
885 // If the length of the input string is known set SrcLen to it.
886 uint64_t SrcLen = GetStringLength(Src);
887 if (SrcLen)
888 annotateDereferenceableBytes(CI, 1, SrcLen);
889 else
890 return nullptr;
891
892 --SrcLen; // Unbias length.
893
894 if (SrcLen == 0) {
895 // Transform st{p,r}ncpy(D, "", N) to memset(D, '\0', N) for any N.
896 Align MemSetAlign =
897 CI->getAttributes().getParamAttrs(0).getAlignment().valueOrOne();
898 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, MemSetAlign);
899 AttrBuilder ArgAttrs(CI->getContext(), CI->getAttributes().getParamAttrs(0));
900 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes(
901 CI->getContext(), 0, ArgAttrs));
902 copyFlags(*CI, NewCI);
903 return Dst;
904 }
905
906 if (N > SrcLen + 1) {
907 if (N > 128)
908 // Bail if N is large or unknown.
909 return nullptr;
910
911 // st{p,r}ncpy(D, "a", N) -> memcpy(D, "a\0\0\0", N) for N <= 128.
912 StringRef Str;
913 if (!getConstantStringInfo(Src, Str))
914 return nullptr;
915 std::string SrcStr = Str.str();
916 // Create a bigger, nul-padded array with the same length, SrcLen,
917 // as the original string.
918 SrcStr.resize(N, '\0');
919 Src = B.CreateGlobalString(SrcStr, "str", /*AddressSpace=*/0,
920 /*M=*/nullptr, /*AddNull=*/false);
921 }
922
923 // st{p,r}ncpy(D, S, N) -> memcpy(align 1 D, align 1 S, N) when both
924 // S and N are constant.
925 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
926 TLI->getAsSizeT(N, *CI->getModule()));
927 mergeAttributesAndFlags(NewCI, *CI);
928 if (!RetEnd)
929 return Dst;
930
931 // stpncpy(D, S, N) returns the address of the first null in D if it writes
932 // one, otherwise D + N.
933 Value *Off = B.getInt64(std::min(SrcLen, N));
934 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, Off, "endptr");
935}
936
937Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B,
938 unsigned CharSize,
939 Value *Bound) {
940 Value *Src = CI->getArgOperand(0);
941 Type *CharTy = B.getIntNTy(CharSize);
942
944 (!Bound || isKnownNonZero(Bound, DL))) {
945 // Fold strlen:
946 // strlen(x) != 0 --> *x != 0
947 // strlen(x) == 0 --> *x == 0
948 // and likewise strnlen with constant N > 0:
949 // strnlen(x, N) != 0 --> *x != 0
950 // strnlen(x, N) == 0 --> *x == 0
951 return B.CreateZExt(B.CreateLoad(CharTy, Src, "char0"),
952 CI->getType());
953 }
954
955 if (Bound) {
956 if (ConstantInt *BoundCst = dyn_cast<ConstantInt>(Bound)) {
957 if (BoundCst->isZero())
958 // Fold strnlen(s, 0) -> 0 for any s, constant or otherwise.
959 return ConstantInt::get(CI->getType(), 0);
960
961 if (BoundCst->isOne()) {
962 // Fold strnlen(s, 1) -> *s ? 1 : 0 for any s.
963 Value *CharVal = B.CreateLoad(CharTy, Src, "strnlen.char0");
964 Value *ZeroChar = ConstantInt::get(CharTy, 0);
965 Value *Cmp = B.CreateICmpNE(CharVal, ZeroChar, "strnlen.char0cmp");
966 return B.CreateZExt(Cmp, CI->getType());
967 }
968 }
969 }
970
971 if (uint64_t Len = GetStringLength(Src, CharSize)) {
972 Value *LenC = ConstantInt::get(CI->getType(), Len - 1);
973 // Fold strlen("xyz") -> 3 and strnlen("xyz", 2) -> 2
974 // and strnlen("xyz", Bound) -> min(3, Bound) for nonconstant Bound.
975 if (Bound)
976 return B.CreateBinaryIntrinsic(Intrinsic::umin, LenC, Bound);
977 return LenC;
978 }
979
980 if (Bound)
981 // Punt for strnlen for now.
982 return nullptr;
983
984 // If s is a constant pointer pointing to a string literal, we can fold
985 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
986 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
987 // We only try to simplify strlen when the pointer s points to an array
988 // of CharSize elements. Otherwise, we would need to scale the offset x before
989 // doing the subtraction. This will make the optimization more complex, and
990 // it's not very useful because calling strlen for a pointer of other types is
991 // very uncommon.
992 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
993 unsigned BW = DL.getIndexTypeSizeInBits(GEP->getType());
994 SmallMapVector<Value *, APInt, 4> VarOffsets;
995 APInt ConstOffset(BW, 0);
996 assert(CharSize % 8 == 0 && "Expected a multiple of 8 sized CharSize");
997 // Check the gep is a single variable offset.
998 if (!GEP->collectOffset(DL, BW, VarOffsets, ConstOffset) ||
999 VarOffsets.size() != 1 || ConstOffset != 0 ||
1000 VarOffsets.begin()->second != CharSize / 8)
1001 return nullptr;
1002
1003 ConstantDataArraySlice Slice;
1004 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
1005 uint64_t NullTermIdx;
1006 if (Slice.Array == nullptr) {
1007 NullTermIdx = 0;
1008 } else {
1009 NullTermIdx = ~((uint64_t)0);
1010 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
1011 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
1012 NullTermIdx = I;
1013 break;
1014 }
1015 }
1016 // If the string does not have '\0', leave it to strlen to compute
1017 // its length.
1018 if (NullTermIdx == ~((uint64_t)0))
1019 return nullptr;
1020 }
1021
1022 Value *Offset = VarOffsets.begin()->first;
1023 KnownBits Known = computeKnownBits(Offset, DL, nullptr, CI, nullptr);
1024
1025 // If Offset is not provably in the range [0, NullTermIdx], we can still
1026 // optimize if we can prove that the program has undefined behavior when
1027 // Offset is outside that range. That is the case when GEP->getOperand(0)
1028 // is a pointer to an object whose memory extent is NullTermIdx+1.
1029 if ((Known.isNonNegative() && Known.getMaxValue().ule(NullTermIdx)) ||
1030 (isa<GlobalVariable>(GEP->getOperand(0)) &&
1031 NullTermIdx == Slice.Length - 1)) {
1032 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
1033 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
1034 Offset);
1035 }
1036 }
1037 }
1038
1039 // strlen(x?"foo":"bars") --> x ? 3 : 4
1040 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
1041 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
1042 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
1043 if (LenTrue && LenFalse) {
1044 ORE.emit([&]() {
1045 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
1046 << "folded strlen(select) to select of constants";
1047 });
1048 return B.CreateSelect(SI->getCondition(),
1049 ConstantInt::get(CI->getType(), LenTrue - 1),
1050 ConstantInt::get(CI->getType(), LenFalse - 1));
1051 }
1052 }
1053
1054 return nullptr;
1055}
1056
1057Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) {
1058 if (Value *V = optimizeStringLength(CI, B, 8))
1059 return V;
1061 return nullptr;
1062}
1063
1064Value *LibCallSimplifier::optimizeStrNLen(CallInst *CI, IRBuilderBase &B) {
1065 Value *Bound = CI->getArgOperand(1);
1066 if (Value *V = optimizeStringLength(CI, B, 8, Bound))
1067 return V;
1068
1069 if (isKnownNonZero(Bound, DL))
1071 return nullptr;
1072}
1073
1074Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) {
1075 Module &M = *CI->getModule();
1076 unsigned WCharSize = TLI->getWCharSize(M) * 8;
1077 // We cannot perform this optimization without wchar_size metadata.
1078 if (WCharSize == 0)
1079 return nullptr;
1080
1081 return optimizeStringLength(CI, B, WCharSize);
1082}
1083
1084Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) {
1085 StringRef S1, S2;
1086 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
1087 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
1088
1089 // strpbrk(s, "") -> nullptr
1090 // strpbrk("", s) -> nullptr
1091 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
1092 return Constant::getNullValue(CI->getType());
1093
1094 // Constant folding.
1095 if (HasS1 && HasS2) {
1096 size_t I = S1.find_first_of(S2);
1097 if (I == StringRef::npos) // No match.
1098 return Constant::getNullValue(CI->getType());
1099
1100 return B.CreateInBoundsGEP(B.getInt8Ty(), CI->getArgOperand(0),
1101 B.getInt64(I), "strpbrk");
1102 }
1103
1104 // strpbrk(s, "a") -> strchr(s, 'a')
1105 if (HasS2 && S2.size() == 1)
1106 return copyFlags(*CI, emitStrChr(CI->getArgOperand(0), S2[0], B, TLI));
1107
1108 return nullptr;
1109}
1110
1111Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) {
1112 Value *EndPtr = CI->getArgOperand(1);
1113 if (isa<ConstantPointerNull>(EndPtr)) {
1114 // With a null EndPtr, this function won't capture the main argument.
1115 // It would be readonly too, except that it still may write to errno.
1118 }
1119
1120 return nullptr;
1121}
1122
1123Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) {
1124 StringRef S1, S2;
1125 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
1126 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
1127
1128 // strspn(s, "") -> 0
1129 // strspn("", s) -> 0
1130 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
1131 return Constant::getNullValue(CI->getType());
1132
1133 // Constant folding.
1134 if (HasS1 && HasS2) {
1135 size_t Pos = S1.find_first_not_of(S2);
1136 if (Pos == StringRef::npos)
1137 Pos = S1.size();
1138 return ConstantInt::get(CI->getType(), Pos);
1139 }
1140
1141 return nullptr;
1142}
1143
1144Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) {
1145 StringRef S1, S2;
1146 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
1147 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
1148
1149 // strcspn("", s) -> 0
1150 if (HasS1 && S1.empty())
1151 return Constant::getNullValue(CI->getType());
1152
1153 // Constant folding.
1154 if (HasS1 && HasS2) {
1155 size_t Pos = S1.find_first_of(S2);
1156 if (Pos == StringRef::npos)
1157 Pos = S1.size();
1158 return ConstantInt::get(CI->getType(), Pos);
1159 }
1160
1161 // strcspn(s, "") -> strlen(s)
1162 if (HasS2 && S2.empty())
1163 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, DL, TLI));
1164
1165 return nullptr;
1166}
1167
1168Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) {
1169 // fold strstr(x, x) -> x.
1170 if (CI->getArgOperand(0) == CI->getArgOperand(1))
1171 return CI->getArgOperand(0);
1172
1173 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
1175 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
1176 if (!StrLen)
1177 return nullptr;
1178 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
1179 StrLen, B, DL, TLI);
1180 if (!StrNCmp)
1181 return nullptr;
1182 for (User *U : llvm::make_early_inc_range(CI->users())) {
1183 ICmpInst *Old = cast<ICmpInst>(U);
1184 Value *Cmp =
1185 B.CreateICmp(Old->getPredicate(), StrNCmp,
1186 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
1187 replaceAllUsesWith(Old, Cmp);
1188 }
1189 return CI;
1190 }
1191
1192 // See if either input string is a constant string.
1193 StringRef SearchStr, ToFindStr;
1194 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
1195 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
1196
1197 // fold strstr(x, "") -> x.
1198 if (HasStr2 && ToFindStr.empty())
1199 return CI->getArgOperand(0);
1200
1201 // If both strings are known, constant fold it.
1202 if (HasStr1 && HasStr2) {
1203 size_t Offset = SearchStr.find(ToFindStr);
1204
1205 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
1206 return Constant::getNullValue(CI->getType());
1207
1208 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
1209 return B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), CI->getArgOperand(0),
1210 Offset, "strstr");
1211 }
1212
1213 // fold strstr(x, "y") -> strchr(x, 'y').
1214 if (HasStr2 && ToFindStr.size() == 1) {
1215 return emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
1216 }
1217
1219 return nullptr;
1220}
1221
1222Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) {
1223 Value *SrcStr = CI->getArgOperand(0);
1224 Value *Size = CI->getArgOperand(2);
1226 Value *CharVal = CI->getArgOperand(1);
1227 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1228 Value *NullPtr = Constant::getNullValue(CI->getType());
1229
1230 if (LenC) {
1231 if (LenC->isZero())
1232 // Fold memrchr(x, y, 0) --> null.
1233 return NullPtr;
1234
1235 if (LenC->isOne()) {
1236 // Fold memrchr(x, y, 1) --> *x == y ? x : null for any x and y,
1237 // constant or otherwise.
1238 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memrchr.char0");
1239 // Slice off the character's high end bits.
1240 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1241 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memrchr.char0cmp");
1242 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memrchr.sel");
1243 }
1244 }
1245
1246 StringRef Str;
1247 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false))
1248 return nullptr;
1249
1250 if (Str.size() == 0)
1251 // If the array is empty fold memrchr(A, C, N) to null for any value
1252 // of C and N on the basis that the only valid value of N is zero
1253 // (otherwise the call is undefined).
1254 return NullPtr;
1255
1256 uint64_t EndOff = UINT64_MAX;
1257 if (LenC) {
1258 EndOff = LenC->getZExtValue();
1259 if (Str.size() < EndOff)
1260 // Punt out-of-bounds accesses to sanitizers and/or libc.
1261 return nullptr;
1262 }
1263
1264 if (ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal)) {
1265 // Fold memrchr(S, C, N) for a constant C.
1266 size_t Pos = Str.rfind(CharC->getZExtValue(), EndOff);
1267 if (Pos == StringRef::npos)
1268 // When the character is not in the source array fold the result
1269 // to null regardless of Size.
1270 return NullPtr;
1271
1272 if (LenC)
1273 // Fold memrchr(s, c, N) --> s + Pos for constant N > Pos.
1274 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos));
1275
1276 if (Str.find(Str[Pos]) == Pos) {
1277 // When there is just a single occurrence of C in S, i.e., the one
1278 // in Str[Pos], fold
1279 // memrchr(s, c, N) --> N <= Pos ? null : s + Pos
1280 // for nonconstant N.
1281 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos),
1282 "memrchr.cmp");
1283 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr,
1284 B.getInt64(Pos), "memrchr.ptr_plus");
1285 return B.CreateSelect(Cmp, NullPtr, SrcPlus, "memrchr.sel");
1286 }
1287 }
1288
1289 // Truncate the string to search at most EndOff characters.
1290 Str = Str.substr(0, EndOff);
1291 if (Str.find_first_not_of(Str[0]) != StringRef::npos)
1292 return nullptr;
1293
1294 // If the source array consists of all equal characters, then for any
1295 // C and N (whether in bounds or not), fold memrchr(S, C, N) to
1296 // N != 0 && *S == C ? S + N - 1 : null
1297 Type *SizeTy = Size->getType();
1298 Type *Int8Ty = B.getInt8Ty();
1299 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1300 // Slice off the sought character's high end bits.
1301 CharVal = B.CreateTrunc(CharVal, Int8Ty);
1302 Value *CEqS0 = B.CreateICmpEQ(ConstantInt::get(Int8Ty, Str[0]), CharVal);
1303 Value *And = B.CreateLogicalAnd(NNeZ, CEqS0);
1304 Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1));
1305 Value *SrcPlus =
1306 B.CreateInBoundsGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus");
1307 return B.CreateSelect(And, SrcPlus, NullPtr, "memrchr.sel");
1308}
1309
1310Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) {
1311 Value *SrcStr = CI->getArgOperand(0);
1312 Value *Size = CI->getArgOperand(2);
1313
1314 if (isKnownNonZero(Size, DL)) {
1316 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1317 return memChrToCharCompare(CI, Size, B, DL);
1318 }
1319
1320 Value *CharVal = CI->getArgOperand(1);
1321 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
1322 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1323 Value *NullPtr = Constant::getNullValue(CI->getType());
1324
1325 // memchr(x, y, 0) -> null
1326 if (LenC) {
1327 if (LenC->isZero())
1328 return NullPtr;
1329
1330 if (LenC->isOne()) {
1331 // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y,
1332 // constant or otherwise.
1333 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0");
1334 // Slice off the character's high end bits.
1335 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1336 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp");
1337 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memchr.sel");
1338 }
1339 }
1340
1341 StringRef Str;
1342 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false))
1343 return nullptr;
1344
1345 if (CharC) {
1346 size_t Pos = Str.find(CharC->getZExtValue());
1347 if (Pos == StringRef::npos)
1348 // When the character is not in the source array fold the result
1349 // to null regardless of Size.
1350 return NullPtr;
1351
1352 // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos
1353 // When the constant Size is less than or equal to the character
1354 // position also fold the result to null.
1355 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos),
1356 "memchr.cmp");
1357 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos),
1358 "memchr.ptr");
1359 return B.CreateSelect(Cmp, NullPtr, SrcPlus);
1360 }
1361
1362 if (Str.size() == 0)
1363 // If the array is empty fold memchr(A, C, N) to null for any value
1364 // of C and N on the basis that the only valid value of N is zero
1365 // (otherwise the call is undefined).
1366 return NullPtr;
1367
1368 if (LenC)
1369 Str = substr(Str, LenC->getZExtValue());
1370
1371 size_t Pos = Str.find_first_not_of(Str[0]);
1372 if (Pos == StringRef::npos
1373 || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) {
1374 // If the source array consists of at most two consecutive sequences
1375 // of the same characters, then for any C and N (whether in bounds or
1376 // not), fold memchr(S, C, N) to
1377 // N != 0 && *S == C ? S : null
1378 // or for the two sequences to:
1379 // N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null)
1380 // ^Sel2 ^Sel1 are denoted above.
1381 // The latter makes it also possible to fold strchr() calls with strings
1382 // of the same characters.
1383 Type *SizeTy = Size->getType();
1384 Type *Int8Ty = B.getInt8Ty();
1385
1386 // Slice off the sought character's high end bits.
1387 CharVal = B.CreateTrunc(CharVal, Int8Ty);
1388
1389 Value *Sel1 = NullPtr;
1390 if (Pos != StringRef::npos) {
1391 // Handle two consecutive sequences of the same characters.
1392 Value *PosVal = ConstantInt::get(SizeTy, Pos);
1393 Value *StrPos = ConstantInt::get(Int8Ty, Str[Pos]);
1394 Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos);
1395 Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal);
1396 Value *And = B.CreateAnd(CEqSPos, NGtPos);
1397 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal);
1398 Sel1 = B.CreateSelect(And, SrcPlus, NullPtr, "memchr.sel1");
1399 }
1400
1401 Value *Str0 = ConstantInt::get(Int8Ty, Str[0]);
1402 Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal);
1403 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1404 Value *And = B.CreateAnd(NNeZ, CEqS0);
1405 return B.CreateSelect(And, SrcStr, Sel1, "memchr.sel2");
1406 }
1407
1408 if (!LenC) {
1409 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1410 // S is dereferenceable so it's safe to load from it and fold
1411 // memchr(S, C, N) == S to N && *S == C for any C and N.
1412 // TODO: This is safe even for nonconstant S.
1413 return memChrToCharCompare(CI, Size, B, DL);
1414
1415 // From now on we need a constant length and constant array.
1416 return nullptr;
1417 }
1418
1419 bool OptForSize = llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
1421
1422 // If the char is variable but the input str and length are not we can turn
1423 // this memchr call into a simple bit field test. Of course this only works
1424 // when the return value is only checked against null.
1425 //
1426 // It would be really nice to reuse switch lowering here but we can't change
1427 // the CFG at this point.
1428 //
1429 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
1430 // != 0
1431 // after bounds check.
1432 if (OptForSize || Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI))
1433 return nullptr;
1434
1435 unsigned char Max =
1436 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
1437 reinterpret_cast<const unsigned char *>(Str.end()));
1438
1439 // Make sure the bit field we're about to create fits in a register on the
1440 // target.
1441 // FIXME: On a 64 bit architecture this prevents us from using the
1442 // interesting range of alpha ascii chars. We could do better by emitting
1443 // two bitfields or shifting the range by 64 if no lower chars are used.
1444 if (!DL.fitsInLegalInteger(Max + 1)) {
1445 // Build chain of ORs
1446 // Transform:
1447 // memchr("abcd", C, 4) != nullptr
1448 // to:
1449 // (C == 'a' || C == 'b' || C == 'c' || C == 'd') != 0
1450 std::string SortedStr = Str.str();
1451 llvm::sort(SortedStr);
1452 // Compute the number of of non-contiguous ranges.
1453 unsigned NonContRanges = 1;
1454 for (size_t i = 1; i < SortedStr.size(); ++i) {
1455 if (SortedStr[i] > SortedStr[i - 1] + 1) {
1456 NonContRanges++;
1457 }
1458 }
1459
1460 // Restrict this optimization to profitable cases with one or two range
1461 // checks.
1462 if (NonContRanges > 2)
1463 return nullptr;
1464
1465 // Slice off the character's high end bits.
1466 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1467
1468 SmallVector<Value *> CharCompares;
1469 for (unsigned char C : SortedStr)
1470 CharCompares.push_back(B.CreateICmpEQ(CharVal, B.getInt8(C)));
1471
1472 return B.CreateIntToPtr(B.CreateOr(CharCompares), CI->getType());
1473 }
1474
1475 // For the bit field use a power-of-2 type with at least 8 bits to avoid
1476 // creating unnecessary illegal types.
1477 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
1478
1479 // Now build the bit field.
1480 APInt Bitfield(Width, 0);
1481 for (char C : Str)
1482 Bitfield.setBit((unsigned char)C);
1483 Value *BitfieldC = B.getInt(Bitfield);
1484
1485 // Adjust width of "C" to the bitfield width, then mask off the high bits.
1486 Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType());
1487 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
1488
1489 // First check that the bit field access is within bounds.
1490 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
1491 "memchr.bounds");
1492
1493 // Create code that checks if the given bit is set in the field.
1494 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
1495 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
1496
1497 // Finally merge both checks and cast to pointer type. The inttoptr
1498 // implicitly zexts the i1 to intptr type.
1499 return B.CreateIntToPtr(B.CreateLogicalAnd(Bounds, Bits, "memchr"),
1500 CI->getType());
1501}
1502
1503// Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant
1504// arrays LHS and RHS and nonconstant Size.
1506 Value *Size, bool StrNCmp,
1507 IRBuilderBase &B, const DataLayout &DL) {
1508 if (LHS == RHS) // memcmp(s,s,x) -> 0
1509 return Constant::getNullValue(CI->getType());
1510
1511 StringRef LStr, RStr;
1512 if (!getConstantStringInfo(LHS, LStr, /*TrimAtNul=*/false) ||
1513 !getConstantStringInfo(RHS, RStr, /*TrimAtNul=*/false))
1514 return nullptr;
1515
1516 // If the contents of both constant arrays are known, fold a call to
1517 // memcmp(A, B, N) to
1518 // N <= Pos ? 0 : (A < B ? -1 : B < A ? +1 : 0)
1519 // where Pos is the first mismatch between A and B, determined below.
1520
1521 uint64_t Pos = 0;
1522 Value *Zero = ConstantInt::get(CI->getType(), 0);
1523 for (uint64_t MinSize = std::min(LStr.size(), RStr.size()); ; ++Pos) {
1524 if (Pos == MinSize ||
1525 (StrNCmp && (LStr[Pos] == '\0' && RStr[Pos] == '\0'))) {
1526 // One array is a leading part of the other of equal or greater
1527 // size, or for strncmp, the arrays are equal strings.
1528 // Fold the result to zero. Size is assumed to be in bounds, since
1529 // otherwise the call would be undefined.
1530 return Zero;
1531 }
1532
1533 if (LStr[Pos] != RStr[Pos])
1534 break;
1535 }
1536
1537 // Normalize the result.
1538 typedef unsigned char UChar;
1539 int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1;
1540 Value *MaxSize = ConstantInt::get(Size->getType(), Pos);
1541 Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize);
1542 Value *Res = ConstantInt::getSigned(CI->getType(), IRes);
1543 return B.CreateSelect(Cmp, Zero, Res);
1544}
1545
1546// Optimize a memcmp call CI with constant size Len.
1548 uint64_t Len, IRBuilderBase &B,
1549 const DataLayout &DL) {
1550 if (Len == 0) // memcmp(s1,s2,0) -> 0
1551 return Constant::getNullValue(CI->getType());
1552
1553 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1554 if (Len == 1) {
1555 Value *LHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), LHS, "lhsc"),
1556 CI->getType(), "lhsv");
1557 Value *RHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), RHS, "rhsc"),
1558 CI->getType(), "rhsv");
1559 return B.CreateSub(LHSV, RHSV, "chardiff");
1560 }
1561
1562 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
1563 // TODO: The case where both inputs are constants does not need to be limited
1564 // to legal integers or equality comparison. See block below this.
1565 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
1566 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
1567 Align PrefAlignment = DL.getPrefTypeAlign(IntType);
1568
1569 // First, see if we can fold either argument to a constant.
1570 Value *LHSV = nullptr;
1571 if (auto *LHSC = dyn_cast<Constant>(LHS))
1572 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
1573
1574 Value *RHSV = nullptr;
1575 if (auto *RHSC = dyn_cast<Constant>(RHS))
1576 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
1577
1578 // Don't generate unaligned loads. If either source is constant data,
1579 // alignment doesn't matter for that source because there is no load.
1580 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
1581 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
1582 if (!LHSV)
1583 LHSV = B.CreateLoad(IntType, LHS, "lhsv");
1584 if (!RHSV)
1585 RHSV = B.CreateLoad(IntType, RHS, "rhsv");
1586 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
1587 }
1588 }
1589
1590 return nullptr;
1591}
1592
1593// Most simplifications for memcmp also apply to bcmp.
1594Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
1595 IRBuilderBase &B) {
1596 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1597 Value *Size = CI->getArgOperand(2);
1598
1599 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1600
1601 if (Value *Res = optimizeMemCmpVarSize(CI, LHS, RHS, Size, false, B, DL))
1602 return Res;
1603
1604 // Handle constant Size.
1605 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1606 if (!LenC)
1607 return nullptr;
1608
1609 return optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL);
1610}
1611
1612Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) {
1613 Module *M = CI->getModule();
1614 if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
1615 return V;
1616
1617 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
1618 // bcmp can be more efficient than memcmp because it only has to know that
1619 // there is a difference, not how different one is to the other.
1620 if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) &&
1622 Value *LHS = CI->getArgOperand(0);
1623 Value *RHS = CI->getArgOperand(1);
1624 Value *Size = CI->getArgOperand(2);
1625 return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI));
1626 }
1627
1628 return nullptr;
1629}
1630
1631Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) {
1632 return optimizeMemCmpBCmpCommon(CI, B);
1633}
1634
1635Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) {
1636 Value *Size = CI->getArgOperand(2);
1637 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1638 if (isa<IntrinsicInst>(CI))
1639 return nullptr;
1640
1641 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
1642 CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1),
1643 CI->getArgOperand(1), Align(1), Size);
1644 mergeAttributesAndFlags(NewCI, *CI);
1645 return CI->getArgOperand(0);
1646}
1647
1648Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) {
1649 Value *Dst = CI->getArgOperand(0);
1650 Value *Src = CI->getArgOperand(1);
1651 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1652 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3));
1653 StringRef SrcStr;
1654 if (CI->use_empty() && Dst == Src)
1655 return Dst;
1656 // memccpy(d, s, c, 0) -> nullptr
1657 if (N) {
1658 if (N->isNullValue())
1659 return Constant::getNullValue(CI->getType());
1660 if (!getConstantStringInfo(Src, SrcStr, /*TrimAtNul=*/false) ||
1661 // TODO: Handle zeroinitializer.
1662 !StopChar)
1663 return nullptr;
1664 } else {
1665 return nullptr;
1666 }
1667
1668 // Wrap arg 'c' of type int to char
1669 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF);
1670 if (Pos == StringRef::npos) {
1671 if (N->getZExtValue() <= SrcStr.size()) {
1672 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1),
1673 CI->getArgOperand(3)));
1674 return Constant::getNullValue(CI->getType());
1675 }
1676 return nullptr;
1677 }
1678
1679 Value *NewN =
1680 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue()));
1681 // memccpy -> llvm.memcpy
1682 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN));
1683 return Pos + 1 <= N->getZExtValue()
1684 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN)
1686}
1687
1688Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) {
1689 Value *Dst = CI->getArgOperand(0);
1690 Value *N = CI->getArgOperand(2);
1691 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1692 CallInst *NewCI =
1693 B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N);
1694 // Propagate attributes, but memcpy has no return value, so make sure that
1695 // any return attributes are compliant.
1696 // TODO: Attach return value attributes to the 1st operand to preserve them?
1697 mergeAttributesAndFlags(NewCI, *CI);
1698 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1699}
1700
1701Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) {
1702 Value *Size = CI->getArgOperand(2);
1703 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1704 if (isa<IntrinsicInst>(CI))
1705 return nullptr;
1706
1707 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
1708 CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1),
1709 CI->getArgOperand(1), Align(1), Size);
1710 mergeAttributesAndFlags(NewCI, *CI);
1711 return CI->getArgOperand(0);
1712}
1713
1714Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) {
1715 Value *Size = CI->getArgOperand(2);
1717 if (isa<IntrinsicInst>(CI))
1718 return nullptr;
1719
1720 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
1721 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1722 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1));
1723 mergeAttributesAndFlags(NewCI, *CI);
1724 return CI->getArgOperand(0);
1725}
1726
1727Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) {
1729 Value *Malloc = emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1730 if (auto *MallocCI = dyn_cast_or_null<CallInst>(Malloc))
1731 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alloc_token))
1732 MallocCI->setMetadata(LLVMContext::MD_alloc_token, MD);
1733 return copyFlags(*CI, Malloc);
1734 }
1735
1736 return nullptr;
1737}
1738
1739// Optionally allow optimization of nobuiltin calls to operator new and its
1740// variants.
1741Value *LibCallSimplifier::maybeOptimizeNoBuiltinOperatorNew(CallInst *CI,
1742 IRBuilderBase &B) {
1743 if (!OptimizeHotColdNew)
1744 return nullptr;
1746 if (!Callee)
1747 return nullptr;
1748 LibFunc Func;
1749 if (!TLI->getLibFunc(*Callee, Func))
1750 return nullptr;
1751 switch (Func) {
1752 case LibFunc_Znwm:
1753 case LibFunc_ZnwmRKSt9nothrow_t:
1754 case LibFunc_ZnwmSt11align_val_t:
1755 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
1756 case LibFunc_Znam:
1757 case LibFunc_ZnamRKSt9nothrow_t:
1758 case LibFunc_ZnamSt11align_val_t:
1759 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
1760 case LibFunc_size_returning_new:
1761 case LibFunc_size_returning_new_aligned:
1762 // By default normal operator new calls (not already passing a hot_cold_t
1763 // parameter) are not mutated if the call is not marked builtin. Optionally
1764 // enable that in cases where it is known to be safe.
1766 return nullptr;
1767 break;
1768 case LibFunc_Znwm12__hot_cold_t:
1769 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
1770 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
1771 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1772 case LibFunc_Znam12__hot_cold_t:
1773 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
1774 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
1775 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1776 case LibFunc_size_returning_new_hot_cold:
1777 case LibFunc_size_returning_new_aligned_hot_cold:
1778 // If the nobuiltin call already passes a hot_cold_t parameter, allow update
1779 // of that parameter when enabled.
1781 return nullptr;
1782 break;
1783 default:
1784 return nullptr;
1785 }
1786 return optimizeNew(CI, B, Func);
1787}
1788
1789// When enabled, replace operator new() calls marked with a hot or cold memprof
1790// attribute with an operator new() call that takes a __hot_cold_t parameter.
1791// Currently this is supported by the open source version of tcmalloc, see:
1792// https://github.com/google/tcmalloc/blob/master/tcmalloc/new_extension.h
1793Value *LibCallSimplifier::optimizeNew(CallInst *CI, IRBuilderBase &B,
1794 LibFunc &Func) {
1795 if (!OptimizeHotColdNew)
1796 return nullptr;
1797
1798 uint8_t HotCold;
1799 if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "cold")
1800 HotCold = ColdNewHintValue;
1801 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() ==
1802 "notcold")
1803 HotCold = NotColdNewHintValue;
1804 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "hot")
1805 HotCold = HotNewHintValue;
1806 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() ==
1807 "ambiguous")
1808 HotCold = AmbiguousNewHintValue;
1809 else
1810 return nullptr;
1811
1812 // For calls that already pass a hot/cold hint, only update the hint if
1813 // directed by OptimizeExistingHotColdNew. For other calls to new, add a hint
1814 // if cold or hot, and leave as-is for default handling if "notcold" aka warm.
1815 // Note that in cases where we decide it is "notcold", it might be slightly
1816 // better to replace the hinted call with a non hinted call, to avoid the
1817 // extra parameter and the if condition check of the hint value in the
1818 // allocator. This can be considered in the future.
1819 Value *NewCall = nullptr;
1820 switch (Func) {
1821 case LibFunc_Znwm12__hot_cold_t:
1823 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1824 LibFunc_Znwm12__hot_cold_t, HotCold);
1825 break;
1826 case LibFunc_Znwm:
1827 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1828 LibFunc_Znwm12__hot_cold_t, HotCold);
1829 break;
1830 case LibFunc_Znam12__hot_cold_t:
1832 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1833 LibFunc_Znam12__hot_cold_t, HotCold);
1834 break;
1835 case LibFunc_Znam:
1836 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1837 LibFunc_Znam12__hot_cold_t, HotCold);
1838 break;
1839 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
1841 NewCall = emitHotColdNewNoThrow(
1842 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1843 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold);
1844 break;
1845 case LibFunc_ZnwmRKSt9nothrow_t:
1846 NewCall = emitHotColdNewNoThrow(
1847 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1848 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold);
1849 break;
1850 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
1852 NewCall = emitHotColdNewNoThrow(
1853 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1854 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold);
1855 break;
1856 case LibFunc_ZnamRKSt9nothrow_t:
1857 NewCall = emitHotColdNewNoThrow(
1858 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1859 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold);
1860 break;
1861 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
1863 NewCall = emitHotColdNewAligned(
1864 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1865 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold);
1866 break;
1867 case LibFunc_ZnwmSt11align_val_t:
1868 NewCall = emitHotColdNewAligned(
1869 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1870 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold);
1871 break;
1872 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
1874 NewCall = emitHotColdNewAligned(
1875 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1876 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold);
1877 break;
1878 case LibFunc_ZnamSt11align_val_t:
1879 NewCall = emitHotColdNewAligned(
1880 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1881 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold);
1882 break;
1883 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1886 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1887 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1888 HotCold);
1889 break;
1890 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
1892 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1893 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t, HotCold);
1894 break;
1895 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1898 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1899 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1900 HotCold);
1901 break;
1902 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
1904 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1905 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t, HotCold);
1906 break;
1907 case LibFunc_size_returning_new:
1908 NewCall = emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI,
1909 LibFunc_size_returning_new_hot_cold,
1910 HotCold);
1911 break;
1912 case LibFunc_size_returning_new_hot_cold:
1914 NewCall = emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI,
1915 LibFunc_size_returning_new_hot_cold,
1916 HotCold);
1917 break;
1918 case LibFunc_size_returning_new_aligned:
1920 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1921 LibFunc_size_returning_new_aligned_hot_cold, HotCold);
1922 break;
1923 case LibFunc_size_returning_new_aligned_hot_cold:
1926 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1927 LibFunc_size_returning_new_aligned_hot_cold, HotCold);
1928 break;
1929 default:
1930 return nullptr;
1931 }
1932
1933 if (auto *NewCI = dyn_cast_or_null<Instruction>(NewCall))
1934 NewCI->copyMetadata(*CI);
1935
1936 return NewCall;
1937}
1938
1939//===----------------------------------------------------------------------===//
1940// Math Library Optimizations
1941//===----------------------------------------------------------------------===//
1942
1943// Replace a libcall \p CI with a call to intrinsic \p IID
1945 Intrinsic::ID IID) {
1946 Value *NewCall = B.CreateUnaryIntrinsic(IID, CI->getArgOperand(0), CI);
1947 NewCall->takeName(CI);
1948 return copyFlags(*CI, NewCall);
1949}
1950
1952 Intrinsic::ID IID) {
1953 Value *NewCall = B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0),
1954 CI->getArgOperand(1), CI);
1955 NewCall->takeName(CI);
1956 return copyFlags(*CI, NewCall);
1957}
1958
1959/// Return a variant of Val with float type.
1960/// Currently this works in two cases: If Val is an FPExtension of a float
1961/// value to something bigger, simply return the operand.
1962/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1963/// loss of precision do so.
1965 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1966 Value *Op = Cast->getOperand(0);
1967 if (Op->getType()->isFloatTy())
1968 return Op;
1969 }
1970 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1971 APFloat F = Const->getValueAPF();
1972 bool losesInfo;
1974 &losesInfo);
1975 if (!losesInfo)
1976 return ConstantFP::get(Const->getContext(), F);
1977 }
1978 return nullptr;
1979}
1980
1981/// Shrink double -> float functions.
1983 bool isBinary, const TargetLibraryInfo *TLI,
1984 bool isPrecise = false) {
1985 Function *CalleeFn = CI->getCalledFunction();
1986 if (!CI->getType()->isDoubleTy() || !CalleeFn)
1987 return nullptr;
1988
1989 // If not all the uses of the function are converted to float, then bail out.
1990 // This matters if the precision of the result is more important than the
1991 // precision of the arguments.
1992 if (isPrecise)
1993 for (User *U : CI->users()) {
1995 if (!Cast || !Cast->getType()->isFloatTy())
1996 return nullptr;
1997 }
1998
1999 // If this is something like 'g((double) float)', convert to 'gf(float)'.
2000 Value *V[2];
2002 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
2003 if (!V[0] || (isBinary && !V[1]))
2004 return nullptr;
2005
2006 // If call isn't an intrinsic, check that it isn't within a function with the
2007 // same name as the float version of this call, otherwise the result is an
2008 // infinite loop. For example, from MinGW-w64:
2009 //
2010 // float expf(float val) { return (float) exp((double) val); }
2011 StringRef CalleeName = CalleeFn->getName();
2012 bool IsIntrinsic = CalleeFn->isIntrinsic();
2013 if (!IsIntrinsic) {
2014 StringRef CallerName = CI->getFunction()->getName();
2015 if (CallerName.ends_with('f') &&
2016 CallerName.size() == (CalleeName.size() + 1) &&
2017 CallerName.starts_with(CalleeName))
2018 return nullptr;
2019 }
2020
2021 // Propagate the math semantics from the current function to the new function.
2023 B.setFastMathFlags(CI->getFastMathFlags());
2024
2025 // g((double) float) -> (double) gf(float)
2026 Value *R;
2027 if (IsIntrinsic) {
2028 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
2029 R = isBinary ? B.CreateIntrinsic(IID, B.getFloatTy(), V)
2030 : B.CreateIntrinsic(IID, B.getFloatTy(), V[0]);
2031 } else {
2032 AttributeList CallsiteAttrs = CI->getAttributes();
2033 R = isBinary
2034 ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B,
2035 CallsiteAttrs)
2036 : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CallsiteAttrs);
2037 }
2038 return B.CreateFPExt(R, B.getDoubleTy());
2039}
2040
2041/// Shrink double -> float for unary functions.
2043 const TargetLibraryInfo *TLI,
2044 bool isPrecise = false) {
2045 return optimizeDoubleFP(CI, B, false, TLI, isPrecise);
2046}
2047
2048/// Shrink double -> float for binary functions.
2050 const TargetLibraryInfo *TLI,
2051 bool isPrecise = false) {
2052 return optimizeDoubleFP(CI, B, true, TLI, isPrecise);
2053}
2054
2055/// Shrink double -> float for llvm.sincos.
2057 auto *RetTy = dyn_cast<StructType>(CI->getType());
2058 if (!RetTy || RetTy->getNumElements() != 2 ||
2059 !RetTy->getElementType(0)->getScalarType()->isDoubleTy())
2060 return nullptr;
2061
2063 if (!X)
2064 if (auto *Ext = dyn_cast<FPExtInst>(CI->getArgOperand(0)))
2065 if (Ext->getOperand(0)->getType()->getScalarType()->isFloatTy())
2066 X = Ext->getOperand(0);
2067 if (!X)
2068 return nullptr;
2069
2070 for (User *U : CI->users()) {
2071 auto *EV = dyn_cast<ExtractValueInst>(U);
2072 if (!EV)
2073 return nullptr;
2074 for (User *EVU : EV->users()) {
2075 auto *Cast = dyn_cast<FPTruncInst>(EVU);
2076 if (!Cast || !Cast->getType()->getScalarType()->isFloatTy())
2077 return nullptr;
2078 }
2079 }
2080
2082 B.setFastMathFlags(CI->getFastMathFlags());
2083
2084 Value *NewCall = B.CreateIntrinsic(Intrinsic::sincos, X->getType(), X);
2085 cast<Instruction>(NewCall)->setMetadata(
2086 LLVMContext::MD_fpmath, CI->getMetadata(LLVMContext::MD_fpmath));
2087 Value *Res = PoisonValue::get(RetTy);
2088 for (unsigned I = 0; I != 2; ++I) {
2089 Value *Ext = B.CreateFPExt(B.CreateExtractValue(NewCall, I),
2090 RetTy->getElementType(I));
2091 Res = B.CreateInsertValue(Res, Ext, I);
2092 }
2093 return Res;
2094}
2095
2096// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
2097Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) {
2098 Value *Real, *Imag;
2099
2100 if (CI->arg_size() == 1) {
2101
2102 if (!CI->isFast())
2103 return nullptr;
2104
2105 Value *Op = CI->getArgOperand(0);
2106 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
2107
2108 Real = B.CreateExtractValue(Op, 0, "real");
2109 Imag = B.CreateExtractValue(Op, 1, "imag");
2110
2111 } else {
2112 assert(CI->arg_size() == 2 && "Unexpected signature for cabs!");
2113
2114 Real = CI->getArgOperand(0);
2115 Imag = CI->getArgOperand(1);
2116
2117 // if real or imaginary part is zero, simplify to abs(cimag(z))
2118 // or abs(creal(z))
2119 Value *AbsOp = nullptr;
2120 if (ConstantFP *ConstReal = dyn_cast<ConstantFP>(Real)) {
2121 if (ConstReal->isZero())
2122 AbsOp = Imag;
2123
2124 } else if (ConstantFP *ConstImag = dyn_cast<ConstantFP>(Imag)) {
2125 if (ConstImag->isZero())
2126 AbsOp = Real;
2127 }
2128
2129 if (AbsOp)
2130 return copyFlags(*CI, B.CreateFAbs(AbsOp, CI, "cabs"));
2131
2132 if (!CI->isFast())
2133 return nullptr;
2134 }
2135
2136 // Propagate fast-math flags from the existing call to new instructions.
2137 Value *RealReal = B.CreateFMulFMF(Real, Real, CI);
2138 Value *ImagImag = B.CreateFMulFMF(Imag, Imag, CI);
2139 return copyFlags(
2140 *CI, B.CreateUnaryIntrinsic(Intrinsic::sqrt,
2141 B.CreateFAddFMF(RealReal, ImagImag, CI), CI,
2142 "cabs"));
2143}
2144
2145// Return a properly extended integer (DstWidth bits wide) if the operation is
2146// an itofp.
2147static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) {
2148 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
2149 Value *Op = cast<Instruction>(I2F)->getOperand(0);
2150 // Make sure that the exponent fits inside an "int" of size DstWidth,
2151 // thus avoiding any range issues that FP has not.
2152 unsigned BitWidth = Op->getType()->getScalarSizeInBits();
2153 if (BitWidth < DstWidth || (BitWidth == DstWidth && isa<SIToFPInst>(I2F))) {
2154 Type *IntTy = Op->getType()->getWithNewBitWidth(DstWidth);
2155 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, IntTy)
2156 : B.CreateZExt(Op, IntTy);
2157 }
2158 }
2159
2160 return nullptr;
2161}
2162
2163/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
2164/// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
2165/// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
2166Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) {
2167 Module *M = Pow->getModule();
2168 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
2169 Type *Ty = Pow->getType();
2170 bool Ignored;
2171
2172 // Evaluate special cases related to a nested function as the base.
2173
2174 // pow(exp(x), y) -> exp(x * y)
2175 // pow(exp2(x), y) -> exp2(x * y)
2176 // If exp{,2}() is used only once, it is better to fold two transcendental
2177 // math functions into one. If used again, exp{,2}() would still have to be
2178 // called with the original argument, then keep both original transcendental
2179 // functions. However, this transformation is only safe with fully relaxed
2180 // math semantics, since, besides rounding differences, it changes overflow
2181 // and underflow behavior quite dramatically. For example:
2182 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
2183 // Whereas:
2184 // exp(1000 * 0.001) = exp(1)
2185 // TODO: Loosen the requirement for fully relaxed math semantics.
2186 // TODO: Handle exp10() when more targets have it available.
2187 CallInst *BaseFn = dyn_cast<CallInst>(Base);
2188 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
2189 LibFunc LibFn;
2190
2191 Function *CalleeFn = BaseFn->getCalledFunction();
2192 if (CalleeFn && TLI->getLibFunc(CalleeFn->getName(), LibFn) &&
2193 isLibFuncEmittable(M, TLI, LibFn)) {
2194 StringRef ExpName;
2196 Value *ExpFn;
2197 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
2198
2199 switch (LibFn) {
2200 default:
2201 return nullptr;
2202 case LibFunc_expf:
2203 case LibFunc_exp:
2204 case LibFunc_expl:
2205 ExpName = TLI->getName(LibFunc_exp);
2206 ID = Intrinsic::exp;
2207 LibFnFloat = LibFunc_expf;
2208 LibFnDouble = LibFunc_exp;
2209 LibFnLongDouble = LibFunc_expl;
2210 break;
2211 case LibFunc_exp2f:
2212 case LibFunc_exp2:
2213 case LibFunc_exp2l:
2214 ExpName = TLI->getName(LibFunc_exp2);
2215 ID = Intrinsic::exp2;
2216 LibFnFloat = LibFunc_exp2f;
2217 LibFnDouble = LibFunc_exp2;
2218 LibFnLongDouble = LibFunc_exp2l;
2219 break;
2220 }
2221
2222 // Create new exp{,2}() with the product as its argument.
2223 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
2224 ExpFn = BaseFn->doesNotAccessMemory()
2225 ? B.CreateUnaryIntrinsic(ID, FMul, nullptr, ExpName)
2226 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
2227 LibFnLongDouble, B,
2228 BaseFn->getAttributes());
2229
2230 // Since the new exp{,2}() is different from the original one, dead code
2231 // elimination cannot be trusted to remove it, since it may have side
2232 // effects (e.g., errno). When the only consumer for the original
2233 // exp{,2}() is pow(), then it has to be explicitly erased.
2234 substituteInParent(BaseFn, ExpFn);
2235 return ExpFn;
2236 }
2237 }
2238
2239 // Evaluate special cases related to a constant base.
2240
2241 const APFloat *BaseF;
2242 if (!match(Base, m_APFloat(BaseF)))
2243 return nullptr;
2244
2245 AttributeList NoAttrs; // Attributes are only meaningful on the original call
2246
2247 const bool UseIntrinsic = Pow->doesNotAccessMemory();
2248
2249 // pow(2.0, itofp(x)) -> ldexp(1.0, x)
2250 if ((UseIntrinsic || !Ty->isVectorTy()) && BaseF->isExactlyValue(2.0) &&
2251 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
2252 (UseIntrinsic ||
2253 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) {
2254
2255 // TODO: Shouldn't really need to depend on getIntToFPVal for intrinsic. Can
2256 // just directly use the original integer type.
2257 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) {
2258 Constant *One = ConstantFP::get(Ty, 1.0);
2259
2260 if (UseIntrinsic) {
2261 return copyFlags(*Pow, B.CreateIntrinsic(Intrinsic::ldexp,
2262 {Ty, ExpoI->getType()},
2263 {One, ExpoI}, Pow, "exp2"));
2264 }
2265
2267 One, ExpoI, TLI, LibFunc_ldexp, LibFunc_ldexpf,
2268 LibFunc_ldexpl, B, NoAttrs));
2269 }
2270 }
2271
2272 // pow(2.0 ** n, x) -> exp2(n * x)
2273 if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
2274 APFloat BaseR = APFloat(1.0);
2275 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
2276 BaseR = BaseR / *BaseF;
2277 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
2278 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
2279 APSInt NI(64, false);
2280 if ((IsInteger || IsReciprocal) &&
2281 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
2282 APFloat::opOK &&
2283 NI > 1 && NI.isPowerOf2()) {
2284 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
2285 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
2286 if (Pow->doesNotAccessMemory())
2287 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul,
2288 nullptr, "exp2"));
2289 else
2290 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
2291 LibFunc_exp2f,
2292 LibFunc_exp2l, B, NoAttrs));
2293 }
2294 }
2295
2296 // pow(10.0, x) -> exp10(x)
2297 if (BaseF->isExactlyValue(10.0) &&
2298 hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) {
2299
2300 if (Pow->doesNotAccessMemory()) {
2301 return B.CreateIntrinsic(Intrinsic::exp10, {Ty}, {Expo}, Pow, "exp10", {},
2302 [Pow](CallInst *CI) { CI->copyIRFlags(Pow); });
2303 }
2304
2305 return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10,
2306 LibFunc_exp10f, LibFunc_exp10l,
2307 B, NoAttrs));
2308 }
2309
2310 // pow(x, y) -> exp2(log2(x) * y)
2311 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() &&
2312 !BaseF->isNegative()) {
2313 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN.
2314 // Luckily optimizePow has already handled the x == 1 case.
2315 assert(!match(Base, m_FPOne()) &&
2316 "pow(1.0, y) should have been simplified earlier!");
2317
2318 Value *Log = nullptr;
2319 if (Ty->isFloatTy())
2320 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
2321 else if (Ty->isDoubleTy())
2322 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
2323
2324 if (Log) {
2325 Value *FMul = B.CreateFMul(Log, Expo, "mul");
2326 if (Pow->doesNotAccessMemory())
2327 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul,
2328 nullptr, "exp2"));
2329 else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f,
2330 LibFunc_exp2l))
2331 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
2332 LibFunc_exp2f,
2333 LibFunc_exp2l, B, NoAttrs));
2334 }
2335 }
2336
2337 return nullptr;
2338}
2339
2340static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
2341 Module *M, IRBuilderBase &B,
2342 const TargetLibraryInfo *TLI) {
2343 // If errno is never set, then use the intrinsic for sqrt().
2344 if (NoErrno)
2345 return B.CreateUnaryIntrinsic(Intrinsic::sqrt, V, nullptr, "sqrt");
2346
2347 // Otherwise, use the libcall for sqrt().
2348 if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
2349 LibFunc_sqrtl))
2350 // TODO: We also should check that the target can in fact lower the sqrt()
2351 // libcall. We currently have no way to ask this question, so we ask if
2352 // the target has a sqrt() libcall, which is not exactly the same.
2353 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
2354 LibFunc_sqrtl, B, Attrs);
2355
2356 return nullptr;
2357}
2358
2359/// Use square root in place of pow(x, +/-0.5).
2360Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) {
2361 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
2362 Module *Mod = Pow->getModule();
2363 Type *Ty = Pow->getType();
2364
2365 const APFloat *ExpoF;
2366 if (!match(Expo, m_APFloat(ExpoF)) ||
2367 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
2368 return nullptr;
2369
2370 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step,
2371 // so that requires fast-math-flags (afn or reassoc).
2372 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc()))
2373 return nullptr;
2374
2375 // If we have a pow() library call (accesses memory) and we can't guarantee
2376 // that the base is not an infinity, give up:
2377 // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting
2378 // errno), but sqrt(-Inf) is required by various standards to set errno.
2379 if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() &&
2381 Base, SimplifyQuery(DL, TLI, DT, AC, Pow, true, true, DC)))
2382 return nullptr;
2383
2384 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), Mod, B,
2385 TLI);
2386 if (!Sqrt)
2387 return nullptr;
2388
2389 // Handle signed zero base by expanding to fabs(sqrt(x)).
2390 if (!Pow->hasNoSignedZeros())
2391 Sqrt = B.CreateFAbs(Sqrt, nullptr, "abs");
2392
2393 Sqrt = copyFlags(*Pow, Sqrt);
2394
2395 // Handle non finite base by expanding to
2396 // (x == -infinity ? +infinity : sqrt(x)).
2397 if (!Pow->hasNoInfs()) {
2398 Value *PosInf = ConstantFP::getInfinity(Ty),
2399 *NegInf = ConstantFP::getInfinity(Ty, true);
2400 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
2401 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
2402 }
2403
2404 // If the exponent is negative, then get the reciprocal.
2405 if (ExpoF->isNegative())
2406 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
2407
2408 return Sqrt;
2409}
2410
2412 IRBuilderBase &B) {
2413 Value *Args[] = {Base, Expo};
2414 Type *Types[] = {Base->getType(), Expo->getType()};
2415 return B.CreateIntrinsic(Intrinsic::powi, Types, Args);
2416}
2417
2418Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) {
2419 Value *Base = Pow->getArgOperand(0);
2420 Value *Expo = Pow->getArgOperand(1);
2421 Function *Callee = Pow->getCalledFunction();
2422 StringRef Name = Callee->getName();
2423 Type *Ty = Pow->getType();
2424 Module *M = Pow->getModule();
2425 bool AllowApprox = Pow->hasApproxFunc();
2426 bool Ignored;
2427
2428 // Propagate the math semantics from the call to any created instructions.
2429 IRBuilderBase::FastMathFlagGuard Guard(B);
2430 B.setFastMathFlags(Pow->getFastMathFlags());
2431 // Evaluate special cases related to the base.
2432
2433 // pow(1.0, x) -> 1.0
2434 if (match(Base, m_FPOne()))
2435 return Base;
2436
2437 if (Value *Exp = replacePowWithExp(Pow, B))
2438 return Exp;
2439
2440 // Evaluate special cases related to the exponent.
2441
2442 // pow(x, -1.0) -> 1.0 / x
2443 if (match(Expo, m_SpecificFP(-1.0)))
2444 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
2445
2446 // pow(x, +/-0.0) -> 1.0
2447 if (match(Expo, m_AnyZeroFP()))
2448 return ConstantFP::get(Ty, 1.0);
2449
2450 // pow(x, 1.0) -> x
2451 if (match(Expo, m_FPOne()))
2452 return Base;
2453
2454 // pow(x, 2.0) -> x * x
2455 if (match(Expo, m_SpecificFP(2.0)) && Pow->doesNotAccessMemory())
2456 return B.CreateFMul(Base, Base, "square");
2457
2458 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
2459 return Sqrt;
2460
2461 // If we can approximate pow:
2462 // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction
2463 // pow(x, n) -> powi(x, n) if n is a constant signed integer value
2464 const APFloat *ExpoF;
2465 if (AllowApprox && match(Expo, m_APFloat(ExpoF)) &&
2466 !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) {
2467 APFloat ExpoA(abs(*ExpoF));
2468 APFloat ExpoI(*ExpoF);
2469 Value *Sqrt = nullptr;
2470 if (!ExpoA.isInteger()) {
2471 APFloat Expo2 = ExpoA;
2472 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
2473 // is no floating point exception and the result is an integer, then
2474 // ExpoA == integer + 0.5
2475 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
2476 return nullptr;
2477
2478 if (!Expo2.isInteger())
2479 return nullptr;
2480
2481 if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) !=
2483 return nullptr;
2484 if (!ExpoI.isInteger())
2485 return nullptr;
2486 ExpoF = &ExpoI;
2487
2488 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), M,
2489 B, TLI);
2490 if (!Sqrt)
2491 return nullptr;
2492 }
2493
2494 // 0.5 fraction is now optionally handled.
2495 // Do pow -> powi for remaining integer exponent
2496 APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false);
2497 if (ExpoF->isInteger() &&
2498 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
2499 APFloat::opOK) {
2500 Value *PowI = copyFlags(
2501 *Pow,
2503 Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo),
2504 M, B));
2505
2506 if (PowI && Sqrt)
2507 return B.CreateFMul(PowI, Sqrt);
2508
2509 return PowI;
2510 }
2511 }
2512
2513 // powf(x, itofp(y)) -> powi(x, y)
2514 // The powi exponent must be a scalar integer, so a vector y is not usable.
2515 if (AllowApprox && !Expo->getType()->isVectorTy() &&
2516 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
2517 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
2518 return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B));
2519 }
2520
2521 // Shrink pow() to powf() if the arguments are single precision,
2522 // unless the result is expected to be double precision.
2523 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
2524 hasFloatVersion(M, Name)) {
2525 if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true))
2526 return Shrunk;
2527 }
2528
2529 return nullptr;
2530}
2531
2532Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) {
2533 Module *M = CI->getModule();
2535 StringRef Name = Callee->getName();
2536 Value *Ret = nullptr;
2537 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
2538 hasFloatVersion(M, Name))
2539 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2540
2541 // If we have an llvm.exp2 intrinsic, emit the llvm.ldexp intrinsic. If we
2542 // have the libcall, emit the libcall.
2543 //
2544 // TODO: In principle we should be able to just always use the intrinsic for
2545 // any doesNotAccessMemory callsite.
2546
2547 const bool UseIntrinsic = Callee->isIntrinsic();
2548 // Bail out for vectors because the code below only expects scalars.
2549 Type *Ty = CI->getType();
2550 if (!UseIntrinsic && Ty->isVectorTy())
2551 return Ret;
2552
2553 // exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize
2554 // exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize
2555 Value *Op = CI->getArgOperand(0);
2556 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
2557 (UseIntrinsic ||
2558 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) {
2559 if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize())) {
2560 Constant *One = ConstantFP::get(Ty, 1.0);
2561
2562 if (UseIntrinsic) {
2563 return copyFlags(*CI, B.CreateIntrinsic(Intrinsic::ldexp,
2564 {Ty, Exp->getType()},
2565 {One, Exp}, CI));
2566 }
2567
2568 IRBuilderBase::FastMathFlagGuard Guard(B);
2569 B.setFastMathFlags(CI->getFastMathFlags());
2570 return copyFlags(*CI, emitBinaryFloatFnCall(
2571 One, Exp, TLI, LibFunc_ldexp, LibFunc_ldexpf,
2572 LibFunc_ldexpl, B, AttributeList()));
2573 }
2574 }
2575
2576 return Ret;
2577}
2578
2579Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B,
2580 Intrinsic::ID IID) {
2581 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
2582 // the intrinsics for improved optimization (for example, vectorization).
2583 // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
2584 // From the C standard draft WG14/N1256:
2585 // "Ideally, fmax would be sensitive to the sign of zero, for example
2586 // fmax(-0.0, +0.0) would return +0; however, implementation in software
2587 // might be impractical."
2588 FastMathFlags FMF = CI->getFastMathFlags();
2589 FMF.setNoSignedZeros();
2590 return copyFlags(*CI, B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0),
2591 CI->getArgOperand(1), FMF));
2592}
2593
2594Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) {
2595 Function *LogFn = Log->getCalledFunction();
2596 StringRef LogNm = LogFn->getName();
2597 Intrinsic::ID LogID = LogFn->getIntrinsicID();
2598 Module *Mod = Log->getModule();
2599 Type *Ty = Log->getType();
2600
2601 if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm))
2602 if (Value *Ret = optimizeUnaryDoubleFP(Log, B, TLI, true))
2603 return Ret;
2604
2605 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
2606
2607 // This is only applicable to log(), log2(), log10().
2608 if (TLI->getLibFunc(LogNm, LogLb)) {
2609 switch (LogLb) {
2610 case LibFunc_logf:
2611 LogID = Intrinsic::log;
2612 ExpLb = LibFunc_expf;
2613 Exp2Lb = LibFunc_exp2f;
2614 Exp10Lb = LibFunc_exp10f;
2615 PowLb = LibFunc_powf;
2616 break;
2617 case LibFunc_log:
2618 LogID = Intrinsic::log;
2619 ExpLb = LibFunc_exp;
2620 Exp2Lb = LibFunc_exp2;
2621 Exp10Lb = LibFunc_exp10;
2622 PowLb = LibFunc_pow;
2623 break;
2624 case LibFunc_logl:
2625 LogID = Intrinsic::log;
2626 ExpLb = LibFunc_expl;
2627 Exp2Lb = LibFunc_exp2l;
2628 Exp10Lb = LibFunc_exp10l;
2629 PowLb = LibFunc_powl;
2630 break;
2631 case LibFunc_log2f:
2632 LogID = Intrinsic::log2;
2633 ExpLb = LibFunc_expf;
2634 Exp2Lb = LibFunc_exp2f;
2635 Exp10Lb = LibFunc_exp10f;
2636 PowLb = LibFunc_powf;
2637 break;
2638 case LibFunc_log2:
2639 LogID = Intrinsic::log2;
2640 ExpLb = LibFunc_exp;
2641 Exp2Lb = LibFunc_exp2;
2642 Exp10Lb = LibFunc_exp10;
2643 PowLb = LibFunc_pow;
2644 break;
2645 case LibFunc_log2l:
2646 LogID = Intrinsic::log2;
2647 ExpLb = LibFunc_expl;
2648 Exp2Lb = LibFunc_exp2l;
2649 Exp10Lb = LibFunc_exp10l;
2650 PowLb = LibFunc_powl;
2651 break;
2652 case LibFunc_log10f:
2653 LogID = Intrinsic::log10;
2654 ExpLb = LibFunc_expf;
2655 Exp2Lb = LibFunc_exp2f;
2656 Exp10Lb = LibFunc_exp10f;
2657 PowLb = LibFunc_powf;
2658 break;
2659 case LibFunc_log10:
2660 LogID = Intrinsic::log10;
2661 ExpLb = LibFunc_exp;
2662 Exp2Lb = LibFunc_exp2;
2663 Exp10Lb = LibFunc_exp10;
2664 PowLb = LibFunc_pow;
2665 break;
2666 case LibFunc_log10l:
2667 LogID = Intrinsic::log10;
2668 ExpLb = LibFunc_expl;
2669 Exp2Lb = LibFunc_exp2l;
2670 Exp10Lb = LibFunc_exp10l;
2671 PowLb = LibFunc_powl;
2672 break;
2673 default:
2674 return nullptr;
2675 }
2676
2677 // Convert libcall to intrinsic if the value is known > 0.
2678 bool IsKnownNoErrno = Log->hasNoNaNs() && Log->hasNoInfs();
2679 if (!IsKnownNoErrno) {
2680 SimplifyQuery SQ(DL, TLI, DT, AC, Log, true, true, DC);
2681 KnownFPClass Known = computeKnownFPClass(
2682 Log->getOperand(0),
2684 Function *F = Log->getParent()->getParent();
2685 const fltSemantics &FltSem = Ty->getScalarType()->getFltSemantics();
2686 IsKnownNoErrno =
2687 Known.cannotBeOrderedLessThanZero() &&
2688 Known.isKnownNeverLogicalZero(F->getDenormalMode(FltSem));
2689 }
2690 if (IsKnownNoErrno) {
2691 Value *NewLog = B.CreateUnaryIntrinsic(LogID, Log->getArgOperand(0), Log);
2692 if (auto *I = dyn_cast<Instruction>(NewLog)) {
2693 I->copyMetadata(*Log);
2694 return copyFlags(*Log, I);
2695 }
2696 return NewLog;
2697 }
2698 } else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
2699 LogID == Intrinsic::log10) {
2700 if (Ty->getScalarType()->isFloatTy()) {
2701 ExpLb = LibFunc_expf;
2702 Exp2Lb = LibFunc_exp2f;
2703 Exp10Lb = LibFunc_exp10f;
2704 PowLb = LibFunc_powf;
2705 } else if (Ty->getScalarType()->isDoubleTy()) {
2706 ExpLb = LibFunc_exp;
2707 Exp2Lb = LibFunc_exp2;
2708 Exp10Lb = LibFunc_exp10;
2709 PowLb = LibFunc_pow;
2710 } else
2711 return nullptr;
2712 } else
2713 return nullptr;
2714
2715 // The earlier call must also be 'fast' in order to do these transforms.
2716 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
2717 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
2718 return nullptr;
2719
2720 IRBuilderBase::FastMathFlagGuard Guard(B);
2721 B.setFastMathFlags(FastMathFlags::getFast());
2722
2723 Intrinsic::ID ArgID = Arg->getIntrinsicID();
2724 LibFunc ArgLb = NotLibFunc;
2725 TLI->getLibFunc(*Arg, ArgLb);
2726
2727 // log(pow(x,y)) -> y*log(x)
2728 AttributeList NoAttrs;
2729 if (ArgLb == PowLb || ArgID == Intrinsic::pow || ArgID == Intrinsic::powi) {
2730 Value *LogX =
2731 Log->doesNotAccessMemory()
2732 ? B.CreateUnaryIntrinsic(LogID, Arg->getOperand(0), nullptr, "log")
2733 : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, NoAttrs);
2734 Value *Y = Arg->getArgOperand(1);
2735 // Cast exponent to FP if integer.
2736 if (ArgID == Intrinsic::powi)
2737 Y = B.CreateSIToFP(Y, Ty, "cast");
2738 Value *MulY = B.CreateFMul(Y, LogX, "mul");
2739 // Since pow() may have side effects, e.g. errno,
2740 // dead code elimination may not be trusted to remove it.
2741 substituteInParent(Arg, MulY);
2742 return MulY;
2743 }
2744
2745 // log(exp{,2,10}(y)) -> y*log({e,2,10})
2746 // TODO: There is no exp10() intrinsic yet.
2747 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
2748 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
2749 Constant *Eul;
2750 if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
2751 // FIXME: Add more precise value of e for long double.
2752 Eul = ConstantFP::get(Log->getType(), numbers::e);
2753 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
2754 Eul = ConstantFP::get(Log->getType(), 2.0);
2755 else
2756 Eul = ConstantFP::get(Log->getType(), 10.0);
2757 Value *LogE = Log->doesNotAccessMemory()
2758 ? B.CreateUnaryIntrinsic(LogID, Eul, nullptr, "log")
2759 : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, NoAttrs);
2760 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
2761 // Since exp() may have side effects, e.g. errno,
2762 // dead code elimination may not be trusted to remove it.
2763 substituteInParent(Arg, MulY);
2764 return MulY;
2765 }
2766
2767 return nullptr;
2768}
2769
2770// sqrt(exp(X)) -> exp(X * 0.5)
2771Value *LibCallSimplifier::mergeSqrtToExp(CallInst *CI, IRBuilderBase &B) {
2772 if (!CI->hasAllowReassoc())
2773 return nullptr;
2774
2775 Function *SqrtFn = CI->getCalledFunction();
2776 CallInst *Arg = dyn_cast<CallInst>(CI->getArgOperand(0));
2777 if (!Arg || !Arg->hasAllowReassoc() || !Arg->hasOneUse())
2778 return nullptr;
2779 Intrinsic::ID ArgID = Arg->getIntrinsicID();
2780 LibFunc ArgLb = NotLibFunc;
2781 TLI->getLibFunc(*Arg, ArgLb);
2782
2783 LibFunc SqrtLb, ExpLb, Exp2Lb, Exp10Lb;
2784
2785 if (TLI->getLibFunc(SqrtFn->getName(), SqrtLb))
2786 switch (SqrtLb) {
2787 case LibFunc_sqrtf:
2788 ExpLb = LibFunc_expf;
2789 Exp2Lb = LibFunc_exp2f;
2790 Exp10Lb = LibFunc_exp10f;
2791 break;
2792 case LibFunc_sqrt:
2793 ExpLb = LibFunc_exp;
2794 Exp2Lb = LibFunc_exp2;
2795 Exp10Lb = LibFunc_exp10;
2796 break;
2797 case LibFunc_sqrtl:
2798 ExpLb = LibFunc_expl;
2799 Exp2Lb = LibFunc_exp2l;
2800 Exp10Lb = LibFunc_exp10l;
2801 break;
2802 default:
2803 return nullptr;
2804 }
2805 else if (SqrtFn->getIntrinsicID() == Intrinsic::sqrt) {
2806 if (CI->getType()->getScalarType()->isFloatTy()) {
2807 ExpLb = LibFunc_expf;
2808 Exp2Lb = LibFunc_exp2f;
2809 Exp10Lb = LibFunc_exp10f;
2810 } else if (CI->getType()->getScalarType()->isDoubleTy()) {
2811 ExpLb = LibFunc_exp;
2812 Exp2Lb = LibFunc_exp2;
2813 Exp10Lb = LibFunc_exp10;
2814 } else
2815 return nullptr;
2816 } else
2817 return nullptr;
2818
2819 if (ArgLb != ExpLb && ArgLb != Exp2Lb && ArgLb != Exp10Lb &&
2820 ArgID != Intrinsic::exp && ArgID != Intrinsic::exp2)
2821 return nullptr;
2822
2823 IRBuilderBase::InsertPointGuard Guard(B);
2824 B.SetInsertPoint(Arg);
2825 auto *ExpOperand = Arg->getOperand(0);
2826 auto *FMul =
2827 B.CreateFMulFMF(ExpOperand, ConstantFP::get(ExpOperand->getType(), 0.5),
2828 CI, "merged.sqrt");
2829
2830 Arg->setOperand(0, FMul);
2831 return Arg;
2832}
2833
2834Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) {
2835 Module *M = CI->getModule();
2837 Value *Ret = nullptr;
2838 // TODO: Once we have a way (other than checking for the existince of the
2839 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
2840 // condition below.
2841 if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) &&
2842 (Callee->getName() == "sqrt" ||
2843 Callee->getIntrinsicID() == Intrinsic::sqrt))
2844 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2845
2846 if (Value *Opt = mergeSqrtToExp(CI, B))
2847 return Opt;
2848
2849 if (!CI->isFast())
2850 return Ret;
2851
2853 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
2854 return Ret;
2855
2856 // We're looking for a repeated factor in a multiplication tree,
2857 // so we can do this fold: sqrt(x * x) -> fabs(x);
2858 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
2859 Value *Op0 = I->getOperand(0);
2860 Value *Op1 = I->getOperand(1);
2861 Value *RepeatOp = nullptr;
2862 Value *OtherOp = nullptr;
2863 if (Op0 == Op1) {
2864 // Simple match: the operands of the multiply are identical.
2865 RepeatOp = Op0;
2866 } else {
2867 // Look for a more complicated pattern: one of the operands is itself
2868 // a multiply, so search for a common factor in that multiply.
2869 // Note: We don't bother looking any deeper than this first level or for
2870 // variations of this pattern because instcombine's visitFMUL and/or the
2871 // reassociation pass should give us this form.
2872 Value *MulOp;
2873 if (match(Op0, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) &&
2874 cast<Instruction>(Op0)->isFast()) {
2875 // Pattern: sqrt((x * x) * z)
2876 RepeatOp = MulOp;
2877 OtherOp = Op1;
2878 } else if (match(Op1, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) &&
2879 cast<Instruction>(Op1)->isFast()) {
2880 // Pattern: sqrt(z * (x * x))
2881 RepeatOp = MulOp;
2882 OtherOp = Op0;
2883 }
2884 }
2885 if (!RepeatOp)
2886 return Ret;
2887
2888 // Fast math flags for any created instructions should match the sqrt
2889 // and multiply.
2890
2891 // If we found a repeated factor, hoist it out of the square root and
2892 // replace it with the fabs of that factor.
2893 Value *FabsCall = B.CreateFAbs(RepeatOp, I, "fabs");
2894 if (OtherOp) {
2895 // If we found a non-repeated factor, we still need to get its square
2896 // root. We then multiply that by the value that was simplified out
2897 // of the square root calculation.
2898 Value *SqrtCall =
2899 B.CreateUnaryIntrinsic(Intrinsic::sqrt, OtherOp, I, "sqrt");
2900 return copyFlags(*CI, B.CreateFMulFMF(FabsCall, SqrtCall, I));
2901 }
2902 return copyFlags(*CI, FabsCall);
2903}
2904
2905Value *LibCallSimplifier::optimizeFMod(CallInst *CI, IRBuilderBase &B) {
2906
2907 // fmod(x,y) sets errno if y == 0 or x == +/-inf. frem does not set errno,
2908 // so the fold is valid only when we can prove fmod wouldn't either.
2909 bool IsNoErrno = CI->hasNoNaNs();
2910 if (!IsNoErrno) {
2911 SimplifyQuery SQ(DL, TLI, DT, AC, CI, true, true, DC);
2912 KnownFPClass Known0 = computeKnownFPClass(CI->getOperand(0), fcInf, SQ);
2913 if (Known0.isKnownNeverInfinity()) {
2914 KnownFPClass Known1 =
2916 Function *F = CI->getParent()->getParent();
2917 const fltSemantics &FltSem =
2919 IsNoErrno = Known1.isKnownNeverLogicalZero(F->getDenormalMode(FltSem));
2920 }
2921 }
2922
2923 if (IsNoErrno)
2924 return B.CreateFRemFMF(CI->getOperand(0), CI->getOperand(1), CI);
2925 return nullptr;
2926}
2927
2928Value *LibCallSimplifier::optimizeTrigInversionPairs(CallInst *CI,
2929 IRBuilderBase &B) {
2930 Module *M = CI->getModule();
2932 Value *Ret = nullptr;
2933 StringRef Name = Callee->getName();
2934 if (UnsafeFPShrink &&
2935 (Name == "tan" || Name == "atanh" || Name == "sinh" || Name == "cosh" ||
2936 Name == "asinh") &&
2937 hasFloatVersion(M, Name))
2938 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2939
2940 Value *Op1 = CI->getArgOperand(0);
2941 auto *OpC = dyn_cast<CallInst>(Op1);
2942 if (!OpC)
2943 return Ret;
2944
2945 // Both calls must be 'fast' in order to remove them.
2946 if (!CI->isFast() || !OpC->isFast())
2947 return Ret;
2948
2949 // tan(atan(x)) -> x
2950 // atanh(tanh(x)) -> x
2951 // sinh(asinh(x)) -> x
2952 // asinh(sinh(x)) -> x
2953 // cosh(acosh(x)) -> x
2954 LibFunc Func;
2955 Function *F = OpC->getCalledFunction();
2956 if (F && TLI->getLibFunc(F->getName(), Func) &&
2957 isLibFuncEmittable(M, TLI, Func)) {
2958 LibFunc inverseFunc = llvm::StringSwitch<LibFunc>(Callee->getName())
2959 .Case("tan", LibFunc_atan)
2960 .Case("atanh", LibFunc_tanh)
2961 .Case("sinh", LibFunc_asinh)
2962 .Case("cosh", LibFunc_acosh)
2963 .Case("tanf", LibFunc_atanf)
2964 .Case("atanhf", LibFunc_tanhf)
2965 .Case("sinhf", LibFunc_asinhf)
2966 .Case("coshf", LibFunc_acoshf)
2967 .Case("tanl", LibFunc_atanl)
2968 .Case("atanhl", LibFunc_tanhl)
2969 .Case("sinhl", LibFunc_asinhl)
2970 .Case("coshl", LibFunc_acoshl)
2971 .Case("asinh", LibFunc_sinh)
2972 .Case("asinhf", LibFunc_sinhf)
2973 .Case("asinhl", LibFunc_sinhl)
2974 .Default(NotLibFunc); // Used as error value
2975 if (Func == inverseFunc)
2976 Ret = OpC->getArgOperand(0);
2977 }
2978 return Ret;
2979}
2980
2981static bool isTrigLibCall(CallInst *CI) {
2982 // We can only hope to do anything useful if we can ignore things like errno
2983 // and floating-point exceptions.
2984 // We already checked the prototype.
2985 return CI->doesNotThrow() && CI->doesNotAccessMemory();
2986}
2987
2988static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg,
2989 bool UseFloat, Value *&Sin, Value *&Cos,
2990 Value *&SinCos, const TargetLibraryInfo *TLI) {
2991 Module *M = OrigCallee->getParent();
2992 Type *ArgTy = Arg->getType();
2993 Type *ResTy;
2994 StringRef Name;
2995
2996 Triple T(OrigCallee->getParent()->getTargetTriple());
2997 if (UseFloat) {
2998 Name = "__sincospif_stret";
2999
3000 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
3001 // x86_64 can't use {float, float} since that would be returned in both
3002 // xmm0 and xmm1, which isn't what a real struct would do.
3003 ResTy = T.getArch() == Triple::x86_64
3004 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2))
3005 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
3006 } else {
3007 Name = "__sincospi_stret";
3008 ResTy = StructType::get(ArgTy, ArgTy);
3009 }
3010
3011 if (!isLibFuncEmittable(M, TLI, Name))
3012 return false;
3013 LibFunc TheLibFunc;
3014 TLI->getLibFunc(Name, TheLibFunc);
3016 M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy);
3017
3018 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
3019 // If the argument is an instruction, it must dominate all uses so put our
3020 // sincos call there.
3021 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
3022 } else {
3023 // Otherwise (e.g. for a constant) the beginning of the function is as
3024 // good a place as any.
3025 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
3026 B.SetInsertPoint(&EntryBB, EntryBB.begin());
3027 }
3028
3029 SinCos = B.CreateCall(Callee, Arg, "sincospi");
3030
3031 if (SinCos->getType()->isStructTy()) {
3032 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
3033 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
3034 } else {
3035 Sin = B.CreateExtractElement(SinCos, uint64_t{0}, "sinpi");
3036 Cos = B.CreateExtractElement(SinCos, uint64_t{1}, "cospi");
3037 }
3038
3039 return true;
3040}
3041
3042static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven,
3043 IRBuilderBase &B) {
3044 Value *X;
3045 Value *Src = CI->getArgOperand(0);
3046
3047 if (match(Src, m_OneUse(m_FNeg(m_Value(X))))) {
3048 auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
3049 auto *CallInst = copyFlags(*CI, Call);
3050 if (IsEven) {
3051 // Even function: f(-x) = f(x)
3052 return CallInst;
3053 }
3054 // Odd function: f(-x) = -f(x)
3055 return B.CreateFNegFMF(CallInst, CI);
3056 }
3057
3058 // Even function: f(abs(x)) = f(x), f(copysign(x, y)) = f(x)
3059 if (IsEven && (match(Src, m_FAbs(m_Value(X))) ||
3060 match(Src, m_CopySign(m_Value(X), m_Value())))) {
3061 auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
3062 return copyFlags(*CI, Call);
3063 }
3064
3065 return nullptr;
3066}
3067
3068Value *LibCallSimplifier::optimizeSymmetric(CallInst *CI, LibFunc Func,
3069 IRBuilderBase &B) {
3070 switch (Func) {
3071 case LibFunc_cos:
3072 case LibFunc_cosf:
3073 case LibFunc_cosl:
3074
3075 case LibFunc_cosh:
3076 case LibFunc_coshf:
3077 case LibFunc_coshl:
3078 return optimizeSymmetricCall(CI, /*IsEven*/ true, B);
3079
3080 case LibFunc_sin:
3081 case LibFunc_sinf:
3082 case LibFunc_sinl:
3083
3084 case LibFunc_sinh:
3085 case LibFunc_sinhf:
3086 case LibFunc_sinhl:
3087
3088 case LibFunc_tan:
3089 case LibFunc_tanf:
3090 case LibFunc_tanl:
3091
3092 case LibFunc_tanh:
3093 case LibFunc_tanhf:
3094 case LibFunc_tanhl:
3095
3096 case LibFunc_erf:
3097 case LibFunc_erff:
3098 case LibFunc_erfl:
3099 return optimizeSymmetricCall(CI, /*IsEven*/ false, B);
3100
3101 default:
3102 return nullptr;
3103 }
3104}
3105
3106Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, bool IsSin, IRBuilderBase &B) {
3107 // Make sure the prototype is as expected, otherwise the rest of the
3108 // function is probably invalid and likely to abort.
3109 if (!isTrigLibCall(CI))
3110 return nullptr;
3111
3112 Value *Arg = CI->getArgOperand(0);
3113 if (isa<ConstantData>(Arg))
3114 return nullptr;
3115
3118 SmallVector<CallInst *, 1> SinCosCalls;
3119
3120 bool IsFloat = Arg->getType()->isFloatTy();
3121
3122 // Look for all compatible sinpi, cospi and sincospi calls with the same
3123 // argument. If there are enough (in some sense) we can make the
3124 // substitution.
3125 Function *F = CI->getFunction();
3126 for (User *U : Arg->users())
3127 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
3128
3129 // It's only worthwhile if both sinpi and cospi are actually used.
3130 if (SinCalls.empty() || CosCalls.empty())
3131 return nullptr;
3132
3133 Value *Sin, *Cos, *SinCos;
3134 if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
3135 SinCos, TLI))
3136 return nullptr;
3137
3138 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
3139 Value *Res) {
3140 for (CallInst *C : Calls)
3141 replaceAllUsesWith(C, Res);
3142 };
3143
3144 replaceTrigInsts(SinCalls, Sin);
3145 replaceTrigInsts(CosCalls, Cos);
3146 replaceTrigInsts(SinCosCalls, SinCos);
3147
3148 return IsSin ? Sin : Cos;
3149}
3150
3151void LibCallSimplifier::classifyArgUse(
3152 Value *Val, Function *F, bool IsFloat,
3155 SmallVectorImpl<CallInst *> &SinCosCalls) {
3156 auto *CI = dyn_cast<CallInst>(Val);
3157 if (!CI || CI->use_empty())
3158 return;
3159
3160 // Don't consider calls in other functions.
3161 if (CI->getFunction() != F)
3162 return;
3163
3164 Module *M = CI->getModule();
3166 LibFunc Func;
3167 if (!Callee || !TLI->getLibFunc(*Callee, Func) ||
3168 !isLibFuncEmittable(M, TLI, Func) ||
3169 !isTrigLibCall(CI))
3170 return;
3171
3172 if (IsFloat) {
3173 if (Func == LibFunc_sinpif)
3174 SinCalls.push_back(CI);
3175 else if (Func == LibFunc_cospif)
3176 CosCalls.push_back(CI);
3177 else if (Func == LibFunc_sincospif_stret)
3178 SinCosCalls.push_back(CI);
3179 } else {
3180 if (Func == LibFunc_sinpi)
3181 SinCalls.push_back(CI);
3182 else if (Func == LibFunc_cospi)
3183 CosCalls.push_back(CI);
3184 else if (Func == LibFunc_sincospi_stret)
3185 SinCosCalls.push_back(CI);
3186 }
3187}
3188
3189/// Constant folds remquo
3190Value *LibCallSimplifier::optimizeRemquo(CallInst *CI, IRBuilderBase &B) {
3191 const APFloat *X, *Y;
3192 if (!match(CI->getArgOperand(0), m_APFloat(X)) ||
3193 !match(CI->getArgOperand(1), m_APFloat(Y)))
3194 return nullptr;
3195
3196 APFloat::opStatus Status;
3197 APFloat Quot = *X;
3198 Status = Quot.divide(*Y, APFloat::rmNearestTiesToEven);
3199 if (Status != APFloat::opOK && Status != APFloat::opInexact)
3200 return nullptr;
3201 APFloat Rem = *X;
3202 if (Rem.remainder(*Y) != APFloat::opOK)
3203 return nullptr;
3204
3205 // TODO: We can only keep at least the three of the last bits of x/y
3206 unsigned IntBW = TLI->getIntSize();
3207 APSInt QuotInt(IntBW, /*isUnsigned=*/false);
3208 bool IsExact;
3209 Status =
3210 Quot.convertToInteger(QuotInt, APFloat::rmNearestTiesToEven, &IsExact);
3211 if (Status != APFloat::opOK && Status != APFloat::opInexact)
3212 return nullptr;
3213
3214 B.CreateAlignedStore(
3215 ConstantInt::getSigned(B.getIntNTy(IntBW), QuotInt.getExtValue()),
3216 CI->getArgOperand(2), CI->getParamAlign(2));
3217 return ConstantFP::get(CI->getType(), Rem);
3218}
3219
3220/// Constant folds fdim
3221Value *LibCallSimplifier::optimizeFdim(CallInst *CI, IRBuilderBase &B) {
3222 // Cannot perform the fold unless the call has attribute memory(none)
3223 if (!CI->doesNotAccessMemory())
3224 return nullptr;
3225
3226 // TODO : Handle undef values
3227 // Propagate poison if any
3228 if (isa<PoisonValue>(CI->getArgOperand(0)))
3229 return CI->getArgOperand(0);
3230 if (isa<PoisonValue>(CI->getArgOperand(1)))
3231 return CI->getArgOperand(1);
3232
3233 const APFloat *X, *Y;
3234 // Check if both values are constants
3235 if (!match(CI->getArgOperand(0), m_APFloat(X)) ||
3236 !match(CI->getArgOperand(1), m_APFloat(Y)))
3237 return nullptr;
3238
3239 // C99 fdim(x, y) = (x > y) ? x - y : +0.
3240 if (X->compare(*Y) != APFloat::cmpGreaterThan && !X->isNaN() && !Y->isNaN())
3241 return ConstantFP::getZero(CI->getType());
3242 APFloat Difference = *X;
3244 return ConstantFP::get(CI->getType(), Difference);
3245}
3246
3247//===----------------------------------------------------------------------===//
3248// Integer Library Call Optimizations
3249//===----------------------------------------------------------------------===//
3250
3251Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) {
3252 // All variants of ffs return int which need not be 32 bits wide.
3253 // ffs{,l,ll}(x) -> x != 0 ? (int)llvm.cttz(x)+1 : 0
3254 Type *RetType = CI->getType();
3255 Value *Op = CI->getArgOperand(0);
3256 Type *ArgType = Op->getType();
3257 Value *V = B.CreateIntrinsic(Intrinsic::cttz, {ArgType}, {Op, B.getTrue()},
3258 nullptr, "cttz");
3259 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
3260 V = B.CreateIntCast(V, RetType, false);
3261
3262 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
3263 return B.CreateSelect(Cond, V, ConstantInt::get(RetType, 0));
3264}
3265
3266Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) {
3267 // All variants of fls return int which need not be 32 bits wide.
3268 // fls{,l,ll}(x) -> (int)(sizeInBits(x) - llvm.ctlz(x, false))
3269 Value *Op = CI->getArgOperand(0);
3270 Type *ArgType = Op->getType();
3271 Value *V = B.CreateIntrinsic(Intrinsic::ctlz, {ArgType}, {Op, B.getFalse()},
3272 nullptr, "ctlz");
3273 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
3274 V);
3275 return B.CreateIntCast(V, CI->getType(), false);
3276}
3277
3278Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) {
3279 // abs(x) -> x <s 0 ? -x : x
3280 // The negation has 'nsw' because abs of INT_MIN is undefined.
3281 Value *X = CI->getArgOperand(0);
3282 Value *IsNeg = B.CreateIsNeg(X);
3283 Value *NegX = B.CreateNSWNeg(X, "neg");
3284 return B.CreateSelect(IsNeg, NegX, X);
3285}
3286
3287Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) {
3288 // isdigit(c) -> (c-'0') <u 10
3289 Value *Op = CI->getArgOperand(0);
3290 Type *ArgType = Op->getType();
3291 Op = B.CreateSub(Op, ConstantInt::get(ArgType, '0'), "isdigittmp");
3292 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 10), "isdigit");
3293 return B.CreateZExt(Op, CI->getType());
3294}
3295
3296Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) {
3297 // isascii(c) -> c <u 128
3298 Value *Op = CI->getArgOperand(0);
3299 Type *ArgType = Op->getType();
3300 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 128), "isascii");
3301 return B.CreateZExt(Op, CI->getType());
3302}
3303
3304Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) {
3305 // toascii(c) -> c & 0x7f
3306 return B.CreateAnd(CI->getArgOperand(0),
3307 ConstantInt::get(CI->getType(), 0x7F));
3308}
3309
3310// Fold calls to atoi, atol, and atoll.
3311Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) {
3312 StringRef Str;
3313 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
3314 return nullptr;
3315
3316 return convertStrToInt(CI, Str, nullptr, 10, /*AsSigned=*/true, B);
3317}
3318
3319// Fold calls to strtol, strtoll, strtoul, and strtoull.
3320Value *LibCallSimplifier::optimizeStrToInt(CallInst *CI, IRBuilderBase &B,
3321 bool AsSigned) {
3322 Value *EndPtr = CI->getArgOperand(1);
3323 if (isa<ConstantPointerNull>(EndPtr)) {
3324 // With a null EndPtr, this function won't capture the main argument.
3325 // It would be readonly too, except that it still may write to errno.
3328 EndPtr = nullptr;
3329 } else if (!isKnownNonZero(EndPtr, DL))
3330 return nullptr;
3331
3332 StringRef Str;
3333 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
3334 return nullptr;
3335
3336 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
3337 return convertStrToInt(CI, Str, EndPtr, CInt->getSExtValue(), AsSigned, B);
3338 }
3339
3340 return nullptr;
3341}
3342
3343//===----------------------------------------------------------------------===//
3344// Formatting and IO Library Call Optimizations
3345//===----------------------------------------------------------------------===//
3346
3347static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
3348
3349Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B,
3350 int StreamArg) {
3352 // Error reporting calls should be cold, mark them as such.
3353 // This applies even to non-builtin calls: it is only a hint and applies to
3354 // functions that the frontend might not understand as builtins.
3355
3356 // This heuristic was suggested in:
3357 // Improving Static Branch Prediction in a Compiler
3358 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
3359 // Proceedings of PACT'98, Oct. 1998, IEEE
3360 if (!CI->hasFnAttr(Attribute::Cold) &&
3361 isReportingError(Callee, CI, StreamArg)) {
3362 CI->addFnAttr(Attribute::Cold);
3363 }
3364
3365 return nullptr;
3366}
3367
3368static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
3369 if (!Callee || !Callee->isDeclaration())
3370 return false;
3371
3372 if (StreamArg < 0)
3373 return true;
3374
3375 // These functions might be considered cold, but only if their stream
3376 // argument is stderr.
3377
3378 if (StreamArg >= (int)CI->arg_size())
3379 return false;
3380 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
3381 if (!LI)
3382 return false;
3384 if (!GV || !GV->isDeclaration())
3385 return false;
3386 return GV->getName() == "stderr";
3387}
3388
3389Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) {
3390 // Check for a fixed format string.
3391 StringRef FormatStr;
3392 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
3393 return nullptr;
3394
3395 // Empty format string -> noop.
3396 if (FormatStr.empty()) // Tolerate printf's declared void.
3397 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
3398
3399 // Do not do any of the following transformations if the printf return value
3400 // is used, in general the printf return value is not compatible with either
3401 // putchar() or puts().
3402 if (!CI->use_empty())
3403 return nullptr;
3404
3405 Type *IntTy = CI->getType();
3406 // printf("x") -> putchar('x'), even for "%" and "%%".
3407 if (FormatStr.size() == 1 || FormatStr == "%%") {
3408 // Convert the character to unsigned char before passing it to putchar
3409 // to avoid host-specific sign extension in the IR. Putchar converts
3410 // it to unsigned char regardless.
3411 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)FormatStr[0]);
3412 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3413 }
3414
3415 // Try to remove call or emit putchar/puts.
3416 if (FormatStr == "%s" && CI->arg_size() > 1) {
3417 StringRef OperandStr;
3418 if (!getConstantStringInfo(CI->getOperand(1), OperandStr))
3419 return nullptr;
3420 // printf("%s", "") --> NOP
3421 if (OperandStr.empty())
3422 return (Value *)CI;
3423 // printf("%s", "a") --> putchar('a')
3424 if (OperandStr.size() == 1) {
3425 // Convert the character to unsigned char before passing it to putchar
3426 // to avoid host-specific sign extension in the IR. Putchar converts
3427 // it to unsigned char regardless.
3428 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)OperandStr[0]);
3429 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3430 }
3431 // printf("%s", str"\n") --> puts(str)
3432 if (OperandStr.back() == '\n') {
3433 if (!isLibFuncEmittable(CI->getModule(), TLI, LibFunc_puts))
3434 return nullptr;
3435 OperandStr = OperandStr.drop_back();
3436 Value *GV = B.CreateGlobalString(OperandStr, "str");
3437 return copyFlags(*CI, emitPutS(GV, B, TLI));
3438 }
3439 return nullptr;
3440 }
3441
3442 // printf("foo\n") --> puts("foo")
3443 if (FormatStr.back() == '\n' &&
3444 !FormatStr.contains('%')) { // No format characters.
3445 if (!isLibFuncEmittable(CI->getModule(), TLI, LibFunc_puts))
3446 return nullptr;
3447 // Create a string literal with no \n on it. We expect the constant merge
3448 // pass to be run after this pass, to merge duplicate strings.
3449 FormatStr = FormatStr.drop_back();
3450 Value *GV = B.CreateGlobalString(FormatStr, "str");
3451 return copyFlags(*CI, emitPutS(GV, B, TLI));
3452 }
3453
3454 // Optimize specific format strings.
3455 // printf("%c", chr) --> putchar(chr)
3456 if (FormatStr == "%c" && CI->arg_size() > 1 &&
3457 CI->getArgOperand(1)->getType()->isIntegerTy()) {
3458 // Convert the argument to the type expected by putchar, i.e., int, which
3459 // need not be 32 bits wide but which is the same as printf's return type.
3460 Value *IntChar = B.CreateIntCast(CI->getArgOperand(1), IntTy, false);
3461 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3462 }
3463
3464 // printf("%s\n", str) --> puts(str)
3465 if (FormatStr == "%s\n" && CI->arg_size() > 1 &&
3466 CI->getArgOperand(1)->getType()->isPointerTy())
3467 return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI));
3468 return nullptr;
3469}
3470
3471Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) {
3472
3473 Module *M = CI->getModule();
3475 FunctionType *FT = Callee->getFunctionType();
3476 if (Value *V = optimizePrintFString(CI, B)) {
3477 return V;
3478 }
3479
3481
3482 // printf(format, ...) -> iprintf(format, ...) if no floating point
3483 // arguments.
3484 if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) &&
3486 FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT,
3487 Callee->getAttributes());
3488 CallInst *New = cast<CallInst>(CI->clone());
3489 New->setCalledFunction(IPrintFFn);
3490 B.Insert(New);
3491 return New;
3492 }
3493
3494 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
3495 // arguments.
3496 if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) &&
3497 !callHasFP128Argument(CI)) {
3498 auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT,
3499 Callee->getAttributes());
3500 CallInst *New = cast<CallInst>(CI->clone());
3501 New->setCalledFunction(SmallPrintFFn);
3502 B.Insert(New);
3503 return New;
3504 }
3505
3506 return nullptr;
3507}
3508
3509Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI,
3510 IRBuilderBase &B) {
3511 // Check for a fixed format string.
3512 StringRef FormatStr;
3513 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
3514 return nullptr;
3515
3516 // If we just have a format string (nothing else crazy) transform it.
3517 Value *Dest = CI->getArgOperand(0);
3518 if (CI->arg_size() == 2) {
3519 // Make sure there's no % in the constant array. We could try to handle
3520 // %% -> % in the future if we cared.
3521 if (FormatStr.contains('%'))
3522 return nullptr; // we found a format specifier, bail out.
3523
3524 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
3525 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(1), Align(1),
3526 // Copy the null byte.
3527 TLI->getAsSizeT(FormatStr.size() + 1, *CI->getModule()));
3528 return ConstantInt::get(CI->getType(), FormatStr.size());
3529 }
3530
3531 // The remaining optimizations require the format string to be "%s" or "%c"
3532 // and have an extra operand.
3533 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
3534 return nullptr;
3535
3536 // Decode the second character of the format string.
3537 if (FormatStr[1] == 'c') {
3538 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
3539 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
3540 return nullptr;
3541 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
3542 Value *Ptr = Dest;
3543 B.CreateStore(V, Ptr);
3544 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
3545 B.CreateStore(B.getInt8(0), Ptr);
3546
3547 return ConstantInt::get(CI->getType(), 1);
3548 }
3549
3550 if (FormatStr[1] == 's') {
3551 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
3552 // strlen(str)+1)
3553 if (!CI->getArgOperand(2)->getType()->isPointerTy())
3554 return nullptr;
3555
3556 if (CI->use_empty())
3557 // sprintf(dest, "%s", str) -> strcpy(dest, str)
3558 return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI));
3559
3560 uint64_t SrcLen = GetStringLength(CI->getArgOperand(2));
3561 if (SrcLen) {
3562 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1),
3563 TLI->getAsSizeT(SrcLen, *CI->getModule()));
3564 // Returns total number of characters written without null-character.
3565 return ConstantInt::get(CI->getType(), SrcLen - 1);
3566 } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) {
3567 // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest
3568 Value *PtrDiff = B.CreatePtrDiff(V, Dest);
3569 return B.CreateIntCast(PtrDiff, CI->getType(), false);
3570 }
3571
3572 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
3574 return nullptr;
3575
3576 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
3577 if (!Len)
3578 return nullptr;
3579 Value *IncLen =
3580 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
3581 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen);
3582
3583 // The sprintf result is the unincremented number of bytes in the string.
3584 return B.CreateIntCast(Len, CI->getType(), false);
3585 }
3586 return nullptr;
3587}
3588
3589Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) {
3590 Module *M = CI->getModule();
3592 FunctionType *FT = Callee->getFunctionType();
3593 if (Value *V = optimizeSPrintFString(CI, B)) {
3594 return V;
3595 }
3596
3598
3599 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
3600 // point arguments.
3601 if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) &&
3603 FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf,
3604 FT, Callee->getAttributes());
3605 CallInst *New = cast<CallInst>(CI->clone());
3606 New->setCalledFunction(SIPrintFFn);
3607 B.Insert(New);
3608 return New;
3609 }
3610
3611 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
3612 // floating point arguments.
3613 if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) &&
3614 !callHasFP128Argument(CI)) {
3615 auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT,
3616 Callee->getAttributes());
3617 CallInst *New = cast<CallInst>(CI->clone());
3618 New->setCalledFunction(SmallSPrintFFn);
3619 B.Insert(New);
3620 return New;
3621 }
3622
3623 return nullptr;
3624}
3625
3626// Transform an snprintf call CI with the bound N to format the string Str
3627// either to a call to memcpy, or to single character a store, or to nothing,
3628// and fold the result to a constant. A nonnull StrArg refers to the string
3629// argument being formatted. Otherwise the call is one with N < 2 and
3630// the "%c" directive to format a single character.
3631Value *LibCallSimplifier::emitSnPrintfMemCpy(CallInst *CI, Value *StrArg,
3632 StringRef Str, uint64_t N,
3633 IRBuilderBase &B) {
3634 assert(StrArg || (N < 2 && Str.size() == 1));
3635
3636 unsigned IntBits = TLI->getIntSize();
3637 uint64_t IntMax = maxIntN(IntBits);
3638 if (Str.size() > IntMax)
3639 // Bail if the string is longer than INT_MAX. POSIX requires
3640 // implementations to set errno to EOVERFLOW in this case, in
3641 // addition to when N is larger than that (checked by the caller).
3642 return nullptr;
3643
3644 Value *StrLen = ConstantInt::get(CI->getType(), Str.size());
3645 if (N == 0)
3646 return StrLen;
3647
3648 // Set to the number of bytes to copy fron StrArg which is also
3649 // the offset of the terinating nul.
3650 uint64_t NCopy;
3651 if (N > Str.size())
3652 // Copy the full string, including the terminating nul (which must
3653 // be present regardless of the bound).
3654 NCopy = Str.size() + 1;
3655 else
3656 NCopy = N - 1;
3657
3658 Value *DstArg = CI->getArgOperand(0);
3659 if (NCopy && StrArg)
3660 // Transform the call to lvm.memcpy(dst, fmt, N).
3661 copyFlags(*CI, B.CreateMemCpy(DstArg, Align(1), StrArg, Align(1),
3662 TLI->getAsSizeT(NCopy, *CI->getModule())));
3663
3664 if (N > Str.size())
3665 // Return early when the whole format string, including the final nul,
3666 // has been copied.
3667 return StrLen;
3668
3669 // Otherwise, when truncating the string append a terminating nul.
3670 Type *Int8Ty = B.getInt8Ty();
3671 Value *NulOff = B.getIntN(IntBits, NCopy);
3672 Value *DstEnd = B.CreateInBoundsGEP(Int8Ty, DstArg, NulOff, "endptr");
3673 B.CreateStore(ConstantInt::get(Int8Ty, 0), DstEnd);
3674 return StrLen;
3675}
3676
3677Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI,
3678 IRBuilderBase &B) {
3679 // Check for size
3680 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3681 if (!Size)
3682 return nullptr;
3683
3684 uint64_t N = Size->getZExtValue();
3685 uint64_t IntMax = maxIntN(TLI->getIntSize());
3686 if (N > IntMax)
3687 // Bail if the bound exceeds INT_MAX. POSIX requires implementations
3688 // to set errno to EOVERFLOW in this case.
3689 return nullptr;
3690
3691 Value *DstArg = CI->getArgOperand(0);
3692 Value *FmtArg = CI->getArgOperand(2);
3693
3694 // Check for a fixed format string.
3695 StringRef FormatStr;
3696 if (!getConstantStringInfo(FmtArg, FormatStr))
3697 return nullptr;
3698
3699 // If we just have a format string (nothing else crazy) transform it.
3700 if (CI->arg_size() == 3) {
3701 if (FormatStr.contains('%'))
3702 // Bail if the format string contains a directive and there are
3703 // no arguments. We could handle "%%" in the future.
3704 return nullptr;
3705
3706 return emitSnPrintfMemCpy(CI, FmtArg, FormatStr, N, B);
3707 }
3708
3709 // The remaining optimizations require the format string to be "%s" or "%c"
3710 // and have an extra operand.
3711 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() != 4)
3712 return nullptr;
3713
3714 // Decode the second character of the format string.
3715 if (FormatStr[1] == 'c') {
3716 if (N <= 1) {
3717 // Use an arbitary string of length 1 to transform the call into
3718 // either a nul store (N == 1) or a no-op (N == 0) and fold it
3719 // to one.
3720 StringRef CharStr("*");
3721 return emitSnPrintfMemCpy(CI, nullptr, CharStr, N, B);
3722 }
3723
3724 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
3725 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
3726 return nullptr;
3727 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
3728 Value *Ptr = DstArg;
3729 B.CreateStore(V, Ptr);
3730 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
3731 B.CreateStore(B.getInt8(0), Ptr);
3732 return ConstantInt::get(CI->getType(), 1);
3733 }
3734
3735 if (FormatStr[1] != 's')
3736 return nullptr;
3737
3738 Value *StrArg = CI->getArgOperand(3);
3739 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
3740 StringRef Str;
3741 if (!getConstantStringInfo(StrArg, Str))
3742 return nullptr;
3743
3744 return emitSnPrintfMemCpy(CI, StrArg, Str, N, B);
3745}
3746
3747Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) {
3748 if (Value *V = optimizeSnPrintFString(CI, B)) {
3749 return V;
3750 }
3751
3752 if (isKnownNonZero(CI->getOperand(1), DL))
3754 return nullptr;
3755}
3756
3757Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI,
3758 IRBuilderBase &B) {
3759 optimizeErrorReporting(CI, B, 0);
3760
3761 // All the optimizations depend on the format string.
3762 StringRef FormatStr;
3763 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
3764 return nullptr;
3765
3766 // Do not do any of the following transformations if the fprintf return
3767 // value is used, in general the fprintf return value is not compatible
3768 // with fwrite(), fputc() or fputs().
3769 if (!CI->use_empty())
3770 return nullptr;
3771
3772 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
3773 if (CI->arg_size() == 2) {
3774 // Could handle %% -> % if we cared.
3775 if (FormatStr.contains('%'))
3776 return nullptr; // We found a format specifier.
3777
3778 return copyFlags(
3779 *CI, emitFWrite(CI->getArgOperand(1),
3780 TLI->getAsSizeT(FormatStr.size(), *CI->getModule()),
3781 CI->getArgOperand(0), B, DL, TLI));
3782 }
3783
3784 // The remaining optimizations require the format string to be "%s" or "%c"
3785 // and have an extra operand.
3786 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
3787 return nullptr;
3788
3789 // Decode the second character of the format string.
3790 if (FormatStr[1] == 'c') {
3791 // fprintf(F, "%c", chr) --> fputc((int)chr, F)
3792 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
3793 return nullptr;
3794 Type *IntTy = B.getIntNTy(TLI->getIntSize());
3795 Value *V = B.CreateIntCast(CI->getArgOperand(2), IntTy, /*isSigned*/ true,
3796 "chari");
3797 return copyFlags(*CI, emitFPutC(V, CI->getArgOperand(0), B, TLI));
3798 }
3799
3800 if (FormatStr[1] == 's') {
3801 // fprintf(F, "%s", str) --> fputs(str, F)
3802 if (!CI->getArgOperand(2)->getType()->isPointerTy())
3803 return nullptr;
3804 return copyFlags(
3805 *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
3806 }
3807 return nullptr;
3808}
3809
3810Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) {
3811 Module *M = CI->getModule();
3813 FunctionType *FT = Callee->getFunctionType();
3814 if (Value *V = optimizeFPrintFString(CI, B)) {
3815 return V;
3816 }
3817
3818 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
3819 // floating point arguments.
3820 if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) &&
3822 FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf,
3823 FT, Callee->getAttributes());
3824 CallInst *New = cast<CallInst>(CI->clone());
3825 New->setCalledFunction(FIPrintFFn);
3826 B.Insert(New);
3827 return New;
3828 }
3829
3830 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
3831 // 128-bit floating point arguments.
3832 if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) &&
3833 !callHasFP128Argument(CI)) {
3834 auto SmallFPrintFFn =
3835 getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT,
3836 Callee->getAttributes());
3837 CallInst *New = cast<CallInst>(CI->clone());
3838 New->setCalledFunction(SmallFPrintFFn);
3839 B.Insert(New);
3840 return New;
3841 }
3842
3843 return nullptr;
3844}
3845
3846Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) {
3847 optimizeErrorReporting(CI, B, 3);
3848
3849 // Get the element size and count.
3850 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3851 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
3852 if (SizeC && CountC) {
3853 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
3854
3855 // If this is writing zero records, remove the call (it's a noop).
3856 if (Bytes == 0)
3857 return ConstantInt::get(CI->getType(), 0);
3858
3859 // If this is writing one byte, turn it into fputc.
3860 // This optimisation is only valid, if the return value is unused.
3861 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
3862 Value *Char = B.CreateLoad(B.getInt8Ty(), CI->getArgOperand(0), "char");
3863 Type *IntTy = B.getIntNTy(TLI->getIntSize());
3864 Value *Cast = B.CreateIntCast(Char, IntTy, /*isSigned*/ true, "chari");
3865 Value *NewCI = emitFPutC(Cast, CI->getArgOperand(3), B, TLI);
3866 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
3867 }
3868 }
3869
3870 return nullptr;
3871}
3872
3873Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) {
3874 optimizeErrorReporting(CI, B, 1);
3875
3876 // Don't rewrite fputs to fwrite when optimising for size because fwrite
3877 // requires more arguments and thus extra MOVs are required.
3878 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
3880 return nullptr;
3881
3882 // We can't optimize if return value is used.
3883 if (!CI->use_empty())
3884 return nullptr;
3885
3886 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
3887 uint64_t Len = GetStringLength(CI->getArgOperand(0));
3888 if (!Len)
3889 return nullptr;
3890
3891 // Known to have no uses (see above).
3892 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
3893 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
3894 return copyFlags(
3895 *CI,
3897 ConstantInt::get(SizeTTy, Len - 1),
3898 CI->getArgOperand(1), B, DL, TLI));
3899}
3900
3901Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) {
3903 if (!CI->use_empty())
3904 return nullptr;
3905
3906 // Check for a constant string.
3907 // puts("") -> putchar('\n')
3908 StringRef Str;
3909 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) {
3910 // putchar takes an argument of the same type as puts returns, i.e.,
3911 // int, which need not be 32 bits wide.
3912 Type *IntTy = CI->getType();
3913 return copyFlags(*CI, emitPutChar(ConstantInt::get(IntTy, '\n'), B, TLI));
3914 }
3915
3916 return nullptr;
3917}
3918
3919Value *LibCallSimplifier::optimizeExit(CallInst *CI) {
3920
3921 // Mark 'exit' as cold if its not exit(0) (success).
3922 const APInt *C;
3923 if (!CI->hasFnAttr(Attribute::Cold) &&
3924 match(CI->getArgOperand(0), m_APInt(C)) && !C->isZero()) {
3925 CI->addFnAttr(Attribute::Cold);
3926 }
3927 return nullptr;
3928}
3929
3930Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) {
3931 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
3932 return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1),
3933 CI->getArgOperand(0), Align(1),
3934 CI->getArgOperand(2)));
3935}
3936
3937bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) {
3938 SmallString<20> FloatFuncName = FuncName;
3939 FloatFuncName += 'f';
3940 return isLibFuncEmittable(M, TLI, FloatFuncName);
3941}
3942
3943Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
3944 IRBuilderBase &Builder) {
3945 Module *M = CI->getModule();
3946 LibFunc Func;
3948
3949 // Check for string/memory library functions.
3950 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
3951 // Make sure we never change the calling convention.
3952 assert(
3953 (ignoreCallingConv(Func) ||
3955 "Optimizing string/memory libcall would change the calling convention");
3956 switch (Func) {
3957 case LibFunc_strcat:
3958 return optimizeStrCat(CI, Builder);
3959 case LibFunc_strncat:
3960 return optimizeStrNCat(CI, Builder);
3961 case LibFunc_strchr:
3962 return optimizeStrChr(CI, Builder);
3963 case LibFunc_strrchr:
3964 return optimizeStrRChr(CI, Builder);
3965 case LibFunc_strcmp:
3966 return optimizeStrCmp(CI, Builder);
3967 case LibFunc_strncmp:
3968 return optimizeStrNCmp(CI, Builder);
3969 case LibFunc_strcpy:
3970 return optimizeStrCpy(CI, Builder);
3971 case LibFunc_stpcpy:
3972 return optimizeStpCpy(CI, Builder);
3973 case LibFunc_strlcpy:
3974 return optimizeStrLCpy(CI, Builder);
3975 case LibFunc_stpncpy:
3976 return optimizeStringNCpy(CI, /*RetEnd=*/true, Builder);
3977 case LibFunc_strncpy:
3978 return optimizeStringNCpy(CI, /*RetEnd=*/false, Builder);
3979 case LibFunc_strlen:
3980 return optimizeStrLen(CI, Builder);
3981 case LibFunc_strnlen:
3982 return optimizeStrNLen(CI, Builder);
3983 case LibFunc_strpbrk:
3984 return optimizeStrPBrk(CI, Builder);
3985 case LibFunc_strndup:
3986 return optimizeStrNDup(CI, Builder);
3987 case LibFunc_strtol:
3988 case LibFunc_strtod:
3989 case LibFunc_strtof:
3990 case LibFunc_strtoul:
3991 case LibFunc_strtoll:
3992 case LibFunc_strtold:
3993 case LibFunc_strtoull:
3994 return optimizeStrTo(CI, Builder);
3995 case LibFunc_strspn:
3996 return optimizeStrSpn(CI, Builder);
3997 case LibFunc_strcspn:
3998 return optimizeStrCSpn(CI, Builder);
3999 case LibFunc_strstr:
4000 return optimizeStrStr(CI, Builder);
4001 case LibFunc_memchr:
4002 return optimizeMemChr(CI, Builder);
4003 case LibFunc_memrchr:
4004 return optimizeMemRChr(CI, Builder);
4005 case LibFunc_bcmp:
4006 return optimizeBCmp(CI, Builder);
4007 case LibFunc_memcmp:
4008 return optimizeMemCmp(CI, Builder);
4009 case LibFunc_memcpy:
4010 return optimizeMemCpy(CI, Builder);
4011 case LibFunc_memccpy:
4012 return optimizeMemCCpy(CI, Builder);
4013 case LibFunc_mempcpy:
4014 return optimizeMemPCpy(CI, Builder);
4015 case LibFunc_memmove:
4016 return optimizeMemMove(CI, Builder);
4017 case LibFunc_memset:
4018 return optimizeMemSet(CI, Builder);
4019 case LibFunc_realloc:
4020 return optimizeRealloc(CI, Builder);
4021 case LibFunc_wcslen:
4022 return optimizeWcslen(CI, Builder);
4023 case LibFunc_bcopy:
4024 return optimizeBCopy(CI, Builder);
4025 case LibFunc_Znwm:
4026 case LibFunc_ZnwmRKSt9nothrow_t:
4027 case LibFunc_ZnwmSt11align_val_t:
4028 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
4029 case LibFunc_Znam:
4030 case LibFunc_ZnamRKSt9nothrow_t:
4031 case LibFunc_ZnamSt11align_val_t:
4032 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
4033 case LibFunc_Znwm12__hot_cold_t:
4034 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
4035 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
4036 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
4037 case LibFunc_Znam12__hot_cold_t:
4038 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
4039 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
4040 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
4041 case LibFunc_size_returning_new:
4042 case LibFunc_size_returning_new_hot_cold:
4043 case LibFunc_size_returning_new_aligned:
4044 case LibFunc_size_returning_new_aligned_hot_cold:
4045 return optimizeNew(CI, Builder, Func);
4046 default:
4047 break;
4048 }
4049 }
4050 return nullptr;
4051}
4052
4053/// Constant folding nan/nanf/nanl.
4055 StringRef CharSeq;
4056 if (!getConstantStringInfo(CI->getArgOperand(0), CharSeq))
4057 return nullptr;
4058
4059 APInt Fill;
4060 // Treat empty strings as if they were zero.
4061 if (CharSeq.empty())
4062 Fill = APInt(32, 0);
4063 else if (CharSeq.getAsInteger(0, Fill))
4064 return nullptr;
4065
4066 return ConstantFP::getQNaN(CI->getType(), /*Negative=*/false, &Fill);
4067}
4068
4069Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
4070 LibFunc Func,
4071 IRBuilderBase &Builder) {
4072 const Module *M = CI->getModule();
4073
4074 // Don't optimize calls that require strict floating point semantics.
4075 if (CI->isStrictFP())
4076 return nullptr;
4077
4078 if (Value *V = optimizeSymmetric(CI, Func, Builder))
4079 return V;
4080
4081 switch (Func) {
4082 case LibFunc_sinpif:
4083 case LibFunc_sinpi:
4084 return optimizeSinCosPi(CI, /*IsSin*/true, Builder);
4085 case LibFunc_cospif:
4086 case LibFunc_cospi:
4087 return optimizeSinCosPi(CI, /*IsSin*/false, Builder);
4088 case LibFunc_sinf:
4089 case LibFunc_sinl:
4090 if (CI->doesNotAccessMemory())
4091 return replaceUnaryCall(CI, Builder, Intrinsic::sin);
4092 return nullptr;
4093 case LibFunc_cosf:
4094 case LibFunc_cosl:
4095 if (CI->doesNotAccessMemory())
4096 return replaceUnaryCall(CI, Builder, Intrinsic::cos);
4097 return nullptr;
4098 case LibFunc_powf:
4099 case LibFunc_pow:
4100 case LibFunc_powl:
4101 return optimizePow(CI, Builder);
4102 case LibFunc_exp2l:
4103 case LibFunc_exp2:
4104 case LibFunc_exp2f:
4105 return optimizeExp2(CI, Builder);
4106 case LibFunc_fabsf:
4107 case LibFunc_fabs:
4108 case LibFunc_fabsl:
4109 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
4110 case LibFunc_sqrtf:
4111 case LibFunc_sqrt:
4112 case LibFunc_sqrtl:
4113 return optimizeSqrt(CI, Builder);
4114 case LibFunc_fmod:
4115 case LibFunc_fmodf:
4116 case LibFunc_fmodl:
4117 return optimizeFMod(CI, Builder);
4118 case LibFunc_logf:
4119 case LibFunc_log:
4120 case LibFunc_logl:
4121 case LibFunc_log10f:
4122 case LibFunc_log10:
4123 case LibFunc_log10l:
4124 case LibFunc_log1pf:
4125 case LibFunc_log1p:
4126 case LibFunc_log1pl:
4127 case LibFunc_log2f:
4128 case LibFunc_log2:
4129 case LibFunc_log2l:
4130 case LibFunc_logbf:
4131 case LibFunc_logb:
4132 case LibFunc_logbl:
4133 return optimizeLog(CI, Builder);
4134 case LibFunc_tan:
4135 case LibFunc_tanf:
4136 case LibFunc_tanl:
4137 case LibFunc_sinh:
4138 case LibFunc_sinhf:
4139 case LibFunc_sinhl:
4140 case LibFunc_asinh:
4141 case LibFunc_asinhf:
4142 case LibFunc_asinhl:
4143 case LibFunc_cosh:
4144 case LibFunc_coshf:
4145 case LibFunc_coshl:
4146 case LibFunc_atanh:
4147 case LibFunc_atanhf:
4148 case LibFunc_atanhl:
4149 return optimizeTrigInversionPairs(CI, Builder);
4150 case LibFunc_ceil:
4151 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
4152 case LibFunc_floor:
4153 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
4154 case LibFunc_round:
4155 return replaceUnaryCall(CI, Builder, Intrinsic::round);
4156 case LibFunc_roundeven:
4157 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven);
4158 case LibFunc_nearbyint:
4159 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
4160 case LibFunc_rint:
4161 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
4162 case LibFunc_trunc:
4163 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
4164 case LibFunc_sin:
4165 case LibFunc_cos:
4166 if (UnsafeFPShrink &&
4167 hasFloatVersion(M, CI->getCalledFunction()->getName()))
4168 if (Value *V = optimizeUnaryDoubleFP(CI, Builder, TLI, true))
4169 return V;
4170 if (CI->doesNotAccessMemory())
4171 return replaceUnaryCall(
4172 CI, Builder, Func == LibFunc_sin ? Intrinsic::sin : Intrinsic::cos);
4173 return nullptr;
4174 case LibFunc_acos:
4175 case LibFunc_acosh:
4176 case LibFunc_asin:
4177 case LibFunc_atan:
4178 case LibFunc_cbrt:
4179 case LibFunc_exp:
4180 case LibFunc_exp10:
4181 case LibFunc_expm1:
4182 case LibFunc_tanh:
4183 if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName()))
4184 return optimizeUnaryDoubleFP(CI, Builder, TLI, true);
4185 return nullptr;
4186 case LibFunc_copysign:
4187 if (hasFloatVersion(M, CI->getCalledFunction()->getName()))
4188 return optimizeBinaryDoubleFP(CI, Builder, TLI);
4189 return nullptr;
4190 case LibFunc_fdim:
4191 case LibFunc_fdimf:
4192 case LibFunc_fdiml:
4193 return optimizeFdim(CI, Builder);
4194 case LibFunc_fminf:
4195 case LibFunc_fmin:
4196 case LibFunc_fminl:
4197 return optimizeFMinFMax(CI, Builder, Intrinsic::minnum);
4198 case LibFunc_fmaxf:
4199 case LibFunc_fmax:
4200 case LibFunc_fmaxl:
4201 return optimizeFMinFMax(CI, Builder, Intrinsic::maxnum);
4202 case LibFunc_fminimum_numf:
4203 case LibFunc_fminimum_num:
4204 case LibFunc_fminimum_numl:
4205 return replaceBinaryCall(CI, Builder, Intrinsic::minimumnum);
4206 case LibFunc_fmaximum_numf:
4207 case LibFunc_fmaximum_num:
4208 case LibFunc_fmaximum_numl:
4209 return replaceBinaryCall(CI, Builder, Intrinsic::maximumnum);
4210 case LibFunc_cabs:
4211 case LibFunc_cabsf:
4212 case LibFunc_cabsl:
4213 return optimizeCAbs(CI, Builder);
4214 case LibFunc_remquo:
4215 case LibFunc_remquof:
4216 case LibFunc_remquol:
4217 return optimizeRemquo(CI, Builder);
4218 case LibFunc_nan:
4219 case LibFunc_nanf:
4220 case LibFunc_nanl:
4221 return optimizeNaN(CI);
4222 default:
4223 return nullptr;
4224 }
4225}
4226
4228 Module *M = CI->getModule();
4229 assert(!CI->isMustTailCall() && "These transforms aren't musttail safe.");
4230
4231 // TODO: Split out the code below that operates on FP calls so that
4232 // we can all non-FP calls with the StrictFP attribute to be
4233 // optimized.
4234 if (CI->isNoBuiltin()) {
4235 // Optionally update operator new calls.
4236 return maybeOptimizeNoBuiltinOperatorNew(CI, Builder);
4237 }
4238
4239 LibFunc Func;
4240 Function *Callee = CI->getCalledFunction();
4241 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
4242
4244 CI->getOperandBundlesAsDefs(OpBundles);
4245
4247 Builder.setDefaultOperandBundles(OpBundles);
4248
4249 // Command-line parameter overrides instruction attribute.
4250 // This can't be moved to optimizeFloatingPointLibCall() because it may be
4251 // used by the intrinsic optimizations.
4252 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
4253 UnsafeFPShrink = EnableUnsafeFPShrink;
4254 else if (isa<FPMathOperator>(CI) && CI->isFast())
4255 UnsafeFPShrink = true;
4256
4257 // First, check for intrinsics.
4259 if (!IsCallingConvC)
4260 return nullptr;
4261 // The FP intrinsics have corresponding constrained versions so we don't
4262 // need to check for the StrictFP attribute here.
4263 switch (II->getIntrinsicID()) {
4264 case Intrinsic::pow:
4265 return optimizePow(CI, Builder);
4266 case Intrinsic::exp2:
4267 return optimizeExp2(CI, Builder);
4268 case Intrinsic::log:
4269 case Intrinsic::log2:
4270 case Intrinsic::log10:
4271 return optimizeLog(CI, Builder);
4272 case Intrinsic::sqrt:
4273 return optimizeSqrt(CI, Builder);
4274 case Intrinsic::memset:
4275 return optimizeMemSet(CI, Builder);
4276 case Intrinsic::memcpy:
4277 return optimizeMemCpy(CI, Builder);
4278 case Intrinsic::memmove:
4279 return optimizeMemMove(CI, Builder);
4280 case Intrinsic::sin:
4281 case Intrinsic::cos:
4282 if (UnsafeFPShrink)
4283 return optimizeUnaryDoubleFP(CI, Builder, TLI, /*isPrecise=*/true);
4284 return nullptr;
4285 case Intrinsic::sincos:
4286 if (UnsafeFPShrink)
4287 return optimizeSinCosDoubleFP(CI, Builder);
4288 return nullptr;
4289 default:
4290 return nullptr;
4291 }
4292 }
4293
4294 // Also try to simplify calls to fortified library functions.
4295 if (Value *SimplifiedFortifiedCI =
4296 FortifiedSimplifier.optimizeCall(CI, Builder))
4297 return SimplifiedFortifiedCI;
4298
4299 // Then check for known library functions.
4300 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
4301 // We never change the calling convention.
4302 if (!ignoreCallingConv(Func) && !IsCallingConvC)
4303 return nullptr;
4304 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
4305 return V;
4306 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
4307 return V;
4308 switch (Func) {
4309 case LibFunc_ffs:
4310 case LibFunc_ffsl:
4311 case LibFunc_ffsll:
4312 return optimizeFFS(CI, Builder);
4313 case LibFunc_fls:
4314 case LibFunc_flsl:
4315 case LibFunc_flsll:
4316 return optimizeFls(CI, Builder);
4317 case LibFunc_abs:
4318 case LibFunc_labs:
4319 case LibFunc_llabs:
4320 return optimizeAbs(CI, Builder);
4321 case LibFunc_isdigit:
4322 return optimizeIsDigit(CI, Builder);
4323 case LibFunc_isascii:
4324 return optimizeIsAscii(CI, Builder);
4325 case LibFunc_toascii:
4326 return optimizeToAscii(CI, Builder);
4327 case LibFunc_atoi:
4328 case LibFunc_atol:
4329 case LibFunc_atoll:
4330 return optimizeAtoi(CI, Builder);
4331 case LibFunc_strtol:
4332 case LibFunc_strtoll:
4333 return optimizeStrToInt(CI, Builder, /*AsSigned=*/true);
4334 case LibFunc_strtoul:
4335 case LibFunc_strtoull:
4336 return optimizeStrToInt(CI, Builder, /*AsSigned=*/false);
4337 case LibFunc_printf:
4338 return optimizePrintF(CI, Builder);
4339 case LibFunc_sprintf:
4340 return optimizeSPrintF(CI, Builder);
4341 case LibFunc_snprintf:
4342 return optimizeSnPrintF(CI, Builder);
4343 case LibFunc_fprintf:
4344 return optimizeFPrintF(CI, Builder);
4345 case LibFunc_fwrite:
4346 return optimizeFWrite(CI, Builder);
4347 case LibFunc_fputs:
4348 return optimizeFPuts(CI, Builder);
4349 case LibFunc_puts:
4350 return optimizePuts(CI, Builder);
4351 case LibFunc_perror:
4352 return optimizeErrorReporting(CI, Builder);
4353 case LibFunc_vfprintf:
4354 case LibFunc_fiprintf:
4355 return optimizeErrorReporting(CI, Builder, 0);
4356 case LibFunc_exit:
4357 case LibFunc_Exit:
4358 return optimizeExit(CI);
4359 default:
4360 return nullptr;
4361 }
4362 }
4363 return nullptr;
4364}
4365
4367 const DataLayout &DL, const TargetLibraryInfo *TLI, DominatorTree *DT,
4370 function_ref<void(Instruction *, Value *)> Replacer,
4371 function_ref<void(Instruction *)> Eraser)
4372 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), DT(DT), DC(DC), AC(AC),
4373 ORE(ORE), BFI(BFI), PSI(PSI), Replacer(Replacer), Eraser(Eraser) {}
4374
4375void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
4376 // Indirect through the replacer used in this instance.
4377 Replacer(I, With);
4378}
4379
4380void LibCallSimplifier::eraseFromParent(Instruction *I) {
4381 Eraser(I);
4382}
4383
4384// TODO:
4385// Additional cases that we need to add to this file:
4386//
4387// cbrt:
4388// * cbrt(expN(X)) -> expN(x/3)
4389// * cbrt(sqrt(x)) -> pow(x,1/6)
4390// * cbrt(cbrt(x)) -> pow(x,1/9)
4391//
4392// exp, expf, expl:
4393// * exp(log(x)) -> x
4394//
4395// log, logf, logl:
4396// * log(exp(x)) -> x
4397// * log(exp(y)) -> y*log(e)
4398// * log(exp10(y)) -> y*log(10)
4399// * log(sqrt(x)) -> 0.5*log(x)
4400//
4401// pow, powf, powl:
4402// * pow(sqrt(x),y) -> pow(x,y*0.5)
4403// * pow(pow(x,y),z)-> pow(x,y*z)
4404//
4405// signbit:
4406// * signbit(cnst) -> cnst'
4407// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
4408//
4409// sqrt, sqrtf, sqrtl:
4410// * sqrt(expN(x)) -> expN(x*0.5)
4411// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
4412// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
4413//
4414
4415//===----------------------------------------------------------------------===//
4416// Fortified Library Call Optimizations
4417//===----------------------------------------------------------------------===//
4418
4419bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(
4420 CallInst *CI, unsigned ObjSizeOp, std::optional<unsigned> SizeOp,
4421 std::optional<unsigned> StrOp, std::optional<unsigned> FlagOp) {
4422 // If this function takes a flag argument, the implementation may use it to
4423 // perform extra checks. Don't fold into the non-checking variant.
4424 if (FlagOp) {
4425 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
4426 if (!Flag || !Flag->isZero())
4427 return false;
4428 }
4429
4430 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
4431 return true;
4432
4433 if (ConstantInt *ObjSizeCI =
4434 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
4435 if (ObjSizeCI->isMinusOne())
4436 return true;
4437 // If the object size wasn't -1 (unknown), bail out if we were asked to.
4438 if (OnlyLowerUnknownSize)
4439 return false;
4440 if (StrOp) {
4441 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
4442 // If the length is 0 we don't know how long it is and so we can't
4443 // remove the check.
4444 if (Len)
4445 annotateDereferenceableBytes(CI, *StrOp, Len);
4446 else
4447 return false;
4448 return ObjSizeCI->getZExtValue() >= Len;
4449 }
4450
4451 if (SizeOp) {
4452 if (ConstantInt *SizeCI =
4454 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
4455 }
4456 }
4457 return false;
4458}
4459
4460Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
4461 IRBuilderBase &B) {
4462 if (isFortifiedCallFoldable(CI, 3, 2)) {
4463 CallInst *NewCI =
4464 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
4465 Align(1), CI->getArgOperand(2));
4466 mergeAttributesAndFlags(NewCI, *CI);
4467 return CI->getArgOperand(0);
4468 }
4469 return nullptr;
4470}
4471
4472Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
4473 IRBuilderBase &B) {
4474 if (isFortifiedCallFoldable(CI, 3, 2)) {
4475 CallInst *NewCI =
4476 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
4477 Align(1), CI->getArgOperand(2));
4478 mergeAttributesAndFlags(NewCI, *CI);
4479 return CI->getArgOperand(0);
4480 }
4481 return nullptr;
4482}
4483
4484Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
4485 IRBuilderBase &B) {
4486 if (isFortifiedCallFoldable(CI, 3, 2)) {
4487 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
4488 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val,
4489 CI->getArgOperand(2), Align(1));
4490 mergeAttributesAndFlags(NewCI, *CI);
4491 return CI->getArgOperand(0);
4492 }
4493 return nullptr;
4494}
4495
4496Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI,
4497 IRBuilderBase &B) {
4498 const DataLayout &DL = CI->getDataLayout();
4499 if (isFortifiedCallFoldable(CI, 3, 2))
4500 if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1),
4501 CI->getArgOperand(2), B, DL, TLI)) {
4503 }
4504 return nullptr;
4505}
4506
4507Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
4509 LibFunc Func) {
4510 const DataLayout &DL = CI->getDataLayout();
4511 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
4512 *ObjSize = CI->getArgOperand(2);
4513
4514 // __stpcpy_chk(x,x,...) -> x+strlen(x)
4515 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
4516 Value *StrLen = emitStrLen(Src, B, DL, TLI);
4517 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
4518 }
4519
4520 // If a) we don't have any length information, or b) we know this will
4521 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
4522 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
4523 // TODO: It might be nice to get a maximum length out of the possible
4524 // string lengths for varying.
4525 if (isFortifiedCallFoldable(CI, 2, std::nullopt, 1)) {
4526 if (Func == LibFunc_strcpy_chk)
4527 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
4528 else
4529 return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI));
4530 }
4531
4532 if (OnlyLowerUnknownSize)
4533 return nullptr;
4534
4535 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
4536 uint64_t Len = GetStringLength(Src);
4537 if (Len)
4538 annotateDereferenceableBytes(CI, 1, Len);
4539 else
4540 return nullptr;
4541
4542 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
4543 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
4544 Value *LenV = ConstantInt::get(SizeTTy, Len);
4545 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
4546 // If the function was an __stpcpy_chk, and we were able to fold it into
4547 // a __memcpy_chk, we still need to return the correct end pointer.
4548 if (Ret && Func == LibFunc_stpcpy_chk)
4549 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst,
4550 ConstantInt::get(SizeTTy, Len - 1));
4551 return copyFlags(*CI, cast<CallInst>(Ret));
4552}
4553
4554Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI,
4555 IRBuilderBase &B) {
4556 if (isFortifiedCallFoldable(CI, 1, std::nullopt, 0))
4557 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B,
4558 CI->getDataLayout(), TLI));
4559 return nullptr;
4560}
4561
4562Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
4564 LibFunc Func) {
4565 if (isFortifiedCallFoldable(CI, 3, 2)) {
4566 if (Func == LibFunc_strncpy_chk)
4567 return copyFlags(*CI,
4569 CI->getArgOperand(2), B, TLI));
4570 else
4571 return copyFlags(*CI,
4573 CI->getArgOperand(2), B, TLI));
4574 }
4575
4576 return nullptr;
4577}
4578
4579Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
4580 IRBuilderBase &B) {
4581 if (isFortifiedCallFoldable(CI, 4, 3))
4582 return copyFlags(
4583 *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
4584 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI));
4585
4586 return nullptr;
4587}
4588
4589Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
4590 IRBuilderBase &B) {
4591 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) {
4592 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5));
4593 return copyFlags(*CI,
4595 CI->getArgOperand(4), VariadicArgs, B, TLI));
4596 }
4597
4598 return nullptr;
4599}
4600
4601Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
4602 IRBuilderBase &B) {
4603 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) {
4604 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4));
4605 return copyFlags(*CI,
4607 VariadicArgs, B, TLI));
4608 }
4609
4610 return nullptr;
4611}
4612
4613Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
4614 IRBuilderBase &B) {
4615 if (isFortifiedCallFoldable(CI, 2))
4616 return copyFlags(
4617 *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI));
4618
4619 return nullptr;
4620}
4621
4622Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
4623 IRBuilderBase &B) {
4624 if (isFortifiedCallFoldable(CI, 3))
4625 return copyFlags(*CI,
4627 CI->getArgOperand(2), B, TLI));
4628
4629 return nullptr;
4630}
4631
4632Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
4633 IRBuilderBase &B) {
4634 if (isFortifiedCallFoldable(CI, 3))
4635 return copyFlags(*CI,
4637 CI->getArgOperand(2), B, TLI));
4638
4639 return nullptr;
4640}
4641
4642Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
4643 IRBuilderBase &B) {
4644 if (isFortifiedCallFoldable(CI, 3))
4645 return copyFlags(*CI,
4647 CI->getArgOperand(2), B, TLI));
4648
4649 return nullptr;
4650}
4651
4652Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
4653 IRBuilderBase &B) {
4654 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2))
4655 return copyFlags(
4656 *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
4657 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI));
4658
4659 return nullptr;
4660}
4661
4662Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
4663 IRBuilderBase &B) {
4664 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1))
4665 return copyFlags(*CI,
4667 CI->getArgOperand(4), B, TLI));
4668
4669 return nullptr;
4670}
4671
4673 IRBuilderBase &Builder) {
4674 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
4675 // Some clang users checked for _chk libcall availability using:
4676 // __has_builtin(__builtin___memcpy_chk)
4677 // When compiling with -fno-builtin, this is always true.
4678 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
4679 // end up with fortified libcalls, which isn't acceptable in a freestanding
4680 // environment which only provides their non-fortified counterparts.
4681 //
4682 // Until we change clang and/or teach external users to check for availability
4683 // differently, disregard the "nobuiltin" attribute and TLI::has.
4684 //
4685 // PR23093.
4686
4687 LibFunc Func;
4688 Function *Callee = CI->getCalledFunction();
4689 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
4690
4692 CI->getOperandBundlesAsDefs(OpBundles);
4693
4695 Builder.setDefaultOperandBundles(OpBundles);
4696
4697 // First, check that this is a known library functions and that the prototype
4698 // is correct.
4699 if (!TLI->getLibFunc(*Callee, Func))
4700 return nullptr;
4701
4702 // We never change the calling convention.
4703 if (!ignoreCallingConv(Func) && !IsCallingConvC)
4704 return nullptr;
4705
4706 switch (Func) {
4707 case LibFunc_memcpy_chk:
4708 return optimizeMemCpyChk(CI, Builder);
4709 case LibFunc_mempcpy_chk:
4710 return optimizeMemPCpyChk(CI, Builder);
4711 case LibFunc_memmove_chk:
4712 return optimizeMemMoveChk(CI, Builder);
4713 case LibFunc_memset_chk:
4714 return optimizeMemSetChk(CI, Builder);
4715 case LibFunc_stpcpy_chk:
4716 case LibFunc_strcpy_chk:
4717 return optimizeStrpCpyChk(CI, Builder, Func);
4718 case LibFunc_strlen_chk:
4719 return optimizeStrLenChk(CI, Builder);
4720 case LibFunc_stpncpy_chk:
4721 case LibFunc_strncpy_chk:
4722 return optimizeStrpNCpyChk(CI, Builder, Func);
4723 case LibFunc_memccpy_chk:
4724 return optimizeMemCCpyChk(CI, Builder);
4725 case LibFunc_snprintf_chk:
4726 return optimizeSNPrintfChk(CI, Builder);
4727 case LibFunc_sprintf_chk:
4728 return optimizeSPrintfChk(CI, Builder);
4729 case LibFunc_strcat_chk:
4730 return optimizeStrCatChk(CI, Builder);
4731 case LibFunc_strlcat_chk:
4732 return optimizeStrLCat(CI, Builder);
4733 case LibFunc_strncat_chk:
4734 return optimizeStrNCatChk(CI, Builder);
4735 case LibFunc_strlcpy_chk:
4736 return optimizeStrLCpyChk(CI, Builder);
4737 case LibFunc_vsnprintf_chk:
4738 return optimizeVSNPrintfChk(CI, Builder);
4739 case LibFunc_vsprintf_chk:
4740 return optimizeVSPrintfChk(CI, Builder);
4741 default:
4742 break;
4743 }
4744 return nullptr;
4745}
4746
4748 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
4749 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
static bool isBinary(MachineInstr &MI)
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
static bool isOnlyUsedInEqualityComparison(Value *V, Value *With)
Return true if it is only used in equality comparisons with With.
static Value * optimizeSinCosDoubleFP(CallInst *CI, IRBuilderBase &B)
Shrink double -> float for llvm.sincos.
static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef< unsigned > ArgNos, Value *Size, const DataLayout &DL)
static cl::opt< unsigned, false, HotColdHintParser > ColdNewHintValue("cold-new-hint-value", cl::Hidden, cl::init(1), cl::desc("Value to pass to hot/cold operator new for cold allocation"))
static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg, bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos, const TargetLibraryInfo *TLI)
static Value * mergeAttributesAndFlags(CallInst *NewCI, const CallInst &Old)
static cl::opt< bool > OptimizeHotColdNew("optimize-hot-cold-new", cl::Hidden, cl::init(false), cl::desc("Enable hot/cold operator new library calls"))
static Value * optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B, const TargetLibraryInfo *TLI, bool isPrecise=false)
Shrink double -> float for binary functions.
static bool ignoreCallingConv(LibFunc Func)
static cl::opt< bool > OptimizeExistingHotColdNew("optimize-existing-hot-cold-new", cl::Hidden, cl::init(false), cl::desc("Enable optimization of existing hot/cold operator new library calls"))
static void annotateDereferenceableBytes(CallInst *CI, ArrayRef< unsigned > ArgNos, uint64_t DereferenceableBytes)
static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg)
static Value * optimizeDoubleFP(CallInst *CI, IRBuilderBase &B, bool isBinary, const TargetLibraryInfo *TLI, bool isPrecise=false)
Shrink double -> float functions.
static Value * optimizeSymmetricCall(CallInst *CI, bool IsEven, IRBuilderBase &B)
static Value * getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, Module *M, IRBuilderBase &B, const TargetLibraryInfo *TLI)
static Value * replaceBinaryCall(CallInst *CI, IRBuilderBase &B, Intrinsic::ID IID)
static Value * valueHasFloatPrecision(Value *Val)
Return a variant of Val with float type.
static Value * optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS, uint64_t Len, IRBuilderBase &B, const DataLayout &DL)
static Value * createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, IRBuilderBase &B)
static Value * convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr, uint64_t Base, bool AsSigned, IRBuilderBase &B)
static Value * memChrToCharCompare(CallInst *CI, Value *NBytes, IRBuilderBase &B, const DataLayout &DL)
static Value * copyFlags(const CallInst &Old, Value *New)
static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, const SimplifyQuery &SQ)
static StringRef substr(StringRef Str, uint64_t Len)
static cl::opt< unsigned, false, HotColdHintParser > HotNewHintValue("hot-new-hint-value", cl::Hidden, cl::init(254), cl::desc("Value to pass to hot/cold operator new for hot allocation"))
static bool isTrigLibCall(CallInst *CI)
static Value * optimizeNaN(CallInst *CI)
Constant folding nan/nanf/nanl.
static bool isOnlyUsedInComparisonWithZero(Value *V)
static Value * replaceUnaryCall(CallInst *CI, IRBuilderBase &B, Intrinsic::ID IID)
static bool callHasFloatingPointArgument(const CallInst *CI)
static Value * optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B, const TargetLibraryInfo *TLI, bool isPrecise=false)
Shrink double -> float for unary functions.
static bool callHasFP128Argument(const CallInst *CI)
static cl::opt< bool > OptimizeNoBuiltinHotColdNew("optimize-nobuiltin-hot-cold-new-new", cl::Hidden, cl::init(false), cl::desc("Enable transformation of nobuiltin operator new library calls"))
static cl::opt< unsigned, false, HotColdHintParser > AmbiguousNewHintValue("ambiguous-new-hint-value", cl::Hidden, cl::init(222), cl::desc("Value to pass to hot/cold operator new for ambiguous allocation"))
static void annotateNonNullNoUndefBasedOnAccess(CallInst *CI, ArrayRef< unsigned > ArgNos)
static Value * optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS, Value *Size, bool StrNCmp, IRBuilderBase &B, const DataLayout &DL)
static Value * getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth)
static cl::opt< bool > EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden, cl::init(false), cl::desc("Enable unsafe double to float " "shrinking for math lib calls"))
static cl::opt< unsigned, false, HotColdHintParser > NotColdNewHintValue("notcold-new-hint-value", cl::Hidden, cl::init(128), cl::desc("Value to pass to hot/cold operator new for " "notcold (warm) allocation"))
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static constexpr roundingMode rmTowardZero
Definition APFloat.h:357
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:356
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:353
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:369
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1304
bool isFiniteNonZero() const
Definition APFloat.h:1585
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5934
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1286
bool isNegative() const
Definition APFloat.h:1575
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:5993
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Definition APFloat.h:1558
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1277
const fltSemantics & getSemantics() const
Definition APFloat.h:1583
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6021
opStatus remainder(const APFloat &RHS)
Definition APFloat.h:1313
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1428
bool isInteger() const
Definition APFloat.h:1592
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
static LLVM_ABI Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
static LLVM_ABI Attribute getWithCaptureInfo(LLVMContext &Context, CaptureInfo CI)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
void removeParamAttrs(unsigned ArgNo, const AttributeMask &AttrsToRemove)
Removes the attributes from the given argument.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Removes the attribute from the given argument.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
void removeRetAttrs(const AttributeMask &AttrsToRemove)
Removes the attributes from the return value.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
uint64_t getParamDereferenceableBytes(unsigned i) const
Extract the number of dereferenceable bytes for a call or parameter (0=unknown).
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
AttributeSet getRetAttributes() const
Return the return attributes for this call.
void setAttributes(AttributeList A)
Set the attributes for this call.
bool doesNotThrow() const
Determine if the call cannot unwind.
Value * getArgOperand(unsigned i) const
uint64_t getParamDereferenceableOrNullBytes(unsigned i) const
Extract the number of dereferenceable_or_null bytes for a parameter (0=unknown).
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
bool isNoTailCall() const
TailCallKind getTailCallKind() const
bool isMustTailCall() const
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
LLVM_ABI uint64_t getElementAsInteger(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This class represents an extension of floating point types.
This class represents a truncation of floating point types.
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
static FastMathFlags getFast()
Definition FMF.h:50
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
LLVM_ABI FortifiedLibCallSimplifier(const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize=false)
LLVM_ABI Value * optimizeCall(CallInst *CI, IRBuilderBase &B)
Take the given call instruction and return a more optimal value to replace the instruction with or 0 ...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:328
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:251
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:727
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isFast() const LLVM_READONLY
Determine whether all fast-math-flags are set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI LibCallSimplifier(const DataLayout &DL, const TargetLibraryInfo *TLI, DominatorTree *DT, DomConditionCache *DC, AssumptionCache *AC, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, function_ref< void(Instruction *, Value *)> Replacer=&replaceAllUsesWithDefault, function_ref< void(Instruction *)> Eraser=&eraseFromParentDefault)
LLVM_ABI Value * optimizeCall(CallInst *CI, IRBuilderBase &B)
optimizeCall - Take the given call instruction and return a more optimal value to replace the instruc...
An instruction for reading from memory.
Value * getPointerOperand()
iterator begin()
Definition MapVector.h:67
size_type size() const
Definition MapVector.h:58
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:323
The optimization diagnostic interface.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis providing profile information.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
char back() const
Get the last character in the string.
Definition StringRef.h:153
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
int compare(StringRef RHS) const
Compare two strings; the result is negative, zero, or positive if this string is lexicographically le...
Definition StringRef.h:177
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:477
static LLVM_ABI bool isCallingConvCCompatible(CallBase *CI)
Returns true if call site / callee has cdecl-compatible calling conventions.
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_CopySign(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
auto m_FAbs(const Opnd0 &Op0)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This namespace contains all of the command line option processing machinery.
Definition MCSchedule.h:35
initializer< Ty > init(const Ty &Val)
constexpr double e
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:578
@ Length
Definition DWP.cpp:578
LLVM_ABI Value * emitUnaryFloatFnCall(Value *Op, const TargetLibraryInfo *TLI, StringRef Name, IRBuilderBase &B, const AttributeList &Attrs)
Emit a call to the unary function named 'Name' (e.g.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
LLVM_ABI Value * emitStrChr(Value *Ptr, char C, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strchr function to the builder, for the specified pointer and character.
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
LLVM_ABI Value * emitPutChar(Value *Char, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the putchar function. This assumes that Char is an 'int'.
LLVM_ABI Value * emitMemCpyChk(Value *Dst, Value *Src, Value *Len, Value *ObjSize, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the __memcpy_chk function to the builder.
LLVM_ABI Value * emitStrNCpy(Value *Dst, Value *Src, Value *Len, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strncpy function to the builder, for the specified pointer arguments and length.
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
@ Known
Known to have no common set bits.
LLVM_ABI Value * emitHotColdNewAlignedNoThrow(Value *Num, Value *Align, Value *NoThrow, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, uint8_t HotCold)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1713
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI Value * emitSPrintf(Value *Dest, Value *Fmt, ArrayRef< Value * > VariadicArgs, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the sprintf function.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
LLVM_ABI Value * emitMemRChr(Value *Ptr, Value *Val, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memrchr function, analogously to emitMemChr.
LLVM_ABI Value * emitStrLCat(Value *Dest, Value *Src, Value *Size, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strlcat function.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
LLVM_ABI bool hasFloatFn(const Module *M, const TargetLibraryInfo *TLI, Type *Ty, LibFunc DoubleFn, LibFunc FloatFn, LibFunc LongDoubleFn)
Check whether the overloaded floating point function corresponding to Ty is available.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * emitStrNCat(Value *Dest, Value *Src, Value *Size, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strncat function.
LLVM_ABI bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
LLVM_ABI Value * emitVSNPrintf(Value *Dest, Value *Size, Value *Fmt, Value *VAList, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the vsnprintf function.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:254
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI Value * emitStrNCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strncmp function to the builder.
LLVM_ABI Value * emitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memcmp function.
LLVM_ABI Value * emitBinaryFloatFnCall(Value *Op1, Value *Op2, const TargetLibraryInfo *TLI, StringRef Name, IRBuilderBase &B, const AttributeList &Attrs)
Emit a call to the binary function named 'Name' (e.g.
bool isAlpha(char C)
Checks if character C is a valid letter as classified by "C" locale.
LLVM_ABI Value * emitFPutS(Value *Str, Value *File, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the fputs function.
LLVM_ABI Value * emitStrDup(Value *Ptr, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strdup function to the builder, for the specified pointer.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI Value * emitBCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the bcmp function.
bool isDigit(char C)
Checks if character C is one of the 10 decimal digits.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:685
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI FunctionCallee getOrInsertLibFunc(Module *M, const TargetLibraryInfo &TLI, LibFunc TheLibFunc, FunctionType *T, AttributeList AttributeList)
Calls getOrInsertFunction() and then makes sure to add mandatory argument attributes.
LLVM_ABI Value * emitStrLen(Value *Ptr, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strlen function to the builder, for the specified pointer.
LLVM_ABI Value * emitFPutC(Value *Char, Value *File, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the fputc function.
LLVM_ABI Value * emitStpNCpy(Value *Dst, Value *Src, Value *Len, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the stpncpy function to the builder, for the specified pointer arguments and length.
LLVM_ABI Value * emitStrCat(Value *Dest, Value *Src, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strcat function.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * emitVSPrintf(Value *Dest, Value *Fmt, Value *VAList, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the vsprintf function.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI Value * emitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the fwrite function.
LLVM_ABI Value * emitSNPrintf(Value *Dest, Value *Size, Value *Fmt, ArrayRef< Value * > Args, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the snprintf function.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
LLVM_ABI Value * emitStpCpy(Value *Dst, Value *Src, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the stpcpy function to the builder, for the specified pointer arguments.
@ FMul
Product of floats.
@ And
Bitwise or logical AND of integers.
char toUpper(char x)
Returns the corresponding uppercase character if x is lowercase.
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
constexpr int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition MathExtras.h:233
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Value * emitHotColdNewNoThrow(Value *Num, Value *NoThrow, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, uint8_t HotCold)
LLVM_ABI Value * emitMalloc(Value *Num, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the malloc function.
LLVM_ABI Value * emitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memchr function.
LLVM_ABI Value * emitHotColdNewAligned(Value *Num, Value *Align, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, uint8_t HotCold)
bool isSpace(char C)
Checks whether character C is whitespace in the "C" locale.
LLVM_ABI Value * emitPutS(Value *Str, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the puts function. This assumes that Str is some pointer.
LLVM_ABI Value * emitMemCCpy(Value *Ptr1, Value *Ptr2, Value *Val, Value *Len, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the memccpy function.
LLVM_ABI Value * emitHotColdSizeReturningNew(Value *Num, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, uint8_t HotCold)
LLVM_ABI Value * emitHotColdNew(Value *Num, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, uint8_t HotCold)
Emit a call to the hot/cold operator new function.
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:264
LLVM_ABI Value * emitStrLCpy(Value *Dest, Value *Src, Value *Size, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strlcpy function.
LLVM_ABI Value * emitHotColdSizeReturningNewAligned(Value *Num, Value *Align, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, uint8_t HotCold)
LLVM_ABI Value * emitStrCpy(Value *Dst, Value *Src, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strcpy function to the builder, for the specified pointer arguments.
LLVM_ABI Value * emitMemPCpy(Value *Dst, Value *Src, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the mempcpy function.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:374
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
const ConstantDataArray * Array
ConstantDataArray pointer.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
static constexpr FPClassTest OrderedLessThanZeroMask
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
Matching combinators.