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