LLVM 24.0.0git
ConstantFolding.cpp
Go to the documentation of this file.
1//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
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 defines routines for folding instructions into constants.
10//
11// Also, to supplement the basic IR ConstantExpr simplifications,
12// this file defines some additional folding routines that can make use of
13// DataLayout information. These functions cannot go in IR due to library
14// dependency issues.
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/APSInt.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/StringRef.h"
32#include "llvm/Config/config.h"
33#include "llvm/IR/Constant.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/IntrinsicsAArch64.h"
47#include "llvm/IR/IntrinsicsAMDGPU.h"
48#include "llvm/IR/IntrinsicsARM.h"
49#include "llvm/IR/IntrinsicsNVPTX.h"
50#include "llvm/IR/IntrinsicsWebAssembly.h"
51#include "llvm/IR/IntrinsicsX86.h"
53#include "llvm/IR/Operator.h"
54#include "llvm/IR/Type.h"
55#include "llvm/IR/Value.h"
56#include "llvm/Support/CRC.h"
59#include "llvm/Support/FPFold.h"
61#include <cassert>
62#include <cerrno>
63#include <cfenv>
64#include <cmath>
65#include <cstdint>
66
67using namespace llvm;
68
70 "disable-fp-call-folding",
71 cl::desc("Disable constant-folding of FP intrinsics and libcalls."),
72 cl::init(false), cl::Hidden);
73
74namespace {
75
76//===----------------------------------------------------------------------===//
77// Constant Folding internal helper functions
78//===----------------------------------------------------------------------===//
79
80static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
81 Constant *C, Type *SrcEltTy,
82 unsigned NumSrcElts,
83 const DataLayout &DL) {
84 // Now that we know that the input value is a vector of integers, just shift
85 // and insert them into our result.
86 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
87 for (unsigned i = 0; i != NumSrcElts; ++i) {
88 Constant *Element;
89 if (DL.isLittleEndian())
90 Element = C->getAggregateElement(NumSrcElts - i - 1);
91 else
92 Element = C->getAggregateElement(i);
93
94 if (isa_and_nonnull<UndefValue>(Element)) {
95 Result <<= BitShift;
96 continue;
97 }
98
99 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
100 if (!ElementCI)
101 return ConstantExpr::getBitCast(C, DestTy);
102
103 Result <<= BitShift;
104 Result |= ElementCI->getValue().zext(Result.getBitWidth());
105 }
106
107 return nullptr;
108}
109
110/// Check whether folding this bitcast into a byte vector would mix poison and
111/// non-poison bits in the same output lane. While integer types track poison on
112/// a per-value basis, byte types track it on a per-bit basis. However,
113/// `ConstantByte` cannot represent values with both poison and non-poison bits.
114///
115/// Source elements are grouped by the output lane they map to. Returns true if
116/// any group contains both poison and non-poison elements.
117static bool foldMixesPoisonBits(Constant *C, unsigned NumSrcElt,
118 unsigned NumDstElt) {
119 // If element counts don't divide evenly, bail out if a poison source element
120 // might span multiple destination lanes.
121 if (NumSrcElt % NumDstElt != 0)
122 return C->containsPoisonElement();
123 unsigned Ratio = NumSrcElt / NumDstElt;
124 for (unsigned i = 0; i != NumSrcElt; i += Ratio) {
125 bool HasPoison = false;
126 bool HasNonPoison = false;
127 for (unsigned j = 0; j != Ratio; ++j) {
128 Constant *Src = C->getAggregateElement(i + j);
129 // Conservatively bail out.
130 if (!Src)
131 return true;
132 if (isa<PoisonValue>(Src))
133 HasPoison = true;
134 else
135 HasNonPoison = true;
136 }
137 if (HasPoison && HasNonPoison)
138 return true;
139 }
140 return false;
141}
142
143/// Track which destination lanes of a bitcast are produced from poison bytes.
144/// A destination lane is marked if any source element mapped to it is poison.
145/// Returns false if an aggregate element cannot be inspected. The caller should
146/// bail out of folding.
147static bool computePoisonDstLanes(Constant *C, unsigned NumSrcElt,
148 unsigned NumDstElt,
149 SmallBitVector &PoisonDstElts) {
150 // If element counts don't divide evenly, bail out if a poison source element
151 // might span multiple destination lanes.
152 if ((NumDstElt < NumSrcElt ? NumSrcElt % NumDstElt : NumDstElt % NumSrcElt))
153 return !C->containsPoisonElement();
154 if (NumDstElt < NumSrcElt) {
155 unsigned Ratio = NumSrcElt / NumDstElt;
156 for (unsigned i = 0; i != NumDstElt; ++i) {
157 for (unsigned j = 0; j != Ratio; ++j) {
158 Constant *Src = C->getAggregateElement(i * Ratio + j);
159 if (!Src)
160 return false;
161 if (isa<PoisonValue>(Src)) {
162 PoisonDstElts[i] = true;
163 break;
164 }
165 }
166 }
167 } else {
168 unsigned Ratio = NumDstElt / NumSrcElt;
169 for (unsigned i = 0; i != NumSrcElt; ++i) {
170 Constant *Src = C->getAggregateElement(i);
171 if (!Src)
172 return false;
173 if (isa<PoisonValue>(Src))
174 PoisonDstElts.set(i * Ratio, (i + 1) * Ratio);
175 }
176 }
177 return true;
178}
179
180/// Constant fold bitcast, symbolically evaluating it with DataLayout.
181/// This always returns a non-null constant, but it may be a
182/// ConstantExpr if unfoldable.
183Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
184 assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&
185 "Invalid constantexpr bitcast!");
186
187 // Catch the obvious splat cases.
188 if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy, DL))
189 return Res;
190
191 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
192 // Handle a vector->scalar integer/fp/byte cast.
193 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy() ||
194 DestTy->isByteTy()) {
195 unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements();
196 Type *SrcEltTy = VTy->getElementType();
197
198 // A byte constant can't represent partial poison or pointer provenance.
199 if (DestTy->isByteTy() &&
200 (C->containsPoisonElement() || SrcEltTy->isPointerTy()))
201 return ConstantExpr::getBitCast(C, DestTy);
202
203 // Bitcasting a byte containing any poison bit to an integer or fp type
204 // yields poison.
205 if (SrcEltTy->isByteTy() && C->containsPoisonElement())
206 return PoisonValue::get(DestTy);
207
208 // If the vector is a vector of floating point or bytes, convert it to a
209 // vector of int to simplify things.
210 Constant *OrigC = C;
211 if (SrcEltTy->isFloatingPointTy() || SrcEltTy->isByteTy()) {
212 unsigned Width = SrcEltTy->getPrimitiveSizeInBits();
213 auto *SrcIVTy = FixedVectorType::get(
214 IntegerType::get(C->getContext(), Width), NumSrcElts);
215 // Ask IR to do the conversion now that #elts line up.
216 C = ConstantExpr::getBitCast(C, SrcIVTy);
217 }
218
219 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
220 // An element that isn't a plain constant, like a pointer cast to a byte,
221 // can't be folded. Byte destinations fall back to a bitcast of the
222 // original vector, as the integer vector C would drop its provenance.
223 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C, SrcEltTy,
224 NumSrcElts, DL))
225 return DestTy->isByteTy() ? ConstantExpr::getBitCast(OrigC, DestTy)
226 : CE;
227
228 if (isa<IntegerType>(DestTy))
229 return ConstantInt::get(DestTy, Result);
230
231 if (isa<ByteType>(DestTy))
232 return ConstantByte::get(DestTy->getContext(), Result);
233
234 APFloat FP(DestTy->getFltSemantics(), Result);
235 return ConstantFP::get(DestTy->getContext(), FP);
236 }
237 }
238
239 // The code below only handles casts to vectors currently.
240 auto *DestVTy = dyn_cast<VectorType>(DestTy);
241 if (!DestVTy)
242 return ConstantExpr::getBitCast(C, DestTy);
243
244 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
245 // vector so the code below can handle it uniformly.
246 if (!isa<VectorType>(C->getType()) &&
248 Constant *Ops = C; // don't take the address of C!
249 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
250 }
251
252 // Some of what follows may extend to cover scalable vectors but the current
253 // implementation is fixed length specific.
254 if (!isa<FixedVectorType>(C->getType()))
255 return ConstantExpr::getBitCast(C, DestTy);
256
257 // If this is a bitcast from constant vector -> vector, fold it.
260 return ConstantExpr::getBitCast(C, DestTy);
261
262 // If the element types match, IR can fold it.
263 unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements();
264 unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements();
265 if (NumDstElt == NumSrcElt)
266 return ConstantExpr::getBitCast(C, DestTy);
267
268 Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType();
269 Type *DstEltTy = DestVTy->getElementType();
270
271 // Otherwise, we're changing the number of elements in a vector, which
272 // requires endianness information to do the right thing. For example,
273 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
274 // folds to (little endian):
275 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
276 // and to (big endian):
277 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
278
279 // First thing is first. We only want to think about integer here, so if
280 // we have something in FP form, recast it as integer.
281 if (DstEltTy->isFloatingPointTy()) {
282 // Fold to an vector of integers with same size as our FP type.
283 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
284 auto *DestIVTy = FixedVectorType::get(
285 IntegerType::get(C->getContext(), FPWidth), NumDstElt);
286 // Recursively handle this integer conversion, if possible.
287 C = FoldBitCast(C, DestIVTy, DL);
288
289 // Finally, IR can handle this now that #elts line up.
290 return ConstantExpr::getBitCast(C, DestTy);
291 }
292
293 // Handle byte destination type by folding through integers.
294 if (DstEltTy->isByteTy()) {
295 // When combining elements into larger byte values, bail out if the fold
296 // mixes poison and non-poison bits in the same destination element. Byte
297 // types track poison per bit, and no constant value can represent that.
298 if (NumDstElt < NumSrcElt && foldMixesPoisonBits(C, NumSrcElt, NumDstElt))
299 return ConstantExpr::getBitCast(C, DestTy);
300
301 // Fold to a vector of integers with same size as the byte type.
302 unsigned ByteWidth = DstEltTy->getPrimitiveSizeInBits();
303 auto *DestIVTy = FixedVectorType::get(
304 IntegerType::get(C->getContext(), ByteWidth), NumDstElt);
305 C = FoldBitCast(C, DestIVTy, DL);
306 return ConstantExpr::getBitCast(C, DestTy);
307 }
308
309 // Okay, we know the destination is integer, if the input is FP, convert
310 // it to integer first.
311 if (SrcEltTy->isFloatingPointTy()) {
312 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
313 auto *SrcIVTy = FixedVectorType::get(
314 IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
315 // Ask IR to do the conversion now that #elts line up.
316 C = ConstantExpr::getBitCast(C, SrcIVTy);
317 assert((isa<ConstantVector>(C) || // FIXME: Remove ConstantVector.
319 "Constant folding cannot fail for plain fp->int bitcast!");
320 }
321
322 // Handle byte source type by folding through integers. Byte types track
323 // poison per bit, so any poison bit makes the destination lane poison.
324 // Record which destination lanes contain poison bits, before the generic
325 // fold below refines them to undef/zero, so they can be restored.
326 SmallBitVector PoisonDstElts(NumDstElt);
327 if (SrcEltTy->isByteTy()) {
328 if (!computePoisonDstLanes(C, NumSrcElt, NumDstElt, PoisonDstElts))
329 return ConstantExpr::getBitCast(C, DestTy);
330
331 unsigned ByteWidth = SrcEltTy->getPrimitiveSizeInBits();
332 auto *SrcIVTy = FixedVectorType::get(
333 IntegerType::get(C->getContext(), ByteWidth), NumSrcElt);
334 // Ask IR to do the conversion now that #elts line up.
335 C = ConstantExpr::getBitCast(C, SrcIVTy);
336 assert((isa<ConstantVector>(C) || // FIXME: Remove ConstantVector.
338 "Constant folding cannot fail for plain byte->int bitcast!");
339 }
340
341 // Now we know that the input and output vectors are both integer vectors
342 // of the same size, and that their #elements is not the same.
343 // Use data buffer for easy non-integer element ratio vectors handling,
344 // For example: <4 x i24> to <3 x i32>.
345 bool isLittleEndian = DL.isLittleEndian();
346 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
347 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
349 unsigned SrcElt = 0;
350
351 APInt Buffer(2 * std::max(SrcBitSize, DstBitSize), 0);
352 APInt UndefMask(Buffer.getBitWidth(), 0);
353 APInt PoisonMask(Buffer.getBitWidth(), 0);
354 unsigned BufferBitSize = 0;
355
356 while (Result.size() != NumDstElt) {
357 // Load SrcElts into Buffer.
358 while (BufferBitSize < DstBitSize) {
359 Constant *Element = C->getAggregateElement(SrcElt++);
360 if (!Element) // Reject constantexpr elements
361 return ConstantExpr::getBitCast(C, DestTy);
362
363 // Shift Buffer & Masks to fit next SrcElt.
364 if (!isLittleEndian) {
365 Buffer <<= SrcBitSize;
366 UndefMask <<= SrcBitSize;
367 PoisonMask <<= SrcBitSize;
368 }
369
370 APInt SrcValue;
371 unsigned BitPosition = isLittleEndian ? BufferBitSize : 0;
372 if (isa<UndefValue>(Element)) {
373 // Set masks fragments bits.
374 UndefMask.setBits(BitPosition, BitPosition + SrcBitSize);
375 if (isa<PoisonValue>(Element))
376 PoisonMask.setBits(BitPosition, BitPosition + SrcBitSize);
377 SrcValue = APInt::getZero(SrcBitSize);
378 } else {
379 auto *Src = dyn_cast<ConstantInt>(Element);
380 if (!Src)
381 return ConstantExpr::getBitCast(C, DestTy);
382 SrcValue = Src->getValue();
383 }
384
385 // Insert src element bits into Buffer on correct position.
386 Buffer.insertBits(SrcValue, BitPosition);
387 BufferBitSize += SrcBitSize;
388 }
389
390 // Create DstElts from Buffer.
391 while (BufferBitSize >= DstBitSize) {
392 unsigned ShiftAmt = isLittleEndian ? 0 : BufferBitSize - DstBitSize;
393 // Emit undef/poison, if all undef mask fragment bits are set.
394 if (UndefMask.extractBits(DstBitSize, ShiftAmt).isAllOnes()) {
395 // Push poison, if any bit in poison mask fragment is set.
396 if (!PoisonMask.extractBits(DstBitSize, ShiftAmt).isZero()) {
397 Result.push_back(PoisonValue::get(DstEltTy));
398 } else {
399 Result.push_back(UndefValue::get(DstEltTy));
400 }
401 } else {
402 // Create and push DstElt.
403 APInt Elt = Buffer.extractBits(DstBitSize, ShiftAmt);
404 Result.push_back(ConstantInt::get(DstEltTy, Elt));
405 }
406
407 // Shift unused Buffer fragment to lower bits.
408 if (isLittleEndian) {
409 Buffer.lshrInPlace(DstBitSize);
410 UndefMask.lshrInPlace(DstBitSize);
411 PoisonMask.lshrInPlace(DstBitSize);
412 }
413 BufferBitSize -= DstBitSize;
414 }
415 }
416
417 // Restore destination lanes whose source bytes contained poison bits.
418 for (unsigned I : PoisonDstElts.set_bits())
419 Result[I] = PoisonValue::get(DstEltTy);
420
421 return ConstantVector::get(Result);
422}
423
424} // end anonymous namespace
425
426/// If this constant is a constant offset from a global, return the global and
427/// the constant. Because of constantexprs, this function is recursive.
429 APInt &Offset, const DataLayout &DL,
430 DSOLocalEquivalent **DSOEquiv) {
431 if (DSOEquiv)
432 *DSOEquiv = nullptr;
433
434 // Trivial case, constant is the global.
435 if ((GV = dyn_cast<GlobalValue>(C))) {
436 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
437 Offset = APInt(BitWidth, 0);
438 return true;
439 }
440
441 if (auto *FoundDSOEquiv = dyn_cast<DSOLocalEquivalent>(C)) {
442 if (DSOEquiv)
443 *DSOEquiv = FoundDSOEquiv;
444 GV = FoundDSOEquiv->getGlobalValue();
445 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
446 Offset = APInt(BitWidth, 0);
447 return true;
448 }
449
450 // Otherwise, if this isn't a constant expr, bail out.
451 auto *CE = dyn_cast<ConstantExpr>(C);
452 if (!CE) return false;
453
454 // Look through ptr->int and ptr->ptr casts.
455 if (CE->getOpcode() == Instruction::PtrToInt ||
456 CE->getOpcode() == Instruction::PtrToAddr)
457 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL,
458 DSOEquiv);
459
460 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
461 auto *GEP = dyn_cast<GEPOperator>(CE);
462 if (!GEP)
463 return false;
464
465 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
466 APInt TmpOffset(BitWidth, 0);
467
468 // If the base isn't a global+constant, we aren't either.
469 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL,
470 DSOEquiv))
471 return false;
472
473 // Otherwise, add any offset that our operands provide.
474 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
475 return false;
476
477 Offset = TmpOffset;
478 return true;
479}
480
482 const DataLayout &DL) {
483 do {
484 Type *SrcTy = C->getType();
485 if (SrcTy == DestTy)
486 return C;
487
488 TypeSize DestSize = DL.getTypeSizeInBits(DestTy);
489 TypeSize SrcSize = DL.getTypeSizeInBits(SrcTy);
490 if (!TypeSize::isKnownGE(SrcSize, DestSize))
491 return nullptr;
492
493 // Catch the obvious splat cases (since all-zeros can coerce non-integral
494 // pointers legally).
495 if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy, DL))
496 return Res;
497
498 // If the type sizes are the same and a cast is legal, just directly
499 // cast the constant.
500 // But be careful not to coerce non-integral pointers illegally.
501 if (SrcSize == DestSize &&
502 DL.isNonIntegralPointerType(SrcTy->getScalarType()) ==
503 DL.isNonIntegralPointerType(DestTy->getScalarType())) {
504 Instruction::CastOps Cast = Instruction::BitCast;
505 // If we are going from a pointer to int or vice versa, we spell the cast
506 // differently.
507 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
508 Cast = Instruction::IntToPtr;
509 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
510 Cast = Instruction::PtrToInt;
511
512 if (CastInst::castIsValid(Cast, C, DestTy))
513 return ConstantFoldCastOperand(Cast, C, DestTy, DL);
514 }
515
516 // If this isn't an aggregate type, there is nothing we can do to drill down
517 // and find a bitcastable constant.
518 if (!SrcTy->isAggregateType() && !SrcTy->isVectorTy())
519 return nullptr;
520
521 // We're simulating a load through a pointer that was bitcast to point to
522 // a different type, so we can try to walk down through the initial
523 // elements of an aggregate to see if some part of the aggregate is
524 // castable to implement the "load" semantic model.
525 if (SrcTy->isStructTy()) {
526 // Struct types might have leading zero-length elements like [0 x i32],
527 // which are certainly not what we are looking for, so skip them.
528 unsigned Elem = 0;
529 Constant *ElemC;
530 do {
531 ElemC = C->getAggregateElement(Elem++);
532 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero());
533 C = ElemC;
534 } else {
535 // For non-byte-sized vector elements, the first element is not
536 // necessarily located at the vector base address.
537 if (auto *VT = dyn_cast<VectorType>(SrcTy))
538 if (!DL.typeSizeEqualsStoreSize(VT->getElementType()))
539 return nullptr;
540
541 C = C->getAggregateElement(0u);
542 }
543 } while (C);
544
545 return nullptr;
546}
547
548/// Return true if \p Ty is or contains a byte type.
549static bool containsByteType(Type *Ty) {
550 if (auto *ATy = dyn_cast<ArrayType>(Ty))
551 return containsByteType(ATy->getElementType());
552 if (auto *STy = dyn_cast<StructType>(Ty))
553 return any_of(STy->elements(), containsByteType);
554 return Ty->isByteOrByteVectorTy();
555}
556
557namespace {
558
559/// Recursive helper to read bits out of global. C is the constant being copied
560/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
561/// results into and BytesLeft is the number of bytes left in
562/// the CurPtr buffer. DL is the DataLayout. When IsByteLoad is true, do not
563/// unwrap inttoptr constant expressions. The caller would reconstruct those
564/// bits as a ConstantByte, dropping the pointer's provenance.
565bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
566 unsigned BytesLeft, const DataLayout &DL,
567 bool IsByteLoad = false) {
568 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
569 "Out of range access");
570
571 // Reading type padding, return zero.
572 if (ByteOffset >= DL.getTypeStoreSize(C->getType()))
573 return true;
574
575 // If this element is zero or undefined, we can just return since *CurPtr is
576 // zero initialized.
578 return true;
579
580 auto *CI = dyn_cast<ConstantInt>(C);
581 if (CI && CI->getType()->isIntegerTy()) {
582 if ((CI->getBitWidth() & 7) != 0)
583 return false;
584 const APInt &Val = CI->getValue();
585 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
586
587 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
588 unsigned n = ByteOffset;
589 if (!DL.isLittleEndian())
590 n = IntBytes - n - 1;
591 CurPtr[i] = Val.extractBits(8, n * 8).getZExtValue();
592 ++ByteOffset;
593 }
594 return true;
595 }
596
597 // Read a `ConstantByte` as an integer with the same bits.
598 auto *CB = dyn_cast<ConstantByte>(C);
599 if (CB && CB->getType()->isByteTy())
600 return ReadDataFromGlobal(ConstantInt::get(C->getContext(), CB->getValue()),
601 ByteOffset, CurPtr, BytesLeft, DL, IsByteLoad);
602
603 auto *CFP = dyn_cast<ConstantFP>(C);
604 if (CFP && CFP->getType()->isFloatingPointTy()) {
605 if (CFP->getType()->isDoubleTy()) {
606 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
607 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL,
608 IsByteLoad);
609 }
610 if (CFP->getType()->isFloatTy()){
611 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
612 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL,
613 IsByteLoad);
614 }
615 if (CFP->getType()->isHalfTy()){
616 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
617 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL,
618 IsByteLoad);
619 }
620 return false;
621 }
622
623 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
624 const StructLayout *SL = DL.getStructLayout(CS->getType());
625 unsigned Index = SL->getElementContainingOffset(ByteOffset);
626 uint64_t CurEltOffset = SL->getElementOffset(Index);
627 ByteOffset -= CurEltOffset;
628
629 while (true) {
630 // If the element access is to the element itself and not to tail padding,
631 // read the bytes from the element.
632 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
633
634 if (ByteOffset < EltSize &&
635 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
636 BytesLeft, DL, IsByteLoad))
637 return false;
638
639 ++Index;
640
641 // Check to see if we read from the last struct element, if so we're done.
642 if (Index == CS->getType()->getNumElements())
643 return true;
644
645 // If we read all of the bytes we needed from this element we're done.
646 uint64_t NextEltOffset = SL->getElementOffset(Index);
647
648 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
649 return true;
650
651 // Move to the next element of the struct.
652 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
653 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
654 ByteOffset = 0;
655 CurEltOffset = NextEltOffset;
656 }
657 // not reached.
658 }
659
663 uint64_t NumElts, EltSize;
664 Type *EltTy;
665 if (auto *AT = dyn_cast<ArrayType>(C->getType())) {
666 NumElts = AT->getNumElements();
667 EltTy = AT->getElementType();
668 EltSize = DL.getTypeAllocSize(EltTy);
669 } else {
670 NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
671 EltTy = cast<FixedVectorType>(C->getType())->getElementType();
672 // TODO: For non-byte-sized vectors, current implementation assumes there is
673 // padding to the next byte boundary between elements.
674 if (!DL.typeSizeEqualsStoreSize(EltTy))
675 return false;
676
677 EltSize = DL.getTypeStoreSize(EltTy);
678 }
679 uint64_t Index = ByteOffset / EltSize;
680 uint64_t Offset = ByteOffset - Index * EltSize;
681
682 for (; Index != NumElts; ++Index) {
683 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
684 BytesLeft, DL, IsByteLoad))
685 return false;
686
687 uint64_t BytesWritten = EltSize - Offset;
688 assert(BytesWritten <= EltSize && "Not indexing into this element?");
689 if (BytesWritten >= BytesLeft)
690 return true;
691
692 Offset = 0;
693 BytesLeft -= BytesWritten;
694 CurPtr += BytesWritten;
695 }
696 return true;
697 }
698
699 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
700 if (CE->getOpcode() == Instruction::IntToPtr &&
701 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
702 // Folding byte loads through the integer operand would rebuild the result
703 // as a `ConstantByte`, dropping the pointer's provenance.
704 if (IsByteLoad)
705 return false;
706 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
707 BytesLeft, DL, IsByteLoad);
708 }
709 }
710
711 // Otherwise, unknown initializer type.
712 return false;
713}
714
715/// OrigLoadTy is the original type being loaded, while LoadTy is the type
716/// currently being folded (which may be integer type mapped from OrigLoadTy).
717Constant *FoldReinterpretLoadFromConst(Constant *C, Type *LoadTy,
718 Type *OrigLoadTy, int64_t Offset,
719 const DataLayout &DL) {
720 // Bail out early. Not expect to load from scalable global variable.
721 if (isa<ScalableVectorType>(LoadTy))
722 return nullptr;
723
724 auto *IntType = dyn_cast<IntegerType>(LoadTy);
725
726 // If this isn't an integer load we can't fold it directly.
727 if (!IntType) {
728 // If this is a non-integer load, we can try folding it as an int load and
729 // then bitcast the result. This can be useful for union cases. Note
730 // that address spaces don't matter here since we're not going to result in
731 // an actual new load.
732 if (!LoadTy->isFloatingPointTy() && !LoadTy->isPointerTy() &&
733 !LoadTy->isByteTy() && !LoadTy->isVectorTy())
734 return nullptr;
735
736 // Reinterpret pointers read from `ConstantByte` as a bitcast, rather than
737 // an inttoptr.
738 if (LoadTy->isPtrOrPtrVectorTy() &&
739 !DL.isNonIntegralPointerType(LoadTy->getScalarType()) &&
740 containsByteType(C->getType())) {
741 Type *ByteTy = DL.getBytePtrType(LoadTy);
742 if (Constant *Res =
743 FoldReinterpretLoadFromConst(C, ByteTy, ByteTy, Offset, DL))
744 return ConstantFoldCastOperand(Instruction::BitCast, Res, LoadTy, DL);
745 }
746
747 Type *MapTy = Type::getIntNTy(C->getContext(),
748 DL.getTypeSizeInBits(LoadTy).getFixedValue());
749 if (Constant *Res =
750 FoldReinterpretLoadFromConst(C, MapTy, OrigLoadTy, Offset, DL)) {
751 if (Res->isNullValue() && !LoadTy->isX86_AMXTy())
752 // Materializing a zero can be done trivially without a bitcast
753 return Constant::getNullValue(LoadTy);
754 Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy;
755 Res = FoldBitCast(Res, CastTy, DL);
756 if (LoadTy->isPtrOrPtrVectorTy()) {
757 // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr
758 if (Res->isNullValue() && !LoadTy->isX86_AMXTy())
759 return Constant::getNullValue(LoadTy);
760 if (DL.isNonIntegralPointerType(LoadTy->getScalarType()))
761 // Be careful not to replace a load of an addrspace value with an inttoptr here
762 return nullptr;
763 Res = ConstantExpr::getIntToPtr(Res, LoadTy);
764 }
765 return Res;
766 }
767 return nullptr;
768 }
769
770 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
771 // Allow folding of large type loads (e.g. <16 x double>).
772 if (BytesLoaded > 128 || BytesLoaded == 0)
773 return nullptr;
774
775 // For scalar integer load, use smaller limit to avoid regression during
776 // memcmp expansion. Codegen may generate inefficient string operations.
777 if (BytesLoaded > 32 && OrigLoadTy->isIntegerTy())
778 return nullptr;
779
780 // If we're not accessing anything in this constant, the result is undefined.
781 if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
782 return PoisonValue::get(IntType);
783
784 // TODO: We should be able to support scalable types.
785 TypeSize InitializerSize = DL.getTypeAllocSize(C->getType());
786 if (InitializerSize.isScalable())
787 return nullptr;
788
789 // If we're not accessing anything in this constant, the result is undefined.
790 if (Offset >= (int64_t)InitializerSize.getFixedValue())
791 return PoisonValue::get(IntType);
792
793 SmallVector<unsigned char, 64> RawBytes(BytesLoaded);
794 unsigned char *CurPtr = RawBytes.data();
795 unsigned BytesLeft = BytesLoaded;
796
797 // If we're loading off the beginning of the global, some bytes may be valid.
798 if (Offset < 0) {
799 CurPtr += -Offset;
800 BytesLeft += Offset;
801 Offset = 0;
802 }
803
804 if (!ReadDataFromGlobal(C, Offset, CurPtr, BytesLeft, DL,
805 /*IsByteLoad=*/OrigLoadTy->isByteOrByteVectorTy()))
806 return nullptr;
807
808 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
809 if (DL.isLittleEndian()) {
810 ResultVal = RawBytes[BytesLoaded - 1];
811 for (unsigned i = 1; i != BytesLoaded; ++i) {
812 ResultVal <<= 8;
813 ResultVal |= RawBytes[BytesLoaded - 1 - i];
814 }
815 } else {
816 ResultVal = RawBytes[0];
817 for (unsigned i = 1; i != BytesLoaded; ++i) {
818 ResultVal <<= 8;
819 ResultVal |= RawBytes[i];
820 }
821 }
822
823 return ConstantInt::get(IntType->getContext(), ResultVal);
824}
825
826} // anonymous namespace
827
828// If GV is a constant with an initializer read its representation starting
829// at Offset and return it as a constant array of unsigned char. Otherwise
830// return null.
832 uint64_t Offset) {
833 if (!GV->isConstant() || !GV->hasDefinitiveInitializer())
834 return nullptr;
835
836 const DataLayout &DL = GV->getDataLayout();
837 Constant *Init = const_cast<Constant *>(GV->getInitializer());
838 TypeSize InitSize = DL.getTypeAllocSize(Init->getType());
839 if (InitSize < Offset)
840 return nullptr;
841
842 uint64_t NBytes = InitSize - Offset;
843 if (NBytes > UINT16_MAX)
844 // Bail for large initializers in excess of 64K to avoid allocating
845 // too much memory.
846 // Offset is assumed to be less than or equal than InitSize (this
847 // is enforced in ReadDataFromGlobal).
848 return nullptr;
849
850 SmallVector<unsigned char, 256> RawBytes(static_cast<size_t>(NBytes));
851 unsigned char *CurPtr = RawBytes.data();
852
853 if (!ReadDataFromGlobal(Init, Offset, CurPtr, NBytes, DL))
854 return nullptr;
855
856 return ConstantDataArray::get(GV->getContext(), RawBytes);
857}
858
859/// If this Offset points exactly to the start of an aggregate element, return
860/// that element, otherwise return nullptr.
862 const DataLayout &DL) {
863 if (Offset.isZero())
864 return Base;
865
867 return nullptr;
868
869 Type *ElemTy = Base->getType();
870 SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
871 if (!Offset.isZero() || !Indices[0].isZero())
872 return nullptr;
873
874 Constant *C = Base;
875 for (const APInt &Index : drop_begin(Indices)) {
876 if (Index.isNegative() || Index.getActiveBits() >= 32)
877 return nullptr;
878
879 C = C->getAggregateElement(Index.getZExtValue());
880 if (!C)
881 return nullptr;
882 }
883
884 return C;
885}
886
888 const APInt &Offset,
889 const DataLayout &DL) {
890 if (Constant *AtOffset = getConstantAtOffset(C, Offset, DL))
891 if (Constant *Result = ConstantFoldLoadThroughBitcast(AtOffset, Ty, DL))
892 return Result;
893
894 // Explicitly check for out-of-bounds access, so we return poison even if the
895 // constant is a uniform value.
896 TypeSize Size = DL.getTypeAllocSize(C->getType());
897 if (!Size.isScalable() && Offset.sge(Size.getFixedValue()))
898 return PoisonValue::get(Ty);
899
900 // Try an offset-independent fold of a uniform value.
901 if (Constant *Result = ConstantFoldLoadFromUniformValue(C, Ty, DL))
902 return Result;
903
904 // Try hard to fold loads from bitcasted strange and non-type-safe things.
905 if (Offset.getSignificantBits() <= 64)
906 if (Constant *Result =
907 FoldReinterpretLoadFromConst(C, Ty, Ty, Offset.getSExtValue(), DL))
908 return Result;
909
910 return nullptr;
911}
912
917
920 const DataLayout &DL) {
921 // We can only fold loads from constant globals with a definitive initializer.
922 // Check this upfront, to skip expensive offset calculations.
924 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
925 return nullptr;
926
927 C = cast<Constant>(C->stripAndAccumulateConstantOffsets(
928 DL, Offset, /* AllowNonInbounds */ true));
929
930 if (C == GV)
931 if (Constant *Result = ConstantFoldLoadFromConst(GV->getInitializer(), Ty,
932 Offset, DL))
933 return Result;
934
935 // If this load comes from anywhere in a uniform constant global, the value
936 // is always the same, regardless of the loaded offset.
937 return ConstantFoldLoadFromUniformValue(GV->getInitializer(), Ty, DL);
938}
939
941 const DataLayout &DL) {
942 APInt Offset(DL.getIndexTypeSizeInBits(C->getType()), 0);
943 return ConstantFoldLoadFromConstPtr(C, Ty, std::move(Offset), DL);
944}
945
947 const DataLayout &DL) {
948 if (isa<PoisonValue>(C))
949 return PoisonValue::get(Ty);
950 if (isa<UndefValue>(C))
951 return UndefValue::get(Ty);
952 // If padding is needed when storing C to memory, then it isn't considered as
953 // uniform.
954 if (!DL.typeSizeEqualsStoreSize(C->getType()))
955 return nullptr;
956 if (C->isNullValue() && !Ty->isX86_AMXTy())
957 return Constant::getNullValue(Ty);
958 if (C->isAllOnesValue() &&
959 (Ty->isIntOrIntVectorTy() || Ty->isByteOrByteVectorTy() ||
960 Ty->isFPOrFPVectorTy()))
961 return Constant::getAllOnesValue(Ty);
962 return nullptr;
963}
964
965namespace {
966
967/// One of Op0/Op1 is a constant expression.
968/// Attempt to symbolically evaluate the result of a binary operator merging
969/// these together. If target data info is available, it is provided as DL,
970/// otherwise DL is null.
971Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
972 const DataLayout &DL) {
973 // SROA
974
975 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
976 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
977 // bits.
978
979 if (Opc == Instruction::And) {
980 KnownBits Known0 = computeKnownBits(Op0, DL);
981 KnownBits Known1 = computeKnownBits(Op1, DL);
982 if ((Known1.One | Known0.Zero).isAllOnes()) {
983 // All the bits of Op0 that the 'and' could be masking are already zero.
984 return Op0;
985 }
986 if ((Known0.One | Known1.Zero).isAllOnes()) {
987 // All the bits of Op1 that the 'and' could be masking are already zero.
988 return Op1;
989 }
990
991 Known0 &= Known1;
992 if (Known0.isConstant())
993 return ConstantInt::get(Op0->getType(), Known0.getConstant());
994 }
995
996 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
997 // constant. This happens frequently when iterating over a global array.
998 if (Opc == Instruction::Sub) {
999 GlobalValue *GV1, *GV2;
1000 APInt Offs1, Offs2;
1001
1002 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
1003 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
1004 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
1005
1006 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
1007 // PtrToInt may change the bitwidth so we have convert to the right size
1008 // first.
1009 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
1010 Offs2.zextOrTrunc(OpSize));
1011 }
1012 }
1013
1014 return nullptr;
1015}
1016
1017/// If array indices are not pointer-sized integers, explicitly cast them so
1018/// that they aren't implicitly casted by the getelementptr.
1019Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
1020 Type *ResultTy, GEPNoWrapFlags NW,
1021 std::optional<ConstantRange> InRange,
1022 const DataLayout &DL, const TargetLibraryInfo *TLI) {
1023 Type *IntIdxTy = DL.getIndexType(ResultTy);
1024 Type *IntIdxScalarTy = IntIdxTy->getScalarType();
1025
1026 bool Any = false;
1028 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
1029 if ((i == 1 ||
1031 SrcElemTy, Ops.slice(1, i - 1)))) &&
1032 Ops[i]->getType()->getScalarType() != IntIdxScalarTy) {
1033 Any = true;
1034 Type *NewType =
1035 Ops[i]->getType()->isVectorTy() ? IntIdxTy : IntIdxScalarTy;
1037 CastInst::getCastOpcode(Ops[i], true, NewType, true), Ops[i], NewType,
1038 DL);
1039 if (!NewIdx)
1040 return nullptr;
1041 NewIdxs.push_back(NewIdx);
1042 } else
1043 NewIdxs.push_back(Ops[i]);
1044 }
1045
1046 if (!Any)
1047 return nullptr;
1048
1049 Constant *C = ConstantExpr::getGetElementPtr(DL, SrcElemTy, Ops[0], NewIdxs,
1050 NW, InRange);
1051 if (!C)
1052 return nullptr;
1053 return ConstantFoldConstant(C, DL, TLI);
1054}
1055
1056/// If we can symbolically evaluate the GEP constant expression, do so.
1057Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
1059 const DataLayout &DL,
1060 const TargetLibraryInfo *TLI) {
1061 Type *SrcElemTy = GEP->getSourceElementType();
1062 Type *ResTy = GEP->getType();
1063 if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy))
1064 return nullptr;
1065
1066 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, GEP->getNoWrapFlags(),
1067 GEP->getInRange(), DL, TLI))
1068 return C;
1069
1070 Constant *Ptr = Ops[0];
1071 if (!Ptr->getType()->isPointerTy())
1072 return nullptr;
1073
1074 Type *IntIdxTy = DL.getIndexType(Ptr->getType());
1075
1076 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1077 if (!isa<ConstantInt>(Ops[i]) || !Ops[i]->getType()->isIntegerTy())
1078 return nullptr;
1079
1080 unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy);
1081 APInt Offset(BitWidth, 0);
1083 reinterpret_cast<const Value *const *>(Ops.data()) + 1, Ops.size() - 1);
1084 if (!GEPOperator::accumulateConstantOffset(SrcElemTy, Indices, DL, Offset))
1085 return nullptr;
1086
1087 std::optional<ConstantRange> InRange = GEP->getInRange();
1088 if (InRange)
1089 InRange = InRange->sextOrTrunc(BitWidth);
1090
1091 // If this is a GEP of a GEP, fold it all into a single GEP.
1092 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
1093 bool Overflow = false;
1094 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
1095 NW &= GEP->getNoWrapFlags();
1096
1097 // Do not try to incorporate the sub-GEP if some index is not a number.
1098 APInt NestedOffset(BitWidth, 0);
1099 if (!GEP->accumulateConstantOffset(DL, NestedOffset))
1100 break;
1101
1102 // Adjust inrange offset and intersect inrange attributes
1103 if (auto GEPRange = GEP->getInRange()) {
1104 auto AdjustedGEPRange = GEPRange->sextOrTrunc(BitWidth).subtract(Offset);
1105 InRange =
1106 InRange ? InRange->intersectWith(AdjustedGEPRange) : AdjustedGEPRange;
1107 }
1108
1109 Ptr = cast<Constant>(GEP->getOperand(0));
1110 SrcElemTy = GEP->getSourceElementType();
1111 Offset = Offset.sadd_ov(NestedOffset, Overflow);
1112 }
1113
1114 // Preserving nusw (without inbounds) also requires that the offset
1115 // additions did not overflow.
1116 if (NW.hasNoUnsignedSignedWrap() && !NW.isInBounds() && Overflow)
1118
1119 // If the base value for this address is a literal integer value, fold the
1120 // getelementptr to the resulting integer value casted to the pointer type.
1121 APInt BaseIntVal(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
1122 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
1123 if (CE->getOpcode() == Instruction::IntToPtr) {
1124 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
1125 BaseIntVal = Base->getValue().zextOrTrunc(BaseIntVal.getBitWidth());
1126 }
1127 }
1128
1129 if ((Ptr->isNullValue() || BaseIntVal != 0) &&
1130 !DL.mustNotIntroduceIntToPtr(Ptr->getType())) {
1131
1132 // If the index size is smaller than the pointer size, add to the low
1133 // bits only.
1134 BaseIntVal.insertBits(BaseIntVal.trunc(BitWidth) + Offset, 0);
1135 Constant *C = ConstantInt::get(Ptr->getContext(), BaseIntVal);
1136 return ConstantExpr::getIntToPtr(C, ResTy);
1137 }
1138
1139 // Try to infer inbounds for GEPs of globals.
1140 if (!NW.isInBounds() && Offset.isNonNegative()) {
1141 bool CanBeNull;
1142 uint64_t DerefBytes = Ptr->getPointerDereferenceableBytes(
1143 DL, CanBeNull, /*CanBeFreed=*/nullptr);
1144 if (DerefBytes != 0 && !CanBeNull && Offset.sle(DerefBytes))
1146 }
1147
1148 // nusw + nneg -> nuw
1149 if (NW.hasNoUnsignedSignedWrap() && Offset.isNonNegative())
1151
1152 // Otherwise canonicalize this to a single ptradd.
1153 LLVMContext &Ctx = Ptr->getContext();
1154 return ConstantExpr::getPtrAdd(Ptr, ConstantInt::get(Ctx, Offset), NW,
1155 InRange);
1156}
1157
1158/// Attempt to constant fold an instruction with the
1159/// specified opcode and operands. If successful, the constant result is
1160/// returned, if not, null is returned. Note that this function can fail when
1161/// attempting to fold instructions like loads and stores, which have no
1162/// constant expression form.
1163Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
1165 const DataLayout &DL,
1166 const TargetLibraryInfo *TLI,
1167 bool AllowNonDeterministic) {
1168 Type *DestTy = InstOrCE->getType();
1169
1170 if (Instruction::isUnaryOp(Opcode))
1171 return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
1172
1173 if (Instruction::isBinaryOp(Opcode)) {
1174 switch (Opcode) {
1175 default:
1176 break;
1177 case Instruction::FAdd:
1178 case Instruction::FSub:
1179 case Instruction::FMul:
1180 case Instruction::FDiv:
1181 case Instruction::FRem:
1182 // Handle floating point instructions separately to account for denormals
1183 // TODO: If a constant expression is being folded rather than an
1184 // instruction, denormals will not be flushed/treated as zero
1185 if (const auto *I = dyn_cast<Instruction>(InstOrCE)) {
1186 return ConstantFoldFPInstOperands(Opcode, Ops[0], Ops[1], DL, I,
1187 AllowNonDeterministic);
1188 }
1189 }
1190 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1191 }
1192
1193 if (Instruction::isCast(Opcode))
1194 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1195
1196 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1197 Type *SrcElemTy = GEP->getSourceElementType();
1199 return nullptr;
1200
1201 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1202 return C;
1203
1204 return ConstantExpr::getGetElementPtr(DL, SrcElemTy, Ops[0], Ops.slice(1),
1205 GEP->getNoWrapFlags(),
1206 GEP->getInRange());
1207 }
1208
1209 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1210 return CE->getWithOperands(Ops);
1211
1212 switch (Opcode) {
1213 default: return nullptr;
1214 case Instruction::ICmp:
1215 case Instruction::FCmp: {
1216 auto *C = cast<CmpInst>(InstOrCE);
1217 return ConstantFoldCompareInstOperands(C->getPredicate(), Ops[0], Ops[1],
1218 DL, TLI, C->getFunction());
1219 }
1220 case Instruction::Freeze:
1221 return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr;
1222 case Instruction::Call:
1223 if (auto *F = dyn_cast<Function>(Ops.back())) {
1224 const auto *Call = cast<CallBase>(InstOrCE);
1226 return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI,
1227 AllowNonDeterministic);
1228 }
1229 return nullptr;
1230 case Instruction::Select:
1231 return ConstantFoldSelectInstruction(Ops[0], Ops[1], Ops[2]);
1232 case Instruction::ExtractElement:
1234 case Instruction::ExtractValue:
1236 Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
1237 case Instruction::InsertElement:
1238 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1239 case Instruction::InsertValue:
1241 Ops[0], Ops[1], cast<InsertValueInst>(InstOrCE)->getIndices());
1242 case Instruction::ShuffleVector:
1244 Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask());
1245 case Instruction::BitInsert:
1246 return ConstantFoldBitInsertOperands(Ops[0], Ops[1], Ops[2], DL);
1247 case Instruction::BitExtract:
1248 return ConstantFoldBitExtractOperands(InstOrCE->getType(), Ops[0], Ops[1],
1249 DL);
1250 case Instruction::Load: {
1251 const auto *LI = dyn_cast<LoadInst>(InstOrCE);
1252 if (LI->isVolatile())
1253 return nullptr;
1254 return ConstantFoldLoadFromConstPtr(Ops[0], LI->getType(), DL);
1255 }
1256 }
1257}
1258
1259} // end anonymous namespace
1260
1261//===----------------------------------------------------------------------===//
1262// Constant Folding public APIs
1263//===----------------------------------------------------------------------===//
1264
1265namespace {
1266
1267Constant *
1268ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1269 const TargetLibraryInfo *TLI,
1272 return const_cast<Constant *>(C);
1273
1275 for (const Use &OldU : C->operands()) {
1276 Constant *OldC = cast<Constant>(&OldU);
1277 Constant *NewC = OldC;
1278 // Recursively fold the ConstantExpr's operands. If we have already folded
1279 // a ConstantExpr, we don't have to process it again.
1280 if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) {
1281 auto It = FoldedOps.find(OldC);
1282 if (It == FoldedOps.end()) {
1283 NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps);
1284 FoldedOps.insert({OldC, NewC});
1285 } else {
1286 NewC = It->second;
1287 }
1288 }
1289 Ops.push_back(NewC);
1290 }
1291
1292 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1293 if (Constant *Res = ConstantFoldInstOperandsImpl(
1294 CE, CE->getOpcode(), Ops, DL, TLI, /*AllowNonDeterministic=*/true))
1295 return Res;
1296 return const_cast<Constant *>(C);
1297 }
1298
1300 return ConstantVector::get(Ops);
1301}
1302
1303} // end anonymous namespace
1304
1306 const DataLayout &DL,
1307 const TargetLibraryInfo *TLI) {
1308 // Handle PHI nodes quickly here...
1309 if (auto *PN = dyn_cast<PHINode>(I)) {
1310 Constant *CommonValue = nullptr;
1311
1313 for (Value *Incoming : PN->incoming_values()) {
1314 // If the incoming value is undef then skip it. Note that while we could
1315 // skip the value if it is equal to the phi node itself we choose not to
1316 // because that would break the rule that constant folding only applies if
1317 // all operands are constants.
1318 if (isa<UndefValue>(Incoming))
1319 continue;
1320 // If the incoming value is not a constant, then give up.
1321 auto *C = dyn_cast<Constant>(Incoming);
1322 if (!C)
1323 return nullptr;
1324 // Fold the PHI's operands.
1325 C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1326 // If the incoming value is a different constant to
1327 // the one we saw previously, then give up.
1328 if (CommonValue && C != CommonValue)
1329 return nullptr;
1330 CommonValue = C;
1331 }
1332
1333 // If we reach here, all incoming values are the same constant or undef.
1334 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1335 }
1336
1337 // Scan the operand list, checking to see if they are all constants, if so,
1338 // hand off to ConstantFoldInstOperandsImpl.
1339 if (!all_of(I->operands(), [](const Use &U) { return isa<Constant>(U); }))
1340 return nullptr;
1341
1344 for (const Use &OpU : I->operands()) {
1345 auto *Op = cast<Constant>(&OpU);
1346 // Fold the Instruction's operands.
1347 Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps);
1348 Ops.push_back(Op);
1349 }
1350
1351 return ConstantFoldInstOperands(I, Ops, DL, TLI);
1352}
1353
1355 const TargetLibraryInfo *TLI) {
1357 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1358}
1359
1362 const DataLayout &DL,
1363 const TargetLibraryInfo *TLI,
1364 bool AllowNonDeterministic) {
1365 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI,
1366 AllowNonDeterministic);
1367}
1368
1370 Constant *Ops0, Constant *Ops1,
1371 const DataLayout &DL,
1372 const TargetLibraryInfo *TLI,
1373 const Function *CtxF) {
1374 CmpInst::Predicate Predicate = (CmpInst::Predicate)IntPredicate;
1375 // fold: icmp (inttoptr x), null -> icmp x, 0
1376 // fold: icmp null, (inttoptr x) -> icmp 0, x
1377 // fold: icmp (ptrtoint x), 0 -> icmp x, null
1378 // fold: icmp 0, (ptrtoint x) -> icmp null, x
1379 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1380 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1381 //
1382 // FIXME: The following comment is out of data and the DataLayout is here now.
1383 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1384 // around to know if bit truncation is happening.
1385 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1386 if (Ops1->isNullValue()) {
1387 if (CE0->getOpcode() == Instruction::IntToPtr) {
1388 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1389 // Convert the integer value to the right size to ensure we get the
1390 // proper extension or truncation.
1391 if (Constant *C = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy,
1392 /*IsSigned*/ false, DL)) {
1393 Constant *Null = Constant::getNullValue(C->getType());
1394 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1395 }
1396 }
1397
1398 // icmp only compares the address part of the pointer, so only do this
1399 // transform if the integer size matches the address size.
1400 if (CE0->getOpcode() == Instruction::PtrToInt ||
1401 CE0->getOpcode() == Instruction::PtrToAddr) {
1402 Type *AddrTy = DL.getAddressType(CE0->getOperand(0)->getType());
1403 if (CE0->getType() == AddrTy) {
1404 Constant *C = CE0->getOperand(0);
1405 Constant *Null = Constant::getNullValue(C->getType());
1406 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1407 }
1408 }
1409 }
1410
1411 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1412 if (CE0->getOpcode() == CE1->getOpcode()) {
1413 if (CE0->getOpcode() == Instruction::IntToPtr) {
1414 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1415
1416 // Convert the integer value to the right size to ensure we get the
1417 // proper extension or truncation.
1418 Constant *C0 = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy,
1419 /*IsSigned*/ false, DL);
1420 Constant *C1 = ConstantFoldIntegerCast(CE1->getOperand(0), IntPtrTy,
1421 /*IsSigned*/ false, DL);
1422 if (C0 && C1)
1423 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1424 }
1425
1426 // icmp only compares the address part of the pointer, so only do this
1427 // transform if the integer size matches the address size.
1428 if (CE0->getOpcode() == Instruction::PtrToInt ||
1429 CE0->getOpcode() == Instruction::PtrToAddr) {
1430 Type *AddrTy = DL.getAddressType(CE0->getOperand(0)->getType());
1431 if (CE0->getType() == AddrTy &&
1432 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1434 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1435 }
1436 }
1437 }
1438 }
1439
1440 // Convert pointer comparison (base+offset1) pred (base+offset2) into
1441 // offset1 pred offset2, for the case where the offset is inbounds. This
1442 // only works for equality and unsigned comparison, as inbounds permits
1443 // crossing the sign boundary. However, the offset comparison itself is
1444 // signed.
1445 if (Ops0->getType()->isPointerTy() && !ICmpInst::isSigned(Predicate)) {
1446 unsigned IndexWidth = DL.getIndexTypeSizeInBits(Ops0->getType());
1447 APInt Offset0(IndexWidth, 0);
1448 bool IsEqPred = ICmpInst::isEquality(Predicate);
1449 Value *Stripped0 = Ops0->stripAndAccumulateConstantOffsets(
1450 DL, Offset0, /*AllowNonInbounds=*/IsEqPred,
1451 /*AllowInvariantGroup=*/false, /*ExternalAnalysis=*/nullptr,
1452 /*LookThroughIntToPtr=*/IsEqPred);
1453 APInt Offset1(IndexWidth, 0);
1454 Value *Stripped1 = Ops1->stripAndAccumulateConstantOffsets(
1455 DL, Offset1, /*AllowNonInbounds=*/IsEqPred,
1456 /*AllowInvariantGroup=*/false, /*ExternalAnalysis=*/nullptr,
1457 /*LookThroughIntToPtr=*/IsEqPred);
1458 if (Stripped0 == Stripped1)
1459 return ConstantInt::getBool(
1460 Ops0->getContext(),
1461 ICmpInst::compare(Offset0, Offset1,
1462 ICmpInst::getSignedPredicate(Predicate)));
1463 }
1464 } else if (isa<ConstantExpr>(Ops1)) {
1465 // If RHS is a constant expression, but the left side isn't, swap the
1466 // operands and try again.
1467 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1468 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1469 }
1470
1471 if (CmpInst::isFPPredicate(Predicate)) {
1472 // Flush any denormal constant float input according to denormal handling
1473 // mode.
1474 Ops0 = FlushFPConstant(Ops0, CtxF, /*IsOutput=*/false);
1475 if (!Ops0)
1476 return nullptr;
1477 Ops1 = FlushFPConstant(Ops1, CtxF, /*IsOutput=*/false);
1478 if (!Ops1)
1479 return nullptr;
1480 }
1481
1482 return ConstantFoldCompareInstruction(Predicate, Ops0, Ops1);
1483}
1484
1486 const DataLayout &DL) {
1488
1489 return ConstantFoldUnaryInstruction(Opcode, Op);
1490}
1491
1493 Constant *RHS,
1494 const DataLayout &DL) {
1496 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1497 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1498 return C;
1499
1501 return ConstantExpr::get(Opcode, LHS, RHS);
1502 return ConstantFoldBinaryInstruction(Opcode, LHS, RHS);
1503}
1504
1507 switch (Mode) {
1509 return nullptr;
1510 case DenormalMode::IEEE:
1511 return ConstantFP::get(Ty, APF);
1513 return ConstantFP::get(
1514 Ty, APFloat::getZero(APF.getSemantics(), APF.isNegative()));
1516 return ConstantFP::get(Ty, APFloat::getZero(APF.getSemantics(), false));
1517 default:
1518 break;
1519 }
1520
1521 llvm_unreachable("unknown denormal mode");
1522}
1523
1524/// Return the instruction's function, or \p CtxF if it is unavailable.
1525static const Function *getCtxFunc(const Instruction *CtxI,
1526 const Function *CtxF) {
1527 if (CtxI && CtxI->getParent())
1528 if (const Function *F = CtxI->getFunction())
1529 return F;
1530 return CtxF;
1531}
1532
1533/// Return the denormal mode for a floating-point operation at \p CtxI or in
1534/// \p CtxF, falling back to Dynamic if neither function is available or the
1535/// type is not floating-point.
1537 const Function *CtxF) {
1538 const Function *F = getCtxFunc(CtxI, CtxF);
1539 if (!F || !Ty->isFPOrFPVectorTy())
1540 return DenormalMode::getDynamic();
1541 return F->getDenormalMode(Ty->getScalarType()->getFltSemantics());
1542}
1543
1545 const Instruction *CtxI, const Function *CtxF) {
1546 assert(Ty->isFPOrFPVectorTy() && "expected floating-point type");
1547 auto Res = tryFoldFP(Opcode, Args, getDenormMode(Ty, CtxI, CtxF));
1548 return Res ? ConstantFP::get(Ty, Res->Value) : nullptr;
1549}
1550
1551static ConstantFP *
1552flushDenormalConstantFP(ConstantFP *CFP, const Function *CtxF, bool IsOutput) {
1553 const APFloat &APF = CFP->getValueAPF();
1554 if (!APF.isDenormal())
1555 return CFP;
1556
1557 DenormalMode Mode = getDenormMode(CFP->getType(), nullptr, CtxF);
1558 return flushDenormalConstant(CFP->getType(), APF,
1559 IsOutput ? Mode.Output : Mode.Input);
1560}
1561
1563 bool IsOutput) {
1564 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Operand))
1565 return flushDenormalConstantFP(CFP, CtxF, IsOutput);
1566
1568 return Operand;
1569
1570 Type *Ty = Operand->getType();
1571 VectorType *VecTy = dyn_cast<VectorType>(Ty);
1572 if (VecTy) {
1573 if (auto *Splat = dyn_cast_or_null<ConstantFP>(Operand->getSplatValue())) {
1574 ConstantFP *Folded = flushDenormalConstantFP(Splat, CtxF, IsOutput);
1575 if (!Folded)
1576 return nullptr;
1578 }
1579
1580 Ty = VecTy->getElementType();
1581 }
1582
1583 if (isa<ConstantExpr>(Operand))
1584 return Operand;
1585
1586 if (const auto *CV = dyn_cast<ConstantVector>(Operand)) {
1588 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1589 Constant *Element = CV->getAggregateElement(i);
1590 if (isa<UndefValue>(Element)) {
1591 NewElts.push_back(Element);
1592 continue;
1593 }
1594
1595 ConstantFP *CFP = dyn_cast<ConstantFP>(Element);
1596 if (!CFP)
1597 return nullptr;
1598
1599 ConstantFP *Folded = flushDenormalConstantFP(CFP, CtxF, IsOutput);
1600 if (!Folded)
1601 return nullptr;
1602 NewElts.push_back(Folded);
1603 }
1604
1605 return ConstantVector::get(NewElts);
1606 }
1607
1608 if (const auto *CDV = dyn_cast<ConstantDataVector>(Operand)) {
1610 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I) {
1611 const APFloat &Elt = CDV->getElementAsAPFloat(I);
1612 if (!Elt.isDenormal()) {
1613 NewElts.push_back(ConstantFP::get(Ty, Elt));
1614 } else {
1615 DenormalMode Mode = getDenormMode(Ty, nullptr, CtxF);
1617 flushDenormalConstant(Ty, Elt, IsOutput ? Mode.Output : Mode.Input);
1618 if (!Folded)
1619 return nullptr;
1620 NewElts.push_back(Folded);
1621 }
1622 }
1623
1624 return ConstantVector::get(NewElts);
1625 }
1626
1627 return nullptr;
1628}
1629
1631 Constant *RHS, const DataLayout &DL,
1632 const Instruction *I,
1633 bool AllowNonDeterministic) {
1634 if (Instruction::isBinaryOp(Opcode)) {
1635 // Flush denormal inputs if needed.
1636 Constant *Op0 =
1637 FlushFPConstant(LHS, I->getFunction(), /* IsOutput */ false);
1638 if (!Op0)
1639 return nullptr;
1640 Constant *Op1 =
1641 FlushFPConstant(RHS, I->getFunction(), /* IsOutput */ false);
1642 if (!Op1)
1643 return nullptr;
1644
1645 // If nsz or an algebraic FMF flag is set, the result of the FP operation
1646 // may change due to future optimization. Don't constant fold them if
1647 // non-deterministic results are not allowed.
1648 if (!AllowNonDeterministic)
1650 if (FP->hasNoSignedZeros() || FP->hasAllowReassoc() ||
1651 FP->hasAllowContract() || FP->hasAllowReciprocal())
1652 return nullptr;
1653
1654 // Calculate constant result.
1655 Constant *C = ConstantFoldBinaryOpOperands(Opcode, Op0, Op1, DL);
1656 if (!C)
1657 return nullptr;
1658
1659 // Flush denormal output if needed.
1660 C = FlushFPConstant(C, I->getFunction(), /* IsOutput */ true);
1661 if (!C)
1662 return nullptr;
1663
1664 // The precise NaN value is non-deterministic.
1665 if (!AllowNonDeterministic && C->isNaN())
1666 return nullptr;
1667
1668 return C;
1669 }
1670 // If instruction lacks a parent/function and the denormal mode cannot be
1671 // determined, use the default (IEEE).
1672 return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
1673}
1674
1676 Type *DestTy, const DataLayout &DL) {
1677 assert(Instruction::isCast(Opcode));
1678
1679 if (auto *CE = dyn_cast<ConstantExpr>(C))
1680 if (CE->isCast())
1681 if (unsigned NewOp = CastInst::isEliminableCastPair(
1682 Instruction::CastOps(CE->getOpcode()),
1683 Instruction::CastOps(Opcode), CE->getOperand(0)->getType(),
1684 C->getType(), DestTy, &DL))
1685 return ConstantFoldCastOperand(NewOp, CE->getOperand(0), DestTy, DL);
1686
1687 switch (Opcode) {
1688 default:
1689 llvm_unreachable("Missing case");
1690 case Instruction::PtrToAddr:
1691 case Instruction::PtrToInt:
1692 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1693 Constant *FoldedValue = nullptr;
1694 // If the input is an inttoptr, eliminate the pair. This requires knowing
1695 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1696 if (CE->getOpcode() == Instruction::IntToPtr) {
1697 // zext/trunc the inttoptr to pointer size. ptrtoaddr is truncated to
1698 // the address size below.
1699 FoldedValue = ConstantFoldIntegerCast(CE->getOperand(0),
1700 DL.getIntPtrType(CE->getType()),
1701 /*IsSigned=*/false, DL);
1702 } else if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
1703 // If we have GEP, we can perform the following folds:
1704 // (ptrtoint/ptrtoaddr (gep null, x)) -> x
1705 // (ptrtoint/ptrtoaddr (gep (gep null, x), y) -> x + y, etc.
1706 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1707 APInt BaseOffset(BitWidth, 0);
1708 auto *Base = cast<Constant>(GEP->stripAndAccumulateConstantOffsets(
1709 DL, BaseOffset, /*AllowNonInbounds=*/true));
1710 if (Base->isNullValue()) {
1711 FoldedValue = ConstantInt::get(CE->getContext(), BaseOffset);
1712 } else {
1713 // ptrtoint/ptrtoaddr (gep i8, Ptr, (sub 0, V))
1714 // -> sub (ptrtoint/ptrtoaddr Ptr), V
1715 if (GEP->getNumIndices() == 1 &&
1716 GEP->getSourceElementType()->isIntegerTy(8)) {
1717 auto *Ptr = cast<Constant>(GEP->getPointerOperand());
1718 auto *Sub = dyn_cast<ConstantExpr>(GEP->getOperand(1));
1719 Type *IntIdxTy = DL.getIndexType(Ptr->getType());
1720 if (Sub && Sub->getType() == IntIdxTy &&
1721 Sub->getOpcode() == Instruction::Sub &&
1722 Sub->getOperand(0)->isNullValue())
1723 FoldedValue = ConstantExpr::getSub(
1724 ConstantExpr::getCast(Opcode, Ptr, IntIdxTy),
1725 Sub->getOperand(1));
1726 }
1727 }
1728 }
1729 if (FoldedValue) {
1730 // Do a zext or trunc to get to the ptrtoint/ptrtoaddr dest size.
1731 return ConstantFoldIntegerCast(FoldedValue, DestTy, /*IsSigned=*/false,
1732 DL);
1733 }
1734 }
1735 break;
1736 case Instruction::IntToPtr:
1737 case Instruction::Trunc:
1738 case Instruction::ZExt:
1739 case Instruction::SExt:
1740 case Instruction::FPTrunc:
1741 case Instruction::FPExt:
1742 case Instruction::UIToFP:
1743 case Instruction::SIToFP:
1744 case Instruction::FPToUI:
1745 case Instruction::FPToSI:
1746 case Instruction::AddrSpaceCast:
1747 break;
1748 case Instruction::BitCast:
1749 return FoldBitCast(C, DestTy, DL);
1750 }
1751
1753 return ConstantExpr::getCast(Opcode, C, DestTy);
1754 return ConstantFoldCastInstruction(Opcode, C, DestTy);
1755}
1756
1758 bool IsSigned, const DataLayout &DL) {
1759 Type *SrcTy = C->getType();
1760 if (SrcTy == DestTy)
1761 return C;
1762 if (SrcTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1763 return ConstantFoldCastOperand(Instruction::Trunc, C, DestTy, DL);
1764 if (IsSigned)
1765 return ConstantFoldCastOperand(Instruction::SExt, C, DestTy, DL);
1766 return ConstantFoldCastOperand(Instruction::ZExt, C, DestTy, DL);
1767}
1768
1771 const DataLayout &DL) {
1772 // bitinsert C, C, undef -> poison
1774 return PoisonValue::get(Base->getType());
1775
1776 // bitinsert poison, poison, C -> poison
1778 return Base;
1779
1780 if (auto *VTy = dyn_cast<VectorType>(Base->getType())) {
1781 // Fast path for splatted constants.
1782 Constant *BaseSplat = Base->getSplatValue();
1783 Constant *ValSplat = Val->getSplatValue();
1784 Constant *OffsetSplat = Offset->getSplatValue();
1785 if (BaseSplat && ValSplat && OffsetSplat) {
1786 Constant *Res =
1787 ConstantFoldBitInsertOperands(BaseSplat, ValSplat, OffsetSplat, DL);
1788 if (!Res)
1789 return nullptr;
1790 return ConstantVector::getSplat(VTy->getElementCount(), Res);
1791 }
1792
1793 auto *FVTy = dyn_cast<FixedVectorType>(VTy);
1794 if (!FVTy)
1795 return nullptr;
1796
1797 // Fold each element and create a vector constant from those constants.
1799 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
1800 Constant *BaseElt = Base->getAggregateElement(I);
1801 Constant *ValElt = Val->getAggregateElement(I);
1802 Constant *OffsetElt = Offset->getAggregateElement(I);
1803 if (!BaseElt || !ValElt || !OffsetElt)
1804 return nullptr;
1805 Constant *Res =
1806 ConstantFoldBitInsertOperands(BaseElt, ValElt, OffsetElt, DL);
1807 if (!Res)
1808 return nullptr;
1809 Result.push_back(Res);
1810 }
1811
1812 return ConstantVector::get(Result);
1813 }
1814
1815 auto *COffset = dyn_cast<ConstantInt>(Offset);
1816 if (!COffset)
1817 return nullptr;
1818
1819 // bitinsert C, C, out_of_range -> poison
1820 unsigned BaseBits = DL.getTypeSizeInBits(Base->getType());
1821 unsigned Bits = DL.getTypeSizeInBits(Val->getType());
1822 uint64_t Off = COffset->getZExtValue();
1823 if (Off + Bits > BaseBits)
1824 return PoisonValue::get(Base->getType());
1825
1826 // Overwriting every bit of the base is a bitcast of the value.
1827 if (Bits == BaseBits)
1828 return ConstantFoldCastOperand(Instruction::BitCast, Val, Base->getType(),
1829 DL);
1830
1831 // bitinsert undef, undef, C -> undef
1832 // Any poison bits are refined to undef.
1834 return UndefValue::get(Base->getType());
1835
1836 // A byte constant can't mix poison or undef bits with other bits.
1837 auto *CB = dyn_cast<ConstantByte>(Base);
1838 // The value bits are unknown.
1839 if (!CB || isa<ConstantExpr>(Val) || Val->getType()->isPointerTy())
1840 return nullptr;
1841
1843 ConstantFoldCastOperand(Instruction::BitCast, Val,
1844 IntegerType::get(Base->getContext(), Bits), DL));
1845 if (!CI)
1846 return nullptr;
1847
1848 APInt Res = CB->getValue();
1849 Res.insertBits(CI->getValue(), Off);
1850 return ConstantByte::get(Base->getType(), Res);
1851}
1852
1855 const DataLayout &DL) {
1856 // bitextract poison, C -> poison
1857 // bitextract C, undef -> poison
1859 return PoisonValue::get(Ty);
1860
1861 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1862 Type *EltTy = VTy->getElementType();
1863 // Fast path for splatted constants.
1864 Constant *SrcSplat = Src->getSplatValue();
1865 Constant *OffsetSplat = Offset->getSplatValue();
1866 if (SrcSplat && OffsetSplat) {
1867 Constant *Res =
1868 ConstantFoldBitExtractOperands(EltTy, SrcSplat, OffsetSplat, DL);
1869 if (!Res)
1870 return nullptr;
1871 return ConstantVector::getSplat(VTy->getElementCount(), Res);
1872 }
1873
1874 auto *FVTy = dyn_cast<FixedVectorType>(VTy);
1875 if (!FVTy)
1876 return nullptr;
1877
1878 // Fold each element and create a vector constant from those constants.
1880 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
1881 Constant *SrcElt = Src->getAggregateElement(I);
1882 Constant *OffsetElt = Offset->getAggregateElement(I);
1883 if (!SrcElt || !OffsetElt)
1884 return nullptr;
1885 Constant *Res =
1886 ConstantFoldBitExtractOperands(EltTy, SrcElt, OffsetElt, DL);
1887 if (!Res)
1888 return nullptr;
1889 Result.push_back(Res);
1890 }
1891
1892 return ConstantVector::get(Result);
1893 }
1894
1895 auto *COffset = dyn_cast<ConstantInt>(Offset);
1896 if (!COffset)
1897 return nullptr;
1898
1899 // bitextract C, out_of_range -> poison
1900 unsigned Bits = DL.getTypeSizeInBits(Ty);
1901 uint64_t Off = COffset->getZExtValue();
1902 if (Off + Bits > DL.getTypeSizeInBits(Src->getType()))
1903 return PoisonValue::get(Ty);
1904
1905 // bitextract undef, C -> undef
1906 if (isa<UndefValue>(Src))
1907 return UndefValue::get(Ty);
1908
1909 auto *CB = dyn_cast<ConstantByte>(Src);
1910 // An integer can't be bitcast to a pointer.
1911 if (!CB || Ty->isPointerTy())
1912 return nullptr;
1913
1914 APInt Res = CB->getValue().extractBits(Bits, Off);
1916 Instruction::BitCast, ConstantInt::get(Src->getContext(), Res), Ty, DL);
1917}
1918
1919//===----------------------------------------------------------------------===//
1920// Constant Folding for Calls
1921//
1922
1923/// Returns true if the intrinsic can be constant folded, given \p IsStrictFP.
1924static bool canConstantFoldIntrinsic(Intrinsic::ID ID, bool IsStrictFP) {
1925 switch (ID) {
1926 // Operations that do not operate floating-point numbers and do not depend on
1927 // FP environment can be folded even in strictfp functions.
1928 case Intrinsic::bswap:
1929 case Intrinsic::ctpop:
1930 case Intrinsic::ctlz:
1931 case Intrinsic::cttz:
1932 case Intrinsic::fshl:
1933 case Intrinsic::fshr:
1934 case Intrinsic::clmul:
1935 case Intrinsic::pdep:
1936 case Intrinsic::pext:
1937 case Intrinsic::launder_invariant_group:
1938 case Intrinsic::masked_load:
1939 case Intrinsic::get_active_lane_mask:
1940 case Intrinsic::mask_beforefirst:
1941 case Intrinsic::abs:
1942 case Intrinsic::smax:
1943 case Intrinsic::smin:
1944 case Intrinsic::umax:
1945 case Intrinsic::umin:
1946 case Intrinsic::scmp:
1947 case Intrinsic::ucmp:
1948 case Intrinsic::sadd_with_overflow:
1949 case Intrinsic::uadd_with_overflow:
1950 case Intrinsic::ssub_with_overflow:
1951 case Intrinsic::usub_with_overflow:
1952 case Intrinsic::smul_with_overflow:
1953 case Intrinsic::umul_with_overflow:
1954 case Intrinsic::smulh:
1955 case Intrinsic::umulh:
1956 case Intrinsic::sadd_sat:
1957 case Intrinsic::uadd_sat:
1958 case Intrinsic::ssub_sat:
1959 case Intrinsic::usub_sat:
1960 case Intrinsic::sshl_sat:
1961 case Intrinsic::ushl_sat:
1962 case Intrinsic::smul_fix:
1963 case Intrinsic::smul_fix_sat:
1964 case Intrinsic::bitreverse:
1965 case Intrinsic::is_constant:
1966 case Intrinsic::vector_reduce_add:
1967 case Intrinsic::vector_reduce_mul:
1968 case Intrinsic::vector_reduce_and:
1969 case Intrinsic::vector_reduce_or:
1970 case Intrinsic::vector_reduce_xor:
1971 case Intrinsic::vector_reduce_smin:
1972 case Intrinsic::vector_reduce_smax:
1973 case Intrinsic::vector_reduce_umin:
1974 case Intrinsic::vector_reduce_umax:
1975 case Intrinsic::vector_partial_reduce_add:
1976 case Intrinsic::vector_extract:
1977 case Intrinsic::vector_insert:
1978 case Intrinsic::vector_interleave2:
1979 case Intrinsic::vector_interleave3:
1980 case Intrinsic::vector_interleave4:
1981 case Intrinsic::vector_interleave5:
1982 case Intrinsic::vector_interleave6:
1983 case Intrinsic::vector_interleave7:
1984 case Intrinsic::vector_interleave8:
1985 case Intrinsic::vector_deinterleave2:
1986 case Intrinsic::vector_deinterleave3:
1987 case Intrinsic::vector_deinterleave4:
1988 case Intrinsic::vector_deinterleave5:
1989 case Intrinsic::vector_deinterleave6:
1990 case Intrinsic::vector_deinterleave7:
1991 case Intrinsic::vector_deinterleave8:
1992 // Target intrinsics
1993 case Intrinsic::amdgcn_perm:
1994 case Intrinsic::amdgcn_wave_reduce_umin:
1995 case Intrinsic::amdgcn_wave_reduce_umax:
1996 case Intrinsic::amdgcn_wave_reduce_max:
1997 case Intrinsic::amdgcn_wave_reduce_min:
1998 case Intrinsic::amdgcn_wave_reduce_and:
1999 case Intrinsic::amdgcn_wave_reduce_or:
2000 case Intrinsic::amdgcn_wave_reduce_xor:
2001 case Intrinsic::amdgcn_wave_reduce_add:
2002 case Intrinsic::amdgcn_wave_reduce_sub:
2003 case Intrinsic::amdgcn_s_wqm:
2004 case Intrinsic::amdgcn_s_quadmask:
2005 case Intrinsic::amdgcn_s_bitreplicate:
2006 case Intrinsic::arm_crc32b:
2007 case Intrinsic::arm_crc32h:
2008 case Intrinsic::arm_crc32w:
2009 case Intrinsic::arm_crc32cb:
2010 case Intrinsic::arm_crc32ch:
2011 case Intrinsic::arm_crc32cw:
2012 case Intrinsic::arm_mve_vctp8:
2013 case Intrinsic::arm_mve_vctp16:
2014 case Intrinsic::arm_mve_vctp32:
2015 case Intrinsic::arm_mve_vctp64:
2016 case Intrinsic::aarch64_crc32b:
2017 case Intrinsic::aarch64_crc32h:
2018 case Intrinsic::aarch64_crc32w:
2019 case Intrinsic::aarch64_crc32x:
2020 case Intrinsic::aarch64_crc32cb:
2021 case Intrinsic::aarch64_crc32ch:
2022 case Intrinsic::aarch64_crc32cw:
2023 case Intrinsic::aarch64_crc32cx:
2024 case Intrinsic::aarch64_sve_convert_from_svbool:
2025 case Intrinsic::wasm_alltrue:
2026 case Intrinsic::wasm_anytrue:
2027 case Intrinsic::wasm_dot:
2028 // WebAssembly float semantics are always known
2029 case Intrinsic::wasm_trunc_signed:
2030 case Intrinsic::wasm_trunc_unsigned:
2031 case Intrinsic::x86_sse42_crc32_32_8:
2032 case Intrinsic::x86_sse42_crc32_32_16:
2033 case Intrinsic::x86_sse42_crc32_32_32:
2034 case Intrinsic::x86_sse42_crc32_64_64:
2035 return true;
2036
2037 // Floating point operations cannot be folded in strictfp functions in
2038 // general case. They can be folded if FP environment is known to compiler.
2039 case Intrinsic::minnum:
2040 case Intrinsic::maxnum:
2041 case Intrinsic::minimum:
2042 case Intrinsic::maximum:
2043 case Intrinsic::minimumnum:
2044 case Intrinsic::maximumnum:
2045 case Intrinsic::log:
2046 case Intrinsic::log2:
2047 case Intrinsic::log10:
2048 case Intrinsic::exp:
2049 case Intrinsic::exp2:
2050 case Intrinsic::exp10:
2051 case Intrinsic::sqrt:
2052 case Intrinsic::sin:
2053 case Intrinsic::cos:
2054 case Intrinsic::sincos:
2055 case Intrinsic::sinh:
2056 case Intrinsic::cosh:
2057 case Intrinsic::atan:
2058 case Intrinsic::pow:
2059 case Intrinsic::powi:
2060 case Intrinsic::ldexp:
2061 case Intrinsic::fma:
2062 case Intrinsic::fmuladd:
2063 case Intrinsic::frexp:
2064 case Intrinsic::fptoui_sat:
2065 case Intrinsic::fptosi_sat:
2066 case Intrinsic::amdgcn_cos:
2067 case Intrinsic::amdgcn_cubeid:
2068 case Intrinsic::amdgcn_cubema:
2069 case Intrinsic::amdgcn_cubesc:
2070 case Intrinsic::amdgcn_cubetc:
2071 case Intrinsic::amdgcn_fmul_legacy:
2072 case Intrinsic::amdgcn_fma_legacy:
2073 case Intrinsic::amdgcn_fract:
2074 case Intrinsic::amdgcn_sin:
2075 // The intrinsics below depend on rounding mode in MXCSR.
2076 case Intrinsic::x86_sse_cvtss2si:
2077 case Intrinsic::x86_sse_cvtss2si64:
2078 case Intrinsic::x86_sse_cvttss2si:
2079 case Intrinsic::x86_sse_cvttss2si64:
2080 case Intrinsic::x86_sse2_cvtsd2si:
2081 case Intrinsic::x86_sse2_cvtsd2si64:
2082 case Intrinsic::x86_sse2_cvttsd2si:
2083 case Intrinsic::x86_sse2_cvttsd2si64:
2084 case Intrinsic::x86_avx512_vcvtss2si32:
2085 case Intrinsic::x86_avx512_vcvtss2si64:
2086 case Intrinsic::x86_avx512_cvttss2si:
2087 case Intrinsic::x86_avx512_cvttss2si64:
2088 case Intrinsic::x86_avx512_vcvtsd2si32:
2089 case Intrinsic::x86_avx512_vcvtsd2si64:
2090 case Intrinsic::x86_avx512_cvttsd2si:
2091 case Intrinsic::x86_avx512_cvttsd2si64:
2092 case Intrinsic::x86_avx512_vcvtss2usi32:
2093 case Intrinsic::x86_avx512_vcvtss2usi64:
2094 case Intrinsic::x86_avx512_cvttss2usi:
2095 case Intrinsic::x86_avx512_cvttss2usi64:
2096 case Intrinsic::x86_avx512_vcvtsd2usi32:
2097 case Intrinsic::x86_avx512_vcvtsd2usi64:
2098 case Intrinsic::x86_avx512_cvttsd2usi:
2099 case Intrinsic::x86_avx512_cvttsd2usi64:
2100
2101 // NVVM FMax intrinsics
2102 case Intrinsic::nvvm_fmax_d:
2103 case Intrinsic::nvvm_fmax_f:
2104 case Intrinsic::nvvm_fmax_ftz_f:
2105 case Intrinsic::nvvm_fmax_ftz_nan_f:
2106 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
2107 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
2108 case Intrinsic::nvvm_fmax_nan_f:
2109 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
2110 case Intrinsic::nvvm_fmax_xorsign_abs_f:
2111
2112 // NVVM FMin intrinsics
2113 case Intrinsic::nvvm_fmin_d:
2114 case Intrinsic::nvvm_fmin_f:
2115 case Intrinsic::nvvm_fmin_ftz_f:
2116 case Intrinsic::nvvm_fmin_ftz_nan_f:
2117 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
2118 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
2119 case Intrinsic::nvvm_fmin_nan_f:
2120 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
2121 case Intrinsic::nvvm_fmin_xorsign_abs_f:
2122
2123 // NVVM float/double to int32/uint32 conversion intrinsics
2124 case Intrinsic::nvvm_f2i_rm:
2125 case Intrinsic::nvvm_f2i_rn:
2126 case Intrinsic::nvvm_f2i_rp:
2127 case Intrinsic::nvvm_f2i_rz:
2128 case Intrinsic::nvvm_f2i_rm_ftz:
2129 case Intrinsic::nvvm_f2i_rn_ftz:
2130 case Intrinsic::nvvm_f2i_rp_ftz:
2131 case Intrinsic::nvvm_f2i_rz_ftz:
2132 case Intrinsic::nvvm_f2ui_rm:
2133 case Intrinsic::nvvm_f2ui_rn:
2134 case Intrinsic::nvvm_f2ui_rp:
2135 case Intrinsic::nvvm_f2ui_rz:
2136 case Intrinsic::nvvm_f2ui_rm_ftz:
2137 case Intrinsic::nvvm_f2ui_rn_ftz:
2138 case Intrinsic::nvvm_f2ui_rp_ftz:
2139 case Intrinsic::nvvm_f2ui_rz_ftz:
2140 case Intrinsic::nvvm_d2i_rm:
2141 case Intrinsic::nvvm_d2i_rn:
2142 case Intrinsic::nvvm_d2i_rp:
2143 case Intrinsic::nvvm_d2i_rz:
2144 case Intrinsic::nvvm_d2ui_rm:
2145 case Intrinsic::nvvm_d2ui_rn:
2146 case Intrinsic::nvvm_d2ui_rp:
2147 case Intrinsic::nvvm_d2ui_rz:
2148
2149 // NVVM float/double to int64/uint64 conversion intrinsics
2150 case Intrinsic::nvvm_f2ll_rm:
2151 case Intrinsic::nvvm_f2ll_rn:
2152 case Intrinsic::nvvm_f2ll_rp:
2153 case Intrinsic::nvvm_f2ll_rz:
2154 case Intrinsic::nvvm_f2ll_rm_ftz:
2155 case Intrinsic::nvvm_f2ll_rn_ftz:
2156 case Intrinsic::nvvm_f2ll_rp_ftz:
2157 case Intrinsic::nvvm_f2ll_rz_ftz:
2158 case Intrinsic::nvvm_f2ull_rm:
2159 case Intrinsic::nvvm_f2ull_rn:
2160 case Intrinsic::nvvm_f2ull_rp:
2161 case Intrinsic::nvvm_f2ull_rz:
2162 case Intrinsic::nvvm_f2ull_rm_ftz:
2163 case Intrinsic::nvvm_f2ull_rn_ftz:
2164 case Intrinsic::nvvm_f2ull_rp_ftz:
2165 case Intrinsic::nvvm_f2ull_rz_ftz:
2166 case Intrinsic::nvvm_d2ll_rm:
2167 case Intrinsic::nvvm_d2ll_rn:
2168 case Intrinsic::nvvm_d2ll_rp:
2169 case Intrinsic::nvvm_d2ll_rz:
2170 case Intrinsic::nvvm_d2ull_rm:
2171 case Intrinsic::nvvm_d2ull_rn:
2172 case Intrinsic::nvvm_d2ull_rp:
2173 case Intrinsic::nvvm_d2ull_rz:
2174
2175 // NVVM math intrinsics:
2176 case Intrinsic::nvvm_ceil_d:
2177 case Intrinsic::nvvm_ceil_f:
2178 case Intrinsic::nvvm_ceil_ftz_f:
2179
2180 case Intrinsic::nvvm_fabs:
2181 case Intrinsic::nvvm_fabs_ftz:
2182
2183 case Intrinsic::nvvm_floor_d:
2184 case Intrinsic::nvvm_floor_f:
2185 case Intrinsic::nvvm_floor_ftz_f:
2186
2187 case Intrinsic::nvvm_rcp_rm_d:
2188 case Intrinsic::nvvm_rcp_rm_f:
2189 case Intrinsic::nvvm_rcp_rm_ftz_f:
2190 case Intrinsic::nvvm_rcp_rn_d:
2191 case Intrinsic::nvvm_rcp_rn_f:
2192 case Intrinsic::nvvm_rcp_rn_ftz_f:
2193 case Intrinsic::nvvm_rcp_rp_d:
2194 case Intrinsic::nvvm_rcp_rp_f:
2195 case Intrinsic::nvvm_rcp_rp_ftz_f:
2196 case Intrinsic::nvvm_rcp_rz_d:
2197 case Intrinsic::nvvm_rcp_rz_f:
2198 case Intrinsic::nvvm_rcp_rz_ftz_f:
2199
2200 case Intrinsic::nvvm_round_d:
2201 case Intrinsic::nvvm_round_f:
2202 case Intrinsic::nvvm_round_ftz_f:
2203
2204 case Intrinsic::nvvm_saturate_d:
2205 case Intrinsic::nvvm_saturate_f:
2206 case Intrinsic::nvvm_saturate_ftz_f:
2207
2208 case Intrinsic::nvvm_sqrt_f:
2209 case Intrinsic::nvvm_sqrt_rn_d:
2210 case Intrinsic::nvvm_sqrt_rn_f:
2211 case Intrinsic::nvvm_sqrt_rn_ftz_f:
2212 return !IsStrictFP;
2213
2214 // NVVM fadd/fmul/fma intrinsics with explicit rounding modes
2215 case Intrinsic::nvvm_fadd:
2216 case Intrinsic::nvvm_fadd_ftz:
2217 case Intrinsic::nvvm_fma:
2218 case Intrinsic::nvvm_fma_ftz:
2219 case Intrinsic::nvvm_fmul:
2220 case Intrinsic::nvvm_fmul_ftz:
2221
2222 // NVVM div intrinsics with explicit rounding modes
2223 case Intrinsic::nvvm_div_rm_d:
2224 case Intrinsic::nvvm_div_rn_d:
2225 case Intrinsic::nvvm_div_rp_d:
2226 case Intrinsic::nvvm_div_rz_d:
2227 case Intrinsic::nvvm_div_rm_f:
2228 case Intrinsic::nvvm_div_rn_f:
2229 case Intrinsic::nvvm_div_rp_f:
2230 case Intrinsic::nvvm_div_rz_f:
2231 case Intrinsic::nvvm_div_rm_ftz_f:
2232 case Intrinsic::nvvm_div_rn_ftz_f:
2233 case Intrinsic::nvvm_div_rp_ftz_f:
2234 case Intrinsic::nvvm_div_rz_ftz_f:
2235
2236 // Sign operations are actually bitwise operations, they do not raise
2237 // exceptions even for SNANs.
2238 case Intrinsic::fabs:
2239 case Intrinsic::copysign:
2240 case Intrinsic::is_fpclass:
2241 // Non-constrained variants of rounding operations means default FP
2242 // environment, they can be folded in any case.
2243 case Intrinsic::ceil:
2244 case Intrinsic::floor:
2245 case Intrinsic::round:
2246 case Intrinsic::roundeven:
2247 case Intrinsic::trunc:
2248 case Intrinsic::nearbyint:
2249 case Intrinsic::rint:
2250 case Intrinsic::canonicalize:
2251
2252 // Constrained intrinsics can be folded if FP environment is known
2253 // to compiler.
2254 case Intrinsic::experimental_constrained_fma:
2255 case Intrinsic::experimental_constrained_fmuladd:
2256 case Intrinsic::experimental_constrained_fadd:
2257 case Intrinsic::experimental_constrained_fsub:
2258 case Intrinsic::experimental_constrained_fmul:
2259 case Intrinsic::experimental_constrained_fdiv:
2260 case Intrinsic::experimental_constrained_frem:
2261 case Intrinsic::experimental_constrained_fpext:
2262 case Intrinsic::experimental_constrained_ceil:
2263 case Intrinsic::experimental_constrained_floor:
2264 case Intrinsic::experimental_constrained_round:
2265 case Intrinsic::experimental_constrained_roundeven:
2266 case Intrinsic::experimental_constrained_trunc:
2267 case Intrinsic::experimental_constrained_nearbyint:
2268 case Intrinsic::experimental_constrained_rint:
2269 case Intrinsic::experimental_constrained_fcmp:
2270 case Intrinsic::experimental_constrained_fcmps:
2271
2272 case Intrinsic::experimental_cttz_elts:
2273 return true;
2274 default:
2275 return false;
2276 }
2277}
2278
2279/// Given a function's return type and its operands, determine if any of them of
2280/// of floating-point type.
2282 return RetTy->isFloatingPointTy() || any_of(Ops, [](Value *V) {
2283 return V->getType()->isFloatingPointTy();
2284 });
2285}
2286
2288 const TargetLibraryInfo *TLI) {
2289 if (Call->isNoBuiltin())
2290 return false;
2291 if (Call->getFunctionType() != F->getFunctionType())
2292 return false;
2293
2294 // Allow FP calls (both libcalls and intrinsics) to avoid being folded.
2295 // This can be useful for GPU targets or in cross-compilation scenarios
2296 // when the exact target FP behaviour is required, and the host compiler's
2297 // behaviour may be slightly different from the device's run-time behaviour.
2300 F->getReturnType(),
2301 ArrayRef<Value *>((Value *const *)(F->arg_begin()), F->arg_size())))
2302 return false;
2303
2304 if (F->getIntrinsicID() != Intrinsic::not_intrinsic)
2305 return canConstantFoldIntrinsic(F->getIntrinsicID(), Call->isStrictFP());
2306
2307 if (!TLI || Call->isStrictFP())
2308 return false;
2309
2310 LibFunc Func = TLI->getLibFunc(*F);
2311 if (Func == NotLibFunc)
2312 return false;
2313
2314 switch (Func) {
2315 case LibFunc_acos:
2316 case LibFunc_acosf:
2317 case LibFunc_acos_finite:
2318 case LibFunc_acosf_finite:
2319 case LibFunc_asin:
2320 case LibFunc_asinf:
2321 case LibFunc_asin_finite:
2322 case LibFunc_asinf_finite:
2323 case LibFunc_atan:
2324 case LibFunc_atanf:
2325 case LibFunc_atan2:
2326 case LibFunc_atan2f:
2327 case LibFunc_atan2_finite:
2328 case LibFunc_atan2f_finite:
2329 case LibFunc_ceil:
2330 case LibFunc_ceilf:
2331 case LibFunc_cosh:
2332 case LibFunc_coshf:
2333 case LibFunc_cosh_finite:
2334 case LibFunc_coshf_finite:
2335 case LibFunc_cos:
2336 case LibFunc_cosf:
2337 case LibFunc_erf:
2338 case LibFunc_erff:
2339 case LibFunc_exp:
2340 case LibFunc_expf:
2341 case LibFunc_exp_finite:
2342 case LibFunc_expf_finite:
2343 case LibFunc_exp2:
2344 case LibFunc_exp2f:
2345 case LibFunc_exp2_finite:
2346 case LibFunc_exp2f_finite:
2347 case LibFunc_fabs:
2348 case LibFunc_fabsf:
2349 case LibFunc_floor:
2350 case LibFunc_floorf:
2351 case LibFunc_fmod:
2352 case LibFunc_fmodf:
2353 case LibFunc_ilogb:
2354 case LibFunc_ilogbf:
2355 case LibFunc_log:
2356 case LibFunc_logf:
2357 case LibFunc_log_finite:
2358 case LibFunc_logf_finite:
2359 case LibFunc_logb:
2360 case LibFunc_logbf:
2361 case LibFunc_logl:
2362 case LibFunc_log2:
2363 case LibFunc_log2f:
2364 case LibFunc_log2_finite:
2365 case LibFunc_log2f_finite:
2366 case LibFunc_log10:
2367 case LibFunc_log10f:
2368 case LibFunc_log10_finite:
2369 case LibFunc_log10f_finite:
2370 case LibFunc_log1p:
2371 case LibFunc_log1pf:
2372 case LibFunc_nearbyint:
2373 case LibFunc_nearbyintf:
2374 case LibFunc_nextafter:
2375 case LibFunc_nextafterf:
2376 case LibFunc_nexttoward:
2377 case LibFunc_nexttowardf:
2378 case LibFunc_pow:
2379 case LibFunc_powf:
2380 case LibFunc_pow_finite:
2381 case LibFunc_powf_finite:
2382 case LibFunc_remainder:
2383 case LibFunc_remainderf:
2384 case LibFunc_rint:
2385 case LibFunc_rintf:
2386 case LibFunc_round:
2387 case LibFunc_roundf:
2388 case LibFunc_roundeven:
2389 case LibFunc_roundevenf:
2390 case LibFunc_sin:
2391 case LibFunc_sinf:
2392 case LibFunc_sinh:
2393 case LibFunc_sinhf:
2394 case LibFunc_sinh_finite:
2395 case LibFunc_sinhf_finite:
2396 case LibFunc_strlen:
2397 case LibFunc_sqrt:
2398 case LibFunc_sqrtf:
2399 case LibFunc_tan:
2400 case LibFunc_tanf:
2401 case LibFunc_tanh:
2402 case LibFunc_tanhf:
2403 case LibFunc_trunc:
2404 case LibFunc_truncf:
2405 return true;
2406 default:
2407 return false;
2408 }
2409}
2410
2411namespace {
2412
2413Constant *GetConstantFoldFPValue(double V, Type *Ty) {
2414 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isBFloatTy()) {
2415 APFloat APF(V);
2416 bool unused;
2417 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
2418 return ConstantFP::get(Ty->getContext(), APF);
2419 }
2420 if (Ty->isDoubleTy())
2421 return ConstantFP::get(Ty->getContext(), APFloat(V));
2422 llvm_unreachable("Can only constant fold half/float/double/bfloat");
2423}
2424
2425#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2426Constant *GetConstantFoldFPValue128(float128 V, Type *Ty) {
2427 if (Ty->isFP128Ty())
2428 return ConstantFP::get(Ty, V);
2429 llvm_unreachable("Can only constant fold fp128");
2430}
2431#endif
2432
2433/// Clear the floating-point exception state.
2434inline void llvm_fenv_clearexcept() {
2435#if defined(FE_ALL_EXCEPT)
2436 feclearexcept(FE_ALL_EXCEPT);
2437#endif
2438 errno = 0;
2439}
2440
2441/// Test if a floating-point exception was raised.
2442inline bool llvm_fenv_testexcept() {
2443 int errno_val = errno;
2444 if (errno_val == ERANGE || errno_val == EDOM)
2445 return true;
2446#if defined(FE_ALL_EXCEPT) && defined(FE_INEXACT)
2447 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
2448 return true;
2449#endif
2450 return false;
2451}
2452
2453static APFloat FTZPreserveSign(const APFloat &V) {
2454 if (V.isDenormal())
2455 return APFloat::getZero(V.getSemantics(), V.isNegative());
2456 return V;
2457}
2458
2459static APFloat FlushToPositiveZero(const APFloat &V) {
2460 if (V.isDenormal())
2461 return APFloat::getZero(V.getSemantics(), false);
2462 return V;
2463}
2464
2465static APFloat FlushWithDenormKind(const APFloat &V,
2466 DenormalMode::DenormalModeKind DenormKind) {
2469 switch (DenormKind) {
2471 return V;
2473 return FTZPreserveSign(V);
2475 return FlushToPositiveZero(V);
2476 default:
2477 llvm_unreachable("Invalid denormal mode!");
2478 }
2479}
2480
2481#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2482Constant *ConstantFoldFP128(float128 (*NativeFP)(float128), const APFloat &V,
2483 Type *Ty) {
2484 llvm_fenv_clearexcept();
2485 float128 Result = NativeFP(V.convertToQuad());
2486 if (llvm_fenv_testexcept()) {
2487 llvm_fenv_clearexcept();
2488 return nullptr;
2489 }
2490
2491 return GetConstantFoldFPValue128(Result, Ty);
2492}
2493#endif
2494
2495Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
2496 const APFloat &V, const APFloat &W, Type *Ty) {
2497 llvm_fenv_clearexcept();
2498 double Result = NativeFP(V.convertToDouble(), W.convertToDouble());
2499 if (llvm_fenv_testexcept()) {
2500 llvm_fenv_clearexcept();
2501 return nullptr;
2502 }
2503
2504 return GetConstantFoldFPValue(Result, Ty);
2505}
2506
2507Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
2508 auto *OpVT = cast<VectorType>(Op->getType());
2509
2510 // This is the same as the underlying binops - poison propagates.
2511 if (Op->containsPoisonElement())
2512 return PoisonValue::get(OpVT->getElementType());
2513
2514 // Shortcut non-accumulating reductions.
2515 if (Constant *SplatVal = Op->getSplatValue()) {
2516 switch (IID) {
2517 case Intrinsic::vector_reduce_and:
2518 case Intrinsic::vector_reduce_or:
2519 case Intrinsic::vector_reduce_smin:
2520 case Intrinsic::vector_reduce_smax:
2521 case Intrinsic::vector_reduce_umin:
2522 case Intrinsic::vector_reduce_umax:
2523 return SplatVal;
2524 case Intrinsic::vector_reduce_add:
2525 if (SplatVal->isNullValue())
2526 return SplatVal;
2527 break;
2528 case Intrinsic::vector_reduce_mul:
2529 if (SplatVal->isNullValue() || SplatVal->isOneValue())
2530 return SplatVal;
2531 break;
2532 case Intrinsic::vector_reduce_xor:
2533 if (SplatVal->isNullValue())
2534 return SplatVal;
2535 if (OpVT->getElementCount().isKnownMultipleOf(2))
2536 return Constant::getNullValue(OpVT->getElementType());
2537 break;
2538 }
2539 }
2540
2542 if (!VT)
2543 return nullptr;
2544
2545 auto *EltC = dyn_cast_or_null<ConstantInt>(Op->getAggregateElement(0U));
2546 if (!EltC)
2547 return nullptr;
2548
2549 APInt Acc = EltC->getValue();
2550 for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
2551 if (!(EltC = dyn_cast_or_null<ConstantInt>(Op->getAggregateElement(I))))
2552 return nullptr;
2553 const APInt &X = EltC->getValue();
2554 switch (IID) {
2555 case Intrinsic::vector_reduce_add:
2556 Acc = Acc + X;
2557 break;
2558 case Intrinsic::vector_reduce_mul:
2559 Acc = Acc * X;
2560 break;
2561 case Intrinsic::vector_reduce_and:
2562 Acc = Acc & X;
2563 break;
2564 case Intrinsic::vector_reduce_or:
2565 Acc = Acc | X;
2566 break;
2567 case Intrinsic::vector_reduce_xor:
2568 Acc = Acc ^ X;
2569 break;
2570 case Intrinsic::vector_reduce_smin:
2571 Acc = APIntOps::smin(Acc, X);
2572 break;
2573 case Intrinsic::vector_reduce_smax:
2574 Acc = APIntOps::smax(Acc, X);
2575 break;
2576 case Intrinsic::vector_reduce_umin:
2577 Acc = APIntOps::umin(Acc, X);
2578 break;
2579 case Intrinsic::vector_reduce_umax:
2580 Acc = APIntOps::umax(Acc, X);
2581 break;
2582 }
2583 }
2584
2585 return ConstantInt::get(Op->getContext(), Acc);
2586}
2587
2588/// Fold a vector partial reduction add using the deterministic grouping
2589/// chosen by TargetLowering::expandPartialReduceMLA. Although the
2590/// LangRef leaves the grouping unspecified, input element I is accumulated
2591/// into result lane I % NumAccElts, with each accumulator element seeding
2592/// its corresponding result lane. Returns nullptr if any element cannot be
2593/// folded.
2594static Constant *constantFoldVectorPartialReduceAdd(Constant *Acc,
2595 Constant *Input,
2596 const DataLayout &DL) {
2597 auto *AccTy = cast<FixedVectorType>(Acc->getType());
2598 // A fixed result type does not guarantee a fixed input type.
2599 auto *InputTy = dyn_cast<FixedVectorType>(Input->getType());
2600 if (!InputTy)
2601 return nullptr;
2602
2603 unsigned NumAccElts = AccTy->getNumElements();
2604 unsigned NumInputElts = InputTy->getNumElements();
2605
2606 SmallVector<Constant *> ResultElts(NumAccElts);
2607 for (unsigned I = 0; I < NumAccElts; ++I) {
2608 ResultElts[I] = Acc->getAggregateElement(I);
2609 if (!ResultElts[I])
2610 return nullptr;
2611 }
2612
2613 for (unsigned I = 0; I < NumInputElts; ++I) {
2614 Constant *InputElt = Input->getAggregateElement(I);
2615 if (!InputElt)
2616 return nullptr;
2617
2618 unsigned ResultIdx = I % NumAccElts;
2620 Instruction::Add, ResultElts[ResultIdx], InputElt, DL);
2621 if (!Folded)
2622 return nullptr;
2623
2624 ResultElts[ResultIdx] = Folded;
2625 }
2626
2627 return ConstantVector::get(ResultElts);
2628}
2629
2630/// Attempt to fold an SSE floating point to integer conversion of a constant
2631/// floating point. If roundTowardZero is false, the default IEEE rounding is
2632/// used (toward nearest, ties to even). This matches the behavior of the
2633/// non-truncating SSE instructions in the default rounding mode. The desired
2634/// integer type Ty is used to select how many bits are available for the
2635/// result. Returns null if the conversion cannot be performed, otherwise
2636/// returns the Constant value resulting from the conversion.
2637Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
2638 Type *Ty, bool IsSigned) {
2639 // All of these conversion intrinsics form an integer of at most 64bits.
2640 unsigned ResultWidth = Ty->getIntegerBitWidth();
2641 assert(ResultWidth <= 64 &&
2642 "Can only constant fold conversions to 64 and 32 bit ints");
2643
2644 uint64_t UIntVal;
2645 bool isExact = false;
2649 Val.convertToInteger(MutableArrayRef(UIntVal), ResultWidth,
2650 IsSigned, mode, &isExact);
2651 if (status != APFloat::opOK &&
2652 (!roundTowardZero || status != APFloat::opInexact))
2653 return nullptr;
2654 return ConstantInt::get(Ty, UIntVal, IsSigned);
2655}
2656
2657double getValueAsDouble(ConstantFP *Op) {
2658 Type *Ty = Op->getType();
2659
2660 if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2661 return Op->getValueAPF().convertToDouble();
2662
2663 bool unused;
2664 APFloat APF = Op->getValueAPF();
2666 return APF.convertToDouble();
2667}
2668
2669static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
2670 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
2671 C = &CI->getValue();
2672 return true;
2673 }
2674 if (isa<UndefValue>(Op)) {
2675 C = nullptr;
2676 return true;
2677 }
2678 return false;
2679}
2680
2681/// Checks if the given intrinsic call, which evaluates to constant, is allowed
2682/// to be folded.
2683///
2684/// \param CI Constrained intrinsic call.
2685/// \param St Exception flags raised during constant evaluation.
2686static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI,
2687 APFloat::opStatus St) {
2688 std::optional<RoundingMode> ORM = CI->getRoundingMode();
2689 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2690
2691 // If the operation does not change exception status flags, it is safe
2692 // to fold.
2693 if (St == APFloat::opStatus::opOK)
2694 return true;
2695
2696 // If evaluation raised FP exception, the result can depend on rounding
2697 // mode. If the latter is unknown, folding is not possible.
2698 if (ORM == RoundingMode::Dynamic)
2699 return false;
2700
2701 // If FP exceptions are ignored, fold the call, even if such exception is
2702 // raised.
2703 if (EB && *EB != fp::ExceptionBehavior::ebStrict)
2704 return true;
2705
2706 // Leave the calculation for runtime so that exception flags be correctly set
2707 // in hardware.
2708 return false;
2709}
2710
2711/// Returns the rounding mode that should be used for constant evaluation.
2712static RoundingMode
2713getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) {
2714 std::optional<RoundingMode> ORM = CI->getRoundingMode();
2715 if (!ORM || *ORM == RoundingMode::Dynamic)
2716 // Even if the rounding mode is unknown, try evaluating the operation.
2717 // If it does not raise inexact exception, rounding was not applied,
2718 // so the result is exact and does not depend on rounding mode. Whether
2719 // other FP exceptions are raised, it does not depend on rounding mode.
2721 return *ORM;
2722}
2723
2724/// Try to constant fold llvm.canonicalize for the given caller and value.
2725static Constant *constantFoldCanonicalize(const Type *Ty, const APFloat &Src,
2726 const Function *CtxF = nullptr) {
2727 // Zero, positive and negative, is always OK to fold.
2728 if (Src.isZero()) {
2729 // Get a fresh 0, since ppc_fp128 does have non-canonical zeros.
2730 return ConstantFP::get(
2731 Ty->getContext(),
2732 APFloat::getZero(Src.getSemantics(), Src.isNegative()));
2733 }
2734
2735 if (!Ty->isIEEELikeFPTy())
2736 return nullptr;
2737
2738 // Zero is always canonical and the sign must be preserved.
2739 //
2740 // Denorms and nans may have special encodings, but it should be OK to fold a
2741 // totally average number.
2742 if (Src.isNormal() || Src.isInfinity())
2743 return ConstantFP::get(Ty->getContext(), Src);
2744
2745 if (Src.isDenormal() && CtxF) {
2746 DenormalMode DenormMode = CtxF->getDenormalMode(Src.getSemantics());
2747
2748 if (DenormMode == DenormalMode::getIEEE())
2749 return ConstantFP::get(Ty->getContext(), Src);
2750
2751 if (DenormMode.Input == DenormalMode::Dynamic)
2752 return nullptr;
2753
2754 // If we know if either input or output is flushed, we can fold.
2755 if ((DenormMode.Input == DenormalMode::Dynamic &&
2756 DenormMode.Output == DenormalMode::IEEE) ||
2757 (DenormMode.Input == DenormalMode::IEEE &&
2758 DenormMode.Output == DenormalMode::Dynamic))
2759 return nullptr;
2760
2761 bool IsPositive =
2762 (!Src.isNegative() || DenormMode.Input == DenormalMode::PositiveZero ||
2763 (DenormMode.Output == DenormalMode::PositiveZero &&
2764 DenormMode.Input == DenormalMode::IEEE));
2765
2766 return ConstantFP::get(Ty->getContext(),
2767 APFloat::getZero(Src.getSemantics(), !IsPositive));
2768 }
2769
2770 return nullptr;
2771}
2772
2773static Constant *ConstantFoldScalarCall1(StringRef Name,
2774 Intrinsic::ID IntrinsicID, Type *Ty,
2776 const TargetLibraryInfo *TLI = nullptr,
2777 const CallBase *Call = nullptr,
2778 const Function *CtxF = nullptr) {
2779 assert(Operands.size() == 1 && "Wrong number of operands.");
2780
2781 if (IntrinsicID == Intrinsic::is_constant) {
2782 // We know we have a "Constant" argument. But we want to only
2783 // return true for manifest constants, not those that depend on
2784 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
2785 if (Operands[0]->isManifestConstant())
2786 return ConstantInt::getTrue(Ty->getContext());
2787 return nullptr;
2788 }
2789
2790 if (isa<UndefValue>(Operands[0])) {
2791 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
2792 // ctpop() is between 0 and bitwidth, pick 0 for undef.
2793 // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
2794 if (IntrinsicID == Intrinsic::cos ||
2795 IntrinsicID == Intrinsic::ctpop ||
2796 IntrinsicID == Intrinsic::fptoui_sat ||
2797 IntrinsicID == Intrinsic::fptosi_sat ||
2798 IntrinsicID == Intrinsic::canonicalize)
2799 return Constant::getNullValue(Ty);
2800 if (IntrinsicID == Intrinsic::bswap ||
2801 IntrinsicID == Intrinsic::bitreverse ||
2802 IntrinsicID == Intrinsic::launder_invariant_group)
2803 return Operands[0];
2804 }
2805
2807 // launder(null) == null iff in addrspace 0
2808 if (IntrinsicID == Intrinsic::launder_invariant_group) {
2809 // If instruction is not yet put in a basic block (e.g. when cloning
2810 // a function during inlining), Call's caller may not be available.
2811 // So check Call's BB first before querying Call->getCaller.
2812 const Function *Caller =
2813 Call && Call->getParent() ? Call->getCaller() : nullptr;
2814 if (Caller &&
2816 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
2817 return Operands[0];
2818 }
2819 return nullptr;
2820 }
2821 }
2822
2823 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
2824 APFloat U = Op->getValueAPF();
2825
2826 // fpext is exact in every rounding mode, so the only exception it can
2827 // raise is invalid for a signaling NaN input. Handle it before the type
2828 // check below so fp128 and x86_fp80 results are folded too.
2829 if (IntrinsicID == Intrinsic::experimental_constrained_fpext) {
2831 if (!CI)
2832 return nullptr;
2833 bool LosesInfo;
2834 APFloat::opStatus St = U.convert(
2835 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &LosesInfo);
2836 if (!mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(CI), St))
2837 return nullptr;
2838 return ConstantFP::get(Ty->getContext(), U);
2839 }
2840
2841 if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
2842 IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
2843 bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
2844
2845 if (U.isNaN())
2846 return nullptr;
2847
2848 unsigned Width = Ty->getIntegerBitWidth();
2849 APSInt Int(Width, !Signed);
2850 bool IsExact = false;
2852 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2853
2855 return ConstantInt::get(Ty, Int);
2856
2857 return nullptr;
2858 }
2859
2860 if (IntrinsicID == Intrinsic::fptoui_sat ||
2861 IntrinsicID == Intrinsic::fptosi_sat) {
2862 // convertToInteger() already has the desired saturation semantics.
2863 APSInt Int(Ty->getIntegerBitWidth(),
2864 IntrinsicID == Intrinsic::fptoui_sat);
2865 bool IsExact;
2866 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2867 return ConstantInt::get(Ty, Int);
2868 }
2869
2870 if (IntrinsicID == Intrinsic::canonicalize)
2871 return constantFoldCanonicalize(Ty, U, getCtxFunc(Call, CtxF));
2872
2873#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2874 if (Ty->isFP128Ty()) {
2875 if (IntrinsicID == Intrinsic::log) {
2876 float128 Result = logf128(Op->getValueAPF().convertToQuad());
2877 return GetConstantFoldFPValue128(Result, Ty);
2878 }
2879
2880 if (TLI && TLI->getLibFunc(Name) == LibFunc_logl &&
2881 TLI->has(LibFunc_logl))
2882 return ConstantFoldFP128(logf128, Op->getValueAPF(), Ty);
2883 }
2884#endif
2885
2886 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy() &&
2887 !Ty->isIntegerTy() && !Ty->isBFloatTy())
2888 return nullptr;
2889
2890 // Use internal versions of these intrinsics.
2891
2892 switch (IntrinsicID) {
2893 default:
2894 break;
2895 case Intrinsic::nearbyint:
2896 case Intrinsic::rint:
2897 case Intrinsic::roundeven:
2898 return tryFoldFPConst(Ty, FPOp::RoundEven, {U}, Call, CtxF);
2899 case Intrinsic::round:
2900 return tryFoldFPConst(Ty, FPOp::Round, {U}, Call, CtxF);
2901 case Intrinsic::ceil:
2902 return tryFoldFPConst(Ty, FPOp::Ceil, {U}, Call, CtxF);
2903 case Intrinsic::floor:
2904 return tryFoldFPConst(Ty, FPOp::Floor, {U}, Call, CtxF);
2905 case Intrinsic::trunc:
2906 return tryFoldFPConst(Ty, FPOp::Trunc, {U}, Call, CtxF);
2907 }
2908
2909 if (IntrinsicID == Intrinsic::fabs) {
2910 U.clearSign();
2911 return ConstantFP::get(Ty, U);
2912 }
2913
2914 if (IntrinsicID == Intrinsic::amdgcn_fract) {
2915 // The v_fract instruction behaves like the OpenCL spec, which defines
2916 // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
2917 // there to prevent fract(-small) from returning 1.0. It returns the
2918 // largest positive floating-point number less than 1.0."
2919 APFloat FloorU(U);
2920 FloorU.roundToIntegral(APFloat::rmTowardNegative);
2921 APFloat FractU(U - FloorU);
2922 APFloat AlmostOne(U.getSemantics(), 1);
2923 AlmostOne.next(/*nextDown*/ true);
2924 return ConstantFP::get(Ty, minimum(FractU, AlmostOne));
2925 }
2926
2927 // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
2928 // raise FP exceptions, unless the argument is signaling NaN.
2929
2931 std::optional<APFloat::roundingMode> RM;
2932 switch (IntrinsicID) {
2933 default:
2934 break;
2935 case Intrinsic::experimental_constrained_nearbyint:
2936 case Intrinsic::experimental_constrained_rint: {
2937 RM = CI->getRoundingMode();
2938 if (!RM || *RM == RoundingMode::Dynamic)
2939 return nullptr;
2940 break;
2941 }
2942 case Intrinsic::experimental_constrained_round:
2944 break;
2945 case Intrinsic::experimental_constrained_ceil:
2947 break;
2948 case Intrinsic::experimental_constrained_floor:
2950 break;
2951 case Intrinsic::experimental_constrained_trunc:
2953 break;
2954 }
2955 if (RM) {
2956 if (U.isFinite()) {
2957 APFloat::opStatus St = U.roundToIntegral(*RM);
2958 if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2959 St == APFloat::opInexact) {
2960 std::optional<fp::ExceptionBehavior> EB =
2962 if (EB == fp::ebStrict)
2963 return nullptr;
2964 }
2965 } else if (U.isSignaling()) {
2966 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2967 if (EB && *EB != fp::ebIgnore)
2968 return nullptr;
2969 U = APFloat::getQNaN(U.getSemantics());
2970 }
2971 return ConstantFP::get(Ty, U);
2972 }
2973 }
2974
2975 // NVVM float/double to signed/unsigned int32/int64 conversions:
2976 switch (IntrinsicID) {
2977 // f2i
2978 case Intrinsic::nvvm_f2i_rm:
2979 case Intrinsic::nvvm_f2i_rn:
2980 case Intrinsic::nvvm_f2i_rp:
2981 case Intrinsic::nvvm_f2i_rz:
2982 case Intrinsic::nvvm_f2i_rm_ftz:
2983 case Intrinsic::nvvm_f2i_rn_ftz:
2984 case Intrinsic::nvvm_f2i_rp_ftz:
2985 case Intrinsic::nvvm_f2i_rz_ftz:
2986 // f2ui
2987 case Intrinsic::nvvm_f2ui_rm:
2988 case Intrinsic::nvvm_f2ui_rn:
2989 case Intrinsic::nvvm_f2ui_rp:
2990 case Intrinsic::nvvm_f2ui_rz:
2991 case Intrinsic::nvvm_f2ui_rm_ftz:
2992 case Intrinsic::nvvm_f2ui_rn_ftz:
2993 case Intrinsic::nvvm_f2ui_rp_ftz:
2994 case Intrinsic::nvvm_f2ui_rz_ftz:
2995 // d2i
2996 case Intrinsic::nvvm_d2i_rm:
2997 case Intrinsic::nvvm_d2i_rn:
2998 case Intrinsic::nvvm_d2i_rp:
2999 case Intrinsic::nvvm_d2i_rz:
3000 // d2ui
3001 case Intrinsic::nvvm_d2ui_rm:
3002 case Intrinsic::nvvm_d2ui_rn:
3003 case Intrinsic::nvvm_d2ui_rp:
3004 case Intrinsic::nvvm_d2ui_rz:
3005 // f2ll
3006 case Intrinsic::nvvm_f2ll_rm:
3007 case Intrinsic::nvvm_f2ll_rn:
3008 case Intrinsic::nvvm_f2ll_rp:
3009 case Intrinsic::nvvm_f2ll_rz:
3010 case Intrinsic::nvvm_f2ll_rm_ftz:
3011 case Intrinsic::nvvm_f2ll_rn_ftz:
3012 case Intrinsic::nvvm_f2ll_rp_ftz:
3013 case Intrinsic::nvvm_f2ll_rz_ftz:
3014 // f2ull
3015 case Intrinsic::nvvm_f2ull_rm:
3016 case Intrinsic::nvvm_f2ull_rn:
3017 case Intrinsic::nvvm_f2ull_rp:
3018 case Intrinsic::nvvm_f2ull_rz:
3019 case Intrinsic::nvvm_f2ull_rm_ftz:
3020 case Intrinsic::nvvm_f2ull_rn_ftz:
3021 case Intrinsic::nvvm_f2ull_rp_ftz:
3022 case Intrinsic::nvvm_f2ull_rz_ftz:
3023 // d2ll
3024 case Intrinsic::nvvm_d2ll_rm:
3025 case Intrinsic::nvvm_d2ll_rn:
3026 case Intrinsic::nvvm_d2ll_rp:
3027 case Intrinsic::nvvm_d2ll_rz:
3028 // d2ull
3029 case Intrinsic::nvvm_d2ull_rm:
3030 case Intrinsic::nvvm_d2ull_rn:
3031 case Intrinsic::nvvm_d2ull_rp:
3032 case Intrinsic::nvvm_d2ull_rz: {
3033 // In float-to-integer conversion, NaN inputs are converted to 0.
3034 if (U.isNaN()) {
3035 // In float-to-integer conversion, NaN inputs are converted to 0
3036 // when the source and destination bitwidths are both less than 64.
3037 if (nvvm::FPToIntegerIntrinsicNaNZero(IntrinsicID))
3038 return ConstantInt::get(Ty, 0);
3039
3040 // Otherwise, the most significant bit is set.
3041 unsigned BitWidth = Ty->getIntegerBitWidth();
3042 uint64_t Val = 1ULL << (BitWidth - 1);
3043 return ConstantInt::get(Ty, APInt(BitWidth, Val, /*IsSigned=*/false));
3044 }
3045
3046 APFloat::roundingMode RMode =
3048 bool IsFTZ = nvvm::FPToIntegerIntrinsicShouldFTZ(IntrinsicID);
3049 bool IsSigned = nvvm::FPToIntegerIntrinsicResultIsSigned(IntrinsicID);
3050
3051 APSInt ResInt(Ty->getIntegerBitWidth(), !IsSigned);
3052 auto FloatToRound = IsFTZ ? FTZPreserveSign(U) : U;
3053
3054 // Return max/min value for integers if the result is +/-inf or
3055 // is too large to fit in the result's integer bitwidth.
3056 bool IsExact = false;
3057 FloatToRound.convertToInteger(ResInt, RMode, &IsExact);
3058 return ConstantInt::get(Ty, ResInt);
3059 }
3060 }
3061
3062 /// We only fold functions with finite arguments. Folding NaN and inf is
3063 /// likely to be aborted with an exception anyway, and some host libms
3064 /// have known errors raising exceptions.
3065 if (!U.isFinite())
3066 return nullptr;
3067
3068 /// Currently APFloat versions of these functions do not exist, so we use
3069 /// the host native double versions. Float versions are not called
3070 /// directly but for all these it is true (float)(f((double)arg)) ==
3071 /// f(arg). Long double not supported yet.
3072 const APFloat &APF = Op->getValueAPF();
3073
3074 switch (IntrinsicID) {
3075 default: break;
3076 case Intrinsic::log:
3077 if (U.isZero())
3078 return ConstantFP::getInfinity(Ty, true);
3079 if (U.isNegative())
3080 return ConstantFP::getNaN(Ty);
3081 if (U.isOne())
3082 return ConstantFP::getZero(Ty);
3083 return ConstantFoldFP(log, APF, Ty);
3084 case Intrinsic::log2:
3085 if (U.isZero())
3086 return ConstantFP::getInfinity(Ty, true);
3087 if (U.isNegative())
3088 return ConstantFP::getNaN(Ty);
3089 if (U.isOne())
3090 return ConstantFP::getZero(Ty);
3091 // TODO: What about hosts that lack a C99 library?
3092 return ConstantFoldFP(log2, APF, Ty);
3093 case Intrinsic::log10:
3094 if (U.isZero())
3095 return ConstantFP::getInfinity(Ty, true);
3096 if (U.isNegative())
3097 return ConstantFP::getNaN(Ty);
3098 if (U.isOne())
3099 return ConstantFP::getZero(Ty);
3100 // TODO: What about hosts that lack a C99 library?
3101 return ConstantFoldFP(log10, APF, Ty);
3102 case Intrinsic::exp:
3103 return ConstantFoldFP(exp, APF, Ty);
3104 case Intrinsic::exp2:
3105 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
3106 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
3107 case Intrinsic::exp10:
3108 // Fold exp10(x) as pow(10, x), in case the host lacks a C99 library.
3109 return ConstantFoldBinaryFP(pow, APFloat(10.0), APF, Ty);
3110 case Intrinsic::sin:
3111 return ConstantFoldFP(sin, APF, Ty);
3112 case Intrinsic::cos:
3113 return ConstantFoldFP(cos, APF, Ty);
3114 case Intrinsic::sinh:
3115 return ConstantFoldFP(sinh, APF, Ty);
3116 case Intrinsic::cosh:
3117 return ConstantFoldFP(cosh, APF, Ty);
3118 case Intrinsic::atan:
3119 // Implement optional behavior from C's Annex F for +/-0.0.
3120 if (U.isZero())
3121 return ConstantFP::get(Ty, U);
3122 return ConstantFoldFP(atan, APF, Ty);
3123 case Intrinsic::sqrt:
3124 return ConstantFoldFP(sqrt, APF, Ty);
3125
3126 // NVVM Intrinsics:
3127 case Intrinsic::nvvm_ceil_ftz_f:
3128 case Intrinsic::nvvm_ceil_f:
3129 case Intrinsic::nvvm_ceil_d:
3130 return ConstantFoldFP(
3131 ceil, APF, Ty,
3133 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3134
3135 case Intrinsic::nvvm_fabs_ftz:
3136 case Intrinsic::nvvm_fabs:
3137 return ConstantFoldFP(
3138 fabs, APF, Ty,
3140 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3141
3142 case Intrinsic::nvvm_floor_ftz_f:
3143 case Intrinsic::nvvm_floor_f:
3144 case Intrinsic::nvvm_floor_d:
3145 return ConstantFoldFP(
3146 floor, APF, Ty,
3148 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3149
3150 case Intrinsic::nvvm_rcp_rm_ftz_f:
3151 case Intrinsic::nvvm_rcp_rn_ftz_f:
3152 case Intrinsic::nvvm_rcp_rp_ftz_f:
3153 case Intrinsic::nvvm_rcp_rz_ftz_f:
3154 case Intrinsic::nvvm_rcp_rm_d:
3155 case Intrinsic::nvvm_rcp_rm_f:
3156 case Intrinsic::nvvm_rcp_rn_d:
3157 case Intrinsic::nvvm_rcp_rn_f:
3158 case Intrinsic::nvvm_rcp_rp_d:
3159 case Intrinsic::nvvm_rcp_rp_f:
3160 case Intrinsic::nvvm_rcp_rz_d:
3161 case Intrinsic::nvvm_rcp_rz_f: {
3162 APFloat::roundingMode RoundMode = nvvm::GetRCPRoundingMode(IntrinsicID);
3163 bool IsFTZ = nvvm::RCPShouldFTZ(IntrinsicID);
3164
3165 auto Denominator = IsFTZ ? FTZPreserveSign(APF) : APF;
3167 APFloat::opStatus Status = Res.divide(Denominator, RoundMode);
3168
3170 if (IsFTZ)
3171 Res = FTZPreserveSign(Res);
3172 return ConstantFP::get(Ty, Res);
3173 }
3174 return nullptr;
3175 }
3176
3177 case Intrinsic::nvvm_round_ftz_f:
3178 case Intrinsic::nvvm_round_f:
3179 case Intrinsic::nvvm_round_d: {
3180 // nvvm_round is lowered to PTX cvt.rni, which will round to nearest
3181 // integer, choosing even integer if source is equidistant between two
3182 // integers, so the semantics are closer to "rint" rather than "round".
3183 bool IsFTZ = nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID);
3184 auto V = IsFTZ ? FTZPreserveSign(APF) : APF;
3185 V.roundToIntegral(APFloat::rmNearestTiesToEven);
3186 return ConstantFP::get(Ty, V);
3187 }
3188
3189 case Intrinsic::nvvm_saturate_ftz_f:
3190 case Intrinsic::nvvm_saturate_d:
3191 case Intrinsic::nvvm_saturate_f: {
3192 bool IsFTZ = nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID);
3193 auto V = IsFTZ ? FTZPreserveSign(APF) : APF;
3194 if (V.isNegative() || V.isZero() || V.isNaN())
3195 return ConstantFP::getZero(Ty);
3197 if (V > One)
3198 return ConstantFP::get(Ty, One);
3199 return ConstantFP::get(Ty, APF);
3200 }
3201
3202 case Intrinsic::nvvm_sqrt_rn_ftz_f:
3203 case Intrinsic::nvvm_sqrt_f:
3204 case Intrinsic::nvvm_sqrt_rn_d:
3205 case Intrinsic::nvvm_sqrt_rn_f:
3206 if (APF.isNegative())
3207 return nullptr;
3208 return ConstantFoldFP(
3209 sqrt, APF, Ty,
3211 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3212
3213 // AMDGCN Intrinsics:
3214 case Intrinsic::amdgcn_cos:
3215 case Intrinsic::amdgcn_sin: {
3216 double V = getValueAsDouble(Op);
3217 if (V < -256.0 || V > 256.0)
3218 // The gfx8 and gfx9 architectures handle arguments outside the range
3219 // [-256, 256] differently. This should be a rare case so bail out
3220 // rather than trying to handle the difference.
3221 return nullptr;
3222 bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
3223 double V4 = V * 4.0;
3224 if (V4 == floor(V4)) {
3225 // Force exact results for quarter-integer inputs.
3226 const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
3227 V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
3228 } else {
3229 if (IsCos)
3230 V = cos(V * 2.0 * numbers::pi);
3231 else
3232 V = sin(V * 2.0 * numbers::pi);
3233 }
3234 return GetConstantFoldFPValue(V, Ty);
3235 }
3236 }
3237
3238 if (!TLI)
3239 return nullptr;
3240
3241 LibFunc Func = TLI->getLibFunc(Name);
3242 if (Func == NotLibFunc)
3243 return nullptr;
3244
3245 switch (Func) {
3246 default:
3247 break;
3248 case LibFunc_acos:
3249 case LibFunc_acosf:
3250 case LibFunc_acos_finite:
3251 case LibFunc_acosf_finite:
3252 if (TLI->has(Func))
3253 return ConstantFoldFP(acos, APF, Ty);
3254 break;
3255 case LibFunc_asin:
3256 case LibFunc_asinf:
3257 case LibFunc_asin_finite:
3258 case LibFunc_asinf_finite:
3259 if (TLI->has(Func))
3260 return ConstantFoldFP(asin, APF, Ty);
3261 break;
3262 case LibFunc_atan:
3263 case LibFunc_atanf:
3264 // Implement optional behavior from C's Annex F for +/-0.0.
3265 if (U.isZero())
3266 return ConstantFP::get(Ty, U);
3267 if (TLI->has(Func))
3268 return ConstantFoldFP(atan, APF, Ty);
3269 break;
3270 case LibFunc_ceil:
3271 case LibFunc_ceilf:
3272 if (TLI->has(Func)) {
3273 U.roundToIntegral(APFloat::rmTowardPositive);
3274 return ConstantFP::get(Ty, U);
3275 }
3276 break;
3277 case LibFunc_cos:
3278 case LibFunc_cosf:
3279 if (TLI->has(Func))
3280 return ConstantFoldFP(cos, APF, Ty);
3281 break;
3282 case LibFunc_cosh:
3283 case LibFunc_coshf:
3284 case LibFunc_cosh_finite:
3285 case LibFunc_coshf_finite:
3286 if (TLI->has(Func))
3287 return ConstantFoldFP(cosh, APF, Ty);
3288 break;
3289 case LibFunc_exp:
3290 case LibFunc_expf:
3291 case LibFunc_exp_finite:
3292 case LibFunc_expf_finite:
3293 if (TLI->has(Func))
3294 return ConstantFoldFP(exp, APF, Ty);
3295 break;
3296 case LibFunc_exp2:
3297 case LibFunc_exp2f:
3298 case LibFunc_exp2_finite:
3299 case LibFunc_exp2f_finite:
3300 if (TLI->has(Func))
3301 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
3302 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
3303 break;
3304 case LibFunc_fabs:
3305 case LibFunc_fabsf:
3306 if (TLI->has(Func)) {
3307 U.clearSign();
3308 return ConstantFP::get(Ty, U);
3309 }
3310 break;
3311 case LibFunc_floor:
3312 case LibFunc_floorf:
3313 if (TLI->has(Func)) {
3314 U.roundToIntegral(APFloat::rmTowardNegative);
3315 return ConstantFP::get(Ty, U);
3316 }
3317 break;
3318 case LibFunc_log:
3319 case LibFunc_logf:
3320 case LibFunc_log_finite:
3321 case LibFunc_logf_finite:
3322 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3323 return ConstantFoldFP(log, APF, Ty);
3324 break;
3325 case LibFunc_log2:
3326 case LibFunc_log2f:
3327 case LibFunc_log2_finite:
3328 case LibFunc_log2f_finite:
3329 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3330 // TODO: What about hosts that lack a C99 library?
3331 return ConstantFoldFP(log2, APF, Ty);
3332 break;
3333 case LibFunc_log10:
3334 case LibFunc_log10f:
3335 case LibFunc_log10_finite:
3336 case LibFunc_log10f_finite:
3337 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3338 // TODO: What about hosts that lack a C99 library?
3339 return ConstantFoldFP(log10, APF, Ty);
3340 break;
3341 case LibFunc_ilogb:
3342 case LibFunc_ilogbf:
3343 if (!APF.isZero() && TLI->has(Func))
3344 return ConstantInt::get(Ty, ilogb(APF), true);
3345 break;
3346 case LibFunc_logb:
3347 case LibFunc_logbf:
3348 if (!APF.isZero() && TLI->has(Func))
3349 return ConstantFoldFP(logb, APF, Ty);
3350 break;
3351 case LibFunc_log1p:
3352 case LibFunc_log1pf:
3353 // Implement optional behavior from C's Annex F for +/-0.0.
3354 if (U.isZero())
3355 return ConstantFP::get(Ty, U);
3356 if (APF > APFloat::getOne(APF.getSemantics(), true) && TLI->has(Func))
3357 return ConstantFoldFP(log1p, APF, Ty);
3358 break;
3359 case LibFunc_logl:
3360 return nullptr;
3361 case LibFunc_erf:
3362 case LibFunc_erff:
3363 if (TLI->has(Func))
3364 return ConstantFoldFP(erf, APF, Ty);
3365 break;
3366 case LibFunc_nearbyint:
3367 case LibFunc_nearbyintf:
3368 case LibFunc_rint:
3369 case LibFunc_rintf:
3370 case LibFunc_roundeven:
3371 case LibFunc_roundevenf:
3372 if (TLI->has(Func)) {
3373 U.roundToIntegral(APFloat::rmNearestTiesToEven);
3374 return ConstantFP::get(Ty, U);
3375 }
3376 break;
3377 case LibFunc_round:
3378 case LibFunc_roundf:
3379 if (TLI->has(Func)) {
3380 U.roundToIntegral(APFloat::rmNearestTiesToAway);
3381 return ConstantFP::get(Ty, U);
3382 }
3383 break;
3384 case LibFunc_sin:
3385 case LibFunc_sinf:
3386 if (TLI->has(Func))
3387 return ConstantFoldFP(sin, APF, Ty);
3388 break;
3389 case LibFunc_sinh:
3390 case LibFunc_sinhf:
3391 case LibFunc_sinh_finite:
3392 case LibFunc_sinhf_finite:
3393 if (TLI->has(Func))
3394 return ConstantFoldFP(sinh, APF, Ty);
3395 break;
3396 case LibFunc_sqrt:
3397 case LibFunc_sqrtf:
3398 if (!APF.isNegative() && TLI->has(Func))
3399 return ConstantFoldFP(sqrt, APF, Ty);
3400 break;
3401 case LibFunc_tan:
3402 case LibFunc_tanf:
3403 if (TLI->has(Func))
3404 return ConstantFoldFP(tan, APF, Ty);
3405 break;
3406 case LibFunc_tanh:
3407 case LibFunc_tanhf:
3408 if (TLI->has(Func))
3409 return ConstantFoldFP(tanh, APF, Ty);
3410 break;
3411 case LibFunc_trunc:
3412 case LibFunc_truncf:
3413 if (TLI->has(Func)) {
3414 U.roundToIntegral(APFloat::rmTowardZero);
3415 return ConstantFP::get(Ty, U);
3416 }
3417 break;
3418 }
3419 return nullptr;
3420 }
3421
3422 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
3423 switch (IntrinsicID) {
3424 case Intrinsic::bswap:
3425 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
3426 case Intrinsic::ctpop:
3427 return ConstantInt::get(Ty, Op->getValue().popcount());
3428 case Intrinsic::bitreverse:
3429 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
3430 case Intrinsic::amdgcn_s_wqm: {
3431 uint64_t Val = Op->getZExtValue();
3432 Val |= (Val & 0x5555555555555555ULL) << 1 |
3433 ((Val >> 1) & 0x5555555555555555ULL);
3434 Val |= (Val & 0x3333333333333333ULL) << 2 |
3435 ((Val >> 2) & 0x3333333333333333ULL);
3436 return ConstantInt::get(Ty, Val);
3437 }
3438
3439 case Intrinsic::amdgcn_s_quadmask: {
3440 uint64_t Val = Op->getZExtValue();
3441 uint64_t QuadMask = 0;
3442 for (unsigned I = 0; I < Op->getBitWidth() / 4; ++I, Val >>= 4) {
3443 if (!(Val & 0xF))
3444 continue;
3445
3446 QuadMask |= (1ULL << I);
3447 }
3448 return ConstantInt::get(Ty, QuadMask);
3449 }
3450
3451 case Intrinsic::amdgcn_s_bitreplicate: {
3452 uint64_t Val = Op->getZExtValue();
3453 Val = (Val & 0x000000000000FFFFULL) | (Val & 0x00000000FFFF0000ULL) << 16;
3454 Val = (Val & 0x000000FF000000FFULL) | (Val & 0x0000FF000000FF00ULL) << 8;
3455 Val = (Val & 0x000F000F000F000FULL) | (Val & 0x00F000F000F000F0ULL) << 4;
3456 Val = (Val & 0x0303030303030303ULL) | (Val & 0x0C0C0C0C0C0C0C0CULL) << 2;
3457 Val = (Val & 0x1111111111111111ULL) | (Val & 0x2222222222222222ULL) << 1;
3458 Val = Val | Val << 1;
3459 return ConstantInt::get(Ty, Val);
3460 }
3461 }
3462 }
3463
3464 if (Operands[0]->getType()->isVectorTy()) {
3465 auto *Op = cast<Constant>(Operands[0]);
3466 switch (IntrinsicID) {
3467 default: break;
3468 case Intrinsic::vector_reduce_add:
3469 case Intrinsic::vector_reduce_mul:
3470 case Intrinsic::vector_reduce_and:
3471 case Intrinsic::vector_reduce_or:
3472 case Intrinsic::vector_reduce_xor:
3473 case Intrinsic::vector_reduce_smin:
3474 case Intrinsic::vector_reduce_smax:
3475 case Intrinsic::vector_reduce_umin:
3476 case Intrinsic::vector_reduce_umax:
3477 if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
3478 return C;
3479 break;
3480 case Intrinsic::x86_sse_cvtss2si:
3481 case Intrinsic::x86_sse_cvtss2si64:
3482 case Intrinsic::x86_sse2_cvtsd2si:
3483 case Intrinsic::x86_sse2_cvtsd2si64:
3484 if (ConstantFP *FPOp =
3485 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
3486 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
3487 /*roundTowardZero=*/false, Ty,
3488 /*IsSigned*/true);
3489 break;
3490 case Intrinsic::x86_sse_cvttss2si:
3491 case Intrinsic::x86_sse_cvttss2si64:
3492 case Intrinsic::x86_sse2_cvttsd2si:
3493 case Intrinsic::x86_sse2_cvttsd2si64:
3494 if (ConstantFP *FPOp =
3495 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
3496 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
3497 /*roundTowardZero=*/true, Ty,
3498 /*IsSigned*/true);
3499 break;
3500
3501 case Intrinsic::wasm_anytrue:
3502 return Op->isNullValue() ? ConstantInt::get(Ty, 0)
3503 : ConstantInt::get(Ty, 1);
3504
3505 case Intrinsic::wasm_alltrue:
3506 // Check each element individually
3507 unsigned E = cast<FixedVectorType>(Op->getType())->getNumElements();
3508 for (unsigned I = 0; I != E; ++I) {
3509 Constant *Elt = Op->getAggregateElement(I);
3510 // Return false as soon as we find a non-true element.
3511 if (Elt && Elt->isNullValue())
3512 return ConstantInt::get(Ty, 0);
3513 // Bail as soon as we find an element we cannot prove to be true.
3514 if (!Elt || !isa<ConstantInt>(Elt))
3515 return nullptr;
3516 }
3517
3518 return ConstantInt::get(Ty, 1);
3519 }
3520 }
3521
3522 if (IntrinsicID != Intrinsic::not_intrinsic || !TLI)
3523 return nullptr;
3524
3525 LibFunc Func = TLI->getLibFunc(Name);
3526 if (Func == NotLibFunc || !TLI->has(Func))
3527 return nullptr;
3528
3529 if (Func != LibFunc_strlen)
3530 return nullptr;
3531
3532 if (isa<PoisonValue>(Operands[0]))
3533 return PoisonValue::get(Ty);
3534
3535 if (uint64_t Len = GetStringLength(Operands[0]))
3536 return ConstantInt::get(Ty, Len - 1);
3537
3538 return nullptr;
3539}
3540
3541static Constant *evaluateCompare(const APFloat &Op1, const APFloat &Op2,
3545 FCmpInst::Predicate Cond = FCmp->getPredicate();
3546 if (FCmp->isSignaling()) {
3547 if (Op1.isNaN() || Op2.isNaN())
3549 } else {
3550 if (Op1.isSignaling() || Op2.isSignaling())
3552 }
3553 bool Result = FCmpInst::compare(Op1, Op2, Cond);
3554 if (mayFoldConstrained(const_cast<ConstrainedFPCmpIntrinsic *>(FCmp), St))
3555 return ConstantInt::get(Call->getType()->getScalarType(), Result);
3556 return nullptr;
3557}
3558
3559static Constant *ConstantFoldNextToward(const APFloat &Op0, const APFloat &Op1,
3560 const Type *RetTy) {
3561 assert(RetTy != nullptr);
3562 bool LosesInfo;
3563
3564 if (Op1.isSignaling())
3565 return nullptr;
3566 if (Op1.isNaN()) {
3567 APFloat Ret(Op1);
3568 Ret.convert(RetTy->getFltSemantics(), detail::rmNearestTiesToEven,
3569 &LosesInfo);
3570 return ConstantFP::get(RetTy->getContext(), Ret);
3571 }
3572
3573 // Recall that the second argument of nexttoward is always a long double,
3574 // so we may need to promote the first argument for comparisons to be valid.
3575 APFloat PromotedOp0(Op0);
3576 PromotedOp0.convert(Op1.getSemantics(), detail::rmNearestTiesToEven,
3577 &LosesInfo);
3578 assert(!LosesInfo && "Unexpected lossy promotion");
3579 const APFloat::cmpResult Result = PromotedOp0.compare(Op1);
3580
3581 // When equal, the standard says we must return the second argument.
3582 // This allows nice behavior such as nexttoward(0.0, -0.0) = -0.0 and
3583 // nexttoward(-0.0, 0.0) = 0.0
3584 if (Result == detail::cmpEqual) {
3585 APFloat Ret(Op1);
3586 Ret.convert(RetTy->getFltSemantics(), detail::rmNearestTiesToEven,
3587 &LosesInfo);
3588 return ConstantFP::get(RetTy->getContext(), Ret);
3589 }
3590
3591 APFloat Next(Op0);
3592 Next.next(/*nextDown=*/Result == APFloat::cmpGreaterThan);
3593 if (Next.isZero() || Next.isDenormal() || Next.isSignaling())
3594 return nullptr;
3595 return ConstantFP::get(RetTy->getContext(), Next);
3596}
3597
3598static Constant *ConstantFoldLibCall2(StringRef Name, Type *Ty,
3600 const TargetLibraryInfo *TLI = nullptr) {
3601 if (!TLI)
3602 return nullptr;
3603
3604 LibFunc Func = TLI->getLibFunc(Name);
3605 if (Func == NotLibFunc)
3606 return nullptr;
3607
3608 const auto *Op1 = dyn_cast<ConstantFP>(Operands[0]);
3609 if (!Op1)
3610 return nullptr;
3611
3612 const auto *Op2 = dyn_cast<ConstantFP>(Operands[1]);
3613 if (!Op2)
3614 return nullptr;
3615
3616 const APFloat &Op1V = Op1->getValueAPF();
3617 const APFloat &Op2V = Op2->getValueAPF();
3618
3619 switch (Func) {
3620 default:
3621 break;
3622 case LibFunc_pow:
3623 case LibFunc_powf:
3624 case LibFunc_pow_finite:
3625 case LibFunc_powf_finite:
3626 if (TLI->has(Func))
3627 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
3628 break;
3629 case LibFunc_fmod:
3630 case LibFunc_fmodf:
3631 if (TLI->has(Func)) {
3632 APFloat V = Op1->getValueAPF();
3633 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
3634 return ConstantFP::get(Ty, V);
3635 }
3636 break;
3637 case LibFunc_remainder:
3638 case LibFunc_remainderf:
3639 if (TLI->has(Func)) {
3640 APFloat V = Op1->getValueAPF();
3641 if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
3642 return ConstantFP::get(Ty, V);
3643 }
3644 break;
3645 case LibFunc_atan2:
3646 case LibFunc_atan2f:
3647 // atan2(+/-0.0, +/-0.0) is known to raise an exception on some libm
3648 // (Solaris), so we do not assume a known result for that.
3649 if (Op1V.isZero() && Op2V.isZero())
3650 return nullptr;
3651 [[fallthrough]];
3652 case LibFunc_atan2_finite:
3653 case LibFunc_atan2f_finite:
3654 if (TLI->has(Func))
3655 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
3656 break;
3657 case LibFunc_nextafter:
3658 case LibFunc_nextafterf:
3659 case LibFunc_nexttoward:
3660 case LibFunc_nexttowardf:
3661 if (TLI->has(Func))
3662 return ConstantFoldNextToward(Op1V, Op2V, Ty);
3663 break;
3664 }
3665
3666 return nullptr;
3667}
3668
3669static Constant *ConstantFoldCRC32(Type *Ty, const APInt *CrcArg,
3670 const APInt *DataArg, unsigned DataBytes,
3671 uint32_t Poly) {
3672 if (!CrcArg || !DataArg)
3673 return nullptr;
3674 uint32_t Crc = CrcArg->getZExtValue();
3675 uint64_t Data = DataArg->getZExtValue();
3676 uint32_t Result = calculateReflectedCRC32(Crc, Data, DataBytes, Poly);
3677 return ConstantInt::get(Ty, Result);
3678}
3679
3680static Constant *ConstantFoldIntrinsicCall2(Intrinsic::ID IntrinsicID, Type *Ty,
3682 const CallBase *Call = nullptr,
3683 const Function *CtxF = nullptr) {
3684 assert(Operands.size() == 2 && "Wrong number of operands.");
3685
3686 if (Ty->isFloatingPointTy()) {
3687 // TODO: We should have undef handling for all of the FP intrinsics that
3688 // are attempted to be folded in this function.
3689 bool IsOp0Undef = isa<UndefValue>(Operands[0]);
3690 bool IsOp1Undef = isa<UndefValue>(Operands[1]);
3691 switch (IntrinsicID) {
3692 case Intrinsic::maxnum:
3693 case Intrinsic::minnum:
3694 case Intrinsic::maximum:
3695 case Intrinsic::minimum:
3696 case Intrinsic::maximumnum:
3697 case Intrinsic::minimumnum:
3698 case Intrinsic::nvvm_fmax_d:
3699 case Intrinsic::nvvm_fmin_d:
3700 // If one argument is undef, return the other argument.
3701 if (IsOp0Undef)
3702 return Operands[1];
3703 if (IsOp1Undef)
3704 return Operands[0];
3705 break;
3706
3707 case Intrinsic::nvvm_fmax_f:
3708 case Intrinsic::nvvm_fmax_ftz_f:
3709 case Intrinsic::nvvm_fmax_ftz_nan_f:
3710 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3711 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3712 case Intrinsic::nvvm_fmax_nan_f:
3713 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3714 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3715
3716 case Intrinsic::nvvm_fmin_f:
3717 case Intrinsic::nvvm_fmin_ftz_f:
3718 case Intrinsic::nvvm_fmin_ftz_nan_f:
3719 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
3720 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
3721 case Intrinsic::nvvm_fmin_nan_f:
3722 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
3723 case Intrinsic::nvvm_fmin_xorsign_abs_f:
3724 // If one arg is undef, the other arg can be returned only if it is
3725 // constant, as we may need to flush it to sign-preserving zero or
3726 // canonicalize the NaN.
3727 if (!IsOp0Undef && !IsOp1Undef)
3728 break;
3729 if (auto *Op = dyn_cast<ConstantFP>(Operands[IsOp0Undef ? 1 : 0])) {
3730 if (Op->isNaN()) {
3731 APInt NVCanonicalNaN(32, 0x7fffffff);
3732 return ConstantFP::get(
3733 Ty, APFloat(Ty->getFltSemantics(), NVCanonicalNaN));
3734 }
3735 if (nvvm::FMinFMaxShouldFTZ(IntrinsicID))
3736 return ConstantFP::get(Ty, FTZPreserveSign(Op->getValueAPF()));
3737 else
3738 return Op;
3739 }
3740 break;
3741 }
3742 }
3743
3744 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
3745 const APFloat &Op1V = Op1->getValueAPF();
3746
3747 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
3748 if (Op2->getType() != Op1->getType())
3749 return nullptr;
3750 const APFloat &Op2V = Op2->getValueAPF();
3751
3752 if (const auto *ConstrIntr =
3754 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
3755 APFloat Res = Op1V;
3757 switch (IntrinsicID) {
3758 default:
3759 return nullptr;
3760 case Intrinsic::experimental_constrained_fadd:
3761 St = Res.add(Op2V, RM);
3762 break;
3763 case Intrinsic::experimental_constrained_fsub:
3764 St = Res.subtract(Op2V, RM);
3765 break;
3766 case Intrinsic::experimental_constrained_fmul:
3767 St = Res.multiply(Op2V, RM);
3768 break;
3769 case Intrinsic::experimental_constrained_fdiv:
3770 St = Res.divide(Op2V, RM);
3771 break;
3772 case Intrinsic::experimental_constrained_frem:
3773 St = Res.mod(Op2V);
3774 break;
3775 case Intrinsic::experimental_constrained_fcmp:
3776 case Intrinsic::experimental_constrained_fcmps:
3777 return evaluateCompare(Op1V, Op2V, ConstrIntr);
3778 }
3779 if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr),
3780 St))
3781 return ConstantFP::get(Ty, Res);
3782 return nullptr;
3783 }
3784
3785 switch (IntrinsicID) {
3786 default:
3787 break;
3788 case Intrinsic::copysign:
3789 return ConstantFP::get(Ty, APFloat::copySign(Op1V, Op2V));
3790 case Intrinsic::minnum:
3791 return tryFoldFPConst(Ty, FPOp::MinNum, {Op1V, Op2V}, Call, CtxF);
3792 case Intrinsic::maxnum:
3793 return tryFoldFPConst(Ty, FPOp::MaxNum, {Op1V, Op2V}, Call, CtxF);
3794 case Intrinsic::minimum:
3795 return tryFoldFPConst(Ty, FPOp::Minimum, {Op1V, Op2V}, Call, CtxF);
3796 case Intrinsic::maximum:
3797 return tryFoldFPConst(Ty, FPOp::Maximum, {Op1V, Op2V}, Call, CtxF);
3798 case Intrinsic::minimumnum:
3799 return tryFoldFPConst(Ty, FPOp::MinimumNum, {Op1V, Op2V}, Call, CtxF);
3800 case Intrinsic::maximumnum:
3801 return tryFoldFPConst(Ty, FPOp::MaximumNum, {Op1V, Op2V}, Call, CtxF);
3802
3803 case Intrinsic::nvvm_fmax_d:
3804 case Intrinsic::nvvm_fmax_f:
3805 case Intrinsic::nvvm_fmax_ftz_f:
3806 case Intrinsic::nvvm_fmax_ftz_nan_f:
3807 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3808 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3809 case Intrinsic::nvvm_fmax_nan_f:
3810 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3811 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3812
3813 case Intrinsic::nvvm_fmin_d:
3814 case Intrinsic::nvvm_fmin_f:
3815 case Intrinsic::nvvm_fmin_ftz_f:
3816 case Intrinsic::nvvm_fmin_ftz_nan_f:
3817 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
3818 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
3819 case Intrinsic::nvvm_fmin_nan_f:
3820 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
3821 case Intrinsic::nvvm_fmin_xorsign_abs_f: {
3822
3823 bool ShouldCanonicalizeNaNs = !(IntrinsicID == Intrinsic::nvvm_fmax_d ||
3824 IntrinsicID == Intrinsic::nvvm_fmin_d);
3825 bool IsFTZ = nvvm::FMinFMaxShouldFTZ(IntrinsicID);
3826 bool IsNaNPropagating = nvvm::FMinFMaxPropagatesNaNs(IntrinsicID);
3827 bool IsXorSignAbs = nvvm::FMinFMaxIsXorSignAbs(IntrinsicID);
3828
3829 APFloat A = IsFTZ ? FTZPreserveSign(Op1V) : Op1V;
3830 APFloat B = IsFTZ ? FTZPreserveSign(Op2V) : Op2V;
3831
3832 bool XorSign = false;
3833 if (IsXorSignAbs) {
3834 XorSign = A.isNegative() ^ B.isNegative();
3835 A = abs(A);
3836 B = abs(B);
3837 }
3838
3839 bool IsFMax = false;
3840 switch (IntrinsicID) {
3841 case Intrinsic::nvvm_fmax_d:
3842 case Intrinsic::nvvm_fmax_f:
3843 case Intrinsic::nvvm_fmax_ftz_f:
3844 case Intrinsic::nvvm_fmax_ftz_nan_f:
3845 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3846 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3847 case Intrinsic::nvvm_fmax_nan_f:
3848 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3849 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3850 IsFMax = true;
3851 break;
3852 }
3853 APFloat Res =
3854 IsFMax ? (IsNaNPropagating ? maximum(A, B) : maximumnum(A, B))
3855 : (IsNaNPropagating ? minimum(A, B) : minimumnum(A, B));
3856
3857 if (ShouldCanonicalizeNaNs && Res.isNaN()) {
3858 APFloat NVCanonicalNaN(Res.getSemantics(), APInt(32, 0x7fffffff));
3859 return ConstantFP::get(Ty, NVCanonicalNaN);
3860 }
3861
3862 if (IsXorSignAbs && XorSign != Res.isNegative())
3863 Res.changeSign();
3864
3865 return ConstantFP::get(Ty, Res);
3866 }
3867
3868 case Intrinsic::nvvm_div_rm_f:
3869 case Intrinsic::nvvm_div_rn_f:
3870 case Intrinsic::nvvm_div_rp_f:
3871 case Intrinsic::nvvm_div_rz_f:
3872 case Intrinsic::nvvm_div_rm_d:
3873 case Intrinsic::nvvm_div_rn_d:
3874 case Intrinsic::nvvm_div_rp_d:
3875 case Intrinsic::nvvm_div_rz_d:
3876 case Intrinsic::nvvm_div_rm_ftz_f:
3877 case Intrinsic::nvvm_div_rn_ftz_f:
3878 case Intrinsic::nvvm_div_rp_ftz_f:
3879 case Intrinsic::nvvm_div_rz_ftz_f: {
3880 bool IsFTZ = nvvm::FDivShouldFTZ(IntrinsicID);
3881 APFloat A = IsFTZ ? FTZPreserveSign(Op1V) : Op1V;
3882 APFloat B = IsFTZ ? FTZPreserveSign(Op2V) : Op2V;
3883 APFloat::roundingMode RoundMode =
3884 nvvm::GetFDivRoundingMode(IntrinsicID);
3885
3886 APFloat Res = A;
3887 APFloat::opStatus Status = Res.divide(B, RoundMode);
3888 if (!Res.isNaN() &&
3890 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
3891 return ConstantFP::get(Ty, Res);
3892 }
3893 return nullptr;
3894 }
3895 }
3896
3897 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
3898 return nullptr;
3899
3900 switch (IntrinsicID) {
3901 default:
3902 break;
3903 case Intrinsic::pow:
3904 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
3905 case Intrinsic::amdgcn_fmul_legacy:
3906 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
3907 // NaN or infinity, gives +0.0.
3908 if (Op1V.isZero() || Op2V.isZero())
3909 return ConstantFP::getZero(Ty);
3910 return ConstantFP::get(Ty, Op1V * Op2V);
3911 }
3912
3913 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
3914 switch (IntrinsicID) {
3915 case Intrinsic::ldexp: {
3916 // APFloat::scalbn takes the exponent as `int`. Clamp wider integer
3917 // exponents into [INT_MIN, INT_MAX] so values still saturate the
3918 // result to +/-inf or +/-0.
3919 APInt Exp = Op2C->getValue();
3920 Exp = Exp.getBitWidth() < 32 ? Exp.sext(32) : Exp.truncSSat(32);
3921 return ConstantFP::get(
3922 Ty->getContext(),
3923 scalbn(Op1V, Exp.getSExtValue(), APFloat::rmNearestTiesToEven));
3924 }
3925 case Intrinsic::is_fpclass: {
3926 FPClassTest Mask = static_cast<FPClassTest>(Op2C->getZExtValue());
3927 bool Result =
3928 ((Mask & fcSNan) && Op1V.isNaN() && Op1V.isSignaling()) ||
3929 ((Mask & fcQNan) && Op1V.isNaN() && !Op1V.isSignaling()) ||
3930 ((Mask & fcNegInf) && Op1V.isNegInfinity()) ||
3931 ((Mask & fcNegNormal) && Op1V.isNormal() && Op1V.isNegative()) ||
3932 ((Mask & fcNegSubnormal) && Op1V.isDenormal() && Op1V.isNegative()) ||
3933 ((Mask & fcNegZero) && Op1V.isZero() && Op1V.isNegative()) ||
3934 ((Mask & fcPosZero) && Op1V.isZero() && !Op1V.isNegative()) ||
3935 ((Mask & fcPosSubnormal) && Op1V.isDenormal() && !Op1V.isNegative()) ||
3936 ((Mask & fcPosNormal) && Op1V.isNormal() && !Op1V.isNegative()) ||
3937 ((Mask & fcPosInf) && Op1V.isPosInfinity());
3938 return ConstantInt::get(Ty, Result);
3939 }
3940 case Intrinsic::powi: {
3941 // Square-and-multiply using the operand's own semantics, matching
3942 // the multiply sequence ExpandPowI builds in SelectionDAG.
3943 int Exp = static_cast<int>(Op2C->getSExtValue());
3944 unsigned UExp = static_cast<unsigned>(Exp);
3945 if (Exp < 0)
3946 UExp = -UExp;
3947 const fltSemantics &Semantics = Op1V.getSemantics();
3948 APFloat Res = APFloat::getOne(Semantics);
3949 APFloat CurSquare = Op1V;
3950 while (UExp) {
3951 if (UExp & 1)
3952 Res = Res * CurSquare;
3953 CurSquare = CurSquare * CurSquare;
3954 UExp >>= 1;
3955 }
3956 if (Exp < 0)
3957 Res = APFloat::getOne(Semantics) / Res;
3958 return ConstantFP::get(Ty, Res);
3959 }
3960 default:
3961 break;
3962 }
3963 }
3964 return nullptr;
3965 }
3966
3967 if (Operands[0]->getType()->isIntegerTy() &&
3968 Operands[1]->getType()->isIntegerTy()) {
3969 const APInt *C0, *C1;
3970 if (!getConstIntOrUndef(Operands[0], C0) ||
3971 !getConstIntOrUndef(Operands[1], C1))
3972 return nullptr;
3973
3974 switch (IntrinsicID) {
3975 default: break;
3976 case Intrinsic::smax:
3977 case Intrinsic::smin:
3978 case Intrinsic::umax:
3979 case Intrinsic::umin:
3980 if (!C0 || !C1)
3981 return MinMaxIntrinsic::getSaturationPoint(IntrinsicID, Ty);
3982 return ConstantInt::get(
3983 Ty, ICmpInst::compare(*C0, *C1,
3984 MinMaxIntrinsic::getPredicate(IntrinsicID))
3985 ? *C0
3986 : *C1);
3987
3988 case Intrinsic::scmp:
3989 case Intrinsic::ucmp:
3990 if (!C0 || !C1)
3991 return ConstantInt::get(Ty, 0);
3992
3993 int Res;
3994 if (IntrinsicID == Intrinsic::scmp)
3995 Res = C0->sgt(*C1) ? 1 : C0->slt(*C1) ? -1 : 0;
3996 else
3997 Res = C0->ugt(*C1) ? 1 : C0->ult(*C1) ? -1 : 0;
3998 return ConstantInt::get(Ty, Res, /*IsSigned=*/true);
3999
4000 case Intrinsic::usub_with_overflow:
4001 case Intrinsic::ssub_with_overflow:
4002 // X - undef -> { 0, false }
4003 // undef - X -> { 0, false }
4004 if (!C0 || !C1)
4005 return Constant::getNullValue(Ty);
4006 [[fallthrough]];
4007 case Intrinsic::uadd_with_overflow:
4008 case Intrinsic::sadd_with_overflow:
4009 // X + undef -> { -1, false }
4010 // undef + x -> { -1, false }
4011 if (!C0 || !C1) {
4012 return ConstantStruct::get(
4013 cast<StructType>(Ty),
4014 {Constant::getAllOnesValue(Ty->getStructElementType(0)),
4015 Constant::getNullValue(Ty->getStructElementType(1))});
4016 }
4017 [[fallthrough]];
4018 case Intrinsic::smul_with_overflow:
4019 case Intrinsic::umul_with_overflow: {
4020 // undef * X -> { 0, false }
4021 // X * undef -> { 0, false }
4022 if (!C0 || !C1)
4023 return Constant::getNullValue(Ty);
4024
4025 APInt Res;
4026 bool Overflow;
4027 switch (IntrinsicID) {
4028 default: llvm_unreachable("Invalid case");
4029 case Intrinsic::sadd_with_overflow:
4030 Res = C0->sadd_ov(*C1, Overflow);
4031 break;
4032 case Intrinsic::uadd_with_overflow:
4033 Res = C0->uadd_ov(*C1, Overflow);
4034 break;
4035 case Intrinsic::ssub_with_overflow:
4036 Res = C0->ssub_ov(*C1, Overflow);
4037 break;
4038 case Intrinsic::usub_with_overflow:
4039 Res = C0->usub_ov(*C1, Overflow);
4040 break;
4041 case Intrinsic::smul_with_overflow:
4042 Res = C0->smul_ov(*C1, Overflow);
4043 break;
4044 case Intrinsic::umul_with_overflow:
4045 Res = C0->umul_ov(*C1, Overflow);
4046 break;
4047 }
4048 Constant *Ops[] = {
4049 ConstantInt::get(Ty->getContext(), Res),
4050 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
4051 };
4053 }
4054 case Intrinsic::uadd_sat:
4055 case Intrinsic::sadd_sat:
4056 if (!C0 || !C1)
4057 return Constant::getAllOnesValue(Ty);
4058 if (IntrinsicID == Intrinsic::uadd_sat)
4059 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
4060 else
4061 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
4062 case Intrinsic::usub_sat:
4063 case Intrinsic::ssub_sat:
4064 if (!C0 || !C1)
4065 return Constant::getNullValue(Ty);
4066 if (IntrinsicID == Intrinsic::usub_sat)
4067 return ConstantInt::get(Ty, C0->usub_sat(*C1));
4068 else
4069 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
4070 case Intrinsic::ushl_sat:
4071 case Intrinsic::sshl_sat:
4072 if (!C0 || !C1)
4073 return nullptr;
4074 if (C1->uge(C1->getBitWidth()))
4075 return PoisonValue::get(Ty);
4076 if (IntrinsicID == Intrinsic::ushl_sat)
4077 return ConstantInt::get(Ty, C0->ushl_sat(*C1));
4078 return ConstantInt::get(Ty, C0->sshl_sat(*C1));
4079 case Intrinsic::cttz:
4080 case Intrinsic::ctlz:
4081 assert(C1 && "Must be constant int");
4082
4083 // cttz(0, 1) and ctlz(0, 1) are poison.
4084 if (C1->isOne() && (!C0 || C0->isZero()))
4085 return PoisonValue::get(Ty);
4086 if (!C0)
4087 return Constant::getNullValue(Ty);
4088 if (IntrinsicID == Intrinsic::cttz)
4089 return ConstantInt::get(Ty, C0->countr_zero());
4090 else
4091 return ConstantInt::get(Ty, C0->countl_zero());
4092
4093 case Intrinsic::abs:
4094 assert(C1 && "Must be constant int");
4095 assert((C1->isOne() || C1->isZero()) && "Must be 0 or 1");
4096
4097 // Undef or minimum val operand with poison min --> poison
4098 if (C1->isOne() && (!C0 || C0->isMinSignedValue()))
4099 return PoisonValue::get(Ty);
4100
4101 // Undef operand with no poison min --> 0 (sign bit must be clear)
4102 if (!C0)
4103 return Constant::getNullValue(Ty);
4104
4105 return ConstantInt::get(Ty, C0->abs());
4106 case Intrinsic::clmul:
4107 if (!C0 || !C1)
4108 return Constant::getNullValue(Ty);
4109 return ConstantInt::get(Ty, APIntOps::clmul(*C0, *C1));
4110 case Intrinsic::pdep:
4111 if (!C0 || !C1)
4112 return Constant::getNullValue(Ty);
4113 return ConstantInt::get(Ty, APIntOps::pdep(*C0, *C1));
4114 case Intrinsic::pext:
4115 if (!C0 || !C1)
4116 return Constant::getNullValue(Ty);
4117 return ConstantInt::get(Ty, APIntOps::pext(*C0, *C1));
4118 case Intrinsic::smulh:
4119 if (!C0 || !C1)
4120 return Constant::getNullValue(Ty);
4121 return ConstantInt::get(Ty, APIntOps::mulhs(*C0, *C1));
4122 case Intrinsic::umulh:
4123 if (!C0 || !C1)
4124 return Constant::getNullValue(Ty);
4125 return ConstantInt::get(Ty, APIntOps::mulhu(*C0, *C1));
4126 case Intrinsic::amdgcn_wave_reduce_add:
4127 case Intrinsic::amdgcn_wave_reduce_sub:
4128 case Intrinsic::amdgcn_wave_reduce_xor: {
4129 if (C0 && C0->isZero())
4130 return Constant::getNullValue(Ty);
4131 return nullptr;
4132 }
4133 case Intrinsic::amdgcn_wave_reduce_umin:
4134 case Intrinsic::amdgcn_wave_reduce_umax:
4135 case Intrinsic::amdgcn_wave_reduce_max:
4136 case Intrinsic::amdgcn_wave_reduce_min:
4137 case Intrinsic::amdgcn_wave_reduce_and:
4138 case Intrinsic::amdgcn_wave_reduce_or:
4139 return Operands[0];
4140 case Intrinsic::aarch64_crc32b:
4141 case Intrinsic::arm_crc32b:
4142 return ConstantFoldCRC32(Ty, C0, C1, 1, 0xEDB88320);
4143 case Intrinsic::aarch64_crc32h:
4144 case Intrinsic::arm_crc32h:
4145 return ConstantFoldCRC32(Ty, C0, C1, 2, 0xEDB88320);
4146 case Intrinsic::aarch64_crc32w:
4147 case Intrinsic::arm_crc32w:
4148 return ConstantFoldCRC32(Ty, C0, C1, 4, 0xEDB88320);
4149 case Intrinsic::aarch64_crc32x:
4150 return ConstantFoldCRC32(Ty, C0, C1, 8, 0xEDB88320);
4151 case Intrinsic::aarch64_crc32cb:
4152 case Intrinsic::arm_crc32cb:
4153 case Intrinsic::x86_sse42_crc32_32_8:
4154 return ConstantFoldCRC32(Ty, C0, C1, 1, 0x82F63B78);
4155 case Intrinsic::aarch64_crc32ch:
4156 case Intrinsic::arm_crc32ch:
4157 case Intrinsic::x86_sse42_crc32_32_16:
4158 return ConstantFoldCRC32(Ty, C0, C1, 2, 0x82F63B78);
4159 case Intrinsic::aarch64_crc32cw:
4160 case Intrinsic::arm_crc32cw:
4161 case Intrinsic::x86_sse42_crc32_32_32:
4162 return ConstantFoldCRC32(Ty, C0, C1, 4, 0x82F63B78);
4163 case Intrinsic::aarch64_crc32cx:
4164 case Intrinsic::x86_sse42_crc32_64_64:
4165 return ConstantFoldCRC32(Ty, C0, C1, 8, 0x82F63B78);
4166 }
4167
4168 return nullptr;
4169 }
4170
4171 // Support ConstantVector in case we have an Undef in the top.
4172 if ((isa<ConstantVector>(Operands[0]) ||
4174 // Check for default rounding mode.
4175 // FIXME: Support other rounding modes?
4177 cast<ConstantInt>(Operands[1])->getValue() == 4) {
4178 auto *Op = cast<Constant>(Operands[0]);
4179 switch (IntrinsicID) {
4180 default: break;
4181 case Intrinsic::x86_avx512_vcvtss2si32:
4182 case Intrinsic::x86_avx512_vcvtss2si64:
4183 case Intrinsic::x86_avx512_vcvtsd2si32:
4184 case Intrinsic::x86_avx512_vcvtsd2si64:
4185 if (ConstantFP *FPOp =
4186 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4187 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4188 /*roundTowardZero=*/false, Ty,
4189 /*IsSigned*/true);
4190 break;
4191 case Intrinsic::x86_avx512_vcvtss2usi32:
4192 case Intrinsic::x86_avx512_vcvtss2usi64:
4193 case Intrinsic::x86_avx512_vcvtsd2usi32:
4194 case Intrinsic::x86_avx512_vcvtsd2usi64:
4195 if (ConstantFP *FPOp =
4196 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4197 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4198 /*roundTowardZero=*/false, Ty,
4199 /*IsSigned*/false);
4200 break;
4201 case Intrinsic::x86_avx512_cvttss2si:
4202 case Intrinsic::x86_avx512_cvttss2si64:
4203 case Intrinsic::x86_avx512_cvttsd2si:
4204 case Intrinsic::x86_avx512_cvttsd2si64:
4205 if (ConstantFP *FPOp =
4206 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4207 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4208 /*roundTowardZero=*/true, Ty,
4209 /*IsSigned*/true);
4210 break;
4211 case Intrinsic::x86_avx512_cvttss2usi:
4212 case Intrinsic::x86_avx512_cvttss2usi64:
4213 case Intrinsic::x86_avx512_cvttsd2usi:
4214 case Intrinsic::x86_avx512_cvttsd2usi64:
4215 if (ConstantFP *FPOp =
4216 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4217 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4218 /*roundTowardZero=*/true, Ty,
4219 /*IsSigned*/false);
4220 break;
4221 }
4222 }
4223
4224 if (IntrinsicID == Intrinsic::experimental_cttz_elts) {
4225 auto *FVTy = dyn_cast<FixedVectorType>(Operands[0]->getType());
4226 bool ZeroIsPoison = cast<ConstantInt>(Operands[1])->isOne();
4227 if (!FVTy)
4228 return nullptr;
4229 unsigned Width = Ty->getIntegerBitWidth();
4230 if (APInt::getMaxValue(Width).ult(FVTy->getNumElements()) ||
4231 Operands[0]->containsPoisonElement())
4232 return PoisonValue::get(Ty);
4233 for (unsigned I = 0; I < FVTy->getNumElements(); ++I) {
4234 Constant *Elt = Operands[0]->getAggregateElement(I);
4235 if (!Elt)
4236 return nullptr;
4237 if (isa<UndefValue>(Elt) || Elt->isNullValue())
4238 continue;
4239 return ConstantInt::get(Ty, I);
4240 }
4241 if (ZeroIsPoison)
4242 return PoisonValue::get(Ty);
4243 return ConstantInt::get(Ty, FVTy->getNumElements());
4244 }
4245 return nullptr;
4246}
4247
4248static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
4249 const APFloat &S0,
4250 const APFloat &S1,
4251 const APFloat &S2) {
4252 unsigned ID;
4253 const fltSemantics &Sem = S0.getSemantics();
4254 APFloat MA(Sem), SC(Sem), TC(Sem);
4255 if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
4256 if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
4257 // S2 < 0
4258 ID = 5;
4259 SC = -S0;
4260 } else {
4261 ID = 4;
4262 SC = S0;
4263 }
4264 MA = S2;
4265 TC = -S1;
4266 } else if (abs(S1) >= abs(S0)) {
4267 if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
4268 // S1 < 0
4269 ID = 3;
4270 TC = -S2;
4271 } else {
4272 ID = 2;
4273 TC = S2;
4274 }
4275 MA = S1;
4276 SC = S0;
4277 } else {
4278 if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
4279 // S0 < 0
4280 ID = 1;
4281 SC = S2;
4282 } else {
4283 ID = 0;
4284 SC = -S2;
4285 }
4286 MA = S0;
4287 TC = -S1;
4288 }
4289 switch (IntrinsicID) {
4290 default:
4291 llvm_unreachable("unhandled amdgcn cube intrinsic");
4292 case Intrinsic::amdgcn_cubeid:
4293 return APFloat(Sem, ID);
4294 case Intrinsic::amdgcn_cubema:
4295 return MA + MA;
4296 case Intrinsic::amdgcn_cubesc:
4297 return SC;
4298 case Intrinsic::amdgcn_cubetc:
4299 return TC;
4300 }
4301}
4302
4303static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
4304 Type *Ty) {
4305 const APInt *C0, *C1, *C2;
4306 if (!getConstIntOrUndef(Operands[0], C0) ||
4307 !getConstIntOrUndef(Operands[1], C1) ||
4308 !getConstIntOrUndef(Operands[2], C2))
4309 return nullptr;
4310
4311 if (!C2)
4312 return UndefValue::get(Ty);
4313
4314 APInt Val(32, 0);
4315 unsigned NumUndefBytes = 0;
4316 for (unsigned I = 0; I < 32; I += 8) {
4317 unsigned Sel = C2->extractBitsAsZExtValue(8, I);
4318 unsigned B = 0;
4319
4320 if (Sel >= 13)
4321 B = 0xff;
4322 else if (Sel == 12)
4323 B = 0x00;
4324 else {
4325 const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
4326 if (!Src)
4327 ++NumUndefBytes;
4328 else if (Sel < 8)
4329 B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
4330 else
4331 B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
4332 }
4333
4334 Val.insertBits(B, I, 8);
4335 }
4336
4337 if (NumUndefBytes == 4)
4338 return UndefValue::get(Ty);
4339
4340 return ConstantInt::get(Ty, Val);
4341}
4342
4343static Constant *ConstantFoldScalarCall3(StringRef Name,
4344 Intrinsic::ID IntrinsicID, Type *Ty,
4346 const TargetLibraryInfo *TLI = nullptr,
4347 const CallBase *Call = nullptr,
4348 const Function *CtxF = nullptr) {
4349 assert(Operands.size() == 3 && "Wrong number of operands.");
4350
4351 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
4352 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
4353 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
4354 const APFloat &C1 = Op1->getValueAPF();
4355 const APFloat &C2 = Op2->getValueAPF();
4356 const APFloat &C3 = Op3->getValueAPF();
4357
4358 if (const auto *ConstrIntr =
4360 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
4361 APFloat Res = C1;
4363 switch (IntrinsicID) {
4364 default:
4365 return nullptr;
4366 case Intrinsic::experimental_constrained_fma:
4367 case Intrinsic::experimental_constrained_fmuladd:
4368 St = Res.fusedMultiplyAdd(C2, C3, RM);
4369 break;
4370 }
4371 if (mayFoldConstrained(
4372 const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St))
4373 return ConstantFP::get(Ty, Res);
4374 return nullptr;
4375 }
4376
4377 switch (IntrinsicID) {
4378 default: break;
4379 case Intrinsic::amdgcn_fma_legacy: {
4380 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
4381 // NaN or infinity, gives +0.0.
4382 if (C1.isZero() || C2.isZero()) {
4383 // It's tempting to just return C3 here, but that would give the
4384 // wrong result if C3 was -0.0.
4385 return ConstantFP::get(Ty, APFloat(0.0f) + C3);
4386 }
4387 APFloat V = C1;
4388 V.fusedMultiplyAdd(C2, C3, APFloat::rmNearestTiesToEven);
4389 return ConstantFP::get(Ty, V);
4390 }
4391 case Intrinsic::fma:
4392 case Intrinsic::fmuladd:
4393 return tryFoldFPConst(Ty, FPOp::FMA, {C1, C2, C3}, Call, CtxF);
4394
4395 case Intrinsic::amdgcn_cubeid:
4396 case Intrinsic::amdgcn_cubema:
4397 case Intrinsic::amdgcn_cubesc:
4398 case Intrinsic::amdgcn_cubetc: {
4399 APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3);
4400 return ConstantFP::get(Ty, V);
4401 }
4402 }
4403 }
4404
4405 // TODO: Add constant folding for the _sat variants.
4406 const bool IsFAdd = IntrinsicID == Intrinsic::nvvm_fadd ||
4407 IntrinsicID == Intrinsic::nvvm_fadd_ftz;
4408 const bool IsFMul = IntrinsicID == Intrinsic::nvvm_fmul ||
4409 IntrinsicID == Intrinsic::nvvm_fmul_ftz;
4410 if (IsFAdd || IsFMul) {
4411 bool IsFTZ = IntrinsicID == Intrinsic::nvvm_fadd_ftz ||
4412 IntrinsicID == Intrinsic::nvvm_fmul_ftz;
4413 APFloat A =
4414 IsFTZ ? FTZPreserveSign(Op1->getValueAPF()) : Op1->getValueAPF();
4415 APFloat B =
4416 IsFTZ ? FTZPreserveSign(Op2->getValueAPF()) : Op2->getValueAPF();
4417
4418 APFloat::roundingMode RoundMode =
4420
4421 APFloat Res = A;
4423 IsFAdd ? Res.add(B, RoundMode) : Res.multiply(B, RoundMode);
4424
4425 if (!Res.isNaN() &&
4427 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
4428 return ConstantFP::get(Ty, Res);
4429 }
4430 return nullptr;
4431 }
4432 }
4433 }
4434
4435 if (IntrinsicID == Intrinsic::smul_fix ||
4436 IntrinsicID == Intrinsic::smul_fix_sat) {
4437 const APInt *C0, *C1;
4438 if (!getConstIntOrUndef(Operands[0], C0) ||
4439 !getConstIntOrUndef(Operands[1], C1))
4440 return nullptr;
4441
4442 // undef * C -> 0
4443 // C * undef -> 0
4444 if (!C0 || !C1)
4445 return Constant::getNullValue(Ty);
4446
4447 // This code performs rounding towards negative infinity in case the result
4448 // cannot be represented exactly for the given scale. Targets that do care
4449 // about rounding should use a target hook for specifying how rounding
4450 // should be done, and provide their own folding to be consistent with
4451 // rounding. This is the same approach as used by
4452 // DAGTypeLegalizer::ExpandIntRes_MULFIX.
4453 unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
4454 unsigned Width = C0->getBitWidth();
4455 assert(Scale < Width && "Illegal scale.");
4456 unsigned ExtendedWidth = Width * 2;
4457 APInt Product =
4458 (C0->sext(ExtendedWidth) * C1->sext(ExtendedWidth)).ashr(Scale);
4459 if (IntrinsicID == Intrinsic::smul_fix_sat) {
4460 APInt Max = APInt::getSignedMaxValue(Width).sext(ExtendedWidth);
4461 APInt Min = APInt::getSignedMinValue(Width).sext(ExtendedWidth);
4462 Product = APIntOps::smin(Product, Max);
4463 Product = APIntOps::smax(Product, Min);
4464 }
4465 return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
4466 }
4467
4468 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
4469 const APInt *C0, *C1, *C2;
4470 if (!getConstIntOrUndef(Operands[0], C0) ||
4471 !getConstIntOrUndef(Operands[1], C1) ||
4472 !getConstIntOrUndef(Operands[2], C2))
4473 return nullptr;
4474
4475 bool IsRight = IntrinsicID == Intrinsic::fshr;
4476 if (!C2)
4477 return Operands[IsRight ? 1 : 0];
4478 if (!C0 && !C1)
4479 return UndefValue::get(Ty);
4480
4481 // The shift amount is interpreted as modulo the bitwidth. If the shift
4482 // amount is effectively 0, avoid UB due to oversized inverse shift below.
4483 unsigned BitWidth = C2->getBitWidth();
4484 unsigned ShAmt = C2->urem(BitWidth);
4485 if (!ShAmt)
4486 return Operands[IsRight ? 1 : 0];
4487
4488 // (C0 << ShlAmt) | (C1 >> LshrAmt)
4489 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
4490 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
4491 if (!C0)
4492 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
4493 if (!C1)
4494 return ConstantInt::get(Ty, C0->shl(ShlAmt));
4495 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
4496 }
4497
4498 if (IntrinsicID == Intrinsic::amdgcn_perm)
4499 return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
4500
4501 return nullptr;
4502}
4503
4504static Constant *ConstantFoldScalarCall4(StringRef Name,
4505 Intrinsic::ID IntrinsicID, Type *Ty,
4507 const TargetLibraryInfo *TLI = nullptr,
4508 const CallBase *Call = nullptr) {
4509 assert(Operands.size() == 4 && "Wrong number of operands.");
4510
4511 // TODO: Add constant folding for the _sat and _relu variants.
4512 if (IntrinsicID == Intrinsic::nvvm_fma ||
4513 IntrinsicID == Intrinsic::nvvm_fma_ftz) {
4514 const auto *Op1 = dyn_cast<ConstantFP>(Operands[0]);
4515 const auto *Op2 = dyn_cast<ConstantFP>(Operands[1]);
4516 const auto *Op3 = dyn_cast<ConstantFP>(Operands[2]);
4517 if (!Op1 || !Op2 || !Op3)
4518 return nullptr;
4519
4520 bool IsFTZ = nvvm::FPArithShouldFTZ(IntrinsicID);
4521 APFloat A =
4522 IsFTZ ? FTZPreserveSign(Op1->getValueAPF()) : Op1->getValueAPF();
4523 APFloat B =
4524 IsFTZ ? FTZPreserveSign(Op2->getValueAPF()) : Op2->getValueAPF();
4525 APFloat C =
4526 IsFTZ ? FTZPreserveSign(Op3->getValueAPF()) : Op3->getValueAPF();
4527
4528 APFloat::roundingMode RoundMode =
4530
4531 APFloat Res = A;
4532 APFloat::opStatus Status = Res.fusedMultiplyAdd(B, C, RoundMode);
4533
4534 if (!Res.isNaN() &&
4536 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
4537 return ConstantFP::get(Ty, Res);
4538 }
4539 return nullptr;
4540 }
4541
4542 return nullptr;
4543}
4544
4545static Constant *ConstantFoldScalarCall(StringRef Name,
4546 Intrinsic::ID IntrinsicID, Type *Ty,
4548 const TargetLibraryInfo *TLI = nullptr,
4549 const CallBase *Call = nullptr,
4550 const Function *CtxF = nullptr) {
4551 if (IntrinsicID != Intrinsic::not_intrinsic &&
4553 intrinsicPropagatesPoison(IntrinsicID))
4554 return PoisonValue::get(Ty);
4555
4556 if (Operands.size() == 1)
4557 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call,
4558 CtxF);
4559
4560 if (Operands.size() == 2) {
4561 if (Constant *FoldedLibCall =
4562 ConstantFoldLibCall2(Name, Ty, Operands, TLI)) {
4563 return FoldedLibCall;
4564 }
4565 return ConstantFoldIntrinsicCall2(IntrinsicID, Ty, Operands, Call, CtxF);
4566 }
4567
4568 if (Operands.size() == 3)
4569 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call,
4570 CtxF);
4571
4572 if (Operands.size() == 4)
4573 return ConstantFoldScalarCall4(Name, IntrinsicID, Ty, Operands, TLI, Call);
4574
4575 return nullptr;
4576}
4577
4578static Constant *ConstantFoldFixedVectorCall(
4579 StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
4581 const TargetLibraryInfo *TLI = nullptr, const CallBase *Call = nullptr,
4582 const Function *CtxF = nullptr) {
4585 Type *Ty = FVTy->getElementType();
4586
4587 switch (IntrinsicID) {
4588 case Intrinsic::masked_load: {
4589 auto *SrcPtr = Operands[0];
4590 auto *Mask = Operands[1];
4591 auto *Passthru = Operands[2];
4592
4593 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
4594
4595 SmallVector<Constant *, 32> NewElements;
4596 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4597 auto *MaskElt = Mask->getAggregateElement(I);
4598 if (!MaskElt)
4599 break;
4600 auto *PassthruElt = Passthru->getAggregateElement(I);
4601 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
4602 if (isa<UndefValue>(MaskElt)) {
4603 if (PassthruElt)
4604 NewElements.push_back(PassthruElt);
4605 else if (VecElt)
4606 NewElements.push_back(VecElt);
4607 else
4608 return nullptr;
4609 }
4610 if (MaskElt->isNullValue()) {
4611 if (!PassthruElt)
4612 return nullptr;
4613 NewElements.push_back(PassthruElt);
4614 } else if (MaskElt->isOneValue()) {
4615 if (!VecElt)
4616 return nullptr;
4617 NewElements.push_back(VecElt);
4618 } else {
4619 return nullptr;
4620 }
4621 }
4622 if (NewElements.size() != FVTy->getNumElements())
4623 return nullptr;
4624 return ConstantVector::get(NewElements);
4625 }
4626 case Intrinsic::arm_mve_vctp8:
4627 case Intrinsic::arm_mve_vctp16:
4628 case Intrinsic::arm_mve_vctp32:
4629 case Intrinsic::arm_mve_vctp64: {
4630 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
4631 unsigned Lanes = FVTy->getNumElements();
4632 uint64_t Limit = Op->getZExtValue();
4633
4635 for (unsigned i = 0; i < Lanes; i++) {
4636 if (i < Limit)
4638 else
4640 }
4641 return ConstantVector::get(NCs);
4642 }
4643 return nullptr;
4644 }
4645 case Intrinsic::get_active_lane_mask: {
4646 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
4647 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
4648 if (Op0 && Op1) {
4649 unsigned Lanes = FVTy->getNumElements();
4650 APInt Base = Op0->getValue();
4651 APInt Limit = Op1->getValue();
4652
4654 for (unsigned I = 0; I < Lanes; I++) {
4655 bool Overflow;
4656 if (Base.uadd_ov(APInt(Base.getBitWidth(), I), Overflow).ult(Limit) &&
4657 !Overflow)
4659 else
4661 }
4662 return ConstantVector::get(NCs);
4663 }
4664 return nullptr;
4665 }
4666 case Intrinsic::mask_beforefirst: {
4669 Constant *Current = True;
4670 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4671 Constant *Elt = Operands[0]->getAggregateElement(I);
4673 return PoisonValue::get(FVTy);
4674 auto *CI = dyn_cast_or_null<ConstantInt>(Elt);
4675 if (!CI)
4676 return nullptr;
4677 if (CI->isOne())
4678 Current = False;
4679 Result[I] = Current;
4680 }
4681 return ConstantVector::get(Result);
4682 }
4683 case Intrinsic::vector_extract: {
4685 Constant *Vec = Operands[0];
4686 if (!Idx || !isa<FixedVectorType>(Vec->getType()))
4687 return nullptr;
4688
4689 unsigned NumElements = FVTy->getNumElements();
4690 unsigned VecNumElements =
4691 cast<FixedVectorType>(Vec->getType())->getNumElements();
4692 unsigned StartingIndex = Idx->getZExtValue();
4693
4694 // Extracting entire vector is nop
4695 if (NumElements == VecNumElements && StartingIndex == 0)
4696 return Vec;
4697
4698 for (unsigned I = StartingIndex, E = StartingIndex + NumElements; I < E;
4699 ++I) {
4700 Constant *Elt = Vec->getAggregateElement(I);
4701 if (!Elt)
4702 return nullptr;
4703 Result[I - StartingIndex] = Elt;
4704 }
4705
4706 return ConstantVector::get(Result);
4707 }
4708 case Intrinsic::vector_insert: {
4709 Constant *Vec = Operands[0];
4710 Constant *SubVec = Operands[1];
4712 if (!Idx || !isa<FixedVectorType>(Vec->getType()))
4713 return nullptr;
4714
4715 unsigned SubVecNumElements =
4716 cast<FixedVectorType>(SubVec->getType())->getNumElements();
4717 unsigned VecNumElements =
4718 cast<FixedVectorType>(Vec->getType())->getNumElements();
4719 unsigned IdxN = Idx->getZExtValue();
4720 // Replacing entire vector with a subvec is nop
4721 if (SubVecNumElements == VecNumElements && IdxN == 0)
4722 return SubVec;
4723
4724 for (unsigned I = 0; I < VecNumElements; ++I) {
4725 Constant *Elt;
4726 if (I < IdxN + SubVecNumElements)
4727 Elt = SubVec->getAggregateElement(I - IdxN);
4728 else
4729 Elt = Vec->getAggregateElement(I);
4730 if (!Elt)
4731 return nullptr;
4732 Result[I] = Elt;
4733 }
4734 return ConstantVector::get(Result);
4735 }
4736 case Intrinsic::vector_interleave2:
4737 case Intrinsic::vector_interleave3:
4738 case Intrinsic::vector_interleave4:
4739 case Intrinsic::vector_interleave5:
4740 case Intrinsic::vector_interleave6:
4741 case Intrinsic::vector_interleave7:
4742 case Intrinsic::vector_interleave8: {
4743 unsigned NumElements =
4744 cast<FixedVectorType>(Operands[0]->getType())->getNumElements();
4745 unsigned NumOperands = Operands.size();
4746 for (unsigned I = 0; I < NumElements; ++I) {
4747 for (unsigned J = 0; J < NumOperands; ++J) {
4748 Constant *Elt = Operands[J]->getAggregateElement(I);
4749 if (!Elt)
4750 return nullptr;
4751 Result[NumOperands * I + J] = Elt;
4752 }
4753 }
4754 return ConstantVector::get(Result);
4755 }
4756 case Intrinsic::vector_partial_reduce_add:
4757 return constantFoldVectorPartialReduceAdd(Operands[0], Operands[1], DL);
4758 case Intrinsic::wasm_dot: {
4759 unsigned NumElements =
4760 cast<FixedVectorType>(Operands[0]->getType())->getNumElements();
4761
4762 assert(NumElements == 8 && Result.size() == 4 &&
4763 "wasm dot takes i16x8 and produces i32x4");
4764 assert(Ty->isIntegerTy());
4765 int32_t MulVector[8];
4766
4767 for (unsigned I = 0; I < NumElements; ++I) {
4768 ConstantInt *Elt0 =
4769 dyn_cast<ConstantInt>(Operands[0]->getAggregateElement(I));
4770 ConstantInt *Elt1 =
4771 dyn_cast<ConstantInt>(Operands[1]->getAggregateElement(I));
4772
4773 if (!Elt0 || !Elt1)
4774 return nullptr;
4775
4776 MulVector[I] = Elt0->getSExtValue() * Elt1->getSExtValue();
4777 }
4778 for (unsigned I = 0; I < Result.size(); I++) {
4779 int64_t IAdd = (int64_t)MulVector[I * 2] + (int64_t)MulVector[I * 2 + 1];
4780 Result[I] = ConstantInt::getSigned(Ty, IAdd, /*ImplicitTrunc=*/true);
4781 }
4782
4783 return ConstantVector::get(Result);
4784 }
4785 case Intrinsic::nvvm_fadd:
4786 case Intrinsic::nvvm_fadd_ftz:
4787 case Intrinsic::nvvm_fma:
4788 case Intrinsic::nvvm_fma_ftz:
4789 case Intrinsic::nvvm_fmul:
4790 case Intrinsic::nvvm_fmul_ftz:
4791 // The rounding mode operand is a scalar, so the lane-wise folding below
4792 // does not apply.
4793 // TODO: Fold these by passing the rounding mode through to every lane.
4794 return nullptr;
4795 default:
4796 break;
4797 }
4798
4799 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4800 // Gather a column of constants.
4801 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
4802 // Some intrinsics use a scalar type for certain arguments.
4803 if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, J, /*TTI=*/nullptr)) {
4804 Lane[J] = Operands[J];
4805 continue;
4806 }
4807
4808 Constant *Agg = Operands[J]->getAggregateElement(I);
4809 if (!Agg)
4810 return nullptr;
4811
4812 Lane[J] = Agg;
4813 }
4814
4815 // Use the regular scalar folding to simplify this column.
4816 Constant *Folded =
4817 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call, CtxF);
4818 if (!Folded)
4819 return nullptr;
4820 Result[I] = Folded;
4821 }
4822
4823 return ConstantVector::get(Result);
4824}
4825
4826static Constant *ConstantFoldScalableVectorCall(
4827 StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
4829 const TargetLibraryInfo *TLI, const CallBase *Call) {
4830 switch (IntrinsicID) {
4831 case Intrinsic::aarch64_sve_convert_from_svbool: {
4832 Constant *Src = Operands[0];
4833 if (!Src->isNullValue())
4834 break;
4835
4836 return ConstantInt::getFalse(SVTy);
4837 }
4838 case Intrinsic::get_active_lane_mask: {
4839 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
4840 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
4841 if (Op0 && Op1 && Op0->getValue().uge(Op1->getValue()))
4842 return ConstantVector::getNullValue(SVTy);
4843 break;
4844 }
4845 case Intrinsic::mask_beforefirst: {
4846 Constant *SplatVal = Operands[0]->getSplatValue();
4847 if (isa_and_nonnull<PoisonValue>(SplatVal))
4848 return PoisonValue::get(SVTy);
4849 if (auto *CI = dyn_cast_if_present<ConstantInt>(SplatVal))
4850 return ConstantInt::getBool(SVTy, CI->isZero());
4851 break;
4852 }
4853 case Intrinsic::vector_interleave2:
4854 case Intrinsic::vector_interleave3:
4855 case Intrinsic::vector_interleave4:
4856 case Intrinsic::vector_interleave5:
4857 case Intrinsic::vector_interleave6:
4858 case Intrinsic::vector_interleave7:
4859 case Intrinsic::vector_interleave8: {
4860 Constant *SplatVal = Operands[0]->getSplatValue();
4861 if (!SplatVal)
4862 return nullptr;
4863
4865 return nullptr;
4866
4867 return ConstantVector::getSplat(SVTy->getElementCount(), SplatVal);
4868 }
4869 default:
4870 break;
4871 }
4872
4873 // If trivially vectorizable, try folding it via the scalar call if all
4874 // operands are splats.
4875
4876 // TODO: ConstantFoldFixedVectorCall should probably check this too?
4877 if (!isTriviallyVectorizable(IntrinsicID))
4878 return nullptr;
4879
4881 for (auto [I, Op] : enumerate(Operands)) {
4882 if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, I, /*TTI=*/nullptr)) {
4883 SplatOps.push_back(Op);
4884 continue;
4885 }
4886 Constant *Splat = Op->getSplatValue();
4887 if (!Splat)
4888 return nullptr;
4889 SplatOps.push_back(Splat);
4890 }
4891 Constant *Folded = ConstantFoldScalarCall(
4892 Name, IntrinsicID, SVTy->getElementType(), SplatOps, TLI, Call);
4893 if (!Folded)
4894 return nullptr;
4896}
4897
4898static std::pair<Constant *, Constant *>
4899ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) {
4900 auto *ConstFP = dyn_cast<ConstantFP>(Op);
4901 if (!ConstFP)
4902 return {};
4903
4904 const APFloat &U = ConstFP->getValueAPF();
4905 int FrexpExp;
4906 APFloat FrexpMant = frexp(U, FrexpExp, APFloat::rmNearestTiesToEven);
4907 Constant *Result0 = ConstantFP::get(ConstFP->getType(), FrexpMant);
4908
4909 // The exponent is an "unspecified value" for inf/nan. We use zero to avoid
4910 // using undef.
4911 Constant *Result1 = FrexpMant.isFinite()
4912 ? ConstantInt::getSigned(IntTy, FrexpExp)
4913 : ConstantInt::getNullValue(IntTy);
4914 return {Result0, Result1};
4915}
4916
4917/// Handle intrinsics that return tuples, which may be tuples of vectors.
4918static Constant *
4919ConstantFoldStructCall(StringRef Name, Intrinsic::ID IntrinsicID,
4921 const DataLayout &DL, const TargetLibraryInfo *TLI,
4922 const CallBase *Call) {
4923
4924 switch (IntrinsicID) {
4925 case Intrinsic::frexp: {
4926 Type *Ty0 = StTy->getContainedType(0);
4927 Type *Ty1 = StTy->getContainedType(1)->getScalarType();
4928
4929 if (auto *FVTy0 = dyn_cast<FixedVectorType>(Ty0)) {
4930 SmallVector<Constant *, 4> Results0(FVTy0->getNumElements());
4931 SmallVector<Constant *, 4> Results1(FVTy0->getNumElements());
4932
4933 for (unsigned I = 0, E = FVTy0->getNumElements(); I != E; ++I) {
4934 Constant *Lane = Operands[0]->getAggregateElement(I);
4935 std::tie(Results0[I], Results1[I]) =
4936 ConstantFoldScalarFrexpCall(Lane, Ty1);
4937 if (!Results0[I])
4938 return nullptr;
4939 }
4940
4941 return ConstantStruct::get(StTy, ConstantVector::get(Results0),
4942 ConstantVector::get(Results1));
4943 }
4944
4945 auto [Result0, Result1] = ConstantFoldScalarFrexpCall(Operands[0], Ty1);
4946 if (!Result0)
4947 return nullptr;
4948 return ConstantStruct::get(StTy, Result0, Result1);
4949 }
4950 case Intrinsic::sincos: {
4951 Type *Ty = StTy->getContainedType(0);
4952 Type *TyScalar = Ty->getScalarType();
4953
4954 auto ConstantFoldScalarSincosCall =
4955 [&](Constant *Op) -> std::pair<Constant *, Constant *> {
4956 Constant *SinResult =
4957 ConstantFoldScalarCall(Name, Intrinsic::sin, TyScalar, Op, TLI, Call);
4958 Constant *CosResult =
4959 ConstantFoldScalarCall(Name, Intrinsic::cos, TyScalar, Op, TLI, Call);
4960 return std::make_pair(SinResult, CosResult);
4961 };
4962
4963 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4964 SmallVector<Constant *> SinResults(FVTy->getNumElements());
4965 SmallVector<Constant *> CosResults(FVTy->getNumElements());
4966
4967 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4968 Constant *Lane = Operands[0]->getAggregateElement(I);
4969 std::tie(SinResults[I], CosResults[I]) =
4970 ConstantFoldScalarSincosCall(Lane);
4971 if (!SinResults[I] || !CosResults[I])
4972 return nullptr;
4973 }
4974
4975 return ConstantStruct::get(StTy, ConstantVector::get(SinResults),
4976 ConstantVector::get(CosResults));
4977 }
4978
4979 if (!Ty->isFloatingPointTy())
4980 return nullptr;
4981
4982 auto [SinResult, CosResult] = ConstantFoldScalarSincosCall(Operands[0]);
4983 if (!SinResult || !CosResult)
4984 return nullptr;
4985 return ConstantStruct::get(StTy, SinResult, CosResult);
4986 }
4987 case Intrinsic::vector_deinterleave2:
4988 case Intrinsic::vector_deinterleave3:
4989 case Intrinsic::vector_deinterleave4:
4990 case Intrinsic::vector_deinterleave5:
4991 case Intrinsic::vector_deinterleave6:
4992 case Intrinsic::vector_deinterleave7:
4993 case Intrinsic::vector_deinterleave8: {
4994 unsigned NumResults = StTy->getNumElements();
4995 auto *Vec = Operands[0];
4996 auto *VecTy = cast<VectorType>(Vec->getType());
4997
4998 ElementCount ResultEC =
4999 VecTy->getElementCount().divideCoefficientBy(NumResults);
5000
5001 if (auto *EltC = Vec->getSplatValue()) {
5002 auto *ResultVec = ConstantVector::getSplat(ResultEC, EltC);
5003 SmallVector<Constant *, 8> Results(NumResults, ResultVec);
5004 return ConstantStruct::get(StTy, Results);
5005 }
5006
5007 if (!ResultEC.isFixed())
5008 return nullptr;
5009
5010 unsigned NumElements = ResultEC.getFixedValue();
5012 SmallVector<Constant *> Elements(NumElements);
5013 for (unsigned I = 0; I != NumResults; ++I) {
5014 for (unsigned J = 0; J != NumElements; ++J) {
5015 Constant *Elt = Vec->getAggregateElement(J * NumResults + I);
5016 if (!Elt)
5017 return nullptr;
5018 Elements[J] = Elt;
5019 }
5020 Results[I] = ConstantVector::get(Elements);
5021 }
5022 return ConstantStruct::get(StTy, Results);
5023 }
5024 default:
5025 // TODO: Constant folding of vector intrinsics that fall through here does
5026 // not work (e.g. overflow intrinsics)
5027 return ConstantFoldScalarCall(Name, IntrinsicID, StTy, Operands, TLI, Call);
5028 }
5029
5030 return nullptr;
5031}
5032
5033} // end anonymous namespace
5034
5035Constant *llvm::ConstantFoldFP(double (*NativeFP)(double), const APFloat &V,
5036 Type *Ty, DenormalMode DenormMode) {
5037 assert(DenormMode.isValid() && "invalid denormal mode");
5040 return nullptr;
5041
5042 llvm_fenv_clearexcept();
5043 APFloat Input = FlushWithDenormKind(V, DenormMode.Input);
5044 double Result = NativeFP(Input.convertToDouble());
5045 if (llvm_fenv_testexcept()) {
5046 llvm_fenv_clearexcept();
5047 return nullptr;
5048 }
5049
5050 Constant *Output = GetConstantFoldFPValue(Result, Ty);
5052 return Output;
5053 auto *CFP = cast<ConstantFP>(Output);
5054 APFloat Res = FlushWithDenormKind(CFP->getValueAPF(), DenormMode.Output);
5055 return ConstantFP::get(Ty->getContext(), Res);
5056}
5057
5060 const DataLayout &DL,
5061 const Function *CtxF) {
5062 // In the absence of CtxF, assume strictfp conservatively.
5063 if (!canConstantFoldIntrinsic(ID, CtxF ? CtxF->isStrictFP() : true) ||
5066 Ty, ArrayRef<Value *>((Value *const *)Ops.data(), Ops.size()))))
5067 return nullptr;
5068 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
5069 return ConstantFoldFixedVectorCall("", ID, FVTy, Ops, DL, /*TLI=*/nullptr,
5070 /*Call=*/nullptr, CtxF);
5071 return ConstantFoldScalarCall("", ID, Ty, Ops, /*TLI=*/nullptr,
5072 /*Call=*/nullptr, CtxF);
5073}
5074
5077 const TargetLibraryInfo *TLI,
5078 bool AllowNonDeterministic) {
5079 if (Call->isNoBuiltin())
5080 return nullptr;
5081 if (!F->hasName())
5082 return nullptr;
5083
5084 // If this is not an intrinsic and not recognized as a library call, bail out.
5085 Intrinsic::ID IID = F->getIntrinsicID();
5086 if (IID == Intrinsic::not_intrinsic) {
5087 if (!TLI)
5088 return nullptr;
5089 if (TLI->getLibFunc(*F) == NotLibFunc)
5090 return nullptr;
5091 }
5092
5093 // Conservatively assume that floating-point libcalls may be
5094 // non-deterministic.
5095 Type *Ty = F->getReturnType();
5096 if (!AllowNonDeterministic && Ty->isFPOrFPVectorTy())
5097 return nullptr;
5098
5099 StringRef Name = F->getName();
5100 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
5101 return ConstantFoldFixedVectorCall(
5102 Name, IID, FVTy, Operands, F->getDataLayout(), TLI, Call);
5103
5104 if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
5105 return ConstantFoldScalableVectorCall(
5106 Name, IID, SVTy, Operands, F->getDataLayout(), TLI, Call);
5107
5108 if (auto *StTy = dyn_cast<StructType>(Ty))
5109 return ConstantFoldStructCall(Name, IID, StTy, Operands,
5110 F->getDataLayout(), TLI, Call);
5111
5112 // TODO: If this is a library function, we already discovered that above,
5113 // so we should pass the LibFunc, not the name (and it might be better
5114 // still to separate intrinsic handling from libcalls).
5115 return ConstantFoldScalarCall(Name, IID, Ty, Operands, TLI, Call);
5116}
5117
5119 const TargetLibraryInfo *TLI) {
5120 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
5121 // (and to some extent ConstantFoldScalarCall).
5122 if (Call->isNoBuiltin() || Call->isStrictFP())
5123 return false;
5124 Function *F = Call->getCalledFunction();
5125 if (!F)
5126 return false;
5127
5128 if (!TLI)
5129 return false;
5130
5131 LibFunc Func = TLI->getLibFunc(*F);
5132 if (Func == NotLibFunc)
5133 return false;
5134
5135 if (Call->arg_size() == 1) {
5136 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
5137 const APFloat &Op = OpC->getValueAPF();
5138 switch (Func) {
5139 case LibFunc_logl:
5140 case LibFunc_log:
5141 case LibFunc_logf:
5142 case LibFunc_log2l:
5143 case LibFunc_log2:
5144 case LibFunc_log2f:
5145 case LibFunc_log10l:
5146 case LibFunc_log10:
5147 case LibFunc_log10f:
5148 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
5149
5150 case LibFunc_ilogb:
5151 return !Op.isNaN() && !Op.isZero() && !Op.isInfinity();
5152
5153 case LibFunc_expl:
5154 case LibFunc_exp:
5155 case LibFunc_expf:
5156 // FIXME: These boundaries are slightly conservative.
5157 if (OpC->getType()->isDoubleTy())
5158 return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
5159 if (OpC->getType()->isFloatTy())
5160 return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
5161 break;
5162
5163 case LibFunc_exp2l:
5164 case LibFunc_exp2:
5165 case LibFunc_exp2f:
5166 // FIXME: These boundaries are slightly conservative.
5167 if (OpC->getType()->isDoubleTy())
5168 return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
5169 if (OpC->getType()->isFloatTy())
5170 return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
5171 break;
5172
5173 case LibFunc_sinl:
5174 case LibFunc_sin:
5175 case LibFunc_sinf:
5176 case LibFunc_cosl:
5177 case LibFunc_cos:
5178 case LibFunc_cosf:
5179 return !Op.isInfinity();
5180
5181 case LibFunc_tanl:
5182 case LibFunc_tan:
5183 case LibFunc_tanf: {
5184 // FIXME: Stop using the host math library.
5185 // FIXME: The computation isn't done in the right precision.
5186 Type *Ty = OpC->getType();
5187 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy())
5188 return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr;
5189 break;
5190 }
5191
5192 case LibFunc_atan:
5193 case LibFunc_atanf:
5194 case LibFunc_atanl:
5195 // Per POSIX, this MAY fail if Op is denormal. We choose not failing.
5196 return true;
5197
5198 case LibFunc_asinl:
5199 case LibFunc_asin:
5200 case LibFunc_asinf:
5201 case LibFunc_acosl:
5202 case LibFunc_acos:
5203 case LibFunc_acosf:
5204 return !(Op < APFloat::getOne(Op.getSemantics(), true) ||
5205 Op > APFloat::getOne(Op.getSemantics()));
5206
5207 case LibFunc_sinh:
5208 case LibFunc_cosh:
5209 case LibFunc_sinhf:
5210 case LibFunc_coshf:
5211 case LibFunc_sinhl:
5212 case LibFunc_coshl:
5213 // FIXME: These boundaries are slightly conservative.
5214 if (OpC->getType()->isDoubleTy())
5215 return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
5216 if (OpC->getType()->isFloatTy())
5217 return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
5218 break;
5219
5220 case LibFunc_sqrtl:
5221 case LibFunc_sqrt:
5222 case LibFunc_sqrtf:
5223 return Op.isNaN() || Op.isZero() || !Op.isNegative();
5224
5225 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
5226 // maybe others?
5227 default:
5228 break;
5229 }
5230 }
5231 }
5232
5233 if (Call->arg_size() == 2) {
5234 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
5235 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
5236 if (Op0C && Op1C) {
5237 const APFloat &Op0 = Op0C->getValueAPF();
5238 const APFloat &Op1 = Op1C->getValueAPF();
5239
5240 switch (Func) {
5241 case LibFunc_powl:
5242 case LibFunc_pow:
5243 case LibFunc_powf: {
5244 // FIXME: Stop using the host math library.
5245 // FIXME: The computation isn't done in the right precision.
5246 Type *Ty = Op0C->getType();
5247 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
5248 if (Ty == Op1C->getType())
5249 return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr;
5250 }
5251 break;
5252 }
5253
5254 case LibFunc_fmodl:
5255 case LibFunc_fmod:
5256 case LibFunc_fmodf:
5257 case LibFunc_remainderl:
5258 case LibFunc_remainder:
5259 case LibFunc_remainderf:
5260 return Op0.isNaN() || Op1.isNaN() ||
5261 (!Op0.isInfinity() && !Op1.isZero());
5262
5263 case LibFunc_atan2:
5264 case LibFunc_atan2f:
5265 case LibFunc_atan2l:
5266 // Although IEEE-754 says atan2(+/-0.0, +/-0.0) are well-defined, and
5267 // GLIBC and MSVC do not appear to raise an error on those, we
5268 // cannot rely on that behavior. POSIX and C11 say that a domain error
5269 // may occur, so allow for that possibility.
5270 return !Op0.isZero() || !Op1.isZero();
5271
5272 case LibFunc_nextafter:
5273 case LibFunc_nextafterf:
5274 case LibFunc_nextafterl:
5275 case LibFunc_nexttoward:
5276 case LibFunc_nexttowardf:
5277 case LibFunc_nexttowardl: {
5278 return ConstantFoldNextToward(Op0, Op1, F->getReturnType()) != nullptr;
5279 }
5280 default:
5281 break;
5282 }
5283 }
5284 }
5285
5286 return false;
5287}
5288
5290 unsigned CastOp, const DataLayout &DL,
5291 PreservedCastFlags *Flags) {
5292 switch (CastOp) {
5293 case Instruction::BitCast:
5294 // Bitcast is always lossless.
5295 return ConstantFoldCastOperand(Instruction::BitCast, C, InvCastTo, DL);
5296 case Instruction::Trunc: {
5297 auto *ZExtC = ConstantFoldCastOperand(Instruction::ZExt, C, InvCastTo, DL);
5298 if (Flags) {
5299 // Truncation back on ZExt value is always NUW.
5300 Flags->NUW = true;
5301 // Test positivity of C.
5302 auto *SExtC =
5303 ConstantFoldCastOperand(Instruction::SExt, C, InvCastTo, DL);
5304 Flags->NSW = ZExtC == SExtC;
5305 }
5306 return ZExtC;
5307 }
5308 case Instruction::SExt:
5309 case Instruction::ZExt: {
5310 auto *InvC = ConstantExpr::getTrunc(C, InvCastTo);
5311 auto *CastInvC = ConstantFoldCastOperand(CastOp, InvC, C->getType(), DL);
5312 // Must satisfy CastOp(InvC) == C.
5313 if (!CastInvC || CastInvC != C)
5314 return nullptr;
5315 if (Flags && CastOp == Instruction::ZExt) {
5316 auto *SExtInvC =
5317 ConstantFoldCastOperand(Instruction::SExt, InvC, C->getType(), DL);
5318 // Test positivity of InvC.
5319 Flags->NNeg = CastInvC == SExtInvC;
5320 }
5321 return InvC;
5322 }
5323 case Instruction::FPExt: {
5324 Constant *InvC =
5325 ConstantFoldCastOperand(Instruction::FPTrunc, C, InvCastTo, DL);
5326 if (InvC) {
5327 Constant *CastInvC =
5328 ConstantFoldCastOperand(CastOp, InvC, C->getType(), DL);
5329 if (CastInvC == C)
5330 return InvC;
5331 }
5332 return nullptr;
5333 }
5334 default:
5335 return nullptr;
5336 }
5337}
5338
5340 const DataLayout &DL,
5341 PreservedCastFlags *Flags) {
5342 return getLosslessInvCast(C, DestTy, Instruction::ZExt, DL, Flags);
5343}
5344
5346 const DataLayout &DL,
5347 PreservedCastFlags *Flags) {
5348 return getLosslessInvCast(C, DestTy, Instruction::SExt, DL, Flags);
5349}
5350
5351void TargetFolder::anchor() {}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Constant * FoldBitCast(Constant *V, Type *DestTy)
static const Function * getCtxFunc(const Instruction *CtxI, const Function *CtxF)
Return the instruction's function, or CtxF if it is unavailable.
static ConstantFP * flushDenormalConstant(Type *Ty, const APFloat &APF, DenormalMode::DenormalModeKind Mode)
Constant * getConstantAtOffset(Constant *Base, APInt Offset, const DataLayout &DL)
If this Offset points exactly to the start of an aggregate element, return that element,...
static cl::opt< bool > DisableFPCallFolding("disable-fp-call-folding", cl::desc("Disable constant-folding of FP intrinsics and libcalls."), cl::init(false), cl::Hidden)
static bool canConstantFoldIntrinsic(Intrinsic::ID ID, bool IsStrictFP)
Returns true if the intrinsic can be constant folded, given IsStrictFP.
static bool containsByteType(Type *Ty)
Return true if Ty is or contains a byte type.
static ConstantFP * flushDenormalConstantFP(ConstantFP *CFP, const Function *CtxF, bool IsOutput)
static DenormalMode getDenormMode(Type *Ty, const Instruction *CtxI, const Function *CtxF)
Return the denormal mode for a floating-point operation at CtxI or in CtxF, falling back to Dynamic i...
static bool anyTypeContainsFP(Type *RetTy, ArrayRef< Value * > Ops)
Given a function's return type and its operands, determine if any of them of of floating-point type.
static Constant * tryFoldFPConst(Type *Ty, FPOp Opcode, ArrayRef< APFloat > Args, const Instruction *CtxI, const Function *CtxF)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file provides fallible floating-point folding operations with explicit rounding and denormal mod...
Hexagon Common GEP
amode Optimize addressing mode
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
This file contains the definitions of the enumerations and flags associated with NVVM Intrinsics,...
if(PassOpts->AAPipeline)
int64_t C1
int64_t C0
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
The Input class is used to parse a yaml document into in-memory structs and vectors.
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:369
static constexpr roundingMode rmTowardZero
Definition APFloat.h:383
llvm::RoundingMode roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
Definition APFloat.h:377
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:382
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:381
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static constexpr roundingMode rmNearestTiesToAway
Definition APFloat.h:384
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:395
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1257
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1345
void copySign(const APFloat &RHS)
Definition APFloat.h:1439
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6103
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1327
bool isNegative() const
Definition APFloat.h:1616
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6336
bool isPosInfinity() const
Definition APFloat.h:1629
bool isNormal() const
Definition APFloat.h:1620
bool isDenormal() const
Definition APFloat.h:1617
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1318
const fltSemantics & getSemantics() const
Definition APFloat.h:1624
bool isNonZero() const
Definition APFloat.h:1625
bool isFinite() const
Definition APFloat.h:1621
bool isNaN() const
Definition APFloat.h:1614
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1225
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1336
bool isSignaling() const
Definition APFloat.h:1618
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1372
bool isZero() const
Definition APFloat.h:1612
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1469
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1363
bool isNegInfinity() const
Definition APFloat.h:1630
void changeSign()
Definition APFloat.h:1434
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1216
bool isInfinity() const
Definition APFloat.h:1613
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
Definition APInt.cpp:517
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static LLVM_ABI Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static LLVM_ABI unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, const DataLayout *DL)
Determine how a pair of casts can be eliminated, if they can be at all.
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1477
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1624
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
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
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
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
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Constrained floating point compare intrinsics.
This is the common base class for constrained floating point intrinsics.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
Wrapper for a function that represents a value that functionally represents the original function.
Definition Constants.h:1143
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
static LLVM_ABI bool compare(const APFloat &LHS, const APFloat &RHS, FCmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
bool isStrictFP() const
Determine if the function has strict floating point sematics.
Definition Function.h:637
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
GEPNoWrapFlags withoutNoUnsignedSignedWrap() const
static GEPNoWrapFlags noUnsignedWrap()
bool hasNoUnsignedSignedWrap() const
bool isInBounds() const
LLVM_ABI bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset, function_ref< bool(Value &, APInt &)> ExternalAnalysis=nullptr) const
Accumulate the constant address offset of this GEP if possible.
Definition Operator.cpp:130
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
bool isCast() const
bool isBinaryOp() const
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
bool isUnaryOp() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static APInt getSaturationPoint(Intrinsic::ID ID, unsigned numBits)
Min/max intrinsics are monotonic, they operate on a fixed-bitwidth values, so there is a certain thre...
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Class to represent scalable SIMD vectors.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
iterator_range< const_set_bits_iterator > set_bits() const
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
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
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:745
LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:243
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:293
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition Type.h:202
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition Type.h:399
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool *CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition Value.cpp:913
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:238
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3184
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3264
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3176
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3244
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3274
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:472
static constexpr cmpResult cmpEqual
Definition APFloat.h:480
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
constexpr double pi
APFloat::roundingMode GetRoundingModeFromImmArg(const Value *ImmArgVal)
DenormalMode GetNVVMDenormMode(bool ShouldFTZ)
bool FPToIntegerIntrinsicNaNZero(Intrinsic::ID IntrinsicID)
APFloat::roundingMode GetFDivRoundingMode(Intrinsic::ID IntrinsicID)
bool FPToIntegerIntrinsicResultIsSigned(Intrinsic::ID IntrinsicID)
APFloat::roundingMode GetFPToIntegerRoundingMode(Intrinsic::ID IntrinsicID)
bool RCPShouldFTZ(Intrinsic::ID IntrinsicID)
bool FPToIntegerIntrinsicShouldFTZ(Intrinsic::ID IntrinsicID)
bool FDivShouldFTZ(Intrinsic::ID IntrinsicID)
bool FMinFMaxIsXorSignAbs(Intrinsic::ID IntrinsicID)
bool FPArithShouldFTZ(Intrinsic::ID IntrinsicID)
bool UnaryMathIntrinsicShouldFTZ(Intrinsic::ID IntrinsicID)
bool FMinFMaxShouldFTZ(Intrinsic::ID IntrinsicID)
APFloat::roundingMode GetRCPRoundingMode(Intrinsic::ID IntrinsicID)
bool FMinFMaxPropagatesNaNs(Intrinsic::ID IntrinsicID)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
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:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Constant * ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy, const DataLayout &DL)
ConstantFoldLoadThroughBitcast - try to cast constant to destination type returning null if unsuccess...
static double log2(double V)
LLVM_ABI Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
LLVM_ABI Constant * ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL, const Instruction *I, bool AllowNonDeterministic=true)
Attempt to constant fold a floating point binary operation with the specified operands,...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:388
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1769
LLVM_ABI Constant * ConstantFoldCompareInstruction(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
LLVM_ABI Constant * ConstantFoldUnaryInstruction(unsigned Opcode, Constant *V)
LLVM_ABI bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
LLVM_ABI bool isMathLibCallNoop(const CallBase *Call, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI std::optional< FPFoldResult > tryFoldFP(FPOp Opcode, ArrayRef< APFloat > Args, DenormalMode Denorms)
Try to evaluate a floating-point operation with the specified inputs.
Definition FPFold.cpp:160
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1849
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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 Constant * ConstantFoldBitInsertOperands(Constant *Base, Constant *Val, Constant *Offset, const DataLayout &DL)
Attempt to constant fold a bitinsert instruction with the specified operands.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1740
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1761
LLVM_ABI Constant * ConstantFoldIntrinsic(Intrinsic::ID ID, ArrayRef< Constant * > Ops, Type *Ty, const DataLayout &DL, const Function *CtxF=nullptr)
LLVM_ABI Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:1762
LLVM_ABI Constant * ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, const DataLayout &DL)
If C is a uniform value where all bits are the same (either all zero, all ones, all undef or all pois...
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
FPOp
The floating-point operations supported by the folding helpers.
Definition FPFold.h:25
@ MaximumNum
Definition FPFold.h:36
@ RoundEven
Definition FPFold.h:42
@ Maximum
Definition FPFold.h:34
@ Minimum
Definition FPFold.h:33
@ MinimumNum
Definition FPFold.h:35
LLVM_ABI Constant * getLosslessUnsignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
LLVM_READONLY LLVM_ABI std::optional< APFloat > exp(const APFloat &X, RoundingMode RM=APFloat::rmNearestTiesToEven, APFloat::opStatus *Status=nullptr)
Implement IEEE 754-2019 exp functions.
Definition APFloat.cpp:6496
@ Off
Use window algorithm after SMS algorithm fails.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1835
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1749
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 Constant * getLosslessSignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
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 Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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 bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI Constant * FlushFPConstant(Constant *Operand, const Function *CtxF, bool IsOutput)
Attempt to flush float point constant according to denormal mode set in the instruction's parent func...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
LLVM_ABI Constant * ConstantFoldBitExtractOperands(Type *Ty, Constant *Src, Constant *Offset, const DataLayout &DL)
Attempt to constant fold a bitextract instruction with the specified result type and operands.
@ Sub
Subtraction of integers.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
@ NearestTiesToEven
roundTiesToEven.
@ Dynamic
Denotes mode unknown at compile time.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
Attempt to constant fold an insertvalue instruction with the specified operands and indices.
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...
constexpr uint32_t calculateReflectedCRC32(uint32_t Crc, uint64_t Data, unsigned DataBytes, uint32_t Poly)
Definition CRC.h:34
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1822
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1862
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
LLVM_ABI Constant * ConstantFoldFP(double(*NativeFP)(double), const APFloat &V, Type *Ty, DenormalMode DenormMode=DenormalMode::getIEEE())
Evaluate NativeFP on V using the host libm, then convert the result to Ty.
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
DenormalModeKind
Represent handled modes for denormal (aka subnormal) modes in the floating point environment.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
constexpr bool isValid() const
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
static constexpr DenormalMode getDynamic()
static constexpr DenormalMode getIEEE()
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58