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::abs:
1841 case Intrinsic::smax:
1842 case Intrinsic::smin:
1843 case Intrinsic::umax:
1844 case Intrinsic::umin:
1845 case Intrinsic::scmp:
1846 case Intrinsic::ucmp:
1847 case Intrinsic::sadd_with_overflow:
1848 case Intrinsic::uadd_with_overflow:
1849 case Intrinsic::ssub_with_overflow:
1850 case Intrinsic::usub_with_overflow:
1851 case Intrinsic::smul_with_overflow:
1852 case Intrinsic::umul_with_overflow:
1853 case Intrinsic::smulh:
1854 case Intrinsic::umulh:
1855 case Intrinsic::sadd_sat:
1856 case Intrinsic::uadd_sat:
1857 case Intrinsic::ssub_sat:
1858 case Intrinsic::usub_sat:
1859 case Intrinsic::smul_fix:
1860 case Intrinsic::smul_fix_sat:
1861 case Intrinsic::bitreverse:
1862 case Intrinsic::is_constant:
1863 case Intrinsic::vector_reduce_add:
1864 case Intrinsic::vector_reduce_mul:
1865 case Intrinsic::vector_reduce_and:
1866 case Intrinsic::vector_reduce_or:
1867 case Intrinsic::vector_reduce_xor:
1868 case Intrinsic::vector_reduce_smin:
1869 case Intrinsic::vector_reduce_smax:
1870 case Intrinsic::vector_reduce_umin:
1871 case Intrinsic::vector_reduce_umax:
1872 case Intrinsic::vector_partial_reduce_add:
1873 case Intrinsic::vector_extract:
1874 case Intrinsic::vector_insert:
1875 case Intrinsic::vector_interleave2:
1876 case Intrinsic::vector_interleave3:
1877 case Intrinsic::vector_interleave4:
1878 case Intrinsic::vector_interleave5:
1879 case Intrinsic::vector_interleave6:
1880 case Intrinsic::vector_interleave7:
1881 case Intrinsic::vector_interleave8:
1882 case Intrinsic::vector_deinterleave2:
1883 case Intrinsic::vector_deinterleave3:
1884 case Intrinsic::vector_deinterleave4:
1885 case Intrinsic::vector_deinterleave5:
1886 case Intrinsic::vector_deinterleave6:
1887 case Intrinsic::vector_deinterleave7:
1888 case Intrinsic::vector_deinterleave8:
1889 // Target intrinsics
1890 case Intrinsic::amdgcn_perm:
1891 case Intrinsic::amdgcn_wave_reduce_umin:
1892 case Intrinsic::amdgcn_wave_reduce_umax:
1893 case Intrinsic::amdgcn_wave_reduce_max:
1894 case Intrinsic::amdgcn_wave_reduce_min:
1895 case Intrinsic::amdgcn_wave_reduce_and:
1896 case Intrinsic::amdgcn_wave_reduce_or:
1897 case Intrinsic::amdgcn_wave_reduce_xor:
1898 case Intrinsic::amdgcn_wave_reduce_add:
1899 case Intrinsic::amdgcn_wave_reduce_sub:
1900 case Intrinsic::amdgcn_s_wqm:
1901 case Intrinsic::amdgcn_s_quadmask:
1902 case Intrinsic::amdgcn_s_bitreplicate:
1903 case Intrinsic::arm_crc32b:
1904 case Intrinsic::arm_crc32h:
1905 case Intrinsic::arm_crc32w:
1906 case Intrinsic::arm_crc32cb:
1907 case Intrinsic::arm_crc32ch:
1908 case Intrinsic::arm_crc32cw:
1909 case Intrinsic::arm_mve_vctp8:
1910 case Intrinsic::arm_mve_vctp16:
1911 case Intrinsic::arm_mve_vctp32:
1912 case Intrinsic::arm_mve_vctp64:
1913 case Intrinsic::aarch64_crc32b:
1914 case Intrinsic::aarch64_crc32h:
1915 case Intrinsic::aarch64_crc32w:
1916 case Intrinsic::aarch64_crc32x:
1917 case Intrinsic::aarch64_crc32cb:
1918 case Intrinsic::aarch64_crc32ch:
1919 case Intrinsic::aarch64_crc32cw:
1920 case Intrinsic::aarch64_crc32cx:
1921 case Intrinsic::aarch64_sve_convert_from_svbool:
1922 case Intrinsic::wasm_alltrue:
1923 case Intrinsic::wasm_anytrue:
1924 case Intrinsic::wasm_dot:
1925 // WebAssembly float semantics are always known
1926 case Intrinsic::wasm_trunc_signed:
1927 case Intrinsic::wasm_trunc_unsigned:
1928 case Intrinsic::x86_sse42_crc32_32_8:
1929 case Intrinsic::x86_sse42_crc32_32_16:
1930 case Intrinsic::x86_sse42_crc32_32_32:
1931 case Intrinsic::x86_sse42_crc32_64_64:
1932 return true;
1933
1934 // Floating point operations cannot be folded in strictfp functions in
1935 // general case. They can be folded if FP environment is known to compiler.
1936 case Intrinsic::minnum:
1937 case Intrinsic::maxnum:
1938 case Intrinsic::minimum:
1939 case Intrinsic::maximum:
1940 case Intrinsic::minimumnum:
1941 case Intrinsic::maximumnum:
1942 case Intrinsic::log:
1943 case Intrinsic::log2:
1944 case Intrinsic::log10:
1945 case Intrinsic::exp:
1946 case Intrinsic::exp2:
1947 case Intrinsic::exp10:
1948 case Intrinsic::sqrt:
1949 case Intrinsic::sin:
1950 case Intrinsic::cos:
1951 case Intrinsic::sincos:
1952 case Intrinsic::sinh:
1953 case Intrinsic::cosh:
1954 case Intrinsic::atan:
1955 case Intrinsic::pow:
1956 case Intrinsic::powi:
1957 case Intrinsic::ldexp:
1958 case Intrinsic::fma:
1959 case Intrinsic::fmuladd:
1960 case Intrinsic::frexp:
1961 case Intrinsic::fptoui_sat:
1962 case Intrinsic::fptosi_sat:
1963 case Intrinsic::amdgcn_cos:
1964 case Intrinsic::amdgcn_cubeid:
1965 case Intrinsic::amdgcn_cubema:
1966 case Intrinsic::amdgcn_cubesc:
1967 case Intrinsic::amdgcn_cubetc:
1968 case Intrinsic::amdgcn_fmul_legacy:
1969 case Intrinsic::amdgcn_fma_legacy:
1970 case Intrinsic::amdgcn_fract:
1971 case Intrinsic::amdgcn_sin:
1972 // The intrinsics below depend on rounding mode in MXCSR.
1973 case Intrinsic::x86_sse_cvtss2si:
1974 case Intrinsic::x86_sse_cvtss2si64:
1975 case Intrinsic::x86_sse_cvttss2si:
1976 case Intrinsic::x86_sse_cvttss2si64:
1977 case Intrinsic::x86_sse2_cvtsd2si:
1978 case Intrinsic::x86_sse2_cvtsd2si64:
1979 case Intrinsic::x86_sse2_cvttsd2si:
1980 case Intrinsic::x86_sse2_cvttsd2si64:
1981 case Intrinsic::x86_avx512_vcvtss2si32:
1982 case Intrinsic::x86_avx512_vcvtss2si64:
1983 case Intrinsic::x86_avx512_cvttss2si:
1984 case Intrinsic::x86_avx512_cvttss2si64:
1985 case Intrinsic::x86_avx512_vcvtsd2si32:
1986 case Intrinsic::x86_avx512_vcvtsd2si64:
1987 case Intrinsic::x86_avx512_cvttsd2si:
1988 case Intrinsic::x86_avx512_cvttsd2si64:
1989 case Intrinsic::x86_avx512_vcvtss2usi32:
1990 case Intrinsic::x86_avx512_vcvtss2usi64:
1991 case Intrinsic::x86_avx512_cvttss2usi:
1992 case Intrinsic::x86_avx512_cvttss2usi64:
1993 case Intrinsic::x86_avx512_vcvtsd2usi32:
1994 case Intrinsic::x86_avx512_vcvtsd2usi64:
1995 case Intrinsic::x86_avx512_cvttsd2usi:
1996 case Intrinsic::x86_avx512_cvttsd2usi64:
1997
1998 // NVVM FMax intrinsics
1999 case Intrinsic::nvvm_fmax_d:
2000 case Intrinsic::nvvm_fmax_f:
2001 case Intrinsic::nvvm_fmax_ftz_f:
2002 case Intrinsic::nvvm_fmax_ftz_nan_f:
2003 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
2004 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
2005 case Intrinsic::nvvm_fmax_nan_f:
2006 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
2007 case Intrinsic::nvvm_fmax_xorsign_abs_f:
2008
2009 // NVVM FMin intrinsics
2010 case Intrinsic::nvvm_fmin_d:
2011 case Intrinsic::nvvm_fmin_f:
2012 case Intrinsic::nvvm_fmin_ftz_f:
2013 case Intrinsic::nvvm_fmin_ftz_nan_f:
2014 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
2015 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
2016 case Intrinsic::nvvm_fmin_nan_f:
2017 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
2018 case Intrinsic::nvvm_fmin_xorsign_abs_f:
2019
2020 // NVVM float/double to int32/uint32 conversion intrinsics
2021 case Intrinsic::nvvm_f2i_rm:
2022 case Intrinsic::nvvm_f2i_rn:
2023 case Intrinsic::nvvm_f2i_rp:
2024 case Intrinsic::nvvm_f2i_rz:
2025 case Intrinsic::nvvm_f2i_rm_ftz:
2026 case Intrinsic::nvvm_f2i_rn_ftz:
2027 case Intrinsic::nvvm_f2i_rp_ftz:
2028 case Intrinsic::nvvm_f2i_rz_ftz:
2029 case Intrinsic::nvvm_f2ui_rm:
2030 case Intrinsic::nvvm_f2ui_rn:
2031 case Intrinsic::nvvm_f2ui_rp:
2032 case Intrinsic::nvvm_f2ui_rz:
2033 case Intrinsic::nvvm_f2ui_rm_ftz:
2034 case Intrinsic::nvvm_f2ui_rn_ftz:
2035 case Intrinsic::nvvm_f2ui_rp_ftz:
2036 case Intrinsic::nvvm_f2ui_rz_ftz:
2037 case Intrinsic::nvvm_d2i_rm:
2038 case Intrinsic::nvvm_d2i_rn:
2039 case Intrinsic::nvvm_d2i_rp:
2040 case Intrinsic::nvvm_d2i_rz:
2041 case Intrinsic::nvvm_d2ui_rm:
2042 case Intrinsic::nvvm_d2ui_rn:
2043 case Intrinsic::nvvm_d2ui_rp:
2044 case Intrinsic::nvvm_d2ui_rz:
2045
2046 // NVVM float/double to int64/uint64 conversion intrinsics
2047 case Intrinsic::nvvm_f2ll_rm:
2048 case Intrinsic::nvvm_f2ll_rn:
2049 case Intrinsic::nvvm_f2ll_rp:
2050 case Intrinsic::nvvm_f2ll_rz:
2051 case Intrinsic::nvvm_f2ll_rm_ftz:
2052 case Intrinsic::nvvm_f2ll_rn_ftz:
2053 case Intrinsic::nvvm_f2ll_rp_ftz:
2054 case Intrinsic::nvvm_f2ll_rz_ftz:
2055 case Intrinsic::nvvm_f2ull_rm:
2056 case Intrinsic::nvvm_f2ull_rn:
2057 case Intrinsic::nvvm_f2ull_rp:
2058 case Intrinsic::nvvm_f2ull_rz:
2059 case Intrinsic::nvvm_f2ull_rm_ftz:
2060 case Intrinsic::nvvm_f2ull_rn_ftz:
2061 case Intrinsic::nvvm_f2ull_rp_ftz:
2062 case Intrinsic::nvvm_f2ull_rz_ftz:
2063 case Intrinsic::nvvm_d2ll_rm:
2064 case Intrinsic::nvvm_d2ll_rn:
2065 case Intrinsic::nvvm_d2ll_rp:
2066 case Intrinsic::nvvm_d2ll_rz:
2067 case Intrinsic::nvvm_d2ull_rm:
2068 case Intrinsic::nvvm_d2ull_rn:
2069 case Intrinsic::nvvm_d2ull_rp:
2070 case Intrinsic::nvvm_d2ull_rz:
2071
2072 // NVVM math intrinsics:
2073 case Intrinsic::nvvm_ceil_d:
2074 case Intrinsic::nvvm_ceil_f:
2075 case Intrinsic::nvvm_ceil_ftz_f:
2076
2077 case Intrinsic::nvvm_fabs:
2078 case Intrinsic::nvvm_fabs_ftz:
2079
2080 case Intrinsic::nvvm_floor_d:
2081 case Intrinsic::nvvm_floor_f:
2082 case Intrinsic::nvvm_floor_ftz_f:
2083
2084 case Intrinsic::nvvm_rcp_rm_d:
2085 case Intrinsic::nvvm_rcp_rm_f:
2086 case Intrinsic::nvvm_rcp_rm_ftz_f:
2087 case Intrinsic::nvvm_rcp_rn_d:
2088 case Intrinsic::nvvm_rcp_rn_f:
2089 case Intrinsic::nvvm_rcp_rn_ftz_f:
2090 case Intrinsic::nvvm_rcp_rp_d:
2091 case Intrinsic::nvvm_rcp_rp_f:
2092 case Intrinsic::nvvm_rcp_rp_ftz_f:
2093 case Intrinsic::nvvm_rcp_rz_d:
2094 case Intrinsic::nvvm_rcp_rz_f:
2095 case Intrinsic::nvvm_rcp_rz_ftz_f:
2096
2097 case Intrinsic::nvvm_round_d:
2098 case Intrinsic::nvvm_round_f:
2099 case Intrinsic::nvvm_round_ftz_f:
2100
2101 case Intrinsic::nvvm_saturate_d:
2102 case Intrinsic::nvvm_saturate_f:
2103 case Intrinsic::nvvm_saturate_ftz_f:
2104
2105 case Intrinsic::nvvm_sqrt_f:
2106 case Intrinsic::nvvm_sqrt_rn_d:
2107 case Intrinsic::nvvm_sqrt_rn_f:
2108 case Intrinsic::nvvm_sqrt_rn_ftz_f:
2109 return !IsStrictFP;
2110
2111 // NVVM fadd/fmul intrinsics with explicit rounding modes
2112 case Intrinsic::nvvm_fadd:
2113 case Intrinsic::nvvm_fadd_ftz:
2114 case Intrinsic::nvvm_fmul:
2115 case Intrinsic::nvvm_fmul_ftz:
2116
2117 // NVVM div intrinsics with explicit rounding modes
2118 case Intrinsic::nvvm_div_rm_d:
2119 case Intrinsic::nvvm_div_rn_d:
2120 case Intrinsic::nvvm_div_rp_d:
2121 case Intrinsic::nvvm_div_rz_d:
2122 case Intrinsic::nvvm_div_rm_f:
2123 case Intrinsic::nvvm_div_rn_f:
2124 case Intrinsic::nvvm_div_rp_f:
2125 case Intrinsic::nvvm_div_rz_f:
2126 case Intrinsic::nvvm_div_rm_ftz_f:
2127 case Intrinsic::nvvm_div_rn_ftz_f:
2128 case Intrinsic::nvvm_div_rp_ftz_f:
2129 case Intrinsic::nvvm_div_rz_ftz_f:
2130
2131 // NVVM fma intrinsics with explicit rounding modes
2132 case Intrinsic::nvvm_fma_rm_d:
2133 case Intrinsic::nvvm_fma_rn_d:
2134 case Intrinsic::nvvm_fma_rp_d:
2135 case Intrinsic::nvvm_fma_rz_d:
2136 case Intrinsic::nvvm_fma_rm_f:
2137 case Intrinsic::nvvm_fma_rn_f:
2138 case Intrinsic::nvvm_fma_rp_f:
2139 case Intrinsic::nvvm_fma_rz_f:
2140 case Intrinsic::nvvm_fma_rm_ftz_f:
2141 case Intrinsic::nvvm_fma_rn_ftz_f:
2142 case Intrinsic::nvvm_fma_rp_ftz_f:
2143 case Intrinsic::nvvm_fma_rz_ftz_f:
2144
2145 // Sign operations are actually bitwise operations, they do not raise
2146 // exceptions even for SNANs.
2147 case Intrinsic::fabs:
2148 case Intrinsic::copysign:
2149 case Intrinsic::is_fpclass:
2150 // Non-constrained variants of rounding operations means default FP
2151 // environment, they can be folded in any case.
2152 case Intrinsic::ceil:
2153 case Intrinsic::floor:
2154 case Intrinsic::round:
2155 case Intrinsic::roundeven:
2156 case Intrinsic::trunc:
2157 case Intrinsic::nearbyint:
2158 case Intrinsic::rint:
2159 case Intrinsic::canonicalize:
2160
2161 // Constrained intrinsics can be folded if FP environment is known
2162 // to compiler.
2163 case Intrinsic::experimental_constrained_fma:
2164 case Intrinsic::experimental_constrained_fmuladd:
2165 case Intrinsic::experimental_constrained_fadd:
2166 case Intrinsic::experimental_constrained_fsub:
2167 case Intrinsic::experimental_constrained_fmul:
2168 case Intrinsic::experimental_constrained_fdiv:
2169 case Intrinsic::experimental_constrained_frem:
2170 case Intrinsic::experimental_constrained_ceil:
2171 case Intrinsic::experimental_constrained_floor:
2172 case Intrinsic::experimental_constrained_round:
2173 case Intrinsic::experimental_constrained_roundeven:
2174 case Intrinsic::experimental_constrained_trunc:
2175 case Intrinsic::experimental_constrained_nearbyint:
2176 case Intrinsic::experimental_constrained_rint:
2177 case Intrinsic::experimental_constrained_fcmp:
2178 case Intrinsic::experimental_constrained_fcmps:
2179
2180 case Intrinsic::experimental_cttz_elts:
2181 return true;
2182 default:
2183 return false;
2184 }
2185}
2186
2187/// Given a function's return type and its operands, determine if any of them of
2188/// of floating-point type.
2190 return RetTy->isFloatingPointTy() || any_of(Ops, [](Value *V) {
2191 return V->getType()->isFloatingPointTy();
2192 });
2193}
2194
2196 const TargetLibraryInfo *TLI) {
2197 if (Call->isNoBuiltin())
2198 return false;
2199 if (Call->getFunctionType() != F->getFunctionType())
2200 return false;
2201
2202 // Allow FP calls (both libcalls and intrinsics) to avoid being folded.
2203 // This can be useful for GPU targets or in cross-compilation scenarios
2204 // when the exact target FP behaviour is required, and the host compiler's
2205 // behaviour may be slightly different from the device's run-time behaviour.
2208 F->getReturnType(),
2209 ArrayRef<Value *>((Value *const *)(F->arg_begin()), F->arg_size())))
2210 return false;
2211
2212 if (F->getIntrinsicID() != Intrinsic::not_intrinsic)
2213 return canConstantFoldIntrinsic(F->getIntrinsicID(), Call->isStrictFP());
2214
2215 if (!TLI || Call->isStrictFP())
2216 return false;
2217
2218 LibFunc Func = TLI->getLibFunc(*F);
2219 if (Func == NotLibFunc)
2220 return false;
2221
2222 switch (Func) {
2223 case LibFunc_acos:
2224 case LibFunc_acosf:
2225 case LibFunc_acos_finite:
2226 case LibFunc_acosf_finite:
2227 case LibFunc_asin:
2228 case LibFunc_asinf:
2229 case LibFunc_asin_finite:
2230 case LibFunc_asinf_finite:
2231 case LibFunc_atan:
2232 case LibFunc_atanf:
2233 case LibFunc_atan2:
2234 case LibFunc_atan2f:
2235 case LibFunc_atan2_finite:
2236 case LibFunc_atan2f_finite:
2237 case LibFunc_ceil:
2238 case LibFunc_ceilf:
2239 case LibFunc_cosh:
2240 case LibFunc_coshf:
2241 case LibFunc_cosh_finite:
2242 case LibFunc_coshf_finite:
2243 case LibFunc_cos:
2244 case LibFunc_cosf:
2245 case LibFunc_erf:
2246 case LibFunc_erff:
2247 case LibFunc_exp:
2248 case LibFunc_expf:
2249 case LibFunc_exp_finite:
2250 case LibFunc_expf_finite:
2251 case LibFunc_exp2:
2252 case LibFunc_exp2f:
2253 case LibFunc_exp2_finite:
2254 case LibFunc_exp2f_finite:
2255 case LibFunc_fabs:
2256 case LibFunc_fabsf:
2257 case LibFunc_floor:
2258 case LibFunc_floorf:
2259 case LibFunc_fmod:
2260 case LibFunc_fmodf:
2261 case LibFunc_ilogb:
2262 case LibFunc_ilogbf:
2263 case LibFunc_log:
2264 case LibFunc_logf:
2265 case LibFunc_log_finite:
2266 case LibFunc_logf_finite:
2267 case LibFunc_logb:
2268 case LibFunc_logbf:
2269 case LibFunc_logl:
2270 case LibFunc_log2:
2271 case LibFunc_log2f:
2272 case LibFunc_log2_finite:
2273 case LibFunc_log2f_finite:
2274 case LibFunc_log10:
2275 case LibFunc_log10f:
2276 case LibFunc_log10_finite:
2277 case LibFunc_log10f_finite:
2278 case LibFunc_log1p:
2279 case LibFunc_log1pf:
2280 case LibFunc_nearbyint:
2281 case LibFunc_nearbyintf:
2282 case LibFunc_nextafter:
2283 case LibFunc_nextafterf:
2284 case LibFunc_nexttoward:
2285 case LibFunc_nexttowardf:
2286 case LibFunc_pow:
2287 case LibFunc_powf:
2288 case LibFunc_pow_finite:
2289 case LibFunc_powf_finite:
2290 case LibFunc_remainder:
2291 case LibFunc_remainderf:
2292 case LibFunc_rint:
2293 case LibFunc_rintf:
2294 case LibFunc_round:
2295 case LibFunc_roundf:
2296 case LibFunc_roundeven:
2297 case LibFunc_roundevenf:
2298 case LibFunc_sin:
2299 case LibFunc_sinf:
2300 case LibFunc_sinh:
2301 case LibFunc_sinhf:
2302 case LibFunc_sinh_finite:
2303 case LibFunc_sinhf_finite:
2304 case LibFunc_sqrt:
2305 case LibFunc_sqrtf:
2306 case LibFunc_tan:
2307 case LibFunc_tanf:
2308 case LibFunc_tanh:
2309 case LibFunc_tanhf:
2310 case LibFunc_trunc:
2311 case LibFunc_truncf:
2312 return true;
2313 default:
2314 return false;
2315 }
2316}
2317
2318namespace {
2319
2320Constant *GetConstantFoldFPValue(double V, Type *Ty) {
2321 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isBFloatTy()) {
2322 APFloat APF(V);
2323 bool unused;
2324 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
2325 return ConstantFP::get(Ty->getContext(), APF);
2326 }
2327 if (Ty->isDoubleTy())
2328 return ConstantFP::get(Ty->getContext(), APFloat(V));
2329 llvm_unreachable("Can only constant fold half/float/double/bfloat");
2330}
2331
2332#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2333Constant *GetConstantFoldFPValue128(float128 V, Type *Ty) {
2334 if (Ty->isFP128Ty())
2335 return ConstantFP::get(Ty, V);
2336 llvm_unreachable("Can only constant fold fp128");
2337}
2338#endif
2339
2340/// Clear the floating-point exception state.
2341inline void llvm_fenv_clearexcept() {
2342#if defined(FE_ALL_EXCEPT)
2343 feclearexcept(FE_ALL_EXCEPT);
2344#endif
2345 errno = 0;
2346}
2347
2348/// Test if a floating-point exception was raised.
2349inline bool llvm_fenv_testexcept() {
2350 int errno_val = errno;
2351 if (errno_val == ERANGE || errno_val == EDOM)
2352 return true;
2353#if defined(FE_ALL_EXCEPT) && defined(FE_INEXACT)
2354 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
2355 return true;
2356#endif
2357 return false;
2358}
2359
2360static APFloat FTZPreserveSign(const APFloat &V) {
2361 if (V.isDenormal())
2362 return APFloat::getZero(V.getSemantics(), V.isNegative());
2363 return V;
2364}
2365
2366static APFloat FlushToPositiveZero(const APFloat &V) {
2367 if (V.isDenormal())
2368 return APFloat::getZero(V.getSemantics(), false);
2369 return V;
2370}
2371
2372static APFloat FlushWithDenormKind(const APFloat &V,
2373 DenormalMode::DenormalModeKind DenormKind) {
2376 switch (DenormKind) {
2378 return V;
2380 return FTZPreserveSign(V);
2382 return FlushToPositiveZero(V);
2383 default:
2384 llvm_unreachable("Invalid denormal mode!");
2385 }
2386}
2387
2388Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V, Type *Ty,
2389 DenormalMode DenormMode = DenormalMode::getIEEE()) {
2390 if (!DenormMode.isValid() ||
2391 DenormMode.Input == DenormalMode::DenormalModeKind::Dynamic ||
2392 DenormMode.Output == DenormalMode::DenormalModeKind::Dynamic)
2393 return nullptr;
2394
2395 llvm_fenv_clearexcept();
2396 auto Input = FlushWithDenormKind(V, DenormMode.Input);
2397 double Result = NativeFP(Input.convertToDouble());
2398 if (llvm_fenv_testexcept()) {
2399 llvm_fenv_clearexcept();
2400 return nullptr;
2401 }
2402
2403 Constant *Output = GetConstantFoldFPValue(Result, Ty);
2404 if (DenormMode.Output == DenormalMode::DenormalModeKind::IEEE)
2405 return Output;
2406 const auto *CFP = static_cast<ConstantFP *>(Output);
2407 const auto Res = FlushWithDenormKind(CFP->getValueAPF(), DenormMode.Output);
2408 return ConstantFP::get(Ty->getContext(), Res);
2409}
2410
2411#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2412Constant *ConstantFoldFP128(float128 (*NativeFP)(float128), const APFloat &V,
2413 Type *Ty) {
2414 llvm_fenv_clearexcept();
2415 float128 Result = NativeFP(V.convertToQuad());
2416 if (llvm_fenv_testexcept()) {
2417 llvm_fenv_clearexcept();
2418 return nullptr;
2419 }
2420
2421 return GetConstantFoldFPValue128(Result, Ty);
2422}
2423#endif
2424
2425Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
2426 const APFloat &V, const APFloat &W, Type *Ty) {
2427 llvm_fenv_clearexcept();
2428 double Result = NativeFP(V.convertToDouble(), W.convertToDouble());
2429 if (llvm_fenv_testexcept()) {
2430 llvm_fenv_clearexcept();
2431 return nullptr;
2432 }
2433
2434 return GetConstantFoldFPValue(Result, Ty);
2435}
2436
2437Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
2438 auto *OpVT = cast<VectorType>(Op->getType());
2439
2440 // This is the same as the underlying binops - poison propagates.
2441 if (Op->containsPoisonElement())
2442 return PoisonValue::get(OpVT->getElementType());
2443
2444 // Shortcut non-accumulating reductions.
2445 if (Constant *SplatVal = Op->getSplatValue()) {
2446 switch (IID) {
2447 case Intrinsic::vector_reduce_and:
2448 case Intrinsic::vector_reduce_or:
2449 case Intrinsic::vector_reduce_smin:
2450 case Intrinsic::vector_reduce_smax:
2451 case Intrinsic::vector_reduce_umin:
2452 case Intrinsic::vector_reduce_umax:
2453 return SplatVal;
2454 case Intrinsic::vector_reduce_add:
2455 if (SplatVal->isNullValue())
2456 return SplatVal;
2457 break;
2458 case Intrinsic::vector_reduce_mul:
2459 if (SplatVal->isNullValue() || SplatVal->isOneValue())
2460 return SplatVal;
2461 break;
2462 case Intrinsic::vector_reduce_xor:
2463 if (SplatVal->isNullValue())
2464 return SplatVal;
2465 if (OpVT->getElementCount().isKnownMultipleOf(2))
2466 return Constant::getNullValue(OpVT->getElementType());
2467 break;
2468 }
2469 }
2470
2472 if (!VT)
2473 return nullptr;
2474
2475 auto *EltC = dyn_cast_or_null<ConstantInt>(Op->getAggregateElement(0U));
2476 if (!EltC)
2477 return nullptr;
2478
2479 APInt Acc = EltC->getValue();
2480 for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
2481 if (!(EltC = dyn_cast_or_null<ConstantInt>(Op->getAggregateElement(I))))
2482 return nullptr;
2483 const APInt &X = EltC->getValue();
2484 switch (IID) {
2485 case Intrinsic::vector_reduce_add:
2486 Acc = Acc + X;
2487 break;
2488 case Intrinsic::vector_reduce_mul:
2489 Acc = Acc * X;
2490 break;
2491 case Intrinsic::vector_reduce_and:
2492 Acc = Acc & X;
2493 break;
2494 case Intrinsic::vector_reduce_or:
2495 Acc = Acc | X;
2496 break;
2497 case Intrinsic::vector_reduce_xor:
2498 Acc = Acc ^ X;
2499 break;
2500 case Intrinsic::vector_reduce_smin:
2501 Acc = APIntOps::smin(Acc, X);
2502 break;
2503 case Intrinsic::vector_reduce_smax:
2504 Acc = APIntOps::smax(Acc, X);
2505 break;
2506 case Intrinsic::vector_reduce_umin:
2507 Acc = APIntOps::umin(Acc, X);
2508 break;
2509 case Intrinsic::vector_reduce_umax:
2510 Acc = APIntOps::umax(Acc, X);
2511 break;
2512 }
2513 }
2514
2515 return ConstantInt::get(Op->getContext(), Acc);
2516}
2517
2518/// Fold a vector partial reduction add using the deterministic grouping
2519/// chosen by TargetLowering::expandPartialReduceMLA. Although the
2520/// LangRef leaves the grouping unspecified, input element I is accumulated
2521/// into result lane I % NumAccElts, with each accumulator element seeding
2522/// its corresponding result lane. Returns nullptr if any element cannot be
2523/// folded.
2524static Constant *constantFoldVectorPartialReduceAdd(Constant *Acc,
2525 Constant *Input,
2526 const DataLayout &DL) {
2527 auto *AccTy = cast<FixedVectorType>(Acc->getType());
2528 // A fixed result type does not guarantee a fixed input type.
2529 auto *InputTy = dyn_cast<FixedVectorType>(Input->getType());
2530 if (!InputTy)
2531 return nullptr;
2532
2533 unsigned NumAccElts = AccTy->getNumElements();
2534 unsigned NumInputElts = InputTy->getNumElements();
2535
2536 SmallVector<Constant *> ResultElts(NumAccElts);
2537 for (unsigned I = 0; I < NumAccElts; ++I) {
2538 ResultElts[I] = Acc->getAggregateElement(I);
2539 if (!ResultElts[I])
2540 return nullptr;
2541 }
2542
2543 for (unsigned I = 0; I < NumInputElts; ++I) {
2544 Constant *InputElt = Input->getAggregateElement(I);
2545 if (!InputElt)
2546 return nullptr;
2547
2548 unsigned ResultIdx = I % NumAccElts;
2550 Instruction::Add, ResultElts[ResultIdx], InputElt, DL);
2551 if (!Folded)
2552 return nullptr;
2553
2554 ResultElts[ResultIdx] = Folded;
2555 }
2556
2557 return ConstantVector::get(ResultElts);
2558}
2559
2560/// Attempt to fold an SSE floating point to integer conversion of a constant
2561/// floating point. If roundTowardZero is false, the default IEEE rounding is
2562/// used (toward nearest, ties to even). This matches the behavior of the
2563/// non-truncating SSE instructions in the default rounding mode. The desired
2564/// integer type Ty is used to select how many bits are available for the
2565/// result. Returns null if the conversion cannot be performed, otherwise
2566/// returns the Constant value resulting from the conversion.
2567Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
2568 Type *Ty, bool IsSigned) {
2569 // All of these conversion intrinsics form an integer of at most 64bits.
2570 unsigned ResultWidth = Ty->getIntegerBitWidth();
2571 assert(ResultWidth <= 64 &&
2572 "Can only constant fold conversions to 64 and 32 bit ints");
2573
2574 uint64_t UIntVal;
2575 bool isExact = false;
2579 Val.convertToInteger(MutableArrayRef(UIntVal), ResultWidth,
2580 IsSigned, mode, &isExact);
2581 if (status != APFloat::opOK &&
2582 (!roundTowardZero || status != APFloat::opInexact))
2583 return nullptr;
2584 return ConstantInt::get(Ty, UIntVal, IsSigned);
2585}
2586
2587double getValueAsDouble(ConstantFP *Op) {
2588 Type *Ty = Op->getType();
2589
2590 if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2591 return Op->getValueAPF().convertToDouble();
2592
2593 bool unused;
2594 APFloat APF = Op->getValueAPF();
2596 return APF.convertToDouble();
2597}
2598
2599static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
2600 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
2601 C = &CI->getValue();
2602 return true;
2603 }
2604 if (isa<UndefValue>(Op)) {
2605 C = nullptr;
2606 return true;
2607 }
2608 return false;
2609}
2610
2611/// Checks if the given intrinsic call, which evaluates to constant, is allowed
2612/// to be folded.
2613///
2614/// \param CI Constrained intrinsic call.
2615/// \param St Exception flags raised during constant evaluation.
2616static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI,
2617 APFloat::opStatus St) {
2618 std::optional<RoundingMode> ORM = CI->getRoundingMode();
2619 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2620
2621 // If the operation does not change exception status flags, it is safe
2622 // to fold.
2623 if (St == APFloat::opStatus::opOK)
2624 return true;
2625
2626 // If evaluation raised FP exception, the result can depend on rounding
2627 // mode. If the latter is unknown, folding is not possible.
2628 if (ORM == RoundingMode::Dynamic)
2629 return false;
2630
2631 // If FP exceptions are ignored, fold the call, even if such exception is
2632 // raised.
2633 if (EB && *EB != fp::ExceptionBehavior::ebStrict)
2634 return true;
2635
2636 // Leave the calculation for runtime so that exception flags be correctly set
2637 // in hardware.
2638 return false;
2639}
2640
2641/// Returns the rounding mode that should be used for constant evaluation.
2642static RoundingMode
2643getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) {
2644 std::optional<RoundingMode> ORM = CI->getRoundingMode();
2645 if (!ORM || *ORM == RoundingMode::Dynamic)
2646 // Even if the rounding mode is unknown, try evaluating the operation.
2647 // If it does not raise inexact exception, rounding was not applied,
2648 // so the result is exact and does not depend on rounding mode. Whether
2649 // other FP exceptions are raised, it does not depend on rounding mode.
2651 return *ORM;
2652}
2653
2654/// Try to constant fold llvm.canonicalize for the given caller and value.
2655static Constant *constantFoldCanonicalize(const Type *Ty, const APFloat &Src,
2656 const Function *CtxF = nullptr) {
2657 // Zero, positive and negative, is always OK to fold.
2658 if (Src.isZero()) {
2659 // Get a fresh 0, since ppc_fp128 does have non-canonical zeros.
2660 return ConstantFP::get(
2661 Ty->getContext(),
2662 APFloat::getZero(Src.getSemantics(), Src.isNegative()));
2663 }
2664
2665 if (!Ty->isIEEELikeFPTy())
2666 return nullptr;
2667
2668 // Zero is always canonical and the sign must be preserved.
2669 //
2670 // Denorms and nans may have special encodings, but it should be OK to fold a
2671 // totally average number.
2672 if (Src.isNormal() || Src.isInfinity())
2673 return ConstantFP::get(Ty->getContext(), Src);
2674
2675 if (Src.isDenormal() && CtxF) {
2676 DenormalMode DenormMode = CtxF->getDenormalMode(Src.getSemantics());
2677
2678 if (DenormMode == DenormalMode::getIEEE())
2679 return ConstantFP::get(Ty->getContext(), Src);
2680
2681 if (DenormMode.Input == DenormalMode::Dynamic)
2682 return nullptr;
2683
2684 // If we know if either input or output is flushed, we can fold.
2685 if ((DenormMode.Input == DenormalMode::Dynamic &&
2686 DenormMode.Output == DenormalMode::IEEE) ||
2687 (DenormMode.Input == DenormalMode::IEEE &&
2688 DenormMode.Output == DenormalMode::Dynamic))
2689 return nullptr;
2690
2691 bool IsPositive =
2692 (!Src.isNegative() || DenormMode.Input == DenormalMode::PositiveZero ||
2693 (DenormMode.Output == DenormalMode::PositiveZero &&
2694 DenormMode.Input == DenormalMode::IEEE));
2695
2696 return ConstantFP::get(Ty->getContext(),
2697 APFloat::getZero(Src.getSemantics(), !IsPositive));
2698 }
2699
2700 return nullptr;
2701}
2702
2703static Constant *ConstantFoldScalarCall1(StringRef Name,
2704 Intrinsic::ID IntrinsicID, Type *Ty,
2706 const TargetLibraryInfo *TLI = nullptr,
2707 const CallBase *Call = nullptr) {
2708 assert(Operands.size() == 1 && "Wrong number of operands.");
2709
2710 if (IntrinsicID == Intrinsic::is_constant) {
2711 // We know we have a "Constant" argument. But we want to only
2712 // return true for manifest constants, not those that depend on
2713 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
2714 if (Operands[0]->isManifestConstant())
2715 return ConstantInt::getTrue(Ty->getContext());
2716 return nullptr;
2717 }
2718
2719 if (isa<UndefValue>(Operands[0])) {
2720 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
2721 // ctpop() is between 0 and bitwidth, pick 0 for undef.
2722 // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
2723 if (IntrinsicID == Intrinsic::cos ||
2724 IntrinsicID == Intrinsic::ctpop ||
2725 IntrinsicID == Intrinsic::fptoui_sat ||
2726 IntrinsicID == Intrinsic::fptosi_sat ||
2727 IntrinsicID == Intrinsic::canonicalize)
2728 return Constant::getNullValue(Ty);
2729 if (IntrinsicID == Intrinsic::bswap ||
2730 IntrinsicID == Intrinsic::bitreverse ||
2731 IntrinsicID == Intrinsic::launder_invariant_group)
2732 return Operands[0];
2733 }
2734
2736 // launder(null) == null iff in addrspace 0
2737 if (IntrinsicID == Intrinsic::launder_invariant_group) {
2738 // If instruction is not yet put in a basic block (e.g. when cloning
2739 // a function during inlining), Call's caller may not be available.
2740 // So check Call's BB first before querying Call->getCaller.
2741 const Function *Caller =
2742 Call && Call->getParent() ? Call->getCaller() : nullptr;
2743 if (Caller &&
2745 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
2746 return Operands[0];
2747 }
2748 return nullptr;
2749 }
2750 }
2751
2752 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
2753 APFloat U = Op->getValueAPF();
2754
2755 if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
2756 IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
2757 bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
2758
2759 if (U.isNaN())
2760 return nullptr;
2761
2762 unsigned Width = Ty->getIntegerBitWidth();
2763 APSInt Int(Width, !Signed);
2764 bool IsExact = false;
2766 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2767
2769 return ConstantInt::get(Ty, Int);
2770
2771 return nullptr;
2772 }
2773
2774 if (IntrinsicID == Intrinsic::fptoui_sat ||
2775 IntrinsicID == Intrinsic::fptosi_sat) {
2776 // convertToInteger() already has the desired saturation semantics.
2777 APSInt Int(Ty->getIntegerBitWidth(),
2778 IntrinsicID == Intrinsic::fptoui_sat);
2779 bool IsExact;
2780 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2781 return ConstantInt::get(Ty, Int);
2782 }
2783
2784 if (IntrinsicID == Intrinsic::canonicalize) {
2785 const Function *CtxF =
2786 Call && Call->getParent() ? Call->getFunction() : nullptr;
2787 return constantFoldCanonicalize(Ty, U, CtxF);
2788 }
2789
2790#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2791 if (Ty->isFP128Ty()) {
2792 if (IntrinsicID == Intrinsic::log) {
2793 float128 Result = logf128(Op->getValueAPF().convertToQuad());
2794 return GetConstantFoldFPValue128(Result, Ty);
2795 }
2796
2797 if (TLI && TLI->getLibFunc(Name) == LibFunc_logl &&
2798 TLI->has(LibFunc_logl))
2799 return ConstantFoldFP128(logf128, Op->getValueAPF(), Ty);
2800 }
2801#endif
2802
2803 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy() &&
2804 !Ty->isIntegerTy() && !Ty->isBFloatTy())
2805 return nullptr;
2806
2807 // Use internal versions of these intrinsics.
2808
2809 if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint ||
2810 IntrinsicID == Intrinsic::roundeven) {
2811 U.roundToIntegral(APFloat::rmNearestTiesToEven);
2812 return ConstantFP::get(Ty, U);
2813 }
2814
2815 if (IntrinsicID == Intrinsic::round) {
2816 U.roundToIntegral(APFloat::rmNearestTiesToAway);
2817 return ConstantFP::get(Ty, U);
2818 }
2819
2820 if (IntrinsicID == Intrinsic::roundeven) {
2821 U.roundToIntegral(APFloat::rmNearestTiesToEven);
2822 return ConstantFP::get(Ty, U);
2823 }
2824
2825 if (IntrinsicID == Intrinsic::ceil) {
2826 U.roundToIntegral(APFloat::rmTowardPositive);
2827 return ConstantFP::get(Ty, U);
2828 }
2829
2830 if (IntrinsicID == Intrinsic::floor) {
2831 U.roundToIntegral(APFloat::rmTowardNegative);
2832 return ConstantFP::get(Ty, U);
2833 }
2834
2835 if (IntrinsicID == Intrinsic::trunc) {
2836 U.roundToIntegral(APFloat::rmTowardZero);
2837 return ConstantFP::get(Ty, U);
2838 }
2839
2840 if (IntrinsicID == Intrinsic::fabs) {
2841 U.clearSign();
2842 return ConstantFP::get(Ty, U);
2843 }
2844
2845 if (IntrinsicID == Intrinsic::amdgcn_fract) {
2846 // The v_fract instruction behaves like the OpenCL spec, which defines
2847 // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
2848 // there to prevent fract(-small) from returning 1.0. It returns the
2849 // largest positive floating-point number less than 1.0."
2850 APFloat FloorU(U);
2851 FloorU.roundToIntegral(APFloat::rmTowardNegative);
2852 APFloat FractU(U - FloorU);
2853 APFloat AlmostOne(U.getSemantics(), 1);
2854 AlmostOne.next(/*nextDown*/ true);
2855 return ConstantFP::get(Ty, minimum(FractU, AlmostOne));
2856 }
2857
2858 // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
2859 // raise FP exceptions, unless the argument is signaling NaN.
2860
2862 std::optional<APFloat::roundingMode> RM;
2863 switch (IntrinsicID) {
2864 default:
2865 break;
2866 case Intrinsic::experimental_constrained_nearbyint:
2867 case Intrinsic::experimental_constrained_rint: {
2868 RM = CI->getRoundingMode();
2869 if (!RM || *RM == RoundingMode::Dynamic)
2870 return nullptr;
2871 break;
2872 }
2873 case Intrinsic::experimental_constrained_round:
2875 break;
2876 case Intrinsic::experimental_constrained_ceil:
2878 break;
2879 case Intrinsic::experimental_constrained_floor:
2881 break;
2882 case Intrinsic::experimental_constrained_trunc:
2884 break;
2885 }
2886 if (RM) {
2887 if (U.isFinite()) {
2888 APFloat::opStatus St = U.roundToIntegral(*RM);
2889 if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2890 St == APFloat::opInexact) {
2891 std::optional<fp::ExceptionBehavior> EB =
2893 if (EB == fp::ebStrict)
2894 return nullptr;
2895 }
2896 } else if (U.isSignaling()) {
2897 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2898 if (EB && *EB != fp::ebIgnore)
2899 return nullptr;
2900 U = APFloat::getQNaN(U.getSemantics());
2901 }
2902 return ConstantFP::get(Ty, U);
2903 }
2904 }
2905
2906 // NVVM float/double to signed/unsigned int32/int64 conversions:
2907 switch (IntrinsicID) {
2908 // f2i
2909 case Intrinsic::nvvm_f2i_rm:
2910 case Intrinsic::nvvm_f2i_rn:
2911 case Intrinsic::nvvm_f2i_rp:
2912 case Intrinsic::nvvm_f2i_rz:
2913 case Intrinsic::nvvm_f2i_rm_ftz:
2914 case Intrinsic::nvvm_f2i_rn_ftz:
2915 case Intrinsic::nvvm_f2i_rp_ftz:
2916 case Intrinsic::nvvm_f2i_rz_ftz:
2917 // f2ui
2918 case Intrinsic::nvvm_f2ui_rm:
2919 case Intrinsic::nvvm_f2ui_rn:
2920 case Intrinsic::nvvm_f2ui_rp:
2921 case Intrinsic::nvvm_f2ui_rz:
2922 case Intrinsic::nvvm_f2ui_rm_ftz:
2923 case Intrinsic::nvvm_f2ui_rn_ftz:
2924 case Intrinsic::nvvm_f2ui_rp_ftz:
2925 case Intrinsic::nvvm_f2ui_rz_ftz:
2926 // d2i
2927 case Intrinsic::nvvm_d2i_rm:
2928 case Intrinsic::nvvm_d2i_rn:
2929 case Intrinsic::nvvm_d2i_rp:
2930 case Intrinsic::nvvm_d2i_rz:
2931 // d2ui
2932 case Intrinsic::nvvm_d2ui_rm:
2933 case Intrinsic::nvvm_d2ui_rn:
2934 case Intrinsic::nvvm_d2ui_rp:
2935 case Intrinsic::nvvm_d2ui_rz:
2936 // f2ll
2937 case Intrinsic::nvvm_f2ll_rm:
2938 case Intrinsic::nvvm_f2ll_rn:
2939 case Intrinsic::nvvm_f2ll_rp:
2940 case Intrinsic::nvvm_f2ll_rz:
2941 case Intrinsic::nvvm_f2ll_rm_ftz:
2942 case Intrinsic::nvvm_f2ll_rn_ftz:
2943 case Intrinsic::nvvm_f2ll_rp_ftz:
2944 case Intrinsic::nvvm_f2ll_rz_ftz:
2945 // f2ull
2946 case Intrinsic::nvvm_f2ull_rm:
2947 case Intrinsic::nvvm_f2ull_rn:
2948 case Intrinsic::nvvm_f2ull_rp:
2949 case Intrinsic::nvvm_f2ull_rz:
2950 case Intrinsic::nvvm_f2ull_rm_ftz:
2951 case Intrinsic::nvvm_f2ull_rn_ftz:
2952 case Intrinsic::nvvm_f2ull_rp_ftz:
2953 case Intrinsic::nvvm_f2ull_rz_ftz:
2954 // d2ll
2955 case Intrinsic::nvvm_d2ll_rm:
2956 case Intrinsic::nvvm_d2ll_rn:
2957 case Intrinsic::nvvm_d2ll_rp:
2958 case Intrinsic::nvvm_d2ll_rz:
2959 // d2ull
2960 case Intrinsic::nvvm_d2ull_rm:
2961 case Intrinsic::nvvm_d2ull_rn:
2962 case Intrinsic::nvvm_d2ull_rp:
2963 case Intrinsic::nvvm_d2ull_rz: {
2964 // In float-to-integer conversion, NaN inputs are converted to 0.
2965 if (U.isNaN()) {
2966 // In float-to-integer conversion, NaN inputs are converted to 0
2967 // when the source and destination bitwidths are both less than 64.
2968 if (nvvm::FPToIntegerIntrinsicNaNZero(IntrinsicID))
2969 return ConstantInt::get(Ty, 0);
2970
2971 // Otherwise, the most significant bit is set.
2972 unsigned BitWidth = Ty->getIntegerBitWidth();
2973 uint64_t Val = 1ULL << (BitWidth - 1);
2974 return ConstantInt::get(Ty, APInt(BitWidth, Val, /*IsSigned=*/false));
2975 }
2976
2977 APFloat::roundingMode RMode =
2979 bool IsFTZ = nvvm::FPToIntegerIntrinsicShouldFTZ(IntrinsicID);
2980 bool IsSigned = nvvm::FPToIntegerIntrinsicResultIsSigned(IntrinsicID);
2981
2982 APSInt ResInt(Ty->getIntegerBitWidth(), !IsSigned);
2983 auto FloatToRound = IsFTZ ? FTZPreserveSign(U) : U;
2984
2985 // Return max/min value for integers if the result is +/-inf or
2986 // is too large to fit in the result's integer bitwidth.
2987 bool IsExact = false;
2988 FloatToRound.convertToInteger(ResInt, RMode, &IsExact);
2989 return ConstantInt::get(Ty, ResInt);
2990 }
2991 }
2992
2993 /// We only fold functions with finite arguments. Folding NaN and inf is
2994 /// likely to be aborted with an exception anyway, and some host libms
2995 /// have known errors raising exceptions.
2996 if (!U.isFinite())
2997 return nullptr;
2998
2999 /// Currently APFloat versions of these functions do not exist, so we use
3000 /// the host native double versions. Float versions are not called
3001 /// directly but for all these it is true (float)(f((double)arg)) ==
3002 /// f(arg). Long double not supported yet.
3003 const APFloat &APF = Op->getValueAPF();
3004
3005 switch (IntrinsicID) {
3006 default: break;
3007 case Intrinsic::log:
3008 if (U.isZero())
3009 return ConstantFP::getInfinity(Ty, true);
3010 if (U.isNegative())
3011 return ConstantFP::getNaN(Ty);
3012 if (U.isOne())
3013 return ConstantFP::getZero(Ty);
3014 return ConstantFoldFP(log, APF, Ty);
3015 case Intrinsic::log2:
3016 if (U.isZero())
3017 return ConstantFP::getInfinity(Ty, true);
3018 if (U.isNegative())
3019 return ConstantFP::getNaN(Ty);
3020 if (U.isOne())
3021 return ConstantFP::getZero(Ty);
3022 // TODO: What about hosts that lack a C99 library?
3023 return ConstantFoldFP(log2, APF, Ty);
3024 case Intrinsic::log10:
3025 if (U.isZero())
3026 return ConstantFP::getInfinity(Ty, true);
3027 if (U.isNegative())
3028 return ConstantFP::getNaN(Ty);
3029 if (U.isOne())
3030 return ConstantFP::getZero(Ty);
3031 // TODO: What about hosts that lack a C99 library?
3032 return ConstantFoldFP(log10, APF, Ty);
3033 case Intrinsic::exp:
3034 return ConstantFoldFP(exp, APF, Ty);
3035 case Intrinsic::exp2:
3036 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
3037 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
3038 case Intrinsic::exp10:
3039 // Fold exp10(x) as pow(10, x), in case the host lacks a C99 library.
3040 return ConstantFoldBinaryFP(pow, APFloat(10.0), APF, Ty);
3041 case Intrinsic::sin:
3042 return ConstantFoldFP(sin, APF, Ty);
3043 case Intrinsic::cos:
3044 return ConstantFoldFP(cos, APF, Ty);
3045 case Intrinsic::sinh:
3046 return ConstantFoldFP(sinh, APF, Ty);
3047 case Intrinsic::cosh:
3048 return ConstantFoldFP(cosh, APF, Ty);
3049 case Intrinsic::atan:
3050 // Implement optional behavior from C's Annex F for +/-0.0.
3051 if (U.isZero())
3052 return ConstantFP::get(Ty, U);
3053 return ConstantFoldFP(atan, APF, Ty);
3054 case Intrinsic::sqrt:
3055 return ConstantFoldFP(sqrt, APF, Ty);
3056
3057 // NVVM Intrinsics:
3058 case Intrinsic::nvvm_ceil_ftz_f:
3059 case Intrinsic::nvvm_ceil_f:
3060 case Intrinsic::nvvm_ceil_d:
3061 return ConstantFoldFP(
3062 ceil, APF, Ty,
3064 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3065
3066 case Intrinsic::nvvm_fabs_ftz:
3067 case Intrinsic::nvvm_fabs:
3068 return ConstantFoldFP(
3069 fabs, APF, Ty,
3071 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3072
3073 case Intrinsic::nvvm_floor_ftz_f:
3074 case Intrinsic::nvvm_floor_f:
3075 case Intrinsic::nvvm_floor_d:
3076 return ConstantFoldFP(
3077 floor, APF, Ty,
3079 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3080
3081 case Intrinsic::nvvm_rcp_rm_ftz_f:
3082 case Intrinsic::nvvm_rcp_rn_ftz_f:
3083 case Intrinsic::nvvm_rcp_rp_ftz_f:
3084 case Intrinsic::nvvm_rcp_rz_ftz_f:
3085 case Intrinsic::nvvm_rcp_rm_d:
3086 case Intrinsic::nvvm_rcp_rm_f:
3087 case Intrinsic::nvvm_rcp_rn_d:
3088 case Intrinsic::nvvm_rcp_rn_f:
3089 case Intrinsic::nvvm_rcp_rp_d:
3090 case Intrinsic::nvvm_rcp_rp_f:
3091 case Intrinsic::nvvm_rcp_rz_d:
3092 case Intrinsic::nvvm_rcp_rz_f: {
3093 APFloat::roundingMode RoundMode = nvvm::GetRCPRoundingMode(IntrinsicID);
3094 bool IsFTZ = nvvm::RCPShouldFTZ(IntrinsicID);
3095
3096 auto Denominator = IsFTZ ? FTZPreserveSign(APF) : APF;
3098 APFloat::opStatus Status = Res.divide(Denominator, RoundMode);
3099
3101 if (IsFTZ)
3102 Res = FTZPreserveSign(Res);
3103 return ConstantFP::get(Ty, Res);
3104 }
3105 return nullptr;
3106 }
3107
3108 case Intrinsic::nvvm_round_ftz_f:
3109 case Intrinsic::nvvm_round_f:
3110 case Intrinsic::nvvm_round_d: {
3111 // nvvm_round is lowered to PTX cvt.rni, which will round to nearest
3112 // integer, choosing even integer if source is equidistant between two
3113 // integers, so the semantics are closer to "rint" rather than "round".
3114 bool IsFTZ = nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID);
3115 auto V = IsFTZ ? FTZPreserveSign(APF) : APF;
3117 return ConstantFP::get(Ty, V);
3118 }
3119
3120 case Intrinsic::nvvm_saturate_ftz_f:
3121 case Intrinsic::nvvm_saturate_d:
3122 case Intrinsic::nvvm_saturate_f: {
3123 bool IsFTZ = nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID);
3124 auto V = IsFTZ ? FTZPreserveSign(APF) : APF;
3125 if (V.isNegative() || V.isZero() || V.isNaN())
3126 return ConstantFP::getZero(Ty);
3128 if (V > One)
3129 return ConstantFP::get(Ty, One);
3130 return ConstantFP::get(Ty, APF);
3131 }
3132
3133 case Intrinsic::nvvm_sqrt_rn_ftz_f:
3134 case Intrinsic::nvvm_sqrt_f:
3135 case Intrinsic::nvvm_sqrt_rn_d:
3136 case Intrinsic::nvvm_sqrt_rn_f:
3137 if (APF.isNegative())
3138 return nullptr;
3139 return ConstantFoldFP(
3140 sqrt, APF, Ty,
3142 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3143
3144 // AMDGCN Intrinsics:
3145 case Intrinsic::amdgcn_cos:
3146 case Intrinsic::amdgcn_sin: {
3147 double V = getValueAsDouble(Op);
3148 if (V < -256.0 || V > 256.0)
3149 // The gfx8 and gfx9 architectures handle arguments outside the range
3150 // [-256, 256] differently. This should be a rare case so bail out
3151 // rather than trying to handle the difference.
3152 return nullptr;
3153 bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
3154 double V4 = V * 4.0;
3155 if (V4 == floor(V4)) {
3156 // Force exact results for quarter-integer inputs.
3157 const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
3158 V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
3159 } else {
3160 if (IsCos)
3161 V = cos(V * 2.0 * numbers::pi);
3162 else
3163 V = sin(V * 2.0 * numbers::pi);
3164 }
3165 return GetConstantFoldFPValue(V, Ty);
3166 }
3167 }
3168
3169 if (!TLI)
3170 return nullptr;
3171
3172 LibFunc Func = TLI->getLibFunc(Name);
3173 if (Func == NotLibFunc)
3174 return nullptr;
3175
3176 switch (Func) {
3177 default:
3178 break;
3179 case LibFunc_acos:
3180 case LibFunc_acosf:
3181 case LibFunc_acos_finite:
3182 case LibFunc_acosf_finite:
3183 if (TLI->has(Func))
3184 return ConstantFoldFP(acos, APF, Ty);
3185 break;
3186 case LibFunc_asin:
3187 case LibFunc_asinf:
3188 case LibFunc_asin_finite:
3189 case LibFunc_asinf_finite:
3190 if (TLI->has(Func))
3191 return ConstantFoldFP(asin, APF, Ty);
3192 break;
3193 case LibFunc_atan:
3194 case LibFunc_atanf:
3195 // Implement optional behavior from C's Annex F for +/-0.0.
3196 if (U.isZero())
3197 return ConstantFP::get(Ty, U);
3198 if (TLI->has(Func))
3199 return ConstantFoldFP(atan, APF, Ty);
3200 break;
3201 case LibFunc_ceil:
3202 case LibFunc_ceilf:
3203 if (TLI->has(Func)) {
3204 U.roundToIntegral(APFloat::rmTowardPositive);
3205 return ConstantFP::get(Ty, U);
3206 }
3207 break;
3208 case LibFunc_cos:
3209 case LibFunc_cosf:
3210 if (TLI->has(Func))
3211 return ConstantFoldFP(cos, APF, Ty);
3212 break;
3213 case LibFunc_cosh:
3214 case LibFunc_coshf:
3215 case LibFunc_cosh_finite:
3216 case LibFunc_coshf_finite:
3217 if (TLI->has(Func))
3218 return ConstantFoldFP(cosh, APF, Ty);
3219 break;
3220 case LibFunc_exp:
3221 case LibFunc_expf:
3222 case LibFunc_exp_finite:
3223 case LibFunc_expf_finite:
3224 if (TLI->has(Func))
3225 return ConstantFoldFP(exp, APF, Ty);
3226 break;
3227 case LibFunc_exp2:
3228 case LibFunc_exp2f:
3229 case LibFunc_exp2_finite:
3230 case LibFunc_exp2f_finite:
3231 if (TLI->has(Func))
3232 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
3233 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
3234 break;
3235 case LibFunc_fabs:
3236 case LibFunc_fabsf:
3237 if (TLI->has(Func)) {
3238 U.clearSign();
3239 return ConstantFP::get(Ty, U);
3240 }
3241 break;
3242 case LibFunc_floor:
3243 case LibFunc_floorf:
3244 if (TLI->has(Func)) {
3245 U.roundToIntegral(APFloat::rmTowardNegative);
3246 return ConstantFP::get(Ty, U);
3247 }
3248 break;
3249 case LibFunc_log:
3250 case LibFunc_logf:
3251 case LibFunc_log_finite:
3252 case LibFunc_logf_finite:
3253 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3254 return ConstantFoldFP(log, APF, Ty);
3255 break;
3256 case LibFunc_log2:
3257 case LibFunc_log2f:
3258 case LibFunc_log2_finite:
3259 case LibFunc_log2f_finite:
3260 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3261 // TODO: What about hosts that lack a C99 library?
3262 return ConstantFoldFP(log2, APF, Ty);
3263 break;
3264 case LibFunc_log10:
3265 case LibFunc_log10f:
3266 case LibFunc_log10_finite:
3267 case LibFunc_log10f_finite:
3268 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3269 // TODO: What about hosts that lack a C99 library?
3270 return ConstantFoldFP(log10, APF, Ty);
3271 break;
3272 case LibFunc_ilogb:
3273 case LibFunc_ilogbf:
3274 if (!APF.isZero() && TLI->has(Func))
3275 return ConstantInt::get(Ty, ilogb(APF), true);
3276 break;
3277 case LibFunc_logb:
3278 case LibFunc_logbf:
3279 if (!APF.isZero() && TLI->has(Func))
3280 return ConstantFoldFP(logb, APF, Ty);
3281 break;
3282 case LibFunc_log1p:
3283 case LibFunc_log1pf:
3284 // Implement optional behavior from C's Annex F for +/-0.0.
3285 if (U.isZero())
3286 return ConstantFP::get(Ty, U);
3287 if (APF > APFloat::getOne(APF.getSemantics(), true) && TLI->has(Func))
3288 return ConstantFoldFP(log1p, APF, Ty);
3289 break;
3290 case LibFunc_logl:
3291 return nullptr;
3292 case LibFunc_erf:
3293 case LibFunc_erff:
3294 if (TLI->has(Func))
3295 return ConstantFoldFP(erf, APF, Ty);
3296 break;
3297 case LibFunc_nearbyint:
3298 case LibFunc_nearbyintf:
3299 case LibFunc_rint:
3300 case LibFunc_rintf:
3301 case LibFunc_roundeven:
3302 case LibFunc_roundevenf:
3303 if (TLI->has(Func)) {
3304 U.roundToIntegral(APFloat::rmNearestTiesToEven);
3305 return ConstantFP::get(Ty, U);
3306 }
3307 break;
3308 case LibFunc_round:
3309 case LibFunc_roundf:
3310 if (TLI->has(Func)) {
3311 U.roundToIntegral(APFloat::rmNearestTiesToAway);
3312 return ConstantFP::get(Ty, U);
3313 }
3314 break;
3315 case LibFunc_sin:
3316 case LibFunc_sinf:
3317 if (TLI->has(Func))
3318 return ConstantFoldFP(sin, APF, Ty);
3319 break;
3320 case LibFunc_sinh:
3321 case LibFunc_sinhf:
3322 case LibFunc_sinh_finite:
3323 case LibFunc_sinhf_finite:
3324 if (TLI->has(Func))
3325 return ConstantFoldFP(sinh, APF, Ty);
3326 break;
3327 case LibFunc_sqrt:
3328 case LibFunc_sqrtf:
3329 if (!APF.isNegative() && TLI->has(Func))
3330 return ConstantFoldFP(sqrt, APF, Ty);
3331 break;
3332 case LibFunc_tan:
3333 case LibFunc_tanf:
3334 if (TLI->has(Func))
3335 return ConstantFoldFP(tan, APF, Ty);
3336 break;
3337 case LibFunc_tanh:
3338 case LibFunc_tanhf:
3339 if (TLI->has(Func))
3340 return ConstantFoldFP(tanh, APF, Ty);
3341 break;
3342 case LibFunc_trunc:
3343 case LibFunc_truncf:
3344 if (TLI->has(Func)) {
3345 U.roundToIntegral(APFloat::rmTowardZero);
3346 return ConstantFP::get(Ty, U);
3347 }
3348 break;
3349 }
3350 return nullptr;
3351 }
3352
3353 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
3354 switch (IntrinsicID) {
3355 case Intrinsic::bswap:
3356 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
3357 case Intrinsic::ctpop:
3358 return ConstantInt::get(Ty, Op->getValue().popcount());
3359 case Intrinsic::bitreverse:
3360 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
3361 case Intrinsic::amdgcn_s_wqm: {
3362 uint64_t Val = Op->getZExtValue();
3363 Val |= (Val & 0x5555555555555555ULL) << 1 |
3364 ((Val >> 1) & 0x5555555555555555ULL);
3365 Val |= (Val & 0x3333333333333333ULL) << 2 |
3366 ((Val >> 2) & 0x3333333333333333ULL);
3367 return ConstantInt::get(Ty, Val);
3368 }
3369
3370 case Intrinsic::amdgcn_s_quadmask: {
3371 uint64_t Val = Op->getZExtValue();
3372 uint64_t QuadMask = 0;
3373 for (unsigned I = 0; I < Op->getBitWidth() / 4; ++I, Val >>= 4) {
3374 if (!(Val & 0xF))
3375 continue;
3376
3377 QuadMask |= (1ULL << I);
3378 }
3379 return ConstantInt::get(Ty, QuadMask);
3380 }
3381
3382 case Intrinsic::amdgcn_s_bitreplicate: {
3383 uint64_t Val = Op->getZExtValue();
3384 Val = (Val & 0x000000000000FFFFULL) | (Val & 0x00000000FFFF0000ULL) << 16;
3385 Val = (Val & 0x000000FF000000FFULL) | (Val & 0x0000FF000000FF00ULL) << 8;
3386 Val = (Val & 0x000F000F000F000FULL) | (Val & 0x00F000F000F000F0ULL) << 4;
3387 Val = (Val & 0x0303030303030303ULL) | (Val & 0x0C0C0C0C0C0C0C0CULL) << 2;
3388 Val = (Val & 0x1111111111111111ULL) | (Val & 0x2222222222222222ULL) << 1;
3389 Val = Val | Val << 1;
3390 return ConstantInt::get(Ty, Val);
3391 }
3392 }
3393 }
3394
3395 if (Operands[0]->getType()->isVectorTy()) {
3396 auto *Op = cast<Constant>(Operands[0]);
3397 switch (IntrinsicID) {
3398 default: break;
3399 case Intrinsic::vector_reduce_add:
3400 case Intrinsic::vector_reduce_mul:
3401 case Intrinsic::vector_reduce_and:
3402 case Intrinsic::vector_reduce_or:
3403 case Intrinsic::vector_reduce_xor:
3404 case Intrinsic::vector_reduce_smin:
3405 case Intrinsic::vector_reduce_smax:
3406 case Intrinsic::vector_reduce_umin:
3407 case Intrinsic::vector_reduce_umax:
3408 if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
3409 return C;
3410 break;
3411 case Intrinsic::x86_sse_cvtss2si:
3412 case Intrinsic::x86_sse_cvtss2si64:
3413 case Intrinsic::x86_sse2_cvtsd2si:
3414 case Intrinsic::x86_sse2_cvtsd2si64:
3415 if (ConstantFP *FPOp =
3416 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
3417 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
3418 /*roundTowardZero=*/false, Ty,
3419 /*IsSigned*/true);
3420 break;
3421 case Intrinsic::x86_sse_cvttss2si:
3422 case Intrinsic::x86_sse_cvttss2si64:
3423 case Intrinsic::x86_sse2_cvttsd2si:
3424 case Intrinsic::x86_sse2_cvttsd2si64:
3425 if (ConstantFP *FPOp =
3426 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
3427 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
3428 /*roundTowardZero=*/true, Ty,
3429 /*IsSigned*/true);
3430 break;
3431
3432 case Intrinsic::wasm_anytrue:
3433 return Op->isNullValue() ? ConstantInt::get(Ty, 0)
3434 : ConstantInt::get(Ty, 1);
3435
3436 case Intrinsic::wasm_alltrue:
3437 // Check each element individually
3438 unsigned E = cast<FixedVectorType>(Op->getType())->getNumElements();
3439 for (unsigned I = 0; I != E; ++I) {
3440 Constant *Elt = Op->getAggregateElement(I);
3441 // Return false as soon as we find a non-true element.
3442 if (Elt && Elt->isNullValue())
3443 return ConstantInt::get(Ty, 0);
3444 // Bail as soon as we find an element we cannot prove to be true.
3445 if (!Elt || !isa<ConstantInt>(Elt))
3446 return nullptr;
3447 }
3448
3449 return ConstantInt::get(Ty, 1);
3450 }
3451 }
3452
3453 return nullptr;
3454}
3455
3456static Constant *evaluateCompare(const APFloat &Op1, const APFloat &Op2,
3460 FCmpInst::Predicate Cond = FCmp->getPredicate();
3461 if (FCmp->isSignaling()) {
3462 if (Op1.isNaN() || Op2.isNaN())
3464 } else {
3465 if (Op1.isSignaling() || Op2.isSignaling())
3467 }
3468 bool Result = FCmpInst::compare(Op1, Op2, Cond);
3469 if (mayFoldConstrained(const_cast<ConstrainedFPCmpIntrinsic *>(FCmp), St))
3470 return ConstantInt::get(Call->getType()->getScalarType(), Result);
3471 return nullptr;
3472}
3473
3474static Constant *ConstantFoldNextToward(const APFloat &Op0, const APFloat &Op1,
3475 const Type *RetTy) {
3476 assert(RetTy != nullptr);
3477 bool LosesInfo;
3478
3479 if (Op1.isSignaling())
3480 return nullptr;
3481 if (Op1.isNaN()) {
3482 APFloat Ret(Op1);
3483 Ret.convert(RetTy->getFltSemantics(), detail::rmNearestTiesToEven,
3484 &LosesInfo);
3485 return ConstantFP::get(RetTy->getContext(), Ret);
3486 }
3487
3488 // Recall that the second argument of nexttoward is always a long double,
3489 // so we may need to promote the first argument for comparisons to be valid.
3490 APFloat PromotedOp0(Op0);
3491 PromotedOp0.convert(Op1.getSemantics(), detail::rmNearestTiesToEven,
3492 &LosesInfo);
3493 assert(!LosesInfo && "Unexpected lossy promotion");
3494 const APFloat::cmpResult Result = PromotedOp0.compare(Op1);
3495
3496 // When equal, the standard says we must return the second argument.
3497 // This allows nice behavior such as nexttoward(0.0, -0.0) = -0.0 and
3498 // nexttoward(-0.0, 0.0) = 0.0
3499 if (Result == detail::cmpEqual) {
3500 APFloat Ret(Op1);
3501 Ret.convert(RetTy->getFltSemantics(), detail::rmNearestTiesToEven,
3502 &LosesInfo);
3503 return ConstantFP::get(RetTy->getContext(), Ret);
3504 }
3505
3506 APFloat Next(Op0);
3507 Next.next(/*nextDown=*/Result == APFloat::cmpGreaterThan);
3508 if (Next.isZero() || Next.isDenormal() || Next.isSignaling())
3509 return nullptr;
3510 return ConstantFP::get(RetTy->getContext(), Next);
3511}
3512
3513static Constant *ConstantFoldLibCall2(StringRef Name, Type *Ty,
3515 const TargetLibraryInfo *TLI = nullptr) {
3516 if (!TLI)
3517 return nullptr;
3518
3519 LibFunc Func = TLI->getLibFunc(Name);
3520 if (Func == NotLibFunc)
3521 return nullptr;
3522
3523 const auto *Op1 = dyn_cast<ConstantFP>(Operands[0]);
3524 if (!Op1)
3525 return nullptr;
3526
3527 const auto *Op2 = dyn_cast<ConstantFP>(Operands[1]);
3528 if (!Op2)
3529 return nullptr;
3530
3531 const APFloat &Op1V = Op1->getValueAPF();
3532 const APFloat &Op2V = Op2->getValueAPF();
3533
3534 switch (Func) {
3535 default:
3536 break;
3537 case LibFunc_pow:
3538 case LibFunc_powf:
3539 case LibFunc_pow_finite:
3540 case LibFunc_powf_finite:
3541 if (TLI->has(Func))
3542 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
3543 break;
3544 case LibFunc_fmod:
3545 case LibFunc_fmodf:
3546 if (TLI->has(Func)) {
3547 APFloat V = Op1->getValueAPF();
3548 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
3549 return ConstantFP::get(Ty, V);
3550 }
3551 break;
3552 case LibFunc_remainder:
3553 case LibFunc_remainderf:
3554 if (TLI->has(Func)) {
3555 APFloat V = Op1->getValueAPF();
3556 if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
3557 return ConstantFP::get(Ty, V);
3558 }
3559 break;
3560 case LibFunc_atan2:
3561 case LibFunc_atan2f:
3562 // atan2(+/-0.0, +/-0.0) is known to raise an exception on some libm
3563 // (Solaris), so we do not assume a known result for that.
3564 if (Op1V.isZero() && Op2V.isZero())
3565 return nullptr;
3566 [[fallthrough]];
3567 case LibFunc_atan2_finite:
3568 case LibFunc_atan2f_finite:
3569 if (TLI->has(Func))
3570 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
3571 break;
3572 case LibFunc_nextafter:
3573 case LibFunc_nextafterf:
3574 case LibFunc_nexttoward:
3575 case LibFunc_nexttowardf:
3576 if (TLI->has(Func))
3577 return ConstantFoldNextToward(Op1V, Op2V, Ty);
3578 break;
3579 }
3580
3581 return nullptr;
3582}
3583
3584static Constant *ConstantFoldCRC32(Type *Ty, const APInt *CrcArg,
3585 const APInt *DataArg, unsigned DataBytes,
3586 uint32_t Poly) {
3587 if (!CrcArg || !DataArg)
3588 return nullptr;
3589 uint32_t Crc = CrcArg->getZExtValue();
3590 uint64_t Data = DataArg->getZExtValue();
3591 uint32_t Result = calculateReflectedCRC32(Crc, Data, DataBytes, Poly);
3592 return ConstantInt::get(Ty, Result);
3593}
3594
3595static Constant *ConstantFoldIntrinsicCall2(Intrinsic::ID IntrinsicID, Type *Ty,
3597 const CallBase *Call = nullptr) {
3598 assert(Operands.size() == 2 && "Wrong number of operands.");
3599
3600 if (Ty->isFloatingPointTy()) {
3601 // TODO: We should have undef handling for all of the FP intrinsics that
3602 // are attempted to be folded in this function.
3603 bool IsOp0Undef = isa<UndefValue>(Operands[0]);
3604 bool IsOp1Undef = isa<UndefValue>(Operands[1]);
3605 switch (IntrinsicID) {
3606 case Intrinsic::maxnum:
3607 case Intrinsic::minnum:
3608 case Intrinsic::maximum:
3609 case Intrinsic::minimum:
3610 case Intrinsic::maximumnum:
3611 case Intrinsic::minimumnum:
3612 case Intrinsic::nvvm_fmax_d:
3613 case Intrinsic::nvvm_fmin_d:
3614 // If one argument is undef, return the other argument.
3615 if (IsOp0Undef)
3616 return Operands[1];
3617 if (IsOp1Undef)
3618 return Operands[0];
3619 break;
3620
3621 case Intrinsic::nvvm_fmax_f:
3622 case Intrinsic::nvvm_fmax_ftz_f:
3623 case Intrinsic::nvvm_fmax_ftz_nan_f:
3624 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3625 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3626 case Intrinsic::nvvm_fmax_nan_f:
3627 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3628 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3629
3630 case Intrinsic::nvvm_fmin_f:
3631 case Intrinsic::nvvm_fmin_ftz_f:
3632 case Intrinsic::nvvm_fmin_ftz_nan_f:
3633 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
3634 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
3635 case Intrinsic::nvvm_fmin_nan_f:
3636 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
3637 case Intrinsic::nvvm_fmin_xorsign_abs_f:
3638 // If one arg is undef, the other arg can be returned only if it is
3639 // constant, as we may need to flush it to sign-preserving zero or
3640 // canonicalize the NaN.
3641 if (!IsOp0Undef && !IsOp1Undef)
3642 break;
3643 if (auto *Op = dyn_cast<ConstantFP>(Operands[IsOp0Undef ? 1 : 0])) {
3644 if (Op->isNaN()) {
3645 APInt NVCanonicalNaN(32, 0x7fffffff);
3646 return ConstantFP::get(
3647 Ty, APFloat(Ty->getFltSemantics(), NVCanonicalNaN));
3648 }
3649 if (nvvm::FMinFMaxShouldFTZ(IntrinsicID))
3650 return ConstantFP::get(Ty, FTZPreserveSign(Op->getValueAPF()));
3651 else
3652 return Op;
3653 }
3654 break;
3655 }
3656 }
3657
3658 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
3659 const APFloat &Op1V = Op1->getValueAPF();
3660
3661 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
3662 if (Op2->getType() != Op1->getType())
3663 return nullptr;
3664 const APFloat &Op2V = Op2->getValueAPF();
3665
3666 if (const auto *ConstrIntr =
3668 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
3669 APFloat Res = Op1V;
3671 switch (IntrinsicID) {
3672 default:
3673 return nullptr;
3674 case Intrinsic::experimental_constrained_fadd:
3675 St = Res.add(Op2V, RM);
3676 break;
3677 case Intrinsic::experimental_constrained_fsub:
3678 St = Res.subtract(Op2V, RM);
3679 break;
3680 case Intrinsic::experimental_constrained_fmul:
3681 St = Res.multiply(Op2V, RM);
3682 break;
3683 case Intrinsic::experimental_constrained_fdiv:
3684 St = Res.divide(Op2V, RM);
3685 break;
3686 case Intrinsic::experimental_constrained_frem:
3687 St = Res.mod(Op2V);
3688 break;
3689 case Intrinsic::experimental_constrained_fcmp:
3690 case Intrinsic::experimental_constrained_fcmps:
3691 return evaluateCompare(Op1V, Op2V, ConstrIntr);
3692 }
3693 if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr),
3694 St))
3695 return ConstantFP::get(Ty, Res);
3696 return nullptr;
3697 }
3698
3699 switch (IntrinsicID) {
3700 default:
3701 break;
3702 case Intrinsic::copysign:
3703 return ConstantFP::get(Ty, APFloat::copySign(Op1V, Op2V));
3704 case Intrinsic::minnum:
3705 return ConstantFP::get(Ty, minnum(Op1V, Op2V));
3706 case Intrinsic::maxnum:
3707 return ConstantFP::get(Ty, maxnum(Op1V, Op2V));
3708 case Intrinsic::minimum:
3709 return ConstantFP::get(Ty, minimum(Op1V, Op2V));
3710 case Intrinsic::maximum:
3711 return ConstantFP::get(Ty, maximum(Op1V, Op2V));
3712 case Intrinsic::minimumnum:
3713 return ConstantFP::get(Ty, minimumnum(Op1V, Op2V));
3714 case Intrinsic::maximumnum:
3715 return ConstantFP::get(Ty, maximumnum(Op1V, Op2V));
3716
3717 case Intrinsic::nvvm_fmax_d:
3718 case Intrinsic::nvvm_fmax_f:
3719 case Intrinsic::nvvm_fmax_ftz_f:
3720 case Intrinsic::nvvm_fmax_ftz_nan_f:
3721 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3722 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3723 case Intrinsic::nvvm_fmax_nan_f:
3724 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3725 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3726
3727 case Intrinsic::nvvm_fmin_d:
3728 case Intrinsic::nvvm_fmin_f:
3729 case Intrinsic::nvvm_fmin_ftz_f:
3730 case Intrinsic::nvvm_fmin_ftz_nan_f:
3731 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
3732 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
3733 case Intrinsic::nvvm_fmin_nan_f:
3734 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
3735 case Intrinsic::nvvm_fmin_xorsign_abs_f: {
3736
3737 bool ShouldCanonicalizeNaNs = !(IntrinsicID == Intrinsic::nvvm_fmax_d ||
3738 IntrinsicID == Intrinsic::nvvm_fmin_d);
3739 bool IsFTZ = nvvm::FMinFMaxShouldFTZ(IntrinsicID);
3740 bool IsNaNPropagating = nvvm::FMinFMaxPropagatesNaNs(IntrinsicID);
3741 bool IsXorSignAbs = nvvm::FMinFMaxIsXorSignAbs(IntrinsicID);
3742
3743 APFloat A = IsFTZ ? FTZPreserveSign(Op1V) : Op1V;
3744 APFloat B = IsFTZ ? FTZPreserveSign(Op2V) : Op2V;
3745
3746 bool XorSign = false;
3747 if (IsXorSignAbs) {
3748 XorSign = A.isNegative() ^ B.isNegative();
3749 A = abs(A);
3750 B = abs(B);
3751 }
3752
3753 bool IsFMax = false;
3754 switch (IntrinsicID) {
3755 case Intrinsic::nvvm_fmax_d:
3756 case Intrinsic::nvvm_fmax_f:
3757 case Intrinsic::nvvm_fmax_ftz_f:
3758 case Intrinsic::nvvm_fmax_ftz_nan_f:
3759 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3760 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3761 case Intrinsic::nvvm_fmax_nan_f:
3762 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3763 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3764 IsFMax = true;
3765 break;
3766 }
3767 APFloat Res =
3768 IsFMax ? (IsNaNPropagating ? maximum(A, B) : maximumnum(A, B))
3769 : (IsNaNPropagating ? minimum(A, B) : minimumnum(A, B));
3770
3771 if (ShouldCanonicalizeNaNs && Res.isNaN()) {
3772 APFloat NVCanonicalNaN(Res.getSemantics(), APInt(32, 0x7fffffff));
3773 return ConstantFP::get(Ty, NVCanonicalNaN);
3774 }
3775
3776 if (IsXorSignAbs && XorSign != Res.isNegative())
3777 Res.changeSign();
3778
3779 return ConstantFP::get(Ty, Res);
3780 }
3781
3782 case Intrinsic::nvvm_div_rm_f:
3783 case Intrinsic::nvvm_div_rn_f:
3784 case Intrinsic::nvvm_div_rp_f:
3785 case Intrinsic::nvvm_div_rz_f:
3786 case Intrinsic::nvvm_div_rm_d:
3787 case Intrinsic::nvvm_div_rn_d:
3788 case Intrinsic::nvvm_div_rp_d:
3789 case Intrinsic::nvvm_div_rz_d:
3790 case Intrinsic::nvvm_div_rm_ftz_f:
3791 case Intrinsic::nvvm_div_rn_ftz_f:
3792 case Intrinsic::nvvm_div_rp_ftz_f:
3793 case Intrinsic::nvvm_div_rz_ftz_f: {
3794 bool IsFTZ = nvvm::FDivShouldFTZ(IntrinsicID);
3795 APFloat A = IsFTZ ? FTZPreserveSign(Op1V) : Op1V;
3796 APFloat B = IsFTZ ? FTZPreserveSign(Op2V) : Op2V;
3797 APFloat::roundingMode RoundMode =
3798 nvvm::GetFDivRoundingMode(IntrinsicID);
3799
3800 APFloat Res = A;
3801 APFloat::opStatus Status = Res.divide(B, RoundMode);
3802 if (!Res.isNaN() &&
3804 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
3805 return ConstantFP::get(Ty, Res);
3806 }
3807 return nullptr;
3808 }
3809 }
3810
3811 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
3812 return nullptr;
3813
3814 switch (IntrinsicID) {
3815 default:
3816 break;
3817 case Intrinsic::pow:
3818 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
3819 case Intrinsic::amdgcn_fmul_legacy:
3820 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
3821 // NaN or infinity, gives +0.0.
3822 if (Op1V.isZero() || Op2V.isZero())
3823 return ConstantFP::getZero(Ty);
3824 return ConstantFP::get(Ty, Op1V * Op2V);
3825 }
3826
3827 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
3828 switch (IntrinsicID) {
3829 case Intrinsic::ldexp: {
3830 // APFloat::scalbn takes the exponent as `int`. Clamp wider integer
3831 // exponents into [INT_MIN, INT_MAX] so values still saturate the
3832 // result to +/-inf or +/-0.
3833 APInt Exp = Op2C->getValue();
3834 Exp = Exp.getBitWidth() < 32 ? Exp.sext(32) : Exp.truncSSat(32);
3835 return ConstantFP::get(
3836 Ty->getContext(),
3837 scalbn(Op1V, Exp.getSExtValue(), APFloat::rmNearestTiesToEven));
3838 }
3839 case Intrinsic::is_fpclass: {
3840 FPClassTest Mask = static_cast<FPClassTest>(Op2C->getZExtValue());
3841 bool Result =
3842 ((Mask & fcSNan) && Op1V.isNaN() && Op1V.isSignaling()) ||
3843 ((Mask & fcQNan) && Op1V.isNaN() && !Op1V.isSignaling()) ||
3844 ((Mask & fcNegInf) && Op1V.isNegInfinity()) ||
3845 ((Mask & fcNegNormal) && Op1V.isNormal() && Op1V.isNegative()) ||
3846 ((Mask & fcNegSubnormal) && Op1V.isDenormal() && Op1V.isNegative()) ||
3847 ((Mask & fcNegZero) && Op1V.isZero() && Op1V.isNegative()) ||
3848 ((Mask & fcPosZero) && Op1V.isZero() && !Op1V.isNegative()) ||
3849 ((Mask & fcPosSubnormal) && Op1V.isDenormal() && !Op1V.isNegative()) ||
3850 ((Mask & fcPosNormal) && Op1V.isNormal() && !Op1V.isNegative()) ||
3851 ((Mask & fcPosInf) && Op1V.isPosInfinity());
3852 return ConstantInt::get(Ty, Result);
3853 }
3854 case Intrinsic::powi: {
3855 // Square-and-multiply using the operand's own semantics, matching
3856 // the multiply sequence ExpandPowI builds in SelectionDAG.
3857 int Exp = static_cast<int>(Op2C->getSExtValue());
3858 unsigned UExp = static_cast<unsigned>(Exp);
3859 if (Exp < 0)
3860 UExp = -UExp;
3861 const fltSemantics &Semantics = Op1V.getSemantics();
3862 APFloat Res = APFloat::getOne(Semantics);
3863 APFloat CurSquare = Op1V;
3864 while (UExp) {
3865 if (UExp & 1)
3866 Res = Res * CurSquare;
3867 CurSquare = CurSquare * CurSquare;
3868 UExp >>= 1;
3869 }
3870 if (Exp < 0)
3871 Res = APFloat::getOne(Semantics) / Res;
3872 return ConstantFP::get(Ty, Res);
3873 }
3874 default:
3875 break;
3876 }
3877 }
3878 return nullptr;
3879 }
3880
3881 if (Operands[0]->getType()->isIntegerTy() &&
3882 Operands[1]->getType()->isIntegerTy()) {
3883 const APInt *C0, *C1;
3884 if (!getConstIntOrUndef(Operands[0], C0) ||
3885 !getConstIntOrUndef(Operands[1], C1))
3886 return nullptr;
3887
3888 switch (IntrinsicID) {
3889 default: break;
3890 case Intrinsic::smax:
3891 case Intrinsic::smin:
3892 case Intrinsic::umax:
3893 case Intrinsic::umin:
3894 if (!C0 || !C1)
3895 return MinMaxIntrinsic::getSaturationPoint(IntrinsicID, Ty);
3896 return ConstantInt::get(
3897 Ty, ICmpInst::compare(*C0, *C1,
3898 MinMaxIntrinsic::getPredicate(IntrinsicID))
3899 ? *C0
3900 : *C1);
3901
3902 case Intrinsic::scmp:
3903 case Intrinsic::ucmp:
3904 if (!C0 || !C1)
3905 return ConstantInt::get(Ty, 0);
3906
3907 int Res;
3908 if (IntrinsicID == Intrinsic::scmp)
3909 Res = C0->sgt(*C1) ? 1 : C0->slt(*C1) ? -1 : 0;
3910 else
3911 Res = C0->ugt(*C1) ? 1 : C0->ult(*C1) ? -1 : 0;
3912 return ConstantInt::get(Ty, Res, /*IsSigned=*/true);
3913
3914 case Intrinsic::usub_with_overflow:
3915 case Intrinsic::ssub_with_overflow:
3916 // X - undef -> { 0, false }
3917 // undef - X -> { 0, false }
3918 if (!C0 || !C1)
3919 return Constant::getNullValue(Ty);
3920 [[fallthrough]];
3921 case Intrinsic::uadd_with_overflow:
3922 case Intrinsic::sadd_with_overflow:
3923 // X + undef -> { -1, false }
3924 // undef + x -> { -1, false }
3925 if (!C0 || !C1) {
3926 return ConstantStruct::get(
3927 cast<StructType>(Ty),
3928 {Constant::getAllOnesValue(Ty->getStructElementType(0)),
3929 Constant::getNullValue(Ty->getStructElementType(1))});
3930 }
3931 [[fallthrough]];
3932 case Intrinsic::smul_with_overflow:
3933 case Intrinsic::umul_with_overflow: {
3934 // undef * X -> { 0, false }
3935 // X * undef -> { 0, false }
3936 if (!C0 || !C1)
3937 return Constant::getNullValue(Ty);
3938
3939 APInt Res;
3940 bool Overflow;
3941 switch (IntrinsicID) {
3942 default: llvm_unreachable("Invalid case");
3943 case Intrinsic::sadd_with_overflow:
3944 Res = C0->sadd_ov(*C1, Overflow);
3945 break;
3946 case Intrinsic::uadd_with_overflow:
3947 Res = C0->uadd_ov(*C1, Overflow);
3948 break;
3949 case Intrinsic::ssub_with_overflow:
3950 Res = C0->ssub_ov(*C1, Overflow);
3951 break;
3952 case Intrinsic::usub_with_overflow:
3953 Res = C0->usub_ov(*C1, Overflow);
3954 break;
3955 case Intrinsic::smul_with_overflow:
3956 Res = C0->smul_ov(*C1, Overflow);
3957 break;
3958 case Intrinsic::umul_with_overflow:
3959 Res = C0->umul_ov(*C1, Overflow);
3960 break;
3961 }
3962 Constant *Ops[] = {
3963 ConstantInt::get(Ty->getContext(), Res),
3964 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
3965 };
3967 }
3968 case Intrinsic::uadd_sat:
3969 case Intrinsic::sadd_sat:
3970 if (!C0 || !C1)
3971 return Constant::getAllOnesValue(Ty);
3972 if (IntrinsicID == Intrinsic::uadd_sat)
3973 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
3974 else
3975 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
3976 case Intrinsic::usub_sat:
3977 case Intrinsic::ssub_sat:
3978 if (!C0 || !C1)
3979 return Constant::getNullValue(Ty);
3980 if (IntrinsicID == Intrinsic::usub_sat)
3981 return ConstantInt::get(Ty, C0->usub_sat(*C1));
3982 else
3983 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
3984 case Intrinsic::cttz:
3985 case Intrinsic::ctlz:
3986 assert(C1 && "Must be constant int");
3987
3988 // cttz(0, 1) and ctlz(0, 1) are poison.
3989 if (C1->isOne() && (!C0 || C0->isZero()))
3990 return PoisonValue::get(Ty);
3991 if (!C0)
3992 return Constant::getNullValue(Ty);
3993 if (IntrinsicID == Intrinsic::cttz)
3994 return ConstantInt::get(Ty, C0->countr_zero());
3995 else
3996 return ConstantInt::get(Ty, C0->countl_zero());
3997
3998 case Intrinsic::abs:
3999 assert(C1 && "Must be constant int");
4000 assert((C1->isOne() || C1->isZero()) && "Must be 0 or 1");
4001
4002 // Undef or minimum val operand with poison min --> poison
4003 if (C1->isOne() && (!C0 || C0->isMinSignedValue()))
4004 return PoisonValue::get(Ty);
4005
4006 // Undef operand with no poison min --> 0 (sign bit must be clear)
4007 if (!C0)
4008 return Constant::getNullValue(Ty);
4009
4010 return ConstantInt::get(Ty, C0->abs());
4011 case Intrinsic::clmul:
4012 if (!C0 || !C1)
4013 return Constant::getNullValue(Ty);
4014 return ConstantInt::get(Ty, APIntOps::clmul(*C0, *C1));
4015 case Intrinsic::pdep:
4016 if (!C0 || !C1)
4017 return Constant::getNullValue(Ty);
4018 return ConstantInt::get(Ty, APIntOps::pdep(*C0, *C1));
4019 case Intrinsic::pext:
4020 if (!C0 || !C1)
4021 return Constant::getNullValue(Ty);
4022 return ConstantInt::get(Ty, APIntOps::pext(*C0, *C1));
4023 case Intrinsic::smulh:
4024 if (!C0 || !C1)
4025 return Constant::getNullValue(Ty);
4026 return ConstantInt::get(Ty, APIntOps::mulhs(*C0, *C1));
4027 case Intrinsic::umulh:
4028 if (!C0 || !C1)
4029 return Constant::getNullValue(Ty);
4030 return ConstantInt::get(Ty, APIntOps::mulhu(*C0, *C1));
4031 case Intrinsic::amdgcn_wave_reduce_add:
4032 case Intrinsic::amdgcn_wave_reduce_sub:
4033 case Intrinsic::amdgcn_wave_reduce_xor: {
4034 if (C0 && C0->isZero())
4035 return Constant::getNullValue(Ty);
4036 return nullptr;
4037 }
4038 case Intrinsic::amdgcn_wave_reduce_umin:
4039 case Intrinsic::amdgcn_wave_reduce_umax:
4040 case Intrinsic::amdgcn_wave_reduce_max:
4041 case Intrinsic::amdgcn_wave_reduce_min:
4042 case Intrinsic::amdgcn_wave_reduce_and:
4043 case Intrinsic::amdgcn_wave_reduce_or:
4044 return Operands[0];
4045 case Intrinsic::aarch64_crc32b:
4046 case Intrinsic::arm_crc32b:
4047 return ConstantFoldCRC32(Ty, C0, C1, 1, 0xEDB88320);
4048 case Intrinsic::aarch64_crc32h:
4049 case Intrinsic::arm_crc32h:
4050 return ConstantFoldCRC32(Ty, C0, C1, 2, 0xEDB88320);
4051 case Intrinsic::aarch64_crc32w:
4052 case Intrinsic::arm_crc32w:
4053 return ConstantFoldCRC32(Ty, C0, C1, 4, 0xEDB88320);
4054 case Intrinsic::aarch64_crc32x:
4055 return ConstantFoldCRC32(Ty, C0, C1, 8, 0xEDB88320);
4056 case Intrinsic::aarch64_crc32cb:
4057 case Intrinsic::arm_crc32cb:
4058 case Intrinsic::x86_sse42_crc32_32_8:
4059 return ConstantFoldCRC32(Ty, C0, C1, 1, 0x82F63B78);
4060 case Intrinsic::aarch64_crc32ch:
4061 case Intrinsic::arm_crc32ch:
4062 case Intrinsic::x86_sse42_crc32_32_16:
4063 return ConstantFoldCRC32(Ty, C0, C1, 2, 0x82F63B78);
4064 case Intrinsic::aarch64_crc32cw:
4065 case Intrinsic::arm_crc32cw:
4066 case Intrinsic::x86_sse42_crc32_32_32:
4067 return ConstantFoldCRC32(Ty, C0, C1, 4, 0x82F63B78);
4068 case Intrinsic::aarch64_crc32cx:
4069 case Intrinsic::x86_sse42_crc32_64_64:
4070 return ConstantFoldCRC32(Ty, C0, C1, 8, 0x82F63B78);
4071 }
4072
4073 return nullptr;
4074 }
4075
4076 // Support ConstantVector in case we have an Undef in the top.
4077 if ((isa<ConstantVector>(Operands[0]) ||
4079 // Check for default rounding mode.
4080 // FIXME: Support other rounding modes?
4082 cast<ConstantInt>(Operands[1])->getValue() == 4) {
4083 auto *Op = cast<Constant>(Operands[0]);
4084 switch (IntrinsicID) {
4085 default: break;
4086 case Intrinsic::x86_avx512_vcvtss2si32:
4087 case Intrinsic::x86_avx512_vcvtss2si64:
4088 case Intrinsic::x86_avx512_vcvtsd2si32:
4089 case Intrinsic::x86_avx512_vcvtsd2si64:
4090 if (ConstantFP *FPOp =
4091 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4092 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4093 /*roundTowardZero=*/false, Ty,
4094 /*IsSigned*/true);
4095 break;
4096 case Intrinsic::x86_avx512_vcvtss2usi32:
4097 case Intrinsic::x86_avx512_vcvtss2usi64:
4098 case Intrinsic::x86_avx512_vcvtsd2usi32:
4099 case Intrinsic::x86_avx512_vcvtsd2usi64:
4100 if (ConstantFP *FPOp =
4101 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4102 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4103 /*roundTowardZero=*/false, Ty,
4104 /*IsSigned*/false);
4105 break;
4106 case Intrinsic::x86_avx512_cvttss2si:
4107 case Intrinsic::x86_avx512_cvttss2si64:
4108 case Intrinsic::x86_avx512_cvttsd2si:
4109 case Intrinsic::x86_avx512_cvttsd2si64:
4110 if (ConstantFP *FPOp =
4111 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4112 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4113 /*roundTowardZero=*/true, Ty,
4114 /*IsSigned*/true);
4115 break;
4116 case Intrinsic::x86_avx512_cvttss2usi:
4117 case Intrinsic::x86_avx512_cvttss2usi64:
4118 case Intrinsic::x86_avx512_cvttsd2usi:
4119 case Intrinsic::x86_avx512_cvttsd2usi64:
4120 if (ConstantFP *FPOp =
4121 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4122 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4123 /*roundTowardZero=*/true, Ty,
4124 /*IsSigned*/false);
4125 break;
4126 }
4127 }
4128
4129 if (IntrinsicID == Intrinsic::experimental_cttz_elts) {
4130 auto *FVTy = dyn_cast<FixedVectorType>(Operands[0]->getType());
4131 bool ZeroIsPoison = cast<ConstantInt>(Operands[1])->isOne();
4132 if (!FVTy)
4133 return nullptr;
4134 unsigned Width = Ty->getIntegerBitWidth();
4135 if (APInt::getMaxValue(Width).ult(FVTy->getNumElements()) ||
4136 Operands[0]->containsPoisonElement())
4137 return PoisonValue::get(Ty);
4138 for (unsigned I = 0; I < FVTy->getNumElements(); ++I) {
4139 Constant *Elt = Operands[0]->getAggregateElement(I);
4140 if (!Elt)
4141 return nullptr;
4142 if (isa<UndefValue>(Elt) || Elt->isNullValue())
4143 continue;
4144 return ConstantInt::get(Ty, I);
4145 }
4146 if (ZeroIsPoison)
4147 return PoisonValue::get(Ty);
4148 return ConstantInt::get(Ty, FVTy->getNumElements());
4149 }
4150 return nullptr;
4151}
4152
4153static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
4154 const APFloat &S0,
4155 const APFloat &S1,
4156 const APFloat &S2) {
4157 unsigned ID;
4158 const fltSemantics &Sem = S0.getSemantics();
4159 APFloat MA(Sem), SC(Sem), TC(Sem);
4160 if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
4161 if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
4162 // S2 < 0
4163 ID = 5;
4164 SC = -S0;
4165 } else {
4166 ID = 4;
4167 SC = S0;
4168 }
4169 MA = S2;
4170 TC = -S1;
4171 } else if (abs(S1) >= abs(S0)) {
4172 if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
4173 // S1 < 0
4174 ID = 3;
4175 TC = -S2;
4176 } else {
4177 ID = 2;
4178 TC = S2;
4179 }
4180 MA = S1;
4181 SC = S0;
4182 } else {
4183 if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
4184 // S0 < 0
4185 ID = 1;
4186 SC = S2;
4187 } else {
4188 ID = 0;
4189 SC = -S2;
4190 }
4191 MA = S0;
4192 TC = -S1;
4193 }
4194 switch (IntrinsicID) {
4195 default:
4196 llvm_unreachable("unhandled amdgcn cube intrinsic");
4197 case Intrinsic::amdgcn_cubeid:
4198 return APFloat(Sem, ID);
4199 case Intrinsic::amdgcn_cubema:
4200 return MA + MA;
4201 case Intrinsic::amdgcn_cubesc:
4202 return SC;
4203 case Intrinsic::amdgcn_cubetc:
4204 return TC;
4205 }
4206}
4207
4208static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
4209 Type *Ty) {
4210 const APInt *C0, *C1, *C2;
4211 if (!getConstIntOrUndef(Operands[0], C0) ||
4212 !getConstIntOrUndef(Operands[1], C1) ||
4213 !getConstIntOrUndef(Operands[2], C2))
4214 return nullptr;
4215
4216 if (!C2)
4217 return UndefValue::get(Ty);
4218
4219 APInt Val(32, 0);
4220 unsigned NumUndefBytes = 0;
4221 for (unsigned I = 0; I < 32; I += 8) {
4222 unsigned Sel = C2->extractBitsAsZExtValue(8, I);
4223 unsigned B = 0;
4224
4225 if (Sel >= 13)
4226 B = 0xff;
4227 else if (Sel == 12)
4228 B = 0x00;
4229 else {
4230 const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
4231 if (!Src)
4232 ++NumUndefBytes;
4233 else if (Sel < 8)
4234 B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
4235 else
4236 B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
4237 }
4238
4239 Val.insertBits(B, I, 8);
4240 }
4241
4242 if (NumUndefBytes == 4)
4243 return UndefValue::get(Ty);
4244
4245 return ConstantInt::get(Ty, Val);
4246}
4247
4248static Constant *ConstantFoldScalarCall3(StringRef Name,
4249 Intrinsic::ID IntrinsicID, Type *Ty,
4251 const TargetLibraryInfo *TLI = nullptr,
4252 const CallBase *Call = nullptr) {
4253 assert(Operands.size() == 3 && "Wrong number of operands.");
4254
4255 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
4256 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
4257 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
4258 const APFloat &C1 = Op1->getValueAPF();
4259 const APFloat &C2 = Op2->getValueAPF();
4260 const APFloat &C3 = Op3->getValueAPF();
4261
4262 if (const auto *ConstrIntr =
4264 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
4265 APFloat Res = C1;
4267 switch (IntrinsicID) {
4268 default:
4269 return nullptr;
4270 case Intrinsic::experimental_constrained_fma:
4271 case Intrinsic::experimental_constrained_fmuladd:
4272 St = Res.fusedMultiplyAdd(C2, C3, RM);
4273 break;
4274 }
4275 if (mayFoldConstrained(
4276 const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St))
4277 return ConstantFP::get(Ty, Res);
4278 return nullptr;
4279 }
4280
4281 switch (IntrinsicID) {
4282 default: break;
4283 case Intrinsic::amdgcn_fma_legacy: {
4284 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
4285 // NaN or infinity, gives +0.0.
4286 if (C1.isZero() || C2.isZero()) {
4287 // It's tempting to just return C3 here, but that would give the
4288 // wrong result if C3 was -0.0.
4289 return ConstantFP::get(Ty, APFloat(0.0f) + C3);
4290 }
4291 [[fallthrough]];
4292 }
4293 case Intrinsic::fma:
4294 case Intrinsic::fmuladd: {
4295 APFloat V = C1;
4297 return ConstantFP::get(Ty, V);
4298 }
4299
4300 case Intrinsic::nvvm_fma_rm_f:
4301 case Intrinsic::nvvm_fma_rn_f:
4302 case Intrinsic::nvvm_fma_rp_f:
4303 case Intrinsic::nvvm_fma_rz_f:
4304 case Intrinsic::nvvm_fma_rm_d:
4305 case Intrinsic::nvvm_fma_rn_d:
4306 case Intrinsic::nvvm_fma_rp_d:
4307 case Intrinsic::nvvm_fma_rz_d:
4308 case Intrinsic::nvvm_fma_rm_ftz_f:
4309 case Intrinsic::nvvm_fma_rn_ftz_f:
4310 case Intrinsic::nvvm_fma_rp_ftz_f:
4311 case Intrinsic::nvvm_fma_rz_ftz_f: {
4312 bool IsFTZ = nvvm::FMAShouldFTZ(IntrinsicID);
4313 APFloat A = IsFTZ ? FTZPreserveSign(C1) : C1;
4314 APFloat B = IsFTZ ? FTZPreserveSign(C2) : C2;
4315 APFloat C = IsFTZ ? FTZPreserveSign(C3) : C3;
4316
4317 APFloat::roundingMode RoundMode =
4318 nvvm::GetFMARoundingMode(IntrinsicID);
4319
4320 APFloat Res = A;
4321 APFloat::opStatus Status = Res.fusedMultiplyAdd(B, C, RoundMode);
4322
4323 if (!Res.isNaN() &&
4325 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
4326 return ConstantFP::get(Ty, Res);
4327 }
4328 return nullptr;
4329 }
4330
4331 case Intrinsic::amdgcn_cubeid:
4332 case Intrinsic::amdgcn_cubema:
4333 case Intrinsic::amdgcn_cubesc:
4334 case Intrinsic::amdgcn_cubetc: {
4335 APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3);
4336 return ConstantFP::get(Ty, V);
4337 }
4338 }
4339 }
4340
4341 // TODO: Add constant folding for the _sat variants.
4342 const bool IsFAdd = IntrinsicID == Intrinsic::nvvm_fadd ||
4343 IntrinsicID == Intrinsic::nvvm_fadd_ftz;
4344 const bool IsFMul = IntrinsicID == Intrinsic::nvvm_fmul ||
4345 IntrinsicID == Intrinsic::nvvm_fmul_ftz;
4346 if (IsFAdd || IsFMul) {
4347 bool IsFTZ = IntrinsicID == Intrinsic::nvvm_fadd_ftz ||
4348 IntrinsicID == Intrinsic::nvvm_fmul_ftz;
4349 APFloat A =
4350 IsFTZ ? FTZPreserveSign(Op1->getValueAPF()) : Op1->getValueAPF();
4351 APFloat B =
4352 IsFTZ ? FTZPreserveSign(Op2->getValueAPF()) : Op2->getValueAPF();
4353
4354 APFloat::roundingMode RoundMode =
4356
4357 APFloat Res = A;
4359 IsFAdd ? Res.add(B, RoundMode) : Res.multiply(B, RoundMode);
4360
4361 if (!Res.isNaN() &&
4363 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
4364 return ConstantFP::get(Ty, Res);
4365 }
4366 return nullptr;
4367 }
4368 }
4369 }
4370
4371 if (IntrinsicID == Intrinsic::smul_fix ||
4372 IntrinsicID == Intrinsic::smul_fix_sat) {
4373 const APInt *C0, *C1;
4374 if (!getConstIntOrUndef(Operands[0], C0) ||
4375 !getConstIntOrUndef(Operands[1], C1))
4376 return nullptr;
4377
4378 // undef * C -> 0
4379 // C * undef -> 0
4380 if (!C0 || !C1)
4381 return Constant::getNullValue(Ty);
4382
4383 // This code performs rounding towards negative infinity in case the result
4384 // cannot be represented exactly for the given scale. Targets that do care
4385 // about rounding should use a target hook for specifying how rounding
4386 // should be done, and provide their own folding to be consistent with
4387 // rounding. This is the same approach as used by
4388 // DAGTypeLegalizer::ExpandIntRes_MULFIX.
4389 unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
4390 unsigned Width = C0->getBitWidth();
4391 assert(Scale < Width && "Illegal scale.");
4392 unsigned ExtendedWidth = Width * 2;
4393 APInt Product =
4394 (C0->sext(ExtendedWidth) * C1->sext(ExtendedWidth)).ashr(Scale);
4395 if (IntrinsicID == Intrinsic::smul_fix_sat) {
4396 APInt Max = APInt::getSignedMaxValue(Width).sext(ExtendedWidth);
4397 APInt Min = APInt::getSignedMinValue(Width).sext(ExtendedWidth);
4398 Product = APIntOps::smin(Product, Max);
4399 Product = APIntOps::smax(Product, Min);
4400 }
4401 return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
4402 }
4403
4404 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
4405 const APInt *C0, *C1, *C2;
4406 if (!getConstIntOrUndef(Operands[0], C0) ||
4407 !getConstIntOrUndef(Operands[1], C1) ||
4408 !getConstIntOrUndef(Operands[2], C2))
4409 return nullptr;
4410
4411 bool IsRight = IntrinsicID == Intrinsic::fshr;
4412 if (!C2)
4413 return Operands[IsRight ? 1 : 0];
4414 if (!C0 && !C1)
4415 return UndefValue::get(Ty);
4416
4417 // The shift amount is interpreted as modulo the bitwidth. If the shift
4418 // amount is effectively 0, avoid UB due to oversized inverse shift below.
4419 unsigned BitWidth = C2->getBitWidth();
4420 unsigned ShAmt = C2->urem(BitWidth);
4421 if (!ShAmt)
4422 return Operands[IsRight ? 1 : 0];
4423
4424 // (C0 << ShlAmt) | (C1 >> LshrAmt)
4425 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
4426 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
4427 if (!C0)
4428 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
4429 if (!C1)
4430 return ConstantInt::get(Ty, C0->shl(ShlAmt));
4431 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
4432 }
4433
4434 if (IntrinsicID == Intrinsic::amdgcn_perm)
4435 return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
4436
4437 return nullptr;
4438}
4439
4440static Constant *ConstantFoldScalarCall(StringRef Name,
4441 Intrinsic::ID IntrinsicID, Type *Ty,
4443 const TargetLibraryInfo *TLI = nullptr,
4444 const CallBase *Call = nullptr) {
4445 if (IntrinsicID != Intrinsic::not_intrinsic &&
4447 intrinsicPropagatesPoison(IntrinsicID))
4448 return PoisonValue::get(Ty);
4449
4450 if (Operands.size() == 1)
4451 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
4452
4453 if (Operands.size() == 2) {
4454 if (Constant *FoldedLibCall =
4455 ConstantFoldLibCall2(Name, Ty, Operands, TLI)) {
4456 return FoldedLibCall;
4457 }
4458 return ConstantFoldIntrinsicCall2(IntrinsicID, Ty, Operands, Call);
4459 }
4460
4461 if (Operands.size() == 3)
4462 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
4463
4464 return nullptr;
4465}
4466
4467static Constant *ConstantFoldFixedVectorCall(
4468 StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
4470 const TargetLibraryInfo *TLI = nullptr, const CallBase *Call = nullptr) {
4473 Type *Ty = FVTy->getElementType();
4474
4475 switch (IntrinsicID) {
4476 case Intrinsic::masked_load: {
4477 auto *SrcPtr = Operands[0];
4478 auto *Mask = Operands[1];
4479 auto *Passthru = Operands[2];
4480
4481 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
4482
4483 SmallVector<Constant *, 32> NewElements;
4484 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4485 auto *MaskElt = Mask->getAggregateElement(I);
4486 if (!MaskElt)
4487 break;
4488 auto *PassthruElt = Passthru->getAggregateElement(I);
4489 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
4490 if (isa<UndefValue>(MaskElt)) {
4491 if (PassthruElt)
4492 NewElements.push_back(PassthruElt);
4493 else if (VecElt)
4494 NewElements.push_back(VecElt);
4495 else
4496 return nullptr;
4497 }
4498 if (MaskElt->isNullValue()) {
4499 if (!PassthruElt)
4500 return nullptr;
4501 NewElements.push_back(PassthruElt);
4502 } else if (MaskElt->isOneValue()) {
4503 if (!VecElt)
4504 return nullptr;
4505 NewElements.push_back(VecElt);
4506 } else {
4507 return nullptr;
4508 }
4509 }
4510 if (NewElements.size() != FVTy->getNumElements())
4511 return nullptr;
4512 return ConstantVector::get(NewElements);
4513 }
4514 case Intrinsic::arm_mve_vctp8:
4515 case Intrinsic::arm_mve_vctp16:
4516 case Intrinsic::arm_mve_vctp32:
4517 case Intrinsic::arm_mve_vctp64: {
4518 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
4519 unsigned Lanes = FVTy->getNumElements();
4520 uint64_t Limit = Op->getZExtValue();
4521
4523 for (unsigned i = 0; i < Lanes; i++) {
4524 if (i < Limit)
4526 else
4528 }
4529 return ConstantVector::get(NCs);
4530 }
4531 return nullptr;
4532 }
4533 case Intrinsic::get_active_lane_mask: {
4534 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
4535 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
4536 if (Op0 && Op1) {
4537 unsigned Lanes = FVTy->getNumElements();
4538 APInt Base = Op0->getValue();
4539 APInt Limit = Op1->getValue();
4540
4542 for (unsigned I = 0; I < Lanes; I++) {
4543 bool Overflow;
4544 if (Base.uadd_ov(APInt(Base.getBitWidth(), I), Overflow).ult(Limit) &&
4545 !Overflow)
4547 else
4549 }
4550 return ConstantVector::get(NCs);
4551 }
4552 return nullptr;
4553 }
4554 case Intrinsic::vector_extract: {
4556 Constant *Vec = Operands[0];
4557 if (!Idx || !isa<FixedVectorType>(Vec->getType()))
4558 return nullptr;
4559
4560 unsigned NumElements = FVTy->getNumElements();
4561 unsigned VecNumElements =
4562 cast<FixedVectorType>(Vec->getType())->getNumElements();
4563 unsigned StartingIndex = Idx->getZExtValue();
4564
4565 // Extracting entire vector is nop
4566 if (NumElements == VecNumElements && StartingIndex == 0)
4567 return Vec;
4568
4569 for (unsigned I = StartingIndex, E = StartingIndex + NumElements; I < E;
4570 ++I) {
4571 Constant *Elt = Vec->getAggregateElement(I);
4572 if (!Elt)
4573 return nullptr;
4574 Result[I - StartingIndex] = Elt;
4575 }
4576
4577 return ConstantVector::get(Result);
4578 }
4579 case Intrinsic::vector_insert: {
4580 Constant *Vec = Operands[0];
4581 Constant *SubVec = Operands[1];
4583 if (!Idx || !isa<FixedVectorType>(Vec->getType()))
4584 return nullptr;
4585
4586 unsigned SubVecNumElements =
4587 cast<FixedVectorType>(SubVec->getType())->getNumElements();
4588 unsigned VecNumElements =
4589 cast<FixedVectorType>(Vec->getType())->getNumElements();
4590 unsigned IdxN = Idx->getZExtValue();
4591 // Replacing entire vector with a subvec is nop
4592 if (SubVecNumElements == VecNumElements && IdxN == 0)
4593 return SubVec;
4594
4595 for (unsigned I = 0; I < VecNumElements; ++I) {
4596 Constant *Elt;
4597 if (I < IdxN + SubVecNumElements)
4598 Elt = SubVec->getAggregateElement(I - IdxN);
4599 else
4600 Elt = Vec->getAggregateElement(I);
4601 if (!Elt)
4602 return nullptr;
4603 Result[I] = Elt;
4604 }
4605 return ConstantVector::get(Result);
4606 }
4607 case Intrinsic::vector_interleave2:
4608 case Intrinsic::vector_interleave3:
4609 case Intrinsic::vector_interleave4:
4610 case Intrinsic::vector_interleave5:
4611 case Intrinsic::vector_interleave6:
4612 case Intrinsic::vector_interleave7:
4613 case Intrinsic::vector_interleave8: {
4614 unsigned NumElements =
4615 cast<FixedVectorType>(Operands[0]->getType())->getNumElements();
4616 unsigned NumOperands = Operands.size();
4617 for (unsigned I = 0; I < NumElements; ++I) {
4618 for (unsigned J = 0; J < NumOperands; ++J) {
4619 Constant *Elt = Operands[J]->getAggregateElement(I);
4620 if (!Elt)
4621 return nullptr;
4622 Result[NumOperands * I + J] = Elt;
4623 }
4624 }
4625 return ConstantVector::get(Result);
4626 }
4627 case Intrinsic::vector_partial_reduce_add:
4628 return constantFoldVectorPartialReduceAdd(Operands[0], Operands[1], DL);
4629 case Intrinsic::wasm_dot: {
4630 unsigned NumElements =
4631 cast<FixedVectorType>(Operands[0]->getType())->getNumElements();
4632
4633 assert(NumElements == 8 && Result.size() == 4 &&
4634 "wasm dot takes i16x8 and produces i32x4");
4635 assert(Ty->isIntegerTy());
4636 int32_t MulVector[8];
4637
4638 for (unsigned I = 0; I < NumElements; ++I) {
4639 ConstantInt *Elt0 =
4640 dyn_cast<ConstantInt>(Operands[0]->getAggregateElement(I));
4641 ConstantInt *Elt1 =
4642 dyn_cast<ConstantInt>(Operands[1]->getAggregateElement(I));
4643
4644 if (!Elt0 || !Elt1)
4645 return nullptr;
4646
4647 MulVector[I] = Elt0->getSExtValue() * Elt1->getSExtValue();
4648 }
4649 for (unsigned I = 0; I < Result.size(); I++) {
4650 int64_t IAdd = (int64_t)MulVector[I * 2] + (int64_t)MulVector[I * 2 + 1];
4651 Result[I] = ConstantInt::getSigned(Ty, IAdd, /*ImplicitTrunc=*/true);
4652 }
4653
4654 return ConstantVector::get(Result);
4655 }
4656 case Intrinsic::nvvm_fadd:
4657 case Intrinsic::nvvm_fadd_ftz:
4658 case Intrinsic::nvvm_fmul:
4659 case Intrinsic::nvvm_fmul_ftz:
4660 // The rounding mode operand is a scalar, so the lane-wise folding below
4661 // does not apply.
4662 // TODO: Fold these by passing the rounding mode through to every lane.
4663 return nullptr;
4664 default:
4665 break;
4666 }
4667
4668 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4669 // Gather a column of constants.
4670 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
4671 // Some intrinsics use a scalar type for certain arguments.
4672 if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, J, /*TTI=*/nullptr)) {
4673 Lane[J] = Operands[J];
4674 continue;
4675 }
4676
4677 Constant *Agg = Operands[J]->getAggregateElement(I);
4678 if (!Agg)
4679 return nullptr;
4680
4681 Lane[J] = Agg;
4682 }
4683
4684 // Use the regular scalar folding to simplify this column.
4685 Constant *Folded =
4686 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
4687 if (!Folded)
4688 return nullptr;
4689 Result[I] = Folded;
4690 }
4691
4692 return ConstantVector::get(Result);
4693}
4694
4695static Constant *ConstantFoldScalableVectorCall(
4696 StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
4698 const TargetLibraryInfo *TLI, const CallBase *Call) {
4699 switch (IntrinsicID) {
4700 case Intrinsic::aarch64_sve_convert_from_svbool: {
4701 Constant *Src = Operands[0];
4702 if (!Src->isNullValue())
4703 break;
4704
4705 return ConstantInt::getFalse(SVTy);
4706 }
4707 case Intrinsic::get_active_lane_mask: {
4708 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
4709 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
4710 if (Op0 && Op1 && Op0->getValue().uge(Op1->getValue()))
4711 return ConstantVector::getNullValue(SVTy);
4712 break;
4713 }
4714 case Intrinsic::vector_interleave2:
4715 case Intrinsic::vector_interleave3:
4716 case Intrinsic::vector_interleave4:
4717 case Intrinsic::vector_interleave5:
4718 case Intrinsic::vector_interleave6:
4719 case Intrinsic::vector_interleave7:
4720 case Intrinsic::vector_interleave8: {
4721 Constant *SplatVal = Operands[0]->getSplatValue();
4722 if (!SplatVal)
4723 return nullptr;
4724
4726 return nullptr;
4727
4728 return ConstantVector::getSplat(SVTy->getElementCount(), SplatVal);
4729 }
4730 default:
4731 break;
4732 }
4733
4734 // If trivially vectorizable, try folding it via the scalar call if all
4735 // operands are splats.
4736
4737 // TODO: ConstantFoldFixedVectorCall should probably check this too?
4738 if (!isTriviallyVectorizable(IntrinsicID))
4739 return nullptr;
4740
4742 for (auto [I, Op] : enumerate(Operands)) {
4743 if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, I, /*TTI=*/nullptr)) {
4744 SplatOps.push_back(Op);
4745 continue;
4746 }
4747 Constant *Splat = Op->getSplatValue();
4748 if (!Splat)
4749 return nullptr;
4750 SplatOps.push_back(Splat);
4751 }
4752 Constant *Folded = ConstantFoldScalarCall(
4753 Name, IntrinsicID, SVTy->getElementType(), SplatOps, TLI, Call);
4754 if (!Folded)
4755 return nullptr;
4756 return ConstantVector::getSplat(SVTy->getElementCount(), Folded);
4757}
4758
4759static std::pair<Constant *, Constant *>
4760ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) {
4761 auto *ConstFP = dyn_cast<ConstantFP>(Op);
4762 if (!ConstFP)
4763 return {};
4764
4765 const APFloat &U = ConstFP->getValueAPF();
4766 int FrexpExp;
4767 APFloat FrexpMant = frexp(U, FrexpExp, APFloat::rmNearestTiesToEven);
4768 Constant *Result0 = ConstantFP::get(ConstFP->getType(), FrexpMant);
4769
4770 // The exponent is an "unspecified value" for inf/nan. We use zero to avoid
4771 // using undef.
4772 Constant *Result1 = FrexpMant.isFinite()
4773 ? ConstantInt::getSigned(IntTy, FrexpExp)
4774 : ConstantInt::getNullValue(IntTy);
4775 return {Result0, Result1};
4776}
4777
4778/// Handle intrinsics that return tuples, which may be tuples of vectors.
4779static Constant *
4780ConstantFoldStructCall(StringRef Name, Intrinsic::ID IntrinsicID,
4782 const DataLayout &DL, const TargetLibraryInfo *TLI,
4783 const CallBase *Call) {
4784
4785 switch (IntrinsicID) {
4786 case Intrinsic::frexp: {
4787 Type *Ty0 = StTy->getContainedType(0);
4788 Type *Ty1 = StTy->getContainedType(1)->getScalarType();
4789
4790 if (auto *FVTy0 = dyn_cast<FixedVectorType>(Ty0)) {
4791 SmallVector<Constant *, 4> Results0(FVTy0->getNumElements());
4792 SmallVector<Constant *, 4> Results1(FVTy0->getNumElements());
4793
4794 for (unsigned I = 0, E = FVTy0->getNumElements(); I != E; ++I) {
4795 Constant *Lane = Operands[0]->getAggregateElement(I);
4796 std::tie(Results0[I], Results1[I]) =
4797 ConstantFoldScalarFrexpCall(Lane, Ty1);
4798 if (!Results0[I])
4799 return nullptr;
4800 }
4801
4802 return ConstantStruct::get(StTy, ConstantVector::get(Results0),
4803 ConstantVector::get(Results1));
4804 }
4805
4806 auto [Result0, Result1] = ConstantFoldScalarFrexpCall(Operands[0], Ty1);
4807 if (!Result0)
4808 return nullptr;
4809 return ConstantStruct::get(StTy, Result0, Result1);
4810 }
4811 case Intrinsic::sincos: {
4812 Type *Ty = StTy->getContainedType(0);
4813 Type *TyScalar = Ty->getScalarType();
4814
4815 auto ConstantFoldScalarSincosCall =
4816 [&](Constant *Op) -> std::pair<Constant *, Constant *> {
4817 Constant *SinResult =
4818 ConstantFoldScalarCall(Name, Intrinsic::sin, TyScalar, Op, TLI, Call);
4819 Constant *CosResult =
4820 ConstantFoldScalarCall(Name, Intrinsic::cos, TyScalar, Op, TLI, Call);
4821 return std::make_pair(SinResult, CosResult);
4822 };
4823
4824 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4825 SmallVector<Constant *> SinResults(FVTy->getNumElements());
4826 SmallVector<Constant *> CosResults(FVTy->getNumElements());
4827
4828 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4829 Constant *Lane = Operands[0]->getAggregateElement(I);
4830 std::tie(SinResults[I], CosResults[I]) =
4831 ConstantFoldScalarSincosCall(Lane);
4832 if (!SinResults[I] || !CosResults[I])
4833 return nullptr;
4834 }
4835
4836 return ConstantStruct::get(StTy, ConstantVector::get(SinResults),
4837 ConstantVector::get(CosResults));
4838 }
4839
4840 if (!Ty->isFloatingPointTy())
4841 return nullptr;
4842
4843 auto [SinResult, CosResult] = ConstantFoldScalarSincosCall(Operands[0]);
4844 if (!SinResult || !CosResult)
4845 return nullptr;
4846 return ConstantStruct::get(StTy, SinResult, CosResult);
4847 }
4848 case Intrinsic::vector_deinterleave2:
4849 case Intrinsic::vector_deinterleave3:
4850 case Intrinsic::vector_deinterleave4:
4851 case Intrinsic::vector_deinterleave5:
4852 case Intrinsic::vector_deinterleave6:
4853 case Intrinsic::vector_deinterleave7:
4854 case Intrinsic::vector_deinterleave8: {
4855 unsigned NumResults = StTy->getNumElements();
4856 auto *Vec = Operands[0];
4857 auto *VecTy = cast<VectorType>(Vec->getType());
4858
4859 ElementCount ResultEC =
4860 VecTy->getElementCount().divideCoefficientBy(NumResults);
4861
4862 if (auto *EltC = Vec->getSplatValue()) {
4863 auto *ResultVec = ConstantVector::getSplat(ResultEC, EltC);
4864 SmallVector<Constant *, 8> Results(NumResults, ResultVec);
4865 return ConstantStruct::get(StTy, Results);
4866 }
4867
4868 if (!ResultEC.isFixed())
4869 return nullptr;
4870
4871 unsigned NumElements = ResultEC.getFixedValue();
4873 SmallVector<Constant *> Elements(NumElements);
4874 for (unsigned I = 0; I != NumResults; ++I) {
4875 for (unsigned J = 0; J != NumElements; ++J) {
4876 Constant *Elt = Vec->getAggregateElement(J * NumResults + I);
4877 if (!Elt)
4878 return nullptr;
4879 Elements[J] = Elt;
4880 }
4881 Results[I] = ConstantVector::get(Elements);
4882 }
4883 return ConstantStruct::get(StTy, Results);
4884 }
4885 default:
4886 // TODO: Constant folding of vector intrinsics that fall through here does
4887 // not work (e.g. overflow intrinsics)
4888 return ConstantFoldScalarCall(Name, IntrinsicID, StTy, Operands, TLI, Call);
4889 }
4890
4891 return nullptr;
4892}
4893
4894} // end anonymous namespace
4895
4898 const DataLayout &DL,
4899 const Function *CtxF) {
4900 // In the absence of CtxF, assume strictfp conservatively.
4901 if (!canConstantFoldIntrinsic(ID, CtxF ? CtxF->isStrictFP() : true) ||
4904 Ty, ArrayRef<Value *>((Value *const *)Ops.data(), Ops.size()))))
4905 return nullptr;
4906 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
4907 return ConstantFoldFixedVectorCall("", ID, FVTy, Ops, DL);
4908 return ConstantFoldScalarCall("", ID, Ty, Ops);
4909}
4910
4913 const TargetLibraryInfo *TLI,
4914 bool AllowNonDeterministic) {
4915 if (Call->isNoBuiltin())
4916 return nullptr;
4917 if (!F->hasName())
4918 return nullptr;
4919
4920 // If this is not an intrinsic and not recognized as a library call, bail out.
4921 Intrinsic::ID IID = F->getIntrinsicID();
4922 if (IID == Intrinsic::not_intrinsic) {
4923 if (!TLI)
4924 return nullptr;
4925 if (TLI->getLibFunc(*F) == NotLibFunc)
4926 return nullptr;
4927 }
4928
4929 // Conservatively assume that floating-point libcalls may be
4930 // non-deterministic.
4931 Type *Ty = F->getReturnType();
4932 if (!AllowNonDeterministic && Ty->isFPOrFPVectorTy())
4933 return nullptr;
4934
4935 StringRef Name = F->getName();
4936 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
4937 return ConstantFoldFixedVectorCall(
4938 Name, IID, FVTy, Operands, F->getDataLayout(), TLI, Call);
4939
4940 if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
4941 return ConstantFoldScalableVectorCall(
4942 Name, IID, SVTy, Operands, F->getDataLayout(), TLI, Call);
4943
4944 if (auto *StTy = dyn_cast<StructType>(Ty))
4945 return ConstantFoldStructCall(Name, IID, StTy, Operands,
4946 F->getDataLayout(), TLI, Call);
4947
4948 // TODO: If this is a library function, we already discovered that above,
4949 // so we should pass the LibFunc, not the name (and it might be better
4950 // still to separate intrinsic handling from libcalls).
4951 return ConstantFoldScalarCall(Name, IID, Ty, Operands, TLI, Call);
4952}
4953
4955 const TargetLibraryInfo *TLI) {
4956 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
4957 // (and to some extent ConstantFoldScalarCall).
4958 if (Call->isNoBuiltin() || Call->isStrictFP())
4959 return false;
4960 Function *F = Call->getCalledFunction();
4961 if (!F)
4962 return false;
4963
4964 if (!TLI)
4965 return false;
4966
4967 LibFunc Func = TLI->getLibFunc(*F);
4968 if (Func == NotLibFunc)
4969 return false;
4970
4971 if (Call->arg_size() == 1) {
4972 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
4973 const APFloat &Op = OpC->getValueAPF();
4974 switch (Func) {
4975 case LibFunc_logl:
4976 case LibFunc_log:
4977 case LibFunc_logf:
4978 case LibFunc_log2l:
4979 case LibFunc_log2:
4980 case LibFunc_log2f:
4981 case LibFunc_log10l:
4982 case LibFunc_log10:
4983 case LibFunc_log10f:
4984 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
4985
4986 case LibFunc_ilogb:
4987 return !Op.isNaN() && !Op.isZero() && !Op.isInfinity();
4988
4989 case LibFunc_expl:
4990 case LibFunc_exp:
4991 case LibFunc_expf:
4992 // FIXME: These boundaries are slightly conservative.
4993 if (OpC->getType()->isDoubleTy())
4994 return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
4995 if (OpC->getType()->isFloatTy())
4996 return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
4997 break;
4998
4999 case LibFunc_exp2l:
5000 case LibFunc_exp2:
5001 case LibFunc_exp2f:
5002 // FIXME: These boundaries are slightly conservative.
5003 if (OpC->getType()->isDoubleTy())
5004 return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
5005 if (OpC->getType()->isFloatTy())
5006 return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
5007 break;
5008
5009 case LibFunc_sinl:
5010 case LibFunc_sin:
5011 case LibFunc_sinf:
5012 case LibFunc_cosl:
5013 case LibFunc_cos:
5014 case LibFunc_cosf:
5015 return !Op.isInfinity();
5016
5017 case LibFunc_tanl:
5018 case LibFunc_tan:
5019 case LibFunc_tanf: {
5020 // FIXME: Stop using the host math library.
5021 // FIXME: The computation isn't done in the right precision.
5022 Type *Ty = OpC->getType();
5023 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy())
5024 return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr;
5025 break;
5026 }
5027
5028 case LibFunc_atan:
5029 case LibFunc_atanf:
5030 case LibFunc_atanl:
5031 // Per POSIX, this MAY fail if Op is denormal. We choose not failing.
5032 return true;
5033
5034 case LibFunc_asinl:
5035 case LibFunc_asin:
5036 case LibFunc_asinf:
5037 case LibFunc_acosl:
5038 case LibFunc_acos:
5039 case LibFunc_acosf:
5040 return !(Op < APFloat::getOne(Op.getSemantics(), true) ||
5041 Op > APFloat::getOne(Op.getSemantics()));
5042
5043 case LibFunc_sinh:
5044 case LibFunc_cosh:
5045 case LibFunc_sinhf:
5046 case LibFunc_coshf:
5047 case LibFunc_sinhl:
5048 case LibFunc_coshl:
5049 // FIXME: These boundaries are slightly conservative.
5050 if (OpC->getType()->isDoubleTy())
5051 return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
5052 if (OpC->getType()->isFloatTy())
5053 return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
5054 break;
5055
5056 case LibFunc_sqrtl:
5057 case LibFunc_sqrt:
5058 case LibFunc_sqrtf:
5059 return Op.isNaN() || Op.isZero() || !Op.isNegative();
5060
5061 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
5062 // maybe others?
5063 default:
5064 break;
5065 }
5066 }
5067 }
5068
5069 if (Call->arg_size() == 2) {
5070 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
5071 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
5072 if (Op0C && Op1C) {
5073 const APFloat &Op0 = Op0C->getValueAPF();
5074 const APFloat &Op1 = Op1C->getValueAPF();
5075
5076 switch (Func) {
5077 case LibFunc_powl:
5078 case LibFunc_pow:
5079 case LibFunc_powf: {
5080 // FIXME: Stop using the host math library.
5081 // FIXME: The computation isn't done in the right precision.
5082 Type *Ty = Op0C->getType();
5083 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
5084 if (Ty == Op1C->getType())
5085 return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr;
5086 }
5087 break;
5088 }
5089
5090 case LibFunc_fmodl:
5091 case LibFunc_fmod:
5092 case LibFunc_fmodf:
5093 case LibFunc_remainderl:
5094 case LibFunc_remainder:
5095 case LibFunc_remainderf:
5096 return Op0.isNaN() || Op1.isNaN() ||
5097 (!Op0.isInfinity() && !Op1.isZero());
5098
5099 case LibFunc_atan2:
5100 case LibFunc_atan2f:
5101 case LibFunc_atan2l:
5102 // Although IEEE-754 says atan2(+/-0.0, +/-0.0) are well-defined, and
5103 // GLIBC and MSVC do not appear to raise an error on those, we
5104 // cannot rely on that behavior. POSIX and C11 say that a domain error
5105 // may occur, so allow for that possibility.
5106 return !Op0.isZero() || !Op1.isZero();
5107
5108 case LibFunc_nextafter:
5109 case LibFunc_nextafterf:
5110 case LibFunc_nextafterl:
5111 case LibFunc_nexttoward:
5112 case LibFunc_nexttowardf:
5113 case LibFunc_nexttowardl: {
5114 return ConstantFoldNextToward(Op0, Op1, F->getReturnType()) != nullptr;
5115 }
5116 default:
5117 break;
5118 }
5119 }
5120 }
5121
5122 return false;
5123}
5124
5126 unsigned CastOp, const DataLayout &DL,
5127 PreservedCastFlags *Flags) {
5128 switch (CastOp) {
5129 case Instruction::BitCast:
5130 // Bitcast is always lossless.
5131 return ConstantFoldCastOperand(Instruction::BitCast, C, InvCastTo, DL);
5132 case Instruction::Trunc: {
5133 auto *ZExtC = ConstantFoldCastOperand(Instruction::ZExt, C, InvCastTo, DL);
5134 if (Flags) {
5135 // Truncation back on ZExt value is always NUW.
5136 Flags->NUW = true;
5137 // Test positivity of C.
5138 auto *SExtC =
5139 ConstantFoldCastOperand(Instruction::SExt, C, InvCastTo, DL);
5140 Flags->NSW = ZExtC == SExtC;
5141 }
5142 return ZExtC;
5143 }
5144 case Instruction::SExt:
5145 case Instruction::ZExt: {
5146 auto *InvC = ConstantExpr::getTrunc(C, InvCastTo);
5147 auto *CastInvC = ConstantFoldCastOperand(CastOp, InvC, C->getType(), DL);
5148 // Must satisfy CastOp(InvC) == C.
5149 if (!CastInvC || CastInvC != C)
5150 return nullptr;
5151 if (Flags && CastOp == Instruction::ZExt) {
5152 auto *SExtInvC =
5153 ConstantFoldCastOperand(Instruction::SExt, InvC, C->getType(), DL);
5154 // Test positivity of InvC.
5155 Flags->NNeg = CastInvC == SExtInvC;
5156 }
5157 return InvC;
5158 }
5159 case Instruction::FPExt: {
5160 Constant *InvC =
5161 ConstantFoldCastOperand(Instruction::FPTrunc, C, InvCastTo, DL);
5162 if (InvC) {
5163 Constant *CastInvC =
5164 ConstantFoldCastOperand(CastOp, InvC, C->getType(), DL);
5165 if (CastInvC == C)
5166 return InvC;
5167 }
5168 return nullptr;
5169 }
5170 default:
5171 return nullptr;
5172 }
5173}
5174
5176 const DataLayout &DL,
5177 PreservedCastFlags *Flags) {
5178 return getLosslessInvCast(C, DestTy, Instruction::ZExt, DL, Flags);
5179}
5180
5182 const DataLayout &DL,
5183 PreservedCastFlags *Flags) {
5184 return getLosslessInvCast(C, DestTy, Instruction::SExt, DL, Flags);
5185}
5186
5187void TargetFolder::anchor() {}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned 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:6034
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:6093
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:43
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:64
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:767
iterator end()
Definition DenseMap.h:687
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:828
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:810
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:68
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:918
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:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:171
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:252
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
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:3165
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3245
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3157
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:3225
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:3255
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:6253
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