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 18 #include "llvm/Analysis/ConstantFolding.h" 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" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Analysis/TargetFolder.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/Config/config.h" 32 #include "llvm/IR/Constant.h" 33 #include "llvm/IR/ConstantFold.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/GlobalValue.h" 39 #include "llvm/IR/GlobalVariable.h" 40 #include "llvm/IR/InstrTypes.h" 41 #include "llvm/IR/Instruction.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/IntrinsicInst.h" 44 #include "llvm/IR/Intrinsics.h" 45 #include "llvm/IR/IntrinsicsAArch64.h" 46 #include "llvm/IR/IntrinsicsAMDGPU.h" 47 #include "llvm/IR/IntrinsicsARM.h" 48 #include "llvm/IR/IntrinsicsWebAssembly.h" 49 #include "llvm/IR/IntrinsicsX86.h" 50 #include "llvm/IR/Operator.h" 51 #include "llvm/IR/Type.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/Support/Casting.h" 54 #include "llvm/Support/ErrorHandling.h" 55 #include "llvm/Support/KnownBits.h" 56 #include "llvm/Support/MathExtras.h" 57 #include <cassert> 58 #include <cerrno> 59 #include <cfenv> 60 #include <cmath> 61 #include <cstdint> 62 63 using namespace llvm; 64 65 namespace { 66 67 //===----------------------------------------------------------------------===// 68 // Constant Folding internal helper functions 69 //===----------------------------------------------------------------------===// 70 71 static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy, 72 Constant *C, Type *SrcEltTy, 73 unsigned NumSrcElts, 74 const DataLayout &DL) { 75 // Now that we know that the input value is a vector of integers, just shift 76 // and insert them into our result. 77 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy); 78 for (unsigned i = 0; i != NumSrcElts; ++i) { 79 Constant *Element; 80 if (DL.isLittleEndian()) 81 Element = C->getAggregateElement(NumSrcElts - i - 1); 82 else 83 Element = C->getAggregateElement(i); 84 85 if (isa_and_nonnull<UndefValue>(Element)) { 86 Result <<= BitShift; 87 continue; 88 } 89 90 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element); 91 if (!ElementCI) 92 return ConstantExpr::getBitCast(C, DestTy); 93 94 Result <<= BitShift; 95 Result |= ElementCI->getValue().zext(Result.getBitWidth()); 96 } 97 98 return nullptr; 99 } 100 101 /// Constant fold bitcast, symbolically evaluating it with DataLayout. 102 /// This always returns a non-null constant, but it may be a 103 /// ConstantExpr if unfoldable. 104 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) { 105 assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) && 106 "Invalid constantexpr bitcast!"); 107 108 // Catch the obvious splat cases. 109 if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy, DL)) 110 return Res; 111 112 if (auto *VTy = dyn_cast<VectorType>(C->getType())) { 113 // Handle a vector->scalar integer/fp cast. 114 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) { 115 unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements(); 116 Type *SrcEltTy = VTy->getElementType(); 117 118 // If the vector is a vector of floating point, convert it to vector of int 119 // to simplify things. 120 if (SrcEltTy->isFloatingPointTy()) { 121 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); 122 auto *SrcIVTy = FixedVectorType::get( 123 IntegerType::get(C->getContext(), FPWidth), NumSrcElts); 124 // Ask IR to do the conversion now that #elts line up. 125 C = ConstantExpr::getBitCast(C, SrcIVTy); 126 } 127 128 APInt Result(DL.getTypeSizeInBits(DestTy), 0); 129 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C, 130 SrcEltTy, NumSrcElts, DL)) 131 return CE; 132 133 if (isa<IntegerType>(DestTy)) 134 return ConstantInt::get(DestTy, Result); 135 136 APFloat FP(DestTy->getFltSemantics(), Result); 137 return ConstantFP::get(DestTy->getContext(), FP); 138 } 139 } 140 141 // The code below only handles casts to vectors currently. 142 auto *DestVTy = dyn_cast<VectorType>(DestTy); 143 if (!DestVTy) 144 return ConstantExpr::getBitCast(C, DestTy); 145 146 // If this is a scalar -> vector cast, convert the input into a <1 x scalar> 147 // vector so the code below can handle it uniformly. 148 if (!isa<VectorType>(C->getType()) && 149 (isa<ConstantFP>(C) || isa<ConstantInt>(C))) { 150 Constant *Ops = C; // don't take the address of C! 151 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL); 152 } 153 154 // If this is a bitcast from constant vector -> vector, fold it. 155 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C)) 156 return ConstantExpr::getBitCast(C, DestTy); 157 158 // If the element types match, IR can fold it. 159 unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements(); 160 unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements(); 161 if (NumDstElt == NumSrcElt) 162 return ConstantExpr::getBitCast(C, DestTy); 163 164 Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType(); 165 Type *DstEltTy = DestVTy->getElementType(); 166 167 // Otherwise, we're changing the number of elements in a vector, which 168 // requires endianness information to do the right thing. For example, 169 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) 170 // folds to (little endian): 171 // <4 x i32> <i32 0, i32 0, i32 1, i32 0> 172 // and to (big endian): 173 // <4 x i32> <i32 0, i32 0, i32 0, i32 1> 174 175 // First thing is first. We only want to think about integer here, so if 176 // we have something in FP form, recast it as integer. 177 if (DstEltTy->isFloatingPointTy()) { 178 // Fold to an vector of integers with same size as our FP type. 179 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits(); 180 auto *DestIVTy = FixedVectorType::get( 181 IntegerType::get(C->getContext(), FPWidth), NumDstElt); 182 // Recursively handle this integer conversion, if possible. 183 C = FoldBitCast(C, DestIVTy, DL); 184 185 // Finally, IR can handle this now that #elts line up. 186 return ConstantExpr::getBitCast(C, DestTy); 187 } 188 189 // Okay, we know the destination is integer, if the input is FP, convert 190 // it to integer first. 191 if (SrcEltTy->isFloatingPointTy()) { 192 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); 193 auto *SrcIVTy = FixedVectorType::get( 194 IntegerType::get(C->getContext(), FPWidth), NumSrcElt); 195 // Ask IR to do the conversion now that #elts line up. 196 C = ConstantExpr::getBitCast(C, SrcIVTy); 197 // If IR wasn't able to fold it, bail out. 198 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector. 199 !isa<ConstantDataVector>(C)) 200 return C; 201 } 202 203 // Now we know that the input and output vectors are both integer vectors 204 // of the same size, and that their #elements is not the same. Do the 205 // conversion here, which depends on whether the input or output has 206 // more elements. 207 bool isLittleEndian = DL.isLittleEndian(); 208 209 SmallVector<Constant*, 32> Result; 210 if (NumDstElt < NumSrcElt) { 211 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>) 212 Constant *Zero = Constant::getNullValue(DstEltTy); 213 unsigned Ratio = NumSrcElt/NumDstElt; 214 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits(); 215 unsigned SrcElt = 0; 216 for (unsigned i = 0; i != NumDstElt; ++i) { 217 // Build each element of the result. 218 Constant *Elt = Zero; 219 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1); 220 for (unsigned j = 0; j != Ratio; ++j) { 221 Constant *Src = C->getAggregateElement(SrcElt++); 222 if (isa_and_nonnull<UndefValue>(Src)) 223 Src = Constant::getNullValue( 224 cast<VectorType>(C->getType())->getElementType()); 225 else 226 Src = dyn_cast_or_null<ConstantInt>(Src); 227 if (!Src) // Reject constantexpr elements. 228 return ConstantExpr::getBitCast(C, DestTy); 229 230 // Zero extend the element to the right size. 231 Src = ConstantFoldCastOperand(Instruction::ZExt, Src, Elt->getType(), 232 DL); 233 assert(Src && "Constant folding cannot fail on plain integers"); 234 235 // Shift it to the right place, depending on endianness. 236 Src = ConstantFoldBinaryOpOperands( 237 Instruction::Shl, Src, ConstantInt::get(Src->getType(), ShiftAmt), 238 DL); 239 assert(Src && "Constant folding cannot fail on plain integers"); 240 241 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize; 242 243 // Mix it in. 244 Elt = ConstantFoldBinaryOpOperands(Instruction::Or, Elt, Src, DL); 245 assert(Elt && "Constant folding cannot fail on plain integers"); 246 } 247 Result.push_back(Elt); 248 } 249 return ConstantVector::get(Result); 250 } 251 252 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) 253 unsigned Ratio = NumDstElt/NumSrcElt; 254 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy); 255 256 // Loop over each source value, expanding into multiple results. 257 for (unsigned i = 0; i != NumSrcElt; ++i) { 258 auto *Element = C->getAggregateElement(i); 259 260 if (!Element) // Reject constantexpr elements. 261 return ConstantExpr::getBitCast(C, DestTy); 262 263 if (isa<UndefValue>(Element)) { 264 // Correctly Propagate undef values. 265 Result.append(Ratio, UndefValue::get(DstEltTy)); 266 continue; 267 } 268 269 auto *Src = dyn_cast<ConstantInt>(Element); 270 if (!Src) 271 return ConstantExpr::getBitCast(C, DestTy); 272 273 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1); 274 for (unsigned j = 0; j != Ratio; ++j) { 275 // Shift the piece of the value into the right place, depending on 276 // endianness. 277 APInt Elt = Src->getValue().lshr(ShiftAmt); 278 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize; 279 280 // Truncate and remember this piece. 281 Result.push_back(ConstantInt::get(DstEltTy, Elt.trunc(DstBitSize))); 282 } 283 } 284 285 return ConstantVector::get(Result); 286 } 287 288 } // end anonymous namespace 289 290 /// If this constant is a constant offset from a global, return the global and 291 /// the constant. Because of constantexprs, this function is recursive. 292 bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, 293 APInt &Offset, const DataLayout &DL, 294 DSOLocalEquivalent **DSOEquiv) { 295 if (DSOEquiv) 296 *DSOEquiv = nullptr; 297 298 // Trivial case, constant is the global. 299 if ((GV = dyn_cast<GlobalValue>(C))) { 300 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType()); 301 Offset = APInt(BitWidth, 0); 302 return true; 303 } 304 305 if (auto *FoundDSOEquiv = dyn_cast<DSOLocalEquivalent>(C)) { 306 if (DSOEquiv) 307 *DSOEquiv = FoundDSOEquiv; 308 GV = FoundDSOEquiv->getGlobalValue(); 309 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType()); 310 Offset = APInt(BitWidth, 0); 311 return true; 312 } 313 314 // Otherwise, if this isn't a constant expr, bail out. 315 auto *CE = dyn_cast<ConstantExpr>(C); 316 if (!CE) return false; 317 318 // Look through ptr->int and ptr->ptr casts. 319 if (CE->getOpcode() == Instruction::PtrToInt || 320 CE->getOpcode() == Instruction::BitCast) 321 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL, 322 DSOEquiv); 323 324 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5) 325 auto *GEP = dyn_cast<GEPOperator>(CE); 326 if (!GEP) 327 return false; 328 329 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType()); 330 APInt TmpOffset(BitWidth, 0); 331 332 // If the base isn't a global+constant, we aren't either. 333 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL, 334 DSOEquiv)) 335 return false; 336 337 // Otherwise, add any offset that our operands provide. 338 if (!GEP->accumulateConstantOffset(DL, TmpOffset)) 339 return false; 340 341 Offset = TmpOffset; 342 return true; 343 } 344 345 Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy, 346 const DataLayout &DL) { 347 do { 348 Type *SrcTy = C->getType(); 349 if (SrcTy == DestTy) 350 return C; 351 352 TypeSize DestSize = DL.getTypeSizeInBits(DestTy); 353 TypeSize SrcSize = DL.getTypeSizeInBits(SrcTy); 354 if (!TypeSize::isKnownGE(SrcSize, DestSize)) 355 return nullptr; 356 357 // Catch the obvious splat cases (since all-zeros can coerce non-integral 358 // pointers legally). 359 if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy, DL)) 360 return Res; 361 362 // If the type sizes are the same and a cast is legal, just directly 363 // cast the constant. 364 // But be careful not to coerce non-integral pointers illegally. 365 if (SrcSize == DestSize && 366 DL.isNonIntegralPointerType(SrcTy->getScalarType()) == 367 DL.isNonIntegralPointerType(DestTy->getScalarType())) { 368 Instruction::CastOps Cast = Instruction::BitCast; 369 // If we are going from a pointer to int or vice versa, we spell the cast 370 // differently. 371 if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) 372 Cast = Instruction::IntToPtr; 373 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) 374 Cast = Instruction::PtrToInt; 375 376 if (CastInst::castIsValid(Cast, C, DestTy)) 377 return ConstantFoldCastOperand(Cast, C, DestTy, DL); 378 } 379 380 // If this isn't an aggregate type, there is nothing we can do to drill down 381 // and find a bitcastable constant. 382 if (!SrcTy->isAggregateType() && !SrcTy->isVectorTy()) 383 return nullptr; 384 385 // We're simulating a load through a pointer that was bitcast to point to 386 // a different type, so we can try to walk down through the initial 387 // elements of an aggregate to see if some part of the aggregate is 388 // castable to implement the "load" semantic model. 389 if (SrcTy->isStructTy()) { 390 // Struct types might have leading zero-length elements like [0 x i32], 391 // which are certainly not what we are looking for, so skip them. 392 unsigned Elem = 0; 393 Constant *ElemC; 394 do { 395 ElemC = C->getAggregateElement(Elem++); 396 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero()); 397 C = ElemC; 398 } else { 399 // For non-byte-sized vector elements, the first element is not 400 // necessarily located at the vector base address. 401 if (auto *VT = dyn_cast<VectorType>(SrcTy)) 402 if (!DL.typeSizeEqualsStoreSize(VT->getElementType())) 403 return nullptr; 404 405 C = C->getAggregateElement(0u); 406 } 407 } while (C); 408 409 return nullptr; 410 } 411 412 namespace { 413 414 /// Recursive helper to read bits out of global. C is the constant being copied 415 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy 416 /// results into and BytesLeft is the number of bytes left in 417 /// the CurPtr buffer. DL is the DataLayout. 418 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr, 419 unsigned BytesLeft, const DataLayout &DL) { 420 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) && 421 "Out of range access"); 422 423 // If this element is zero or undefined, we can just return since *CurPtr is 424 // zero initialized. 425 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) 426 return true; 427 428 if (auto *CI = dyn_cast<ConstantInt>(C)) { 429 if ((CI->getBitWidth() & 7) != 0) 430 return false; 431 const APInt &Val = CI->getValue(); 432 unsigned IntBytes = unsigned(CI->getBitWidth()/8); 433 434 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) { 435 unsigned n = ByteOffset; 436 if (!DL.isLittleEndian()) 437 n = IntBytes - n - 1; 438 CurPtr[i] = Val.extractBits(8, n * 8).getZExtValue(); 439 ++ByteOffset; 440 } 441 return true; 442 } 443 444 if (auto *CFP = dyn_cast<ConstantFP>(C)) { 445 if (CFP->getType()->isDoubleTy()) { 446 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL); 447 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 448 } 449 if (CFP->getType()->isFloatTy()){ 450 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL); 451 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 452 } 453 if (CFP->getType()->isHalfTy()){ 454 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL); 455 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 456 } 457 return false; 458 } 459 460 if (auto *CS = dyn_cast<ConstantStruct>(C)) { 461 const StructLayout *SL = DL.getStructLayout(CS->getType()); 462 unsigned Index = SL->getElementContainingOffset(ByteOffset); 463 uint64_t CurEltOffset = SL->getElementOffset(Index); 464 ByteOffset -= CurEltOffset; 465 466 while (true) { 467 // If the element access is to the element itself and not to tail padding, 468 // read the bytes from the element. 469 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType()); 470 471 if (ByteOffset < EltSize && 472 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr, 473 BytesLeft, DL)) 474 return false; 475 476 ++Index; 477 478 // Check to see if we read from the last struct element, if so we're done. 479 if (Index == CS->getType()->getNumElements()) 480 return true; 481 482 // If we read all of the bytes we needed from this element we're done. 483 uint64_t NextEltOffset = SL->getElementOffset(Index); 484 485 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset) 486 return true; 487 488 // Move to the next element of the struct. 489 CurPtr += NextEltOffset - CurEltOffset - ByteOffset; 490 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset; 491 ByteOffset = 0; 492 CurEltOffset = NextEltOffset; 493 } 494 // not reached. 495 } 496 497 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) || 498 isa<ConstantDataSequential>(C)) { 499 uint64_t NumElts, EltSize; 500 Type *EltTy; 501 if (auto *AT = dyn_cast<ArrayType>(C->getType())) { 502 NumElts = AT->getNumElements(); 503 EltTy = AT->getElementType(); 504 EltSize = DL.getTypeAllocSize(EltTy); 505 } else { 506 NumElts = cast<FixedVectorType>(C->getType())->getNumElements(); 507 EltTy = cast<FixedVectorType>(C->getType())->getElementType(); 508 // TODO: For non-byte-sized vectors, current implementation assumes there is 509 // padding to the next byte boundary between elements. 510 if (!DL.typeSizeEqualsStoreSize(EltTy)) 511 return false; 512 513 EltSize = DL.getTypeStoreSize(EltTy); 514 } 515 uint64_t Index = ByteOffset / EltSize; 516 uint64_t Offset = ByteOffset - Index * EltSize; 517 518 for (; Index != NumElts; ++Index) { 519 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr, 520 BytesLeft, DL)) 521 return false; 522 523 uint64_t BytesWritten = EltSize - Offset; 524 assert(BytesWritten <= EltSize && "Not indexing into this element?"); 525 if (BytesWritten >= BytesLeft) 526 return true; 527 528 Offset = 0; 529 BytesLeft -= BytesWritten; 530 CurPtr += BytesWritten; 531 } 532 return true; 533 } 534 535 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 536 if (CE->getOpcode() == Instruction::IntToPtr && 537 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) { 538 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr, 539 BytesLeft, DL); 540 } 541 } 542 543 // Otherwise, unknown initializer type. 544 return false; 545 } 546 547 Constant *FoldReinterpretLoadFromConst(Constant *C, Type *LoadTy, 548 int64_t Offset, const DataLayout &DL) { 549 // Bail out early. Not expect to load from scalable global variable. 550 if (isa<ScalableVectorType>(LoadTy)) 551 return nullptr; 552 553 auto *IntType = dyn_cast<IntegerType>(LoadTy); 554 555 // If this isn't an integer load we can't fold it directly. 556 if (!IntType) { 557 // If this is a non-integer load, we can try folding it as an int load and 558 // then bitcast the result. This can be useful for union cases. Note 559 // that address spaces don't matter here since we're not going to result in 560 // an actual new load. 561 if (!LoadTy->isFloatingPointTy() && !LoadTy->isPointerTy() && 562 !LoadTy->isVectorTy()) 563 return nullptr; 564 565 Type *MapTy = Type::getIntNTy(C->getContext(), 566 DL.getTypeSizeInBits(LoadTy).getFixedValue()); 567 if (Constant *Res = FoldReinterpretLoadFromConst(C, MapTy, Offset, DL)) { 568 if (Res->isNullValue() && !LoadTy->isX86_AMXTy()) 569 // Materializing a zero can be done trivially without a bitcast 570 return Constant::getNullValue(LoadTy); 571 Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy; 572 Res = FoldBitCast(Res, CastTy, DL); 573 if (LoadTy->isPtrOrPtrVectorTy()) { 574 // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr 575 if (Res->isNullValue() && !LoadTy->isX86_AMXTy()) 576 return Constant::getNullValue(LoadTy); 577 if (DL.isNonIntegralPointerType(LoadTy->getScalarType())) 578 // Be careful not to replace a load of an addrspace value with an inttoptr here 579 return nullptr; 580 Res = ConstantExpr::getIntToPtr(Res, LoadTy); 581 } 582 return Res; 583 } 584 return nullptr; 585 } 586 587 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8; 588 if (BytesLoaded > 32 || BytesLoaded == 0) 589 return nullptr; 590 591 // If we're not accessing anything in this constant, the result is undefined. 592 if (Offset <= -1 * static_cast<int64_t>(BytesLoaded)) 593 return PoisonValue::get(IntType); 594 595 // TODO: We should be able to support scalable types. 596 TypeSize InitializerSize = DL.getTypeAllocSize(C->getType()); 597 if (InitializerSize.isScalable()) 598 return nullptr; 599 600 // If we're not accessing anything in this constant, the result is undefined. 601 if (Offset >= (int64_t)InitializerSize.getFixedValue()) 602 return PoisonValue::get(IntType); 603 604 unsigned char RawBytes[32] = {0}; 605 unsigned char *CurPtr = RawBytes; 606 unsigned BytesLeft = BytesLoaded; 607 608 // If we're loading off the beginning of the global, some bytes may be valid. 609 if (Offset < 0) { 610 CurPtr += -Offset; 611 BytesLeft += Offset; 612 Offset = 0; 613 } 614 615 if (!ReadDataFromGlobal(C, Offset, CurPtr, BytesLeft, DL)) 616 return nullptr; 617 618 APInt ResultVal = APInt(IntType->getBitWidth(), 0); 619 if (DL.isLittleEndian()) { 620 ResultVal = RawBytes[BytesLoaded - 1]; 621 for (unsigned i = 1; i != BytesLoaded; ++i) { 622 ResultVal <<= 8; 623 ResultVal |= RawBytes[BytesLoaded - 1 - i]; 624 } 625 } else { 626 ResultVal = RawBytes[0]; 627 for (unsigned i = 1; i != BytesLoaded; ++i) { 628 ResultVal <<= 8; 629 ResultVal |= RawBytes[i]; 630 } 631 } 632 633 return ConstantInt::get(IntType->getContext(), ResultVal); 634 } 635 636 } // anonymous namespace 637 638 // If GV is a constant with an initializer read its representation starting 639 // at Offset and return it as a constant array of unsigned char. Otherwise 640 // return null. 641 Constant *llvm::ReadByteArrayFromGlobal(const GlobalVariable *GV, 642 uint64_t Offset) { 643 if (!GV->isConstant() || !GV->hasDefinitiveInitializer()) 644 return nullptr; 645 646 const DataLayout &DL = GV->getDataLayout(); 647 Constant *Init = const_cast<Constant *>(GV->getInitializer()); 648 TypeSize InitSize = DL.getTypeAllocSize(Init->getType()); 649 if (InitSize < Offset) 650 return nullptr; 651 652 uint64_t NBytes = InitSize - Offset; 653 if (NBytes > UINT16_MAX) 654 // Bail for large initializers in excess of 64K to avoid allocating 655 // too much memory. 656 // Offset is assumed to be less than or equal than InitSize (this 657 // is enforced in ReadDataFromGlobal). 658 return nullptr; 659 660 SmallVector<unsigned char, 256> RawBytes(static_cast<size_t>(NBytes)); 661 unsigned char *CurPtr = RawBytes.data(); 662 663 if (!ReadDataFromGlobal(Init, Offset, CurPtr, NBytes, DL)) 664 return nullptr; 665 666 return ConstantDataArray::get(GV->getContext(), RawBytes); 667 } 668 669 /// If this Offset points exactly to the start of an aggregate element, return 670 /// that element, otherwise return nullptr. 671 Constant *getConstantAtOffset(Constant *Base, APInt Offset, 672 const DataLayout &DL) { 673 if (Offset.isZero()) 674 return Base; 675 676 if (!isa<ConstantAggregate>(Base) && !isa<ConstantDataSequential>(Base)) 677 return nullptr; 678 679 Type *ElemTy = Base->getType(); 680 SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset); 681 if (!Offset.isZero() || !Indices[0].isZero()) 682 return nullptr; 683 684 Constant *C = Base; 685 for (const APInt &Index : drop_begin(Indices)) { 686 if (Index.isNegative() || Index.getActiveBits() >= 32) 687 return nullptr; 688 689 C = C->getAggregateElement(Index.getZExtValue()); 690 if (!C) 691 return nullptr; 692 } 693 694 return C; 695 } 696 697 Constant *llvm::ConstantFoldLoadFromConst(Constant *C, Type *Ty, 698 const APInt &Offset, 699 const DataLayout &DL) { 700 if (Constant *AtOffset = getConstantAtOffset(C, Offset, DL)) 701 if (Constant *Result = ConstantFoldLoadThroughBitcast(AtOffset, Ty, DL)) 702 return Result; 703 704 // Explicitly check for out-of-bounds access, so we return poison even if the 705 // constant is a uniform value. 706 TypeSize Size = DL.getTypeAllocSize(C->getType()); 707 if (!Size.isScalable() && Offset.sge(Size.getFixedValue())) 708 return PoisonValue::get(Ty); 709 710 // Try an offset-independent fold of a uniform value. 711 if (Constant *Result = ConstantFoldLoadFromUniformValue(C, Ty, DL)) 712 return Result; 713 714 // Try hard to fold loads from bitcasted strange and non-type-safe things. 715 if (Offset.getSignificantBits() <= 64) 716 if (Constant *Result = 717 FoldReinterpretLoadFromConst(C, Ty, Offset.getSExtValue(), DL)) 718 return Result; 719 720 return nullptr; 721 } 722 723 Constant *llvm::ConstantFoldLoadFromConst(Constant *C, Type *Ty, 724 const DataLayout &DL) { 725 return ConstantFoldLoadFromConst(C, Ty, APInt(64, 0), DL); 726 } 727 728 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, 729 APInt Offset, 730 const DataLayout &DL) { 731 // We can only fold loads from constant globals with a definitive initializer. 732 // Check this upfront, to skip expensive offset calculations. 733 auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C)); 734 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer()) 735 return nullptr; 736 737 C = cast<Constant>(C->stripAndAccumulateConstantOffsets( 738 DL, Offset, /* AllowNonInbounds */ true)); 739 740 if (C == GV) 741 if (Constant *Result = ConstantFoldLoadFromConst(GV->getInitializer(), Ty, 742 Offset, DL)) 743 return Result; 744 745 // If this load comes from anywhere in a uniform constant global, the value 746 // is always the same, regardless of the loaded offset. 747 return ConstantFoldLoadFromUniformValue(GV->getInitializer(), Ty, DL); 748 } 749 750 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, 751 const DataLayout &DL) { 752 APInt Offset(DL.getIndexTypeSizeInBits(C->getType()), 0); 753 return ConstantFoldLoadFromConstPtr(C, Ty, std::move(Offset), DL); 754 } 755 756 Constant *llvm::ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, 757 const DataLayout &DL) { 758 if (isa<PoisonValue>(C)) 759 return PoisonValue::get(Ty); 760 if (isa<UndefValue>(C)) 761 return UndefValue::get(Ty); 762 // If padding is needed when storing C to memory, then it isn't considered as 763 // uniform. 764 if (!DL.typeSizeEqualsStoreSize(C->getType())) 765 return nullptr; 766 if (C->isNullValue() && !Ty->isX86_AMXTy()) 767 return Constant::getNullValue(Ty); 768 if (C->isAllOnesValue() && 769 (Ty->isIntOrIntVectorTy() || Ty->isFPOrFPVectorTy())) 770 return Constant::getAllOnesValue(Ty); 771 return nullptr; 772 } 773 774 namespace { 775 776 /// One of Op0/Op1 is a constant expression. 777 /// Attempt to symbolically evaluate the result of a binary operator merging 778 /// these together. If target data info is available, it is provided as DL, 779 /// otherwise DL is null. 780 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1, 781 const DataLayout &DL) { 782 // SROA 783 784 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl. 785 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute 786 // bits. 787 788 if (Opc == Instruction::And) { 789 KnownBits Known0 = computeKnownBits(Op0, DL); 790 KnownBits Known1 = computeKnownBits(Op1, DL); 791 if ((Known1.One | Known0.Zero).isAllOnes()) { 792 // All the bits of Op0 that the 'and' could be masking are already zero. 793 return Op0; 794 } 795 if ((Known0.One | Known1.Zero).isAllOnes()) { 796 // All the bits of Op1 that the 'and' could be masking are already zero. 797 return Op1; 798 } 799 800 Known0 &= Known1; 801 if (Known0.isConstant()) 802 return ConstantInt::get(Op0->getType(), Known0.getConstant()); 803 } 804 805 // If the constant expr is something like &A[123] - &A[4].f, fold this into a 806 // constant. This happens frequently when iterating over a global array. 807 if (Opc == Instruction::Sub) { 808 GlobalValue *GV1, *GV2; 809 APInt Offs1, Offs2; 810 811 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL)) 812 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) { 813 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType()); 814 815 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow. 816 // PtrToInt may change the bitwidth so we have convert to the right size 817 // first. 818 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) - 819 Offs2.zextOrTrunc(OpSize)); 820 } 821 } 822 823 return nullptr; 824 } 825 826 /// If array indices are not pointer-sized integers, explicitly cast them so 827 /// that they aren't implicitly casted by the getelementptr. 828 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops, 829 Type *ResultTy, GEPNoWrapFlags NW, 830 std::optional<ConstantRange> InRange, 831 const DataLayout &DL, const TargetLibraryInfo *TLI) { 832 Type *IntIdxTy = DL.getIndexType(ResultTy); 833 Type *IntIdxScalarTy = IntIdxTy->getScalarType(); 834 835 bool Any = false; 836 SmallVector<Constant*, 32> NewIdxs; 837 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 838 if ((i == 1 || 839 !isa<StructType>(GetElementPtrInst::getIndexedType( 840 SrcElemTy, Ops.slice(1, i - 1)))) && 841 Ops[i]->getType()->getScalarType() != IntIdxScalarTy) { 842 Any = true; 843 Type *NewType = 844 Ops[i]->getType()->isVectorTy() ? IntIdxTy : IntIdxScalarTy; 845 Constant *NewIdx = ConstantFoldCastOperand( 846 CastInst::getCastOpcode(Ops[i], true, NewType, true), Ops[i], NewType, 847 DL); 848 if (!NewIdx) 849 return nullptr; 850 NewIdxs.push_back(NewIdx); 851 } else 852 NewIdxs.push_back(Ops[i]); 853 } 854 855 if (!Any) 856 return nullptr; 857 858 Constant *C = 859 ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], NewIdxs, NW, InRange); 860 return ConstantFoldConstant(C, DL, TLI); 861 } 862 863 /// If we can symbolically evaluate the GEP constant expression, do so. 864 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP, 865 ArrayRef<Constant *> Ops, 866 const DataLayout &DL, 867 const TargetLibraryInfo *TLI) { 868 Type *SrcElemTy = GEP->getSourceElementType(); 869 Type *ResTy = GEP->getType(); 870 if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy)) 871 return nullptr; 872 873 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, GEP->getNoWrapFlags(), 874 GEP->getInRange(), DL, TLI)) 875 return C; 876 877 Constant *Ptr = Ops[0]; 878 if (!Ptr->getType()->isPointerTy()) 879 return nullptr; 880 881 Type *IntIdxTy = DL.getIndexType(Ptr->getType()); 882 883 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 884 if (!isa<ConstantInt>(Ops[i]) || !Ops[i]->getType()->isIntegerTy()) 885 return nullptr; 886 887 unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy); 888 APInt Offset = APInt( 889 BitWidth, 890 DL.getIndexedOffsetInType( 891 SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)), 892 /*isSigned=*/true, /*implicitTrunc=*/true); 893 894 std::optional<ConstantRange> InRange = GEP->getInRange(); 895 if (InRange) 896 InRange = InRange->sextOrTrunc(BitWidth); 897 898 // If this is a GEP of a GEP, fold it all into a single GEP. 899 GEPNoWrapFlags NW = GEP->getNoWrapFlags(); 900 bool Overflow = false; 901 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) { 902 NW &= GEP->getNoWrapFlags(); 903 904 SmallVector<Value *, 4> NestedOps(llvm::drop_begin(GEP->operands())); 905 906 // Do not try the incorporate the sub-GEP if some index is not a number. 907 bool AllConstantInt = true; 908 for (Value *NestedOp : NestedOps) 909 if (!isa<ConstantInt>(NestedOp)) { 910 AllConstantInt = false; 911 break; 912 } 913 if (!AllConstantInt) 914 break; 915 916 // TODO: Try to intersect two inrange attributes? 917 if (!InRange) { 918 InRange = GEP->getInRange(); 919 if (InRange) 920 // Adjust inrange by offset until now. 921 InRange = InRange->sextOrTrunc(BitWidth).subtract(Offset); 922 } 923 924 Ptr = cast<Constant>(GEP->getOperand(0)); 925 SrcElemTy = GEP->getSourceElementType(); 926 Offset = Offset.sadd_ov( 927 APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps), 928 /*isSigned=*/true, /*implicitTrunc=*/true), 929 Overflow); 930 } 931 932 // Preserving nusw (without inbounds) also requires that the offset 933 // additions did not overflow. 934 if (NW.hasNoUnsignedSignedWrap() && !NW.isInBounds() && Overflow) 935 NW = NW.withoutNoUnsignedSignedWrap(); 936 937 // If the base value for this address is a literal integer value, fold the 938 // getelementptr to the resulting integer value casted to the pointer type. 939 APInt BasePtr(BitWidth, 0); 940 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) { 941 if (CE->getOpcode() == Instruction::IntToPtr) { 942 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) 943 BasePtr = Base->getValue().zextOrTrunc(BitWidth); 944 } 945 } 946 947 auto *PTy = cast<PointerType>(Ptr->getType()); 948 if ((Ptr->isNullValue() || BasePtr != 0) && 949 !DL.isNonIntegralPointerType(PTy)) { 950 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr); 951 return ConstantExpr::getIntToPtr(C, ResTy); 952 } 953 954 // Try to infer inbounds for GEPs of globals. 955 // TODO(gep_nowrap): Also infer nuw flag. 956 if (!NW.isInBounds() && Offset.isNonNegative()) { 957 bool CanBeNull, CanBeFreed; 958 uint64_t DerefBytes = 959 Ptr->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 960 if (DerefBytes != 0 && !CanBeNull && Offset.sle(DerefBytes)) 961 NW |= GEPNoWrapFlags::inBounds(); 962 } 963 964 // Otherwise canonicalize this to a single ptradd. 965 LLVMContext &Ctx = Ptr->getContext(); 966 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ctx), Ptr, 967 ConstantInt::get(Ctx, Offset), NW, 968 InRange); 969 } 970 971 /// Attempt to constant fold an instruction with the 972 /// specified opcode and operands. If successful, the constant result is 973 /// returned, if not, null is returned. Note that this function can fail when 974 /// attempting to fold instructions like loads and stores, which have no 975 /// constant expression form. 976 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode, 977 ArrayRef<Constant *> Ops, 978 const DataLayout &DL, 979 const TargetLibraryInfo *TLI, 980 bool AllowNonDeterministic) { 981 Type *DestTy = InstOrCE->getType(); 982 983 if (Instruction::isUnaryOp(Opcode)) 984 return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL); 985 986 if (Instruction::isBinaryOp(Opcode)) { 987 switch (Opcode) { 988 default: 989 break; 990 case Instruction::FAdd: 991 case Instruction::FSub: 992 case Instruction::FMul: 993 case Instruction::FDiv: 994 case Instruction::FRem: 995 // Handle floating point instructions separately to account for denormals 996 // TODO: If a constant expression is being folded rather than an 997 // instruction, denormals will not be flushed/treated as zero 998 if (const auto *I = dyn_cast<Instruction>(InstOrCE)) { 999 return ConstantFoldFPInstOperands(Opcode, Ops[0], Ops[1], DL, I, 1000 AllowNonDeterministic); 1001 } 1002 } 1003 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL); 1004 } 1005 1006 if (Instruction::isCast(Opcode)) 1007 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL); 1008 1009 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) { 1010 Type *SrcElemTy = GEP->getSourceElementType(); 1011 if (!ConstantExpr::isSupportedGetElementPtr(SrcElemTy)) 1012 return nullptr; 1013 1014 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI)) 1015 return C; 1016 1017 return ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], Ops.slice(1), 1018 GEP->getNoWrapFlags(), 1019 GEP->getInRange()); 1020 } 1021 1022 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE)) 1023 return CE->getWithOperands(Ops); 1024 1025 switch (Opcode) { 1026 default: return nullptr; 1027 case Instruction::ICmp: 1028 case Instruction::FCmp: { 1029 auto *C = cast<CmpInst>(InstOrCE); 1030 return ConstantFoldCompareInstOperands(C->getPredicate(), Ops[0], Ops[1], 1031 DL, TLI, C); 1032 } 1033 case Instruction::Freeze: 1034 return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr; 1035 case Instruction::Call: 1036 if (auto *F = dyn_cast<Function>(Ops.back())) { 1037 const auto *Call = cast<CallBase>(InstOrCE); 1038 if (canConstantFoldCallTo(Call, F)) 1039 return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI, 1040 AllowNonDeterministic); 1041 } 1042 return nullptr; 1043 case Instruction::Select: 1044 return ConstantFoldSelectInstruction(Ops[0], Ops[1], Ops[2]); 1045 case Instruction::ExtractElement: 1046 return ConstantExpr::getExtractElement(Ops[0], Ops[1]); 1047 case Instruction::ExtractValue: 1048 return ConstantFoldExtractValueInstruction( 1049 Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices()); 1050 case Instruction::InsertElement: 1051 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]); 1052 case Instruction::InsertValue: 1053 return ConstantFoldInsertValueInstruction( 1054 Ops[0], Ops[1], cast<InsertValueInst>(InstOrCE)->getIndices()); 1055 case Instruction::ShuffleVector: 1056 return ConstantExpr::getShuffleVector( 1057 Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask()); 1058 case Instruction::Load: { 1059 const auto *LI = dyn_cast<LoadInst>(InstOrCE); 1060 if (LI->isVolatile()) 1061 return nullptr; 1062 return ConstantFoldLoadFromConstPtr(Ops[0], LI->getType(), DL); 1063 } 1064 } 1065 } 1066 1067 } // end anonymous namespace 1068 1069 //===----------------------------------------------------------------------===// 1070 // Constant Folding public APIs 1071 //===----------------------------------------------------------------------===// 1072 1073 namespace { 1074 1075 Constant * 1076 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL, 1077 const TargetLibraryInfo *TLI, 1078 SmallDenseMap<Constant *, Constant *> &FoldedOps) { 1079 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C)) 1080 return const_cast<Constant *>(C); 1081 1082 SmallVector<Constant *, 8> Ops; 1083 for (const Use &OldU : C->operands()) { 1084 Constant *OldC = cast<Constant>(&OldU); 1085 Constant *NewC = OldC; 1086 // Recursively fold the ConstantExpr's operands. If we have already folded 1087 // a ConstantExpr, we don't have to process it again. 1088 if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) { 1089 auto It = FoldedOps.find(OldC); 1090 if (It == FoldedOps.end()) { 1091 NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps); 1092 FoldedOps.insert({OldC, NewC}); 1093 } else { 1094 NewC = It->second; 1095 } 1096 } 1097 Ops.push_back(NewC); 1098 } 1099 1100 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1101 if (Constant *Res = ConstantFoldInstOperandsImpl( 1102 CE, CE->getOpcode(), Ops, DL, TLI, /*AllowNonDeterministic=*/true)) 1103 return Res; 1104 return const_cast<Constant *>(C); 1105 } 1106 1107 assert(isa<ConstantVector>(C)); 1108 return ConstantVector::get(Ops); 1109 } 1110 1111 } // end anonymous namespace 1112 1113 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL, 1114 const TargetLibraryInfo *TLI) { 1115 // Handle PHI nodes quickly here... 1116 if (auto *PN = dyn_cast<PHINode>(I)) { 1117 Constant *CommonValue = nullptr; 1118 1119 SmallDenseMap<Constant *, Constant *> FoldedOps; 1120 for (Value *Incoming : PN->incoming_values()) { 1121 // If the incoming value is undef then skip it. Note that while we could 1122 // skip the value if it is equal to the phi node itself we choose not to 1123 // because that would break the rule that constant folding only applies if 1124 // all operands are constants. 1125 if (isa<UndefValue>(Incoming)) 1126 continue; 1127 // If the incoming value is not a constant, then give up. 1128 auto *C = dyn_cast<Constant>(Incoming); 1129 if (!C) 1130 return nullptr; 1131 // Fold the PHI's operands. 1132 C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps); 1133 // If the incoming value is a different constant to 1134 // the one we saw previously, then give up. 1135 if (CommonValue && C != CommonValue) 1136 return nullptr; 1137 CommonValue = C; 1138 } 1139 1140 // If we reach here, all incoming values are the same constant or undef. 1141 return CommonValue ? CommonValue : UndefValue::get(PN->getType()); 1142 } 1143 1144 // Scan the operand list, checking to see if they are all constants, if so, 1145 // hand off to ConstantFoldInstOperandsImpl. 1146 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); })) 1147 return nullptr; 1148 1149 SmallDenseMap<Constant *, Constant *> FoldedOps; 1150 SmallVector<Constant *, 8> Ops; 1151 for (const Use &OpU : I->operands()) { 1152 auto *Op = cast<Constant>(&OpU); 1153 // Fold the Instruction's operands. 1154 Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps); 1155 Ops.push_back(Op); 1156 } 1157 1158 return ConstantFoldInstOperands(I, Ops, DL, TLI); 1159 } 1160 1161 Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL, 1162 const TargetLibraryInfo *TLI) { 1163 SmallDenseMap<Constant *, Constant *> FoldedOps; 1164 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps); 1165 } 1166 1167 Constant *llvm::ConstantFoldInstOperands(Instruction *I, 1168 ArrayRef<Constant *> Ops, 1169 const DataLayout &DL, 1170 const TargetLibraryInfo *TLI, 1171 bool AllowNonDeterministic) { 1172 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI, 1173 AllowNonDeterministic); 1174 } 1175 1176 Constant *llvm::ConstantFoldCompareInstOperands( 1177 unsigned IntPredicate, Constant *Ops0, Constant *Ops1, const DataLayout &DL, 1178 const TargetLibraryInfo *TLI, const Instruction *I) { 1179 CmpInst::Predicate Predicate = (CmpInst::Predicate)IntPredicate; 1180 // fold: icmp (inttoptr x), null -> icmp x, 0 1181 // fold: icmp null, (inttoptr x) -> icmp 0, x 1182 // fold: icmp (ptrtoint x), 0 -> icmp x, null 1183 // fold: icmp 0, (ptrtoint x) -> icmp null, x 1184 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y 1185 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y 1186 // 1187 // FIXME: The following comment is out of data and the DataLayout is here now. 1188 // ConstantExpr::getCompare cannot do this, because it doesn't have DL 1189 // around to know if bit truncation is happening. 1190 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) { 1191 if (Ops1->isNullValue()) { 1192 if (CE0->getOpcode() == Instruction::IntToPtr) { 1193 Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); 1194 // Convert the integer value to the right size to ensure we get the 1195 // proper extension or truncation. 1196 if (Constant *C = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy, 1197 /*IsSigned*/ false, DL)) { 1198 Constant *Null = Constant::getNullValue(C->getType()); 1199 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); 1200 } 1201 } 1202 1203 // Only do this transformation if the int is intptrty in size, otherwise 1204 // there is a truncation or extension that we aren't modeling. 1205 if (CE0->getOpcode() == Instruction::PtrToInt) { 1206 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); 1207 if (CE0->getType() == IntPtrTy) { 1208 Constant *C = CE0->getOperand(0); 1209 Constant *Null = Constant::getNullValue(C->getType()); 1210 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); 1211 } 1212 } 1213 } 1214 1215 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) { 1216 if (CE0->getOpcode() == CE1->getOpcode()) { 1217 if (CE0->getOpcode() == Instruction::IntToPtr) { 1218 Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); 1219 1220 // Convert the integer value to the right size to ensure we get the 1221 // proper extension or truncation. 1222 Constant *C0 = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy, 1223 /*IsSigned*/ false, DL); 1224 Constant *C1 = ConstantFoldIntegerCast(CE1->getOperand(0), IntPtrTy, 1225 /*IsSigned*/ false, DL); 1226 if (C0 && C1) 1227 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI); 1228 } 1229 1230 // Only do this transformation if the int is intptrty in size, otherwise 1231 // there is a truncation or extension that we aren't modeling. 1232 if (CE0->getOpcode() == Instruction::PtrToInt) { 1233 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); 1234 if (CE0->getType() == IntPtrTy && 1235 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) { 1236 return ConstantFoldCompareInstOperands( 1237 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI); 1238 } 1239 } 1240 } 1241 } 1242 1243 // Convert pointer comparison (base+offset1) pred (base+offset2) into 1244 // offset1 pred offset2, for the case where the offset is inbounds. This 1245 // only works for equality and unsigned comparison, as inbounds permits 1246 // crossing the sign boundary. However, the offset comparison itself is 1247 // signed. 1248 if (Ops0->getType()->isPointerTy() && !ICmpInst::isSigned(Predicate)) { 1249 unsigned IndexWidth = DL.getIndexTypeSizeInBits(Ops0->getType()); 1250 APInt Offset0(IndexWidth, 0); 1251 Value *Stripped0 = 1252 Ops0->stripAndAccumulateInBoundsConstantOffsets(DL, Offset0); 1253 APInt Offset1(IndexWidth, 0); 1254 Value *Stripped1 = 1255 Ops1->stripAndAccumulateInBoundsConstantOffsets(DL, Offset1); 1256 if (Stripped0 == Stripped1) 1257 return ConstantInt::getBool( 1258 Ops0->getContext(), 1259 ICmpInst::compare(Offset0, Offset1, 1260 ICmpInst::getSignedPredicate(Predicate))); 1261 } 1262 } else if (isa<ConstantExpr>(Ops1)) { 1263 // If RHS is a constant expression, but the left side isn't, swap the 1264 // operands and try again. 1265 Predicate = ICmpInst::getSwappedPredicate(Predicate); 1266 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI); 1267 } 1268 1269 if (CmpInst::isFPPredicate(Predicate)) { 1270 // Flush any denormal constant float input according to denormal handling 1271 // mode. 1272 Ops0 = FlushFPConstant(Ops0, I, /*IsOutput=*/false); 1273 if (!Ops0) 1274 return nullptr; 1275 Ops1 = FlushFPConstant(Ops1, I, /*IsOutput=*/false); 1276 if (!Ops1) 1277 return nullptr; 1278 } 1279 1280 return ConstantFoldCompareInstruction(Predicate, Ops0, Ops1); 1281 } 1282 1283 Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, 1284 const DataLayout &DL) { 1285 assert(Instruction::isUnaryOp(Opcode)); 1286 1287 return ConstantFoldUnaryInstruction(Opcode, Op); 1288 } 1289 1290 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, 1291 Constant *RHS, 1292 const DataLayout &DL) { 1293 assert(Instruction::isBinaryOp(Opcode)); 1294 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS)) 1295 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL)) 1296 return C; 1297 1298 if (ConstantExpr::isDesirableBinOp(Opcode)) 1299 return ConstantExpr::get(Opcode, LHS, RHS); 1300 return ConstantFoldBinaryInstruction(Opcode, LHS, RHS); 1301 } 1302 1303 static ConstantFP *flushDenormalConstant(Type *Ty, const APFloat &APF, 1304 DenormalMode::DenormalModeKind Mode) { 1305 switch (Mode) { 1306 case DenormalMode::Dynamic: 1307 return nullptr; 1308 case DenormalMode::IEEE: 1309 return ConstantFP::get(Ty->getContext(), APF); 1310 case DenormalMode::PreserveSign: 1311 return ConstantFP::get( 1312 Ty->getContext(), 1313 APFloat::getZero(APF.getSemantics(), APF.isNegative())); 1314 case DenormalMode::PositiveZero: 1315 return ConstantFP::get(Ty->getContext(), 1316 APFloat::getZero(APF.getSemantics(), false)); 1317 default: 1318 break; 1319 } 1320 1321 llvm_unreachable("unknown denormal mode"); 1322 } 1323 1324 /// Return the denormal mode that can be assumed when executing a floating point 1325 /// operation at \p CtxI. 1326 static DenormalMode getInstrDenormalMode(const Instruction *CtxI, Type *Ty) { 1327 if (!CtxI || !CtxI->getParent() || !CtxI->getFunction()) 1328 return DenormalMode::getDynamic(); 1329 return CtxI->getFunction()->getDenormalMode(Ty->getFltSemantics()); 1330 } 1331 1332 static ConstantFP *flushDenormalConstantFP(ConstantFP *CFP, 1333 const Instruction *Inst, 1334 bool IsOutput) { 1335 const APFloat &APF = CFP->getValueAPF(); 1336 if (!APF.isDenormal()) 1337 return CFP; 1338 1339 DenormalMode Mode = getInstrDenormalMode(Inst, CFP->getType()); 1340 return flushDenormalConstant(CFP->getType(), APF, 1341 IsOutput ? Mode.Output : Mode.Input); 1342 } 1343 1344 Constant *llvm::FlushFPConstant(Constant *Operand, const Instruction *Inst, 1345 bool IsOutput) { 1346 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Operand)) 1347 return flushDenormalConstantFP(CFP, Inst, IsOutput); 1348 1349 if (isa<ConstantAggregateZero, UndefValue, ConstantExpr>(Operand)) 1350 return Operand; 1351 1352 Type *Ty = Operand->getType(); 1353 VectorType *VecTy = dyn_cast<VectorType>(Ty); 1354 if (VecTy) { 1355 if (auto *Splat = dyn_cast_or_null<ConstantFP>(Operand->getSplatValue())) { 1356 ConstantFP *Folded = flushDenormalConstantFP(Splat, Inst, IsOutput); 1357 if (!Folded) 1358 return nullptr; 1359 return ConstantVector::getSplat(VecTy->getElementCount(), Folded); 1360 } 1361 1362 Ty = VecTy->getElementType(); 1363 } 1364 1365 if (const auto *CV = dyn_cast<ConstantVector>(Operand)) { 1366 SmallVector<Constant *, 16> NewElts; 1367 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 1368 Constant *Element = CV->getAggregateElement(i); 1369 if (isa<UndefValue>(Element)) { 1370 NewElts.push_back(Element); 1371 continue; 1372 } 1373 1374 ConstantFP *CFP = dyn_cast<ConstantFP>(Element); 1375 if (!CFP) 1376 return nullptr; 1377 1378 ConstantFP *Folded = flushDenormalConstantFP(CFP, Inst, IsOutput); 1379 if (!Folded) 1380 return nullptr; 1381 NewElts.push_back(Folded); 1382 } 1383 1384 return ConstantVector::get(NewElts); 1385 } 1386 1387 if (const auto *CDV = dyn_cast<ConstantDataVector>(Operand)) { 1388 SmallVector<Constant *, 16> NewElts; 1389 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I) { 1390 const APFloat &Elt = CDV->getElementAsAPFloat(I); 1391 if (!Elt.isDenormal()) { 1392 NewElts.push_back(ConstantFP::get(Ty, Elt)); 1393 } else { 1394 DenormalMode Mode = getInstrDenormalMode(Inst, Ty); 1395 ConstantFP *Folded = 1396 flushDenormalConstant(Ty, Elt, IsOutput ? Mode.Output : Mode.Input); 1397 if (!Folded) 1398 return nullptr; 1399 NewElts.push_back(Folded); 1400 } 1401 } 1402 1403 return ConstantVector::get(NewElts); 1404 } 1405 1406 return nullptr; 1407 } 1408 1409 Constant *llvm::ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS, 1410 Constant *RHS, const DataLayout &DL, 1411 const Instruction *I, 1412 bool AllowNonDeterministic) { 1413 if (Instruction::isBinaryOp(Opcode)) { 1414 // Flush denormal inputs if needed. 1415 Constant *Op0 = FlushFPConstant(LHS, I, /* IsOutput */ false); 1416 if (!Op0) 1417 return nullptr; 1418 Constant *Op1 = FlushFPConstant(RHS, I, /* IsOutput */ false); 1419 if (!Op1) 1420 return nullptr; 1421 1422 // If nsz or an algebraic FMF flag is set, the result of the FP operation 1423 // may change due to future optimization. Don't constant fold them if 1424 // non-deterministic results are not allowed. 1425 if (!AllowNonDeterministic) 1426 if (auto *FP = dyn_cast_or_null<FPMathOperator>(I)) 1427 if (FP->hasNoSignedZeros() || FP->hasAllowReassoc() || 1428 FP->hasAllowContract() || FP->hasAllowReciprocal()) 1429 return nullptr; 1430 1431 // Calculate constant result. 1432 Constant *C = ConstantFoldBinaryOpOperands(Opcode, Op0, Op1, DL); 1433 if (!C) 1434 return nullptr; 1435 1436 // Flush denormal output if needed. 1437 C = FlushFPConstant(C, I, /* IsOutput */ true); 1438 if (!C) 1439 return nullptr; 1440 1441 // The precise NaN value is non-deterministic. 1442 if (!AllowNonDeterministic && C->isNaN()) 1443 return nullptr; 1444 1445 return C; 1446 } 1447 // If instruction lacks a parent/function and the denormal mode cannot be 1448 // determined, use the default (IEEE). 1449 return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL); 1450 } 1451 1452 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C, 1453 Type *DestTy, const DataLayout &DL) { 1454 assert(Instruction::isCast(Opcode)); 1455 switch (Opcode) { 1456 default: 1457 llvm_unreachable("Missing case"); 1458 case Instruction::PtrToInt: 1459 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1460 Constant *FoldedValue = nullptr; 1461 // If the input is a inttoptr, eliminate the pair. This requires knowing 1462 // the width of a pointer, so it can't be done in ConstantExpr::getCast. 1463 if (CE->getOpcode() == Instruction::IntToPtr) { 1464 // zext/trunc the inttoptr to pointer size. 1465 FoldedValue = ConstantFoldIntegerCast(CE->getOperand(0), 1466 DL.getIntPtrType(CE->getType()), 1467 /*IsSigned=*/false, DL); 1468 } else if (auto *GEP = dyn_cast<GEPOperator>(CE)) { 1469 // If we have GEP, we can perform the following folds: 1470 // (ptrtoint (gep null, x)) -> x 1471 // (ptrtoint (gep (gep null, x), y) -> x + y, etc. 1472 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType()); 1473 APInt BaseOffset(BitWidth, 0); 1474 auto *Base = cast<Constant>(GEP->stripAndAccumulateConstantOffsets( 1475 DL, BaseOffset, /*AllowNonInbounds=*/true)); 1476 if (Base->isNullValue()) { 1477 FoldedValue = ConstantInt::get(CE->getContext(), BaseOffset); 1478 } else { 1479 // ptrtoint (gep i8, Ptr, (sub 0, V)) -> sub (ptrtoint Ptr), V 1480 if (GEP->getNumIndices() == 1 && 1481 GEP->getSourceElementType()->isIntegerTy(8)) { 1482 auto *Ptr = cast<Constant>(GEP->getPointerOperand()); 1483 auto *Sub = dyn_cast<ConstantExpr>(GEP->getOperand(1)); 1484 Type *IntIdxTy = DL.getIndexType(Ptr->getType()); 1485 if (Sub && Sub->getType() == IntIdxTy && 1486 Sub->getOpcode() == Instruction::Sub && 1487 Sub->getOperand(0)->isNullValue()) 1488 FoldedValue = ConstantExpr::getSub( 1489 ConstantExpr::getPtrToInt(Ptr, IntIdxTy), Sub->getOperand(1)); 1490 } 1491 } 1492 } 1493 if (FoldedValue) { 1494 // Do a zext or trunc to get to the ptrtoint dest size. 1495 return ConstantFoldIntegerCast(FoldedValue, DestTy, /*IsSigned=*/false, 1496 DL); 1497 } 1498 } 1499 break; 1500 case Instruction::IntToPtr: 1501 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if 1502 // the int size is >= the ptr size and the address spaces are the same. 1503 // This requires knowing the width of a pointer, so it can't be done in 1504 // ConstantExpr::getCast. 1505 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1506 if (CE->getOpcode() == Instruction::PtrToInt) { 1507 Constant *SrcPtr = CE->getOperand(0); 1508 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType()); 1509 unsigned MidIntSize = CE->getType()->getScalarSizeInBits(); 1510 1511 if (MidIntSize >= SrcPtrSize) { 1512 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace(); 1513 if (SrcAS == DestTy->getPointerAddressSpace()) 1514 return FoldBitCast(CE->getOperand(0), DestTy, DL); 1515 } 1516 } 1517 } 1518 break; 1519 case Instruction::Trunc: 1520 case Instruction::ZExt: 1521 case Instruction::SExt: 1522 case Instruction::FPTrunc: 1523 case Instruction::FPExt: 1524 case Instruction::UIToFP: 1525 case Instruction::SIToFP: 1526 case Instruction::FPToUI: 1527 case Instruction::FPToSI: 1528 case Instruction::AddrSpaceCast: 1529 break; 1530 case Instruction::BitCast: 1531 return FoldBitCast(C, DestTy, DL); 1532 } 1533 1534 if (ConstantExpr::isDesirableCastOp(Opcode)) 1535 return ConstantExpr::getCast(Opcode, C, DestTy); 1536 return ConstantFoldCastInstruction(Opcode, C, DestTy); 1537 } 1538 1539 Constant *llvm::ConstantFoldIntegerCast(Constant *C, Type *DestTy, 1540 bool IsSigned, const DataLayout &DL) { 1541 Type *SrcTy = C->getType(); 1542 if (SrcTy == DestTy) 1543 return C; 1544 if (SrcTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits()) 1545 return ConstantFoldCastOperand(Instruction::Trunc, C, DestTy, DL); 1546 if (IsSigned) 1547 return ConstantFoldCastOperand(Instruction::SExt, C, DestTy, DL); 1548 return ConstantFoldCastOperand(Instruction::ZExt, C, DestTy, DL); 1549 } 1550 1551 //===----------------------------------------------------------------------===// 1552 // Constant Folding for Calls 1553 // 1554 1555 bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) { 1556 if (Call->isNoBuiltin()) 1557 return false; 1558 if (Call->getFunctionType() != F->getFunctionType()) 1559 return false; 1560 switch (F->getIntrinsicID()) { 1561 // Operations that do not operate floating-point numbers and do not depend on 1562 // FP environment can be folded even in strictfp functions. 1563 case Intrinsic::bswap: 1564 case Intrinsic::ctpop: 1565 case Intrinsic::ctlz: 1566 case Intrinsic::cttz: 1567 case Intrinsic::fshl: 1568 case Intrinsic::fshr: 1569 case Intrinsic::launder_invariant_group: 1570 case Intrinsic::strip_invariant_group: 1571 case Intrinsic::masked_load: 1572 case Intrinsic::get_active_lane_mask: 1573 case Intrinsic::abs: 1574 case Intrinsic::smax: 1575 case Intrinsic::smin: 1576 case Intrinsic::umax: 1577 case Intrinsic::umin: 1578 case Intrinsic::scmp: 1579 case Intrinsic::ucmp: 1580 case Intrinsic::sadd_with_overflow: 1581 case Intrinsic::uadd_with_overflow: 1582 case Intrinsic::ssub_with_overflow: 1583 case Intrinsic::usub_with_overflow: 1584 case Intrinsic::smul_with_overflow: 1585 case Intrinsic::umul_with_overflow: 1586 case Intrinsic::sadd_sat: 1587 case Intrinsic::uadd_sat: 1588 case Intrinsic::ssub_sat: 1589 case Intrinsic::usub_sat: 1590 case Intrinsic::smul_fix: 1591 case Intrinsic::smul_fix_sat: 1592 case Intrinsic::bitreverse: 1593 case Intrinsic::is_constant: 1594 case Intrinsic::vector_reduce_add: 1595 case Intrinsic::vector_reduce_mul: 1596 case Intrinsic::vector_reduce_and: 1597 case Intrinsic::vector_reduce_or: 1598 case Intrinsic::vector_reduce_xor: 1599 case Intrinsic::vector_reduce_smin: 1600 case Intrinsic::vector_reduce_smax: 1601 case Intrinsic::vector_reduce_umin: 1602 case Intrinsic::vector_reduce_umax: 1603 // Target intrinsics 1604 case Intrinsic::amdgcn_perm: 1605 case Intrinsic::amdgcn_wave_reduce_umin: 1606 case Intrinsic::amdgcn_wave_reduce_umax: 1607 case Intrinsic::amdgcn_s_wqm: 1608 case Intrinsic::amdgcn_s_quadmask: 1609 case Intrinsic::amdgcn_s_bitreplicate: 1610 case Intrinsic::arm_mve_vctp8: 1611 case Intrinsic::arm_mve_vctp16: 1612 case Intrinsic::arm_mve_vctp32: 1613 case Intrinsic::arm_mve_vctp64: 1614 case Intrinsic::aarch64_sve_convert_from_svbool: 1615 // WebAssembly float semantics are always known 1616 case Intrinsic::wasm_trunc_signed: 1617 case Intrinsic::wasm_trunc_unsigned: 1618 return true; 1619 1620 // Floating point operations cannot be folded in strictfp functions in 1621 // general case. They can be folded if FP environment is known to compiler. 1622 case Intrinsic::minnum: 1623 case Intrinsic::maxnum: 1624 case Intrinsic::minimum: 1625 case Intrinsic::maximum: 1626 case Intrinsic::log: 1627 case Intrinsic::log2: 1628 case Intrinsic::log10: 1629 case Intrinsic::exp: 1630 case Intrinsic::exp2: 1631 case Intrinsic::exp10: 1632 case Intrinsic::sqrt: 1633 case Intrinsic::sin: 1634 case Intrinsic::cos: 1635 case Intrinsic::sincos: 1636 case Intrinsic::pow: 1637 case Intrinsic::powi: 1638 case Intrinsic::ldexp: 1639 case Intrinsic::fma: 1640 case Intrinsic::fmuladd: 1641 case Intrinsic::frexp: 1642 case Intrinsic::fptoui_sat: 1643 case Intrinsic::fptosi_sat: 1644 case Intrinsic::convert_from_fp16: 1645 case Intrinsic::convert_to_fp16: 1646 case Intrinsic::amdgcn_cos: 1647 case Intrinsic::amdgcn_cubeid: 1648 case Intrinsic::amdgcn_cubema: 1649 case Intrinsic::amdgcn_cubesc: 1650 case Intrinsic::amdgcn_cubetc: 1651 case Intrinsic::amdgcn_fmul_legacy: 1652 case Intrinsic::amdgcn_fma_legacy: 1653 case Intrinsic::amdgcn_fract: 1654 case Intrinsic::amdgcn_sin: 1655 // The intrinsics below depend on rounding mode in MXCSR. 1656 case Intrinsic::x86_sse_cvtss2si: 1657 case Intrinsic::x86_sse_cvtss2si64: 1658 case Intrinsic::x86_sse_cvttss2si: 1659 case Intrinsic::x86_sse_cvttss2si64: 1660 case Intrinsic::x86_sse2_cvtsd2si: 1661 case Intrinsic::x86_sse2_cvtsd2si64: 1662 case Intrinsic::x86_sse2_cvttsd2si: 1663 case Intrinsic::x86_sse2_cvttsd2si64: 1664 case Intrinsic::x86_avx512_vcvtss2si32: 1665 case Intrinsic::x86_avx512_vcvtss2si64: 1666 case Intrinsic::x86_avx512_cvttss2si: 1667 case Intrinsic::x86_avx512_cvttss2si64: 1668 case Intrinsic::x86_avx512_vcvtsd2si32: 1669 case Intrinsic::x86_avx512_vcvtsd2si64: 1670 case Intrinsic::x86_avx512_cvttsd2si: 1671 case Intrinsic::x86_avx512_cvttsd2si64: 1672 case Intrinsic::x86_avx512_vcvtss2usi32: 1673 case Intrinsic::x86_avx512_vcvtss2usi64: 1674 case Intrinsic::x86_avx512_cvttss2usi: 1675 case Intrinsic::x86_avx512_cvttss2usi64: 1676 case Intrinsic::x86_avx512_vcvtsd2usi32: 1677 case Intrinsic::x86_avx512_vcvtsd2usi64: 1678 case Intrinsic::x86_avx512_cvttsd2usi: 1679 case Intrinsic::x86_avx512_cvttsd2usi64: 1680 return !Call->isStrictFP(); 1681 1682 // Sign operations are actually bitwise operations, they do not raise 1683 // exceptions even for SNANs. 1684 case Intrinsic::fabs: 1685 case Intrinsic::copysign: 1686 case Intrinsic::is_fpclass: 1687 // Non-constrained variants of rounding operations means default FP 1688 // environment, they can be folded in any case. 1689 case Intrinsic::ceil: 1690 case Intrinsic::floor: 1691 case Intrinsic::round: 1692 case Intrinsic::roundeven: 1693 case Intrinsic::trunc: 1694 case Intrinsic::nearbyint: 1695 case Intrinsic::rint: 1696 case Intrinsic::canonicalize: 1697 // Constrained intrinsics can be folded if FP environment is known 1698 // to compiler. 1699 case Intrinsic::experimental_constrained_fma: 1700 case Intrinsic::experimental_constrained_fmuladd: 1701 case Intrinsic::experimental_constrained_fadd: 1702 case Intrinsic::experimental_constrained_fsub: 1703 case Intrinsic::experimental_constrained_fmul: 1704 case Intrinsic::experimental_constrained_fdiv: 1705 case Intrinsic::experimental_constrained_frem: 1706 case Intrinsic::experimental_constrained_ceil: 1707 case Intrinsic::experimental_constrained_floor: 1708 case Intrinsic::experimental_constrained_round: 1709 case Intrinsic::experimental_constrained_roundeven: 1710 case Intrinsic::experimental_constrained_trunc: 1711 case Intrinsic::experimental_constrained_nearbyint: 1712 case Intrinsic::experimental_constrained_rint: 1713 case Intrinsic::experimental_constrained_fcmp: 1714 case Intrinsic::experimental_constrained_fcmps: 1715 return true; 1716 default: 1717 return false; 1718 case Intrinsic::not_intrinsic: break; 1719 } 1720 1721 if (!F->hasName() || Call->isStrictFP()) 1722 return false; 1723 1724 // In these cases, the check of the length is required. We don't want to 1725 // return true for a name like "cos\0blah" which strcmp would return equal to 1726 // "cos", but has length 8. 1727 StringRef Name = F->getName(); 1728 switch (Name[0]) { 1729 default: 1730 return false; 1731 case 'a': 1732 return Name == "acos" || Name == "acosf" || 1733 Name == "asin" || Name == "asinf" || 1734 Name == "atan" || Name == "atanf" || 1735 Name == "atan2" || Name == "atan2f"; 1736 case 'c': 1737 return Name == "ceil" || Name == "ceilf" || 1738 Name == "cos" || Name == "cosf" || 1739 Name == "cosh" || Name == "coshf"; 1740 case 'e': 1741 return Name == "exp" || Name == "expf" || Name == "exp2" || 1742 Name == "exp2f" || Name == "erf" || Name == "erff"; 1743 case 'f': 1744 return Name == "fabs" || Name == "fabsf" || 1745 Name == "floor" || Name == "floorf" || 1746 Name == "fmod" || Name == "fmodf"; 1747 case 'i': 1748 return Name == "ilogb" || Name == "ilogbf"; 1749 case 'l': 1750 return Name == "log" || Name == "logf" || Name == "logl" || 1751 Name == "log2" || Name == "log2f" || Name == "log10" || 1752 Name == "log10f" || Name == "logb" || Name == "logbf" || 1753 Name == "log1p" || Name == "log1pf"; 1754 case 'n': 1755 return Name == "nearbyint" || Name == "nearbyintf"; 1756 case 'p': 1757 return Name == "pow" || Name == "powf"; 1758 case 'r': 1759 return Name == "remainder" || Name == "remainderf" || 1760 Name == "rint" || Name == "rintf" || 1761 Name == "round" || Name == "roundf"; 1762 case 's': 1763 return Name == "sin" || Name == "sinf" || 1764 Name == "sinh" || Name == "sinhf" || 1765 Name == "sqrt" || Name == "sqrtf"; 1766 case 't': 1767 return Name == "tan" || Name == "tanf" || 1768 Name == "tanh" || Name == "tanhf" || 1769 Name == "trunc" || Name == "truncf"; 1770 case '_': 1771 // Check for various function names that get used for the math functions 1772 // when the header files are preprocessed with the macro 1773 // __FINITE_MATH_ONLY__ enabled. 1774 // The '12' here is the length of the shortest name that can match. 1775 // We need to check the size before looking at Name[1] and Name[2] 1776 // so we may as well check a limit that will eliminate mismatches. 1777 if (Name.size() < 12 || Name[1] != '_') 1778 return false; 1779 switch (Name[2]) { 1780 default: 1781 return false; 1782 case 'a': 1783 return Name == "__acos_finite" || Name == "__acosf_finite" || 1784 Name == "__asin_finite" || Name == "__asinf_finite" || 1785 Name == "__atan2_finite" || Name == "__atan2f_finite"; 1786 case 'c': 1787 return Name == "__cosh_finite" || Name == "__coshf_finite"; 1788 case 'e': 1789 return Name == "__exp_finite" || Name == "__expf_finite" || 1790 Name == "__exp2_finite" || Name == "__exp2f_finite"; 1791 case 'l': 1792 return Name == "__log_finite" || Name == "__logf_finite" || 1793 Name == "__log10_finite" || Name == "__log10f_finite"; 1794 case 'p': 1795 return Name == "__pow_finite" || Name == "__powf_finite"; 1796 case 's': 1797 return Name == "__sinh_finite" || Name == "__sinhf_finite"; 1798 } 1799 } 1800 } 1801 1802 namespace { 1803 1804 Constant *GetConstantFoldFPValue(double V, Type *Ty) { 1805 if (Ty->isHalfTy() || Ty->isFloatTy()) { 1806 APFloat APF(V); 1807 bool unused; 1808 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused); 1809 return ConstantFP::get(Ty->getContext(), APF); 1810 } 1811 if (Ty->isDoubleTy()) 1812 return ConstantFP::get(Ty->getContext(), APFloat(V)); 1813 llvm_unreachable("Can only constant fold half/float/double"); 1814 } 1815 1816 #if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128) 1817 Constant *GetConstantFoldFPValue128(float128 V, Type *Ty) { 1818 if (Ty->isFP128Ty()) 1819 return ConstantFP::get(Ty, V); 1820 llvm_unreachable("Can only constant fold fp128"); 1821 } 1822 #endif 1823 1824 /// Clear the floating-point exception state. 1825 inline void llvm_fenv_clearexcept() { 1826 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT 1827 feclearexcept(FE_ALL_EXCEPT); 1828 #endif 1829 errno = 0; 1830 } 1831 1832 /// Test if a floating-point exception was raised. 1833 inline bool llvm_fenv_testexcept() { 1834 int errno_val = errno; 1835 if (errno_val == ERANGE || errno_val == EDOM) 1836 return true; 1837 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT 1838 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT)) 1839 return true; 1840 #endif 1841 return false; 1842 } 1843 1844 Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V, 1845 Type *Ty) { 1846 llvm_fenv_clearexcept(); 1847 double Result = NativeFP(V.convertToDouble()); 1848 if (llvm_fenv_testexcept()) { 1849 llvm_fenv_clearexcept(); 1850 return nullptr; 1851 } 1852 1853 return GetConstantFoldFPValue(Result, Ty); 1854 } 1855 1856 #if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128) 1857 Constant *ConstantFoldFP128(float128 (*NativeFP)(float128), const APFloat &V, 1858 Type *Ty) { 1859 llvm_fenv_clearexcept(); 1860 float128 Result = NativeFP(V.convertToQuad()); 1861 if (llvm_fenv_testexcept()) { 1862 llvm_fenv_clearexcept(); 1863 return nullptr; 1864 } 1865 1866 return GetConstantFoldFPValue128(Result, Ty); 1867 } 1868 #endif 1869 1870 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), 1871 const APFloat &V, const APFloat &W, Type *Ty) { 1872 llvm_fenv_clearexcept(); 1873 double Result = NativeFP(V.convertToDouble(), W.convertToDouble()); 1874 if (llvm_fenv_testexcept()) { 1875 llvm_fenv_clearexcept(); 1876 return nullptr; 1877 } 1878 1879 return GetConstantFoldFPValue(Result, Ty); 1880 } 1881 1882 Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) { 1883 FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType()); 1884 if (!VT) 1885 return nullptr; 1886 1887 // This isn't strictly necessary, but handle the special/common case of zero: 1888 // all integer reductions of a zero input produce zero. 1889 if (isa<ConstantAggregateZero>(Op)) 1890 return ConstantInt::get(VT->getElementType(), 0); 1891 1892 // This is the same as the underlying binops - poison propagates. 1893 if (isa<PoisonValue>(Op) || Op->containsPoisonElement()) 1894 return PoisonValue::get(VT->getElementType()); 1895 1896 // TODO: Handle undef. 1897 if (!isa<ConstantVector>(Op) && !isa<ConstantDataVector>(Op)) 1898 return nullptr; 1899 1900 auto *EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(0U)); 1901 if (!EltC) 1902 return nullptr; 1903 1904 APInt Acc = EltC->getValue(); 1905 for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) { 1906 if (!(EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(I)))) 1907 return nullptr; 1908 const APInt &X = EltC->getValue(); 1909 switch (IID) { 1910 case Intrinsic::vector_reduce_add: 1911 Acc = Acc + X; 1912 break; 1913 case Intrinsic::vector_reduce_mul: 1914 Acc = Acc * X; 1915 break; 1916 case Intrinsic::vector_reduce_and: 1917 Acc = Acc & X; 1918 break; 1919 case Intrinsic::vector_reduce_or: 1920 Acc = Acc | X; 1921 break; 1922 case Intrinsic::vector_reduce_xor: 1923 Acc = Acc ^ X; 1924 break; 1925 case Intrinsic::vector_reduce_smin: 1926 Acc = APIntOps::smin(Acc, X); 1927 break; 1928 case Intrinsic::vector_reduce_smax: 1929 Acc = APIntOps::smax(Acc, X); 1930 break; 1931 case Intrinsic::vector_reduce_umin: 1932 Acc = APIntOps::umin(Acc, X); 1933 break; 1934 case Intrinsic::vector_reduce_umax: 1935 Acc = APIntOps::umax(Acc, X); 1936 break; 1937 } 1938 } 1939 1940 return ConstantInt::get(Op->getContext(), Acc); 1941 } 1942 1943 /// Attempt to fold an SSE floating point to integer conversion of a constant 1944 /// floating point. If roundTowardZero is false, the default IEEE rounding is 1945 /// used (toward nearest, ties to even). This matches the behavior of the 1946 /// non-truncating SSE instructions in the default rounding mode. The desired 1947 /// integer type Ty is used to select how many bits are available for the 1948 /// result. Returns null if the conversion cannot be performed, otherwise 1949 /// returns the Constant value resulting from the conversion. 1950 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero, 1951 Type *Ty, bool IsSigned) { 1952 // All of these conversion intrinsics form an integer of at most 64bits. 1953 unsigned ResultWidth = Ty->getIntegerBitWidth(); 1954 assert(ResultWidth <= 64 && 1955 "Can only constant fold conversions to 64 and 32 bit ints"); 1956 1957 uint64_t UIntVal; 1958 bool isExact = false; 1959 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero 1960 : APFloat::rmNearestTiesToEven; 1961 APFloat::opStatus status = 1962 Val.convertToInteger(MutableArrayRef(UIntVal), ResultWidth, 1963 IsSigned, mode, &isExact); 1964 if (status != APFloat::opOK && 1965 (!roundTowardZero || status != APFloat::opInexact)) 1966 return nullptr; 1967 return ConstantInt::get(Ty, UIntVal, IsSigned); 1968 } 1969 1970 double getValueAsDouble(ConstantFP *Op) { 1971 Type *Ty = Op->getType(); 1972 1973 if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) 1974 return Op->getValueAPF().convertToDouble(); 1975 1976 bool unused; 1977 APFloat APF = Op->getValueAPF(); 1978 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused); 1979 return APF.convertToDouble(); 1980 } 1981 1982 static bool getConstIntOrUndef(Value *Op, const APInt *&C) { 1983 if (auto *CI = dyn_cast<ConstantInt>(Op)) { 1984 C = &CI->getValue(); 1985 return true; 1986 } 1987 if (isa<UndefValue>(Op)) { 1988 C = nullptr; 1989 return true; 1990 } 1991 return false; 1992 } 1993 1994 /// Checks if the given intrinsic call, which evaluates to constant, is allowed 1995 /// to be folded. 1996 /// 1997 /// \param CI Constrained intrinsic call. 1998 /// \param St Exception flags raised during constant evaluation. 1999 static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI, 2000 APFloat::opStatus St) { 2001 std::optional<RoundingMode> ORM = CI->getRoundingMode(); 2002 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior(); 2003 2004 // If the operation does not change exception status flags, it is safe 2005 // to fold. 2006 if (St == APFloat::opStatus::opOK) 2007 return true; 2008 2009 // If evaluation raised FP exception, the result can depend on rounding 2010 // mode. If the latter is unknown, folding is not possible. 2011 if (ORM && *ORM == RoundingMode::Dynamic) 2012 return false; 2013 2014 // If FP exceptions are ignored, fold the call, even if such exception is 2015 // raised. 2016 if (EB && *EB != fp::ExceptionBehavior::ebStrict) 2017 return true; 2018 2019 // Leave the calculation for runtime so that exception flags be correctly set 2020 // in hardware. 2021 return false; 2022 } 2023 2024 /// Returns the rounding mode that should be used for constant evaluation. 2025 static RoundingMode 2026 getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) { 2027 std::optional<RoundingMode> ORM = CI->getRoundingMode(); 2028 if (!ORM || *ORM == RoundingMode::Dynamic) 2029 // Even if the rounding mode is unknown, try evaluating the operation. 2030 // If it does not raise inexact exception, rounding was not applied, 2031 // so the result is exact and does not depend on rounding mode. Whether 2032 // other FP exceptions are raised, it does not depend on rounding mode. 2033 return RoundingMode::NearestTiesToEven; 2034 return *ORM; 2035 } 2036 2037 /// Try to constant fold llvm.canonicalize for the given caller and value. 2038 static Constant *constantFoldCanonicalize(const Type *Ty, const CallBase *CI, 2039 const APFloat &Src) { 2040 // Zero, positive and negative, is always OK to fold. 2041 if (Src.isZero()) { 2042 // Get a fresh 0, since ppc_fp128 does have non-canonical zeros. 2043 return ConstantFP::get( 2044 CI->getContext(), 2045 APFloat::getZero(Src.getSemantics(), Src.isNegative())); 2046 } 2047 2048 if (!Ty->isIEEELikeFPTy()) 2049 return nullptr; 2050 2051 // Zero is always canonical and the sign must be preserved. 2052 // 2053 // Denorms and nans may have special encodings, but it should be OK to fold a 2054 // totally average number. 2055 if (Src.isNormal() || Src.isInfinity()) 2056 return ConstantFP::get(CI->getContext(), Src); 2057 2058 if (Src.isDenormal() && CI->getParent() && CI->getFunction()) { 2059 DenormalMode DenormMode = 2060 CI->getFunction()->getDenormalMode(Src.getSemantics()); 2061 2062 if (DenormMode == DenormalMode::getIEEE()) 2063 return ConstantFP::get(CI->getContext(), Src); 2064 2065 if (DenormMode.Input == DenormalMode::Dynamic) 2066 return nullptr; 2067 2068 // If we know if either input or output is flushed, we can fold. 2069 if ((DenormMode.Input == DenormalMode::Dynamic && 2070 DenormMode.Output == DenormalMode::IEEE) || 2071 (DenormMode.Input == DenormalMode::IEEE && 2072 DenormMode.Output == DenormalMode::Dynamic)) 2073 return nullptr; 2074 2075 bool IsPositive = 2076 (!Src.isNegative() || DenormMode.Input == DenormalMode::PositiveZero || 2077 (DenormMode.Output == DenormalMode::PositiveZero && 2078 DenormMode.Input == DenormalMode::IEEE)); 2079 2080 return ConstantFP::get(CI->getContext(), 2081 APFloat::getZero(Src.getSemantics(), !IsPositive)); 2082 } 2083 2084 return nullptr; 2085 } 2086 2087 static Constant *ConstantFoldScalarCall1(StringRef Name, 2088 Intrinsic::ID IntrinsicID, 2089 Type *Ty, 2090 ArrayRef<Constant *> Operands, 2091 const TargetLibraryInfo *TLI, 2092 const CallBase *Call) { 2093 assert(Operands.size() == 1 && "Wrong number of operands."); 2094 2095 if (IntrinsicID == Intrinsic::is_constant) { 2096 // We know we have a "Constant" argument. But we want to only 2097 // return true for manifest constants, not those that depend on 2098 // constants with unknowable values, e.g. GlobalValue or BlockAddress. 2099 if (Operands[0]->isManifestConstant()) 2100 return ConstantInt::getTrue(Ty->getContext()); 2101 return nullptr; 2102 } 2103 2104 if (isa<PoisonValue>(Operands[0])) { 2105 // TODO: All of these operations should probably propagate poison. 2106 if (IntrinsicID == Intrinsic::canonicalize) 2107 return PoisonValue::get(Ty); 2108 } 2109 2110 if (isa<UndefValue>(Operands[0])) { 2111 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN. 2112 // ctpop() is between 0 and bitwidth, pick 0 for undef. 2113 // fptoui.sat and fptosi.sat can always fold to zero (for a zero input). 2114 if (IntrinsicID == Intrinsic::cos || 2115 IntrinsicID == Intrinsic::ctpop || 2116 IntrinsicID == Intrinsic::fptoui_sat || 2117 IntrinsicID == Intrinsic::fptosi_sat || 2118 IntrinsicID == Intrinsic::canonicalize) 2119 return Constant::getNullValue(Ty); 2120 if (IntrinsicID == Intrinsic::bswap || 2121 IntrinsicID == Intrinsic::bitreverse || 2122 IntrinsicID == Intrinsic::launder_invariant_group || 2123 IntrinsicID == Intrinsic::strip_invariant_group) 2124 return Operands[0]; 2125 } 2126 2127 if (isa<ConstantPointerNull>(Operands[0])) { 2128 // launder(null) == null == strip(null) iff in addrspace 0 2129 if (IntrinsicID == Intrinsic::launder_invariant_group || 2130 IntrinsicID == Intrinsic::strip_invariant_group) { 2131 // If instruction is not yet put in a basic block (e.g. when cloning 2132 // a function during inlining), Call's caller may not be available. 2133 // So check Call's BB first before querying Call->getCaller. 2134 const Function *Caller = 2135 Call->getParent() ? Call->getCaller() : nullptr; 2136 if (Caller && 2137 !NullPointerIsDefined( 2138 Caller, Operands[0]->getType()->getPointerAddressSpace())) { 2139 return Operands[0]; 2140 } 2141 return nullptr; 2142 } 2143 } 2144 2145 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) { 2146 if (IntrinsicID == Intrinsic::convert_to_fp16) { 2147 APFloat Val(Op->getValueAPF()); 2148 2149 bool lost = false; 2150 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost); 2151 2152 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt()); 2153 } 2154 2155 APFloat U = Op->getValueAPF(); 2156 2157 if (IntrinsicID == Intrinsic::wasm_trunc_signed || 2158 IntrinsicID == Intrinsic::wasm_trunc_unsigned) { 2159 bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed; 2160 2161 if (U.isNaN()) 2162 return nullptr; 2163 2164 unsigned Width = Ty->getIntegerBitWidth(); 2165 APSInt Int(Width, !Signed); 2166 bool IsExact = false; 2167 APFloat::opStatus Status = 2168 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact); 2169 2170 if (Status == APFloat::opOK || Status == APFloat::opInexact) 2171 return ConstantInt::get(Ty, Int); 2172 2173 return nullptr; 2174 } 2175 2176 if (IntrinsicID == Intrinsic::fptoui_sat || 2177 IntrinsicID == Intrinsic::fptosi_sat) { 2178 // convertToInteger() already has the desired saturation semantics. 2179 APSInt Int(Ty->getIntegerBitWidth(), 2180 IntrinsicID == Intrinsic::fptoui_sat); 2181 bool IsExact; 2182 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact); 2183 return ConstantInt::get(Ty, Int); 2184 } 2185 2186 if (IntrinsicID == Intrinsic::canonicalize) 2187 return constantFoldCanonicalize(Ty, Call, U); 2188 2189 #if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128) 2190 if (Ty->isFP128Ty()) { 2191 if (IntrinsicID == Intrinsic::log) { 2192 float128 Result = logf128(Op->getValueAPF().convertToQuad()); 2193 return GetConstantFoldFPValue128(Result, Ty); 2194 } 2195 2196 LibFunc Fp128Func = NotLibFunc; 2197 if (TLI && TLI->getLibFunc(Name, Fp128Func) && TLI->has(Fp128Func) && 2198 Fp128Func == LibFunc_logl) 2199 return ConstantFoldFP128(logf128, Op->getValueAPF(), Ty); 2200 } 2201 #endif 2202 2203 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy() && 2204 !Ty->isIntegerTy()) 2205 return nullptr; 2206 2207 // Use internal versions of these intrinsics. 2208 2209 if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) { 2210 U.roundToIntegral(APFloat::rmNearestTiesToEven); 2211 return ConstantFP::get(Ty->getContext(), U); 2212 } 2213 2214 if (IntrinsicID == Intrinsic::round) { 2215 U.roundToIntegral(APFloat::rmNearestTiesToAway); 2216 return ConstantFP::get(Ty->getContext(), U); 2217 } 2218 2219 if (IntrinsicID == Intrinsic::roundeven) { 2220 U.roundToIntegral(APFloat::rmNearestTiesToEven); 2221 return ConstantFP::get(Ty->getContext(), U); 2222 } 2223 2224 if (IntrinsicID == Intrinsic::ceil) { 2225 U.roundToIntegral(APFloat::rmTowardPositive); 2226 return ConstantFP::get(Ty->getContext(), U); 2227 } 2228 2229 if (IntrinsicID == Intrinsic::floor) { 2230 U.roundToIntegral(APFloat::rmTowardNegative); 2231 return ConstantFP::get(Ty->getContext(), U); 2232 } 2233 2234 if (IntrinsicID == Intrinsic::trunc) { 2235 U.roundToIntegral(APFloat::rmTowardZero); 2236 return ConstantFP::get(Ty->getContext(), U); 2237 } 2238 2239 if (IntrinsicID == Intrinsic::fabs) { 2240 U.clearSign(); 2241 return ConstantFP::get(Ty->getContext(), U); 2242 } 2243 2244 if (IntrinsicID == Intrinsic::amdgcn_fract) { 2245 // The v_fract instruction behaves like the OpenCL spec, which defines 2246 // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is 2247 // there to prevent fract(-small) from returning 1.0. It returns the 2248 // largest positive floating-point number less than 1.0." 2249 APFloat FloorU(U); 2250 FloorU.roundToIntegral(APFloat::rmTowardNegative); 2251 APFloat FractU(U - FloorU); 2252 APFloat AlmostOne(U.getSemantics(), 1); 2253 AlmostOne.next(/*nextDown*/ true); 2254 return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne)); 2255 } 2256 2257 // Rounding operations (floor, trunc, ceil, round and nearbyint) do not 2258 // raise FP exceptions, unless the argument is signaling NaN. 2259 2260 std::optional<APFloat::roundingMode> RM; 2261 switch (IntrinsicID) { 2262 default: 2263 break; 2264 case Intrinsic::experimental_constrained_nearbyint: 2265 case Intrinsic::experimental_constrained_rint: { 2266 auto CI = cast<ConstrainedFPIntrinsic>(Call); 2267 RM = CI->getRoundingMode(); 2268 if (!RM || *RM == RoundingMode::Dynamic) 2269 return nullptr; 2270 break; 2271 } 2272 case Intrinsic::experimental_constrained_round: 2273 RM = APFloat::rmNearestTiesToAway; 2274 break; 2275 case Intrinsic::experimental_constrained_ceil: 2276 RM = APFloat::rmTowardPositive; 2277 break; 2278 case Intrinsic::experimental_constrained_floor: 2279 RM = APFloat::rmTowardNegative; 2280 break; 2281 case Intrinsic::experimental_constrained_trunc: 2282 RM = APFloat::rmTowardZero; 2283 break; 2284 } 2285 if (RM) { 2286 auto CI = cast<ConstrainedFPIntrinsic>(Call); 2287 if (U.isFinite()) { 2288 APFloat::opStatus St = U.roundToIntegral(*RM); 2289 if (IntrinsicID == Intrinsic::experimental_constrained_rint && 2290 St == APFloat::opInexact) { 2291 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior(); 2292 if (EB && *EB == fp::ebStrict) 2293 return nullptr; 2294 } 2295 } else if (U.isSignaling()) { 2296 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior(); 2297 if (EB && *EB != fp::ebIgnore) 2298 return nullptr; 2299 U = APFloat::getQNaN(U.getSemantics()); 2300 } 2301 return ConstantFP::get(Ty->getContext(), U); 2302 } 2303 2304 /// We only fold functions with finite arguments. Folding NaN and inf is 2305 /// likely to be aborted with an exception anyway, and some host libms 2306 /// have known errors raising exceptions. 2307 if (!U.isFinite()) 2308 return nullptr; 2309 2310 /// Currently APFloat versions of these functions do not exist, so we use 2311 /// the host native double versions. Float versions are not called 2312 /// directly but for all these it is true (float)(f((double)arg)) == 2313 /// f(arg). Long double not supported yet. 2314 const APFloat &APF = Op->getValueAPF(); 2315 2316 switch (IntrinsicID) { 2317 default: break; 2318 case Intrinsic::log: 2319 return ConstantFoldFP(log, APF, Ty); 2320 case Intrinsic::log2: 2321 // TODO: What about hosts that lack a C99 library? 2322 return ConstantFoldFP(log2, APF, Ty); 2323 case Intrinsic::log10: 2324 // TODO: What about hosts that lack a C99 library? 2325 return ConstantFoldFP(log10, APF, Ty); 2326 case Intrinsic::exp: 2327 return ConstantFoldFP(exp, APF, Ty); 2328 case Intrinsic::exp2: 2329 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library. 2330 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty); 2331 case Intrinsic::exp10: 2332 // Fold exp10(x) as pow(10, x), in case the host lacks a C99 library. 2333 return ConstantFoldBinaryFP(pow, APFloat(10.0), APF, Ty); 2334 case Intrinsic::sin: 2335 return ConstantFoldFP(sin, APF, Ty); 2336 case Intrinsic::cos: 2337 return ConstantFoldFP(cos, APF, Ty); 2338 case Intrinsic::sqrt: 2339 return ConstantFoldFP(sqrt, APF, Ty); 2340 case Intrinsic::amdgcn_cos: 2341 case Intrinsic::amdgcn_sin: { 2342 double V = getValueAsDouble(Op); 2343 if (V < -256.0 || V > 256.0) 2344 // The gfx8 and gfx9 architectures handle arguments outside the range 2345 // [-256, 256] differently. This should be a rare case so bail out 2346 // rather than trying to handle the difference. 2347 return nullptr; 2348 bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos; 2349 double V4 = V * 4.0; 2350 if (V4 == floor(V4)) { 2351 // Force exact results for quarter-integer inputs. 2352 const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 }; 2353 V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3]; 2354 } else { 2355 if (IsCos) 2356 V = cos(V * 2.0 * numbers::pi); 2357 else 2358 V = sin(V * 2.0 * numbers::pi); 2359 } 2360 return GetConstantFoldFPValue(V, Ty); 2361 } 2362 } 2363 2364 if (!TLI) 2365 return nullptr; 2366 2367 LibFunc Func = NotLibFunc; 2368 if (!TLI->getLibFunc(Name, Func)) 2369 return nullptr; 2370 2371 switch (Func) { 2372 default: 2373 break; 2374 case LibFunc_acos: 2375 case LibFunc_acosf: 2376 case LibFunc_acos_finite: 2377 case LibFunc_acosf_finite: 2378 if (TLI->has(Func)) 2379 return ConstantFoldFP(acos, APF, Ty); 2380 break; 2381 case LibFunc_asin: 2382 case LibFunc_asinf: 2383 case LibFunc_asin_finite: 2384 case LibFunc_asinf_finite: 2385 if (TLI->has(Func)) 2386 return ConstantFoldFP(asin, APF, Ty); 2387 break; 2388 case LibFunc_atan: 2389 case LibFunc_atanf: 2390 if (TLI->has(Func)) 2391 return ConstantFoldFP(atan, APF, Ty); 2392 break; 2393 case LibFunc_ceil: 2394 case LibFunc_ceilf: 2395 if (TLI->has(Func)) { 2396 U.roundToIntegral(APFloat::rmTowardPositive); 2397 return ConstantFP::get(Ty->getContext(), U); 2398 } 2399 break; 2400 case LibFunc_cos: 2401 case LibFunc_cosf: 2402 if (TLI->has(Func)) 2403 return ConstantFoldFP(cos, APF, Ty); 2404 break; 2405 case LibFunc_cosh: 2406 case LibFunc_coshf: 2407 case LibFunc_cosh_finite: 2408 case LibFunc_coshf_finite: 2409 if (TLI->has(Func)) 2410 return ConstantFoldFP(cosh, APF, Ty); 2411 break; 2412 case LibFunc_exp: 2413 case LibFunc_expf: 2414 case LibFunc_exp_finite: 2415 case LibFunc_expf_finite: 2416 if (TLI->has(Func)) 2417 return ConstantFoldFP(exp, APF, Ty); 2418 break; 2419 case LibFunc_exp2: 2420 case LibFunc_exp2f: 2421 case LibFunc_exp2_finite: 2422 case LibFunc_exp2f_finite: 2423 if (TLI->has(Func)) 2424 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library. 2425 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty); 2426 break; 2427 case LibFunc_fabs: 2428 case LibFunc_fabsf: 2429 if (TLI->has(Func)) { 2430 U.clearSign(); 2431 return ConstantFP::get(Ty->getContext(), U); 2432 } 2433 break; 2434 case LibFunc_floor: 2435 case LibFunc_floorf: 2436 if (TLI->has(Func)) { 2437 U.roundToIntegral(APFloat::rmTowardNegative); 2438 return ConstantFP::get(Ty->getContext(), U); 2439 } 2440 break; 2441 case LibFunc_log: 2442 case LibFunc_logf: 2443 case LibFunc_log_finite: 2444 case LibFunc_logf_finite: 2445 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func)) 2446 return ConstantFoldFP(log, APF, Ty); 2447 break; 2448 case LibFunc_log2: 2449 case LibFunc_log2f: 2450 case LibFunc_log2_finite: 2451 case LibFunc_log2f_finite: 2452 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func)) 2453 // TODO: What about hosts that lack a C99 library? 2454 return ConstantFoldFP(log2, APF, Ty); 2455 break; 2456 case LibFunc_log10: 2457 case LibFunc_log10f: 2458 case LibFunc_log10_finite: 2459 case LibFunc_log10f_finite: 2460 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func)) 2461 // TODO: What about hosts that lack a C99 library? 2462 return ConstantFoldFP(log10, APF, Ty); 2463 break; 2464 case LibFunc_ilogb: 2465 case LibFunc_ilogbf: 2466 if (!APF.isZero() && TLI->has(Func)) 2467 return ConstantInt::get(Ty, ilogb(APF), true); 2468 break; 2469 case LibFunc_logb: 2470 case LibFunc_logbf: 2471 if (!APF.isZero() && TLI->has(Func)) 2472 return ConstantFoldFP(logb, APF, Ty); 2473 break; 2474 case LibFunc_log1p: 2475 case LibFunc_log1pf: 2476 // Implement optional behavior from C's Annex F for +/-0.0. 2477 if (U.isZero()) 2478 return ConstantFP::get(Ty->getContext(), U); 2479 if (APF > APFloat::getOne(APF.getSemantics(), true) && TLI->has(Func)) 2480 return ConstantFoldFP(log1p, APF, Ty); 2481 break; 2482 case LibFunc_logl: 2483 return nullptr; 2484 case LibFunc_erf: 2485 case LibFunc_erff: 2486 if (TLI->has(Func)) 2487 return ConstantFoldFP(erf, APF, Ty); 2488 break; 2489 case LibFunc_nearbyint: 2490 case LibFunc_nearbyintf: 2491 case LibFunc_rint: 2492 case LibFunc_rintf: 2493 if (TLI->has(Func)) { 2494 U.roundToIntegral(APFloat::rmNearestTiesToEven); 2495 return ConstantFP::get(Ty->getContext(), U); 2496 } 2497 break; 2498 case LibFunc_round: 2499 case LibFunc_roundf: 2500 if (TLI->has(Func)) { 2501 U.roundToIntegral(APFloat::rmNearestTiesToAway); 2502 return ConstantFP::get(Ty->getContext(), U); 2503 } 2504 break; 2505 case LibFunc_sin: 2506 case LibFunc_sinf: 2507 if (TLI->has(Func)) 2508 return ConstantFoldFP(sin, APF, Ty); 2509 break; 2510 case LibFunc_sinh: 2511 case LibFunc_sinhf: 2512 case LibFunc_sinh_finite: 2513 case LibFunc_sinhf_finite: 2514 if (TLI->has(Func)) 2515 return ConstantFoldFP(sinh, APF, Ty); 2516 break; 2517 case LibFunc_sqrt: 2518 case LibFunc_sqrtf: 2519 if (!APF.isNegative() && TLI->has(Func)) 2520 return ConstantFoldFP(sqrt, APF, Ty); 2521 break; 2522 case LibFunc_tan: 2523 case LibFunc_tanf: 2524 if (TLI->has(Func)) 2525 return ConstantFoldFP(tan, APF, Ty); 2526 break; 2527 case LibFunc_tanh: 2528 case LibFunc_tanhf: 2529 if (TLI->has(Func)) 2530 return ConstantFoldFP(tanh, APF, Ty); 2531 break; 2532 case LibFunc_trunc: 2533 case LibFunc_truncf: 2534 if (TLI->has(Func)) { 2535 U.roundToIntegral(APFloat::rmTowardZero); 2536 return ConstantFP::get(Ty->getContext(), U); 2537 } 2538 break; 2539 } 2540 return nullptr; 2541 } 2542 2543 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) { 2544 switch (IntrinsicID) { 2545 case Intrinsic::bswap: 2546 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap()); 2547 case Intrinsic::ctpop: 2548 return ConstantInt::get(Ty, Op->getValue().popcount()); 2549 case Intrinsic::bitreverse: 2550 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits()); 2551 case Intrinsic::convert_from_fp16: { 2552 APFloat Val(APFloat::IEEEhalf(), Op->getValue()); 2553 2554 bool lost = false; 2555 APFloat::opStatus status = Val.convert( 2556 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost); 2557 2558 // Conversion is always precise. 2559 (void)status; 2560 assert(status != APFloat::opInexact && !lost && 2561 "Precision lost during fp16 constfolding"); 2562 2563 return ConstantFP::get(Ty->getContext(), Val); 2564 } 2565 2566 case Intrinsic::amdgcn_s_wqm: { 2567 uint64_t Val = Op->getZExtValue(); 2568 Val |= (Val & 0x5555555555555555ULL) << 1 | 2569 ((Val >> 1) & 0x5555555555555555ULL); 2570 Val |= (Val & 0x3333333333333333ULL) << 2 | 2571 ((Val >> 2) & 0x3333333333333333ULL); 2572 return ConstantInt::get(Ty, Val); 2573 } 2574 2575 case Intrinsic::amdgcn_s_quadmask: { 2576 uint64_t Val = Op->getZExtValue(); 2577 uint64_t QuadMask = 0; 2578 for (unsigned I = 0; I < Op->getBitWidth() / 4; ++I, Val >>= 4) { 2579 if (!(Val & 0xF)) 2580 continue; 2581 2582 QuadMask |= (1ULL << I); 2583 } 2584 return ConstantInt::get(Ty, QuadMask); 2585 } 2586 2587 case Intrinsic::amdgcn_s_bitreplicate: { 2588 uint64_t Val = Op->getZExtValue(); 2589 Val = (Val & 0x000000000000FFFFULL) | (Val & 0x00000000FFFF0000ULL) << 16; 2590 Val = (Val & 0x000000FF000000FFULL) | (Val & 0x0000FF000000FF00ULL) << 8; 2591 Val = (Val & 0x000F000F000F000FULL) | (Val & 0x00F000F000F000F0ULL) << 4; 2592 Val = (Val & 0x0303030303030303ULL) | (Val & 0x0C0C0C0C0C0C0C0CULL) << 2; 2593 Val = (Val & 0x1111111111111111ULL) | (Val & 0x2222222222222222ULL) << 1; 2594 Val = Val | Val << 1; 2595 return ConstantInt::get(Ty, Val); 2596 } 2597 2598 default: 2599 return nullptr; 2600 } 2601 } 2602 2603 switch (IntrinsicID) { 2604 default: break; 2605 case Intrinsic::vector_reduce_add: 2606 case Intrinsic::vector_reduce_mul: 2607 case Intrinsic::vector_reduce_and: 2608 case Intrinsic::vector_reduce_or: 2609 case Intrinsic::vector_reduce_xor: 2610 case Intrinsic::vector_reduce_smin: 2611 case Intrinsic::vector_reduce_smax: 2612 case Intrinsic::vector_reduce_umin: 2613 case Intrinsic::vector_reduce_umax: 2614 if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0])) 2615 return C; 2616 break; 2617 } 2618 2619 // Support ConstantVector in case we have an Undef in the top. 2620 if (isa<ConstantVector>(Operands[0]) || 2621 isa<ConstantDataVector>(Operands[0])) { 2622 auto *Op = cast<Constant>(Operands[0]); 2623 switch (IntrinsicID) { 2624 default: break; 2625 case Intrinsic::x86_sse_cvtss2si: 2626 case Intrinsic::x86_sse_cvtss2si64: 2627 case Intrinsic::x86_sse2_cvtsd2si: 2628 case Intrinsic::x86_sse2_cvtsd2si64: 2629 if (ConstantFP *FPOp = 2630 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2631 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2632 /*roundTowardZero=*/false, Ty, 2633 /*IsSigned*/true); 2634 break; 2635 case Intrinsic::x86_sse_cvttss2si: 2636 case Intrinsic::x86_sse_cvttss2si64: 2637 case Intrinsic::x86_sse2_cvttsd2si: 2638 case Intrinsic::x86_sse2_cvttsd2si64: 2639 if (ConstantFP *FPOp = 2640 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2641 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2642 /*roundTowardZero=*/true, Ty, 2643 /*IsSigned*/true); 2644 break; 2645 } 2646 } 2647 2648 return nullptr; 2649 } 2650 2651 static Constant *evaluateCompare(const APFloat &Op1, const APFloat &Op2, 2652 const ConstrainedFPIntrinsic *Call) { 2653 APFloat::opStatus St = APFloat::opOK; 2654 auto *FCmp = cast<ConstrainedFPCmpIntrinsic>(Call); 2655 FCmpInst::Predicate Cond = FCmp->getPredicate(); 2656 if (FCmp->isSignaling()) { 2657 if (Op1.isNaN() || Op2.isNaN()) 2658 St = APFloat::opInvalidOp; 2659 } else { 2660 if (Op1.isSignaling() || Op2.isSignaling()) 2661 St = APFloat::opInvalidOp; 2662 } 2663 bool Result = FCmpInst::compare(Op1, Op2, Cond); 2664 if (mayFoldConstrained(const_cast<ConstrainedFPCmpIntrinsic *>(FCmp), St)) 2665 return ConstantInt::get(Call->getType()->getScalarType(), Result); 2666 return nullptr; 2667 } 2668 2669 static Constant *ConstantFoldLibCall2(StringRef Name, Type *Ty, 2670 ArrayRef<Constant *> Operands, 2671 const TargetLibraryInfo *TLI) { 2672 if (!TLI) 2673 return nullptr; 2674 2675 LibFunc Func = NotLibFunc; 2676 if (!TLI->getLibFunc(Name, Func)) 2677 return nullptr; 2678 2679 const auto *Op1 = dyn_cast<ConstantFP>(Operands[0]); 2680 if (!Op1) 2681 return nullptr; 2682 2683 const auto *Op2 = dyn_cast<ConstantFP>(Operands[1]); 2684 if (!Op2) 2685 return nullptr; 2686 2687 const APFloat &Op1V = Op1->getValueAPF(); 2688 const APFloat &Op2V = Op2->getValueAPF(); 2689 2690 switch (Func) { 2691 default: 2692 break; 2693 case LibFunc_pow: 2694 case LibFunc_powf: 2695 case LibFunc_pow_finite: 2696 case LibFunc_powf_finite: 2697 if (TLI->has(Func)) 2698 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); 2699 break; 2700 case LibFunc_fmod: 2701 case LibFunc_fmodf: 2702 if (TLI->has(Func)) { 2703 APFloat V = Op1->getValueAPF(); 2704 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF())) 2705 return ConstantFP::get(Ty->getContext(), V); 2706 } 2707 break; 2708 case LibFunc_remainder: 2709 case LibFunc_remainderf: 2710 if (TLI->has(Func)) { 2711 APFloat V = Op1->getValueAPF(); 2712 if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF())) 2713 return ConstantFP::get(Ty->getContext(), V); 2714 } 2715 break; 2716 case LibFunc_atan2: 2717 case LibFunc_atan2f: 2718 // atan2(+/-0.0, +/-0.0) is known to raise an exception on some libm 2719 // (Solaris), so we do not assume a known result for that. 2720 if (Op1V.isZero() && Op2V.isZero()) 2721 return nullptr; 2722 [[fallthrough]]; 2723 case LibFunc_atan2_finite: 2724 case LibFunc_atan2f_finite: 2725 if (TLI->has(Func)) 2726 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty); 2727 break; 2728 } 2729 2730 return nullptr; 2731 } 2732 2733 static Constant *ConstantFoldIntrinsicCall2(Intrinsic::ID IntrinsicID, Type *Ty, 2734 ArrayRef<Constant *> Operands, 2735 const CallBase *Call) { 2736 assert(Operands.size() == 2 && "Wrong number of operands."); 2737 2738 if (Ty->isFloatingPointTy()) { 2739 // TODO: We should have undef handling for all of the FP intrinsics that 2740 // are attempted to be folded in this function. 2741 bool IsOp0Undef = isa<UndefValue>(Operands[0]); 2742 bool IsOp1Undef = isa<UndefValue>(Operands[1]); 2743 switch (IntrinsicID) { 2744 case Intrinsic::maxnum: 2745 case Intrinsic::minnum: 2746 case Intrinsic::maximum: 2747 case Intrinsic::minimum: 2748 // If one argument is undef, return the other argument. 2749 if (IsOp0Undef) 2750 return Operands[1]; 2751 if (IsOp1Undef) 2752 return Operands[0]; 2753 break; 2754 } 2755 } 2756 2757 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) { 2758 const APFloat &Op1V = Op1->getValueAPF(); 2759 2760 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { 2761 if (Op2->getType() != Op1->getType()) 2762 return nullptr; 2763 const APFloat &Op2V = Op2->getValueAPF(); 2764 2765 if (const auto *ConstrIntr = 2766 dyn_cast_if_present<ConstrainedFPIntrinsic>(Call)) { 2767 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr); 2768 APFloat Res = Op1V; 2769 APFloat::opStatus St; 2770 switch (IntrinsicID) { 2771 default: 2772 return nullptr; 2773 case Intrinsic::experimental_constrained_fadd: 2774 St = Res.add(Op2V, RM); 2775 break; 2776 case Intrinsic::experimental_constrained_fsub: 2777 St = Res.subtract(Op2V, RM); 2778 break; 2779 case Intrinsic::experimental_constrained_fmul: 2780 St = Res.multiply(Op2V, RM); 2781 break; 2782 case Intrinsic::experimental_constrained_fdiv: 2783 St = Res.divide(Op2V, RM); 2784 break; 2785 case Intrinsic::experimental_constrained_frem: 2786 St = Res.mod(Op2V); 2787 break; 2788 case Intrinsic::experimental_constrained_fcmp: 2789 case Intrinsic::experimental_constrained_fcmps: 2790 return evaluateCompare(Op1V, Op2V, ConstrIntr); 2791 } 2792 if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), 2793 St)) 2794 return ConstantFP::get(Ty->getContext(), Res); 2795 return nullptr; 2796 } 2797 2798 switch (IntrinsicID) { 2799 default: 2800 break; 2801 case Intrinsic::copysign: 2802 return ConstantFP::get(Ty->getContext(), APFloat::copySign(Op1V, Op2V)); 2803 case Intrinsic::minnum: 2804 return ConstantFP::get(Ty->getContext(), minnum(Op1V, Op2V)); 2805 case Intrinsic::maxnum: 2806 return ConstantFP::get(Ty->getContext(), maxnum(Op1V, Op2V)); 2807 case Intrinsic::minimum: 2808 return ConstantFP::get(Ty->getContext(), minimum(Op1V, Op2V)); 2809 case Intrinsic::maximum: 2810 return ConstantFP::get(Ty->getContext(), maximum(Op1V, Op2V)); 2811 } 2812 2813 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy()) 2814 return nullptr; 2815 2816 switch (IntrinsicID) { 2817 default: 2818 break; 2819 case Intrinsic::pow: 2820 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); 2821 case Intrinsic::amdgcn_fmul_legacy: 2822 // The legacy behaviour is that multiplying +/- 0.0 by anything, even 2823 // NaN or infinity, gives +0.0. 2824 if (Op1V.isZero() || Op2V.isZero()) 2825 return ConstantFP::getZero(Ty); 2826 return ConstantFP::get(Ty->getContext(), Op1V * Op2V); 2827 } 2828 2829 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) { 2830 switch (IntrinsicID) { 2831 case Intrinsic::ldexp: { 2832 return ConstantFP::get( 2833 Ty->getContext(), 2834 scalbn(Op1V, Op2C->getSExtValue(), APFloat::rmNearestTiesToEven)); 2835 } 2836 case Intrinsic::is_fpclass: { 2837 FPClassTest Mask = static_cast<FPClassTest>(Op2C->getZExtValue()); 2838 bool Result = 2839 ((Mask & fcSNan) && Op1V.isNaN() && Op1V.isSignaling()) || 2840 ((Mask & fcQNan) && Op1V.isNaN() && !Op1V.isSignaling()) || 2841 ((Mask & fcNegInf) && Op1V.isNegInfinity()) || 2842 ((Mask & fcNegNormal) && Op1V.isNormal() && Op1V.isNegative()) || 2843 ((Mask & fcNegSubnormal) && Op1V.isDenormal() && Op1V.isNegative()) || 2844 ((Mask & fcNegZero) && Op1V.isZero() && Op1V.isNegative()) || 2845 ((Mask & fcPosZero) && Op1V.isZero() && !Op1V.isNegative()) || 2846 ((Mask & fcPosSubnormal) && Op1V.isDenormal() && !Op1V.isNegative()) || 2847 ((Mask & fcPosNormal) && Op1V.isNormal() && !Op1V.isNegative()) || 2848 ((Mask & fcPosInf) && Op1V.isPosInfinity()); 2849 return ConstantInt::get(Ty, Result); 2850 } 2851 case Intrinsic::powi: { 2852 int Exp = static_cast<int>(Op2C->getSExtValue()); 2853 switch (Ty->getTypeID()) { 2854 case Type::HalfTyID: 2855 case Type::FloatTyID: { 2856 APFloat Res(static_cast<float>(std::pow(Op1V.convertToFloat(), Exp))); 2857 if (Ty->isHalfTy()) { 2858 bool Unused; 2859 Res.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 2860 &Unused); 2861 } 2862 return ConstantFP::get(Ty->getContext(), Res); 2863 } 2864 case Type::DoubleTyID: 2865 return ConstantFP::get(Ty, std::pow(Op1V.convertToDouble(), Exp)); 2866 default: 2867 return nullptr; 2868 } 2869 } 2870 default: 2871 break; 2872 } 2873 } 2874 return nullptr; 2875 } 2876 2877 if (Operands[0]->getType()->isIntegerTy() && 2878 Operands[1]->getType()->isIntegerTy()) { 2879 const APInt *C0, *C1; 2880 if (!getConstIntOrUndef(Operands[0], C0) || 2881 !getConstIntOrUndef(Operands[1], C1)) 2882 return nullptr; 2883 2884 switch (IntrinsicID) { 2885 default: break; 2886 case Intrinsic::smax: 2887 case Intrinsic::smin: 2888 case Intrinsic::umax: 2889 case Intrinsic::umin: 2890 // This is the same as for binary ops - poison propagates. 2891 // TODO: Poison handling should be consolidated. 2892 if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1])) 2893 return PoisonValue::get(Ty); 2894 2895 if (!C0 && !C1) 2896 return UndefValue::get(Ty); 2897 if (!C0 || !C1) 2898 return MinMaxIntrinsic::getSaturationPoint(IntrinsicID, Ty); 2899 return ConstantInt::get( 2900 Ty, ICmpInst::compare(*C0, *C1, 2901 MinMaxIntrinsic::getPredicate(IntrinsicID)) 2902 ? *C0 2903 : *C1); 2904 2905 case Intrinsic::scmp: 2906 case Intrinsic::ucmp: 2907 if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1])) 2908 return PoisonValue::get(Ty); 2909 2910 if (!C0 || !C1) 2911 return ConstantInt::get(Ty, 0); 2912 2913 int Res; 2914 if (IntrinsicID == Intrinsic::scmp) 2915 Res = C0->sgt(*C1) ? 1 : C0->slt(*C1) ? -1 : 0; 2916 else 2917 Res = C0->ugt(*C1) ? 1 : C0->ult(*C1) ? -1 : 0; 2918 return ConstantInt::get(Ty, Res, /*IsSigned=*/true); 2919 2920 case Intrinsic::usub_with_overflow: 2921 case Intrinsic::ssub_with_overflow: 2922 // X - undef -> { 0, false } 2923 // undef - X -> { 0, false } 2924 if (!C0 || !C1) 2925 return Constant::getNullValue(Ty); 2926 [[fallthrough]]; 2927 case Intrinsic::uadd_with_overflow: 2928 case Intrinsic::sadd_with_overflow: 2929 // X + undef -> { -1, false } 2930 // undef + x -> { -1, false } 2931 if (!C0 || !C1) { 2932 return ConstantStruct::get( 2933 cast<StructType>(Ty), 2934 {Constant::getAllOnesValue(Ty->getStructElementType(0)), 2935 Constant::getNullValue(Ty->getStructElementType(1))}); 2936 } 2937 [[fallthrough]]; 2938 case Intrinsic::smul_with_overflow: 2939 case Intrinsic::umul_with_overflow: { 2940 // undef * X -> { 0, false } 2941 // X * undef -> { 0, false } 2942 if (!C0 || !C1) 2943 return Constant::getNullValue(Ty); 2944 2945 APInt Res; 2946 bool Overflow; 2947 switch (IntrinsicID) { 2948 default: llvm_unreachable("Invalid case"); 2949 case Intrinsic::sadd_with_overflow: 2950 Res = C0->sadd_ov(*C1, Overflow); 2951 break; 2952 case Intrinsic::uadd_with_overflow: 2953 Res = C0->uadd_ov(*C1, Overflow); 2954 break; 2955 case Intrinsic::ssub_with_overflow: 2956 Res = C0->ssub_ov(*C1, Overflow); 2957 break; 2958 case Intrinsic::usub_with_overflow: 2959 Res = C0->usub_ov(*C1, Overflow); 2960 break; 2961 case Intrinsic::smul_with_overflow: 2962 Res = C0->smul_ov(*C1, Overflow); 2963 break; 2964 case Intrinsic::umul_with_overflow: 2965 Res = C0->umul_ov(*C1, Overflow); 2966 break; 2967 } 2968 Constant *Ops[] = { 2969 ConstantInt::get(Ty->getContext(), Res), 2970 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow) 2971 }; 2972 return ConstantStruct::get(cast<StructType>(Ty), Ops); 2973 } 2974 case Intrinsic::uadd_sat: 2975 case Intrinsic::sadd_sat: 2976 // This is the same as for binary ops - poison propagates. 2977 // TODO: Poison handling should be consolidated. 2978 if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1])) 2979 return PoisonValue::get(Ty); 2980 2981 if (!C0 && !C1) 2982 return UndefValue::get(Ty); 2983 if (!C0 || !C1) 2984 return Constant::getAllOnesValue(Ty); 2985 if (IntrinsicID == Intrinsic::uadd_sat) 2986 return ConstantInt::get(Ty, C0->uadd_sat(*C1)); 2987 else 2988 return ConstantInt::get(Ty, C0->sadd_sat(*C1)); 2989 case Intrinsic::usub_sat: 2990 case Intrinsic::ssub_sat: 2991 // This is the same as for binary ops - poison propagates. 2992 // TODO: Poison handling should be consolidated. 2993 if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1])) 2994 return PoisonValue::get(Ty); 2995 2996 if (!C0 && !C1) 2997 return UndefValue::get(Ty); 2998 if (!C0 || !C1) 2999 return Constant::getNullValue(Ty); 3000 if (IntrinsicID == Intrinsic::usub_sat) 3001 return ConstantInt::get(Ty, C0->usub_sat(*C1)); 3002 else 3003 return ConstantInt::get(Ty, C0->ssub_sat(*C1)); 3004 case Intrinsic::cttz: 3005 case Intrinsic::ctlz: 3006 assert(C1 && "Must be constant int"); 3007 3008 // cttz(0, 1) and ctlz(0, 1) are poison. 3009 if (C1->isOne() && (!C0 || C0->isZero())) 3010 return PoisonValue::get(Ty); 3011 if (!C0) 3012 return Constant::getNullValue(Ty); 3013 if (IntrinsicID == Intrinsic::cttz) 3014 return ConstantInt::get(Ty, C0->countr_zero()); 3015 else 3016 return ConstantInt::get(Ty, C0->countl_zero()); 3017 3018 case Intrinsic::abs: 3019 assert(C1 && "Must be constant int"); 3020 assert((C1->isOne() || C1->isZero()) && "Must be 0 or 1"); 3021 3022 // Undef or minimum val operand with poison min --> poison 3023 if (C1->isOne() && (!C0 || C0->isMinSignedValue())) 3024 return PoisonValue::get(Ty); 3025 3026 // Undef operand with no poison min --> 0 (sign bit must be clear) 3027 if (!C0) 3028 return Constant::getNullValue(Ty); 3029 3030 return ConstantInt::get(Ty, C0->abs()); 3031 case Intrinsic::amdgcn_wave_reduce_umin: 3032 case Intrinsic::amdgcn_wave_reduce_umax: 3033 return dyn_cast<Constant>(Operands[0]); 3034 } 3035 3036 return nullptr; 3037 } 3038 3039 // Support ConstantVector in case we have an Undef in the top. 3040 if ((isa<ConstantVector>(Operands[0]) || 3041 isa<ConstantDataVector>(Operands[0])) && 3042 // Check for default rounding mode. 3043 // FIXME: Support other rounding modes? 3044 isa<ConstantInt>(Operands[1]) && 3045 cast<ConstantInt>(Operands[1])->getValue() == 4) { 3046 auto *Op = cast<Constant>(Operands[0]); 3047 switch (IntrinsicID) { 3048 default: break; 3049 case Intrinsic::x86_avx512_vcvtss2si32: 3050 case Intrinsic::x86_avx512_vcvtss2si64: 3051 case Intrinsic::x86_avx512_vcvtsd2si32: 3052 case Intrinsic::x86_avx512_vcvtsd2si64: 3053 if (ConstantFP *FPOp = 3054 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 3055 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 3056 /*roundTowardZero=*/false, Ty, 3057 /*IsSigned*/true); 3058 break; 3059 case Intrinsic::x86_avx512_vcvtss2usi32: 3060 case Intrinsic::x86_avx512_vcvtss2usi64: 3061 case Intrinsic::x86_avx512_vcvtsd2usi32: 3062 case Intrinsic::x86_avx512_vcvtsd2usi64: 3063 if (ConstantFP *FPOp = 3064 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 3065 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 3066 /*roundTowardZero=*/false, Ty, 3067 /*IsSigned*/false); 3068 break; 3069 case Intrinsic::x86_avx512_cvttss2si: 3070 case Intrinsic::x86_avx512_cvttss2si64: 3071 case Intrinsic::x86_avx512_cvttsd2si: 3072 case Intrinsic::x86_avx512_cvttsd2si64: 3073 if (ConstantFP *FPOp = 3074 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 3075 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 3076 /*roundTowardZero=*/true, Ty, 3077 /*IsSigned*/true); 3078 break; 3079 case Intrinsic::x86_avx512_cvttss2usi: 3080 case Intrinsic::x86_avx512_cvttss2usi64: 3081 case Intrinsic::x86_avx512_cvttsd2usi: 3082 case Intrinsic::x86_avx512_cvttsd2usi64: 3083 if (ConstantFP *FPOp = 3084 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 3085 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 3086 /*roundTowardZero=*/true, Ty, 3087 /*IsSigned*/false); 3088 break; 3089 } 3090 } 3091 return nullptr; 3092 } 3093 3094 static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID, 3095 const APFloat &S0, 3096 const APFloat &S1, 3097 const APFloat &S2) { 3098 unsigned ID; 3099 const fltSemantics &Sem = S0.getSemantics(); 3100 APFloat MA(Sem), SC(Sem), TC(Sem); 3101 if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) { 3102 if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) { 3103 // S2 < 0 3104 ID = 5; 3105 SC = -S0; 3106 } else { 3107 ID = 4; 3108 SC = S0; 3109 } 3110 MA = S2; 3111 TC = -S1; 3112 } else if (abs(S1) >= abs(S0)) { 3113 if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) { 3114 // S1 < 0 3115 ID = 3; 3116 TC = -S2; 3117 } else { 3118 ID = 2; 3119 TC = S2; 3120 } 3121 MA = S1; 3122 SC = S0; 3123 } else { 3124 if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) { 3125 // S0 < 0 3126 ID = 1; 3127 SC = S2; 3128 } else { 3129 ID = 0; 3130 SC = -S2; 3131 } 3132 MA = S0; 3133 TC = -S1; 3134 } 3135 switch (IntrinsicID) { 3136 default: 3137 llvm_unreachable("unhandled amdgcn cube intrinsic"); 3138 case Intrinsic::amdgcn_cubeid: 3139 return APFloat(Sem, ID); 3140 case Intrinsic::amdgcn_cubema: 3141 return MA + MA; 3142 case Intrinsic::amdgcn_cubesc: 3143 return SC; 3144 case Intrinsic::amdgcn_cubetc: 3145 return TC; 3146 } 3147 } 3148 3149 static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands, 3150 Type *Ty) { 3151 const APInt *C0, *C1, *C2; 3152 if (!getConstIntOrUndef(Operands[0], C0) || 3153 !getConstIntOrUndef(Operands[1], C1) || 3154 !getConstIntOrUndef(Operands[2], C2)) 3155 return nullptr; 3156 3157 if (!C2) 3158 return UndefValue::get(Ty); 3159 3160 APInt Val(32, 0); 3161 unsigned NumUndefBytes = 0; 3162 for (unsigned I = 0; I < 32; I += 8) { 3163 unsigned Sel = C2->extractBitsAsZExtValue(8, I); 3164 unsigned B = 0; 3165 3166 if (Sel >= 13) 3167 B = 0xff; 3168 else if (Sel == 12) 3169 B = 0x00; 3170 else { 3171 const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1; 3172 if (!Src) 3173 ++NumUndefBytes; 3174 else if (Sel < 8) 3175 B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8); 3176 else 3177 B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff; 3178 } 3179 3180 Val.insertBits(B, I, 8); 3181 } 3182 3183 if (NumUndefBytes == 4) 3184 return UndefValue::get(Ty); 3185 3186 return ConstantInt::get(Ty, Val); 3187 } 3188 3189 static Constant *ConstantFoldScalarCall3(StringRef Name, 3190 Intrinsic::ID IntrinsicID, 3191 Type *Ty, 3192 ArrayRef<Constant *> Operands, 3193 const TargetLibraryInfo *TLI, 3194 const CallBase *Call) { 3195 assert(Operands.size() == 3 && "Wrong number of operands."); 3196 3197 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) { 3198 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { 3199 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) { 3200 const APFloat &C1 = Op1->getValueAPF(); 3201 const APFloat &C2 = Op2->getValueAPF(); 3202 const APFloat &C3 = Op3->getValueAPF(); 3203 3204 if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) { 3205 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr); 3206 APFloat Res = C1; 3207 APFloat::opStatus St; 3208 switch (IntrinsicID) { 3209 default: 3210 return nullptr; 3211 case Intrinsic::experimental_constrained_fma: 3212 case Intrinsic::experimental_constrained_fmuladd: 3213 St = Res.fusedMultiplyAdd(C2, C3, RM); 3214 break; 3215 } 3216 if (mayFoldConstrained( 3217 const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St)) 3218 return ConstantFP::get(Ty->getContext(), Res); 3219 return nullptr; 3220 } 3221 3222 switch (IntrinsicID) { 3223 default: break; 3224 case Intrinsic::amdgcn_fma_legacy: { 3225 // The legacy behaviour is that multiplying +/- 0.0 by anything, even 3226 // NaN or infinity, gives +0.0. 3227 if (C1.isZero() || C2.isZero()) { 3228 // It's tempting to just return C3 here, but that would give the 3229 // wrong result if C3 was -0.0. 3230 return ConstantFP::get(Ty->getContext(), APFloat(0.0f) + C3); 3231 } 3232 [[fallthrough]]; 3233 } 3234 case Intrinsic::fma: 3235 case Intrinsic::fmuladd: { 3236 APFloat V = C1; 3237 V.fusedMultiplyAdd(C2, C3, APFloat::rmNearestTiesToEven); 3238 return ConstantFP::get(Ty->getContext(), V); 3239 } 3240 case Intrinsic::amdgcn_cubeid: 3241 case Intrinsic::amdgcn_cubema: 3242 case Intrinsic::amdgcn_cubesc: 3243 case Intrinsic::amdgcn_cubetc: { 3244 APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3); 3245 return ConstantFP::get(Ty->getContext(), V); 3246 } 3247 } 3248 } 3249 } 3250 } 3251 3252 if (IntrinsicID == Intrinsic::smul_fix || 3253 IntrinsicID == Intrinsic::smul_fix_sat) { 3254 // poison * C -> poison 3255 // C * poison -> poison 3256 if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1])) 3257 return PoisonValue::get(Ty); 3258 3259 const APInt *C0, *C1; 3260 if (!getConstIntOrUndef(Operands[0], C0) || 3261 !getConstIntOrUndef(Operands[1], C1)) 3262 return nullptr; 3263 3264 // undef * C -> 0 3265 // C * undef -> 0 3266 if (!C0 || !C1) 3267 return Constant::getNullValue(Ty); 3268 3269 // This code performs rounding towards negative infinity in case the result 3270 // cannot be represented exactly for the given scale. Targets that do care 3271 // about rounding should use a target hook for specifying how rounding 3272 // should be done, and provide their own folding to be consistent with 3273 // rounding. This is the same approach as used by 3274 // DAGTypeLegalizer::ExpandIntRes_MULFIX. 3275 unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue(); 3276 unsigned Width = C0->getBitWidth(); 3277 assert(Scale < Width && "Illegal scale."); 3278 unsigned ExtendedWidth = Width * 2; 3279 APInt Product = 3280 (C0->sext(ExtendedWidth) * C1->sext(ExtendedWidth)).ashr(Scale); 3281 if (IntrinsicID == Intrinsic::smul_fix_sat) { 3282 APInt Max = APInt::getSignedMaxValue(Width).sext(ExtendedWidth); 3283 APInt Min = APInt::getSignedMinValue(Width).sext(ExtendedWidth); 3284 Product = APIntOps::smin(Product, Max); 3285 Product = APIntOps::smax(Product, Min); 3286 } 3287 return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width)); 3288 } 3289 3290 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) { 3291 const APInt *C0, *C1, *C2; 3292 if (!getConstIntOrUndef(Operands[0], C0) || 3293 !getConstIntOrUndef(Operands[1], C1) || 3294 !getConstIntOrUndef(Operands[2], C2)) 3295 return nullptr; 3296 3297 bool IsRight = IntrinsicID == Intrinsic::fshr; 3298 if (!C2) 3299 return Operands[IsRight ? 1 : 0]; 3300 if (!C0 && !C1) 3301 return UndefValue::get(Ty); 3302 3303 // The shift amount is interpreted as modulo the bitwidth. If the shift 3304 // amount is effectively 0, avoid UB due to oversized inverse shift below. 3305 unsigned BitWidth = C2->getBitWidth(); 3306 unsigned ShAmt = C2->urem(BitWidth); 3307 if (!ShAmt) 3308 return Operands[IsRight ? 1 : 0]; 3309 3310 // (C0 << ShlAmt) | (C1 >> LshrAmt) 3311 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt; 3312 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt; 3313 if (!C0) 3314 return ConstantInt::get(Ty, C1->lshr(LshrAmt)); 3315 if (!C1) 3316 return ConstantInt::get(Ty, C0->shl(ShlAmt)); 3317 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt)); 3318 } 3319 3320 if (IntrinsicID == Intrinsic::amdgcn_perm) 3321 return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty); 3322 3323 return nullptr; 3324 } 3325 3326 static Constant *ConstantFoldScalarCall(StringRef Name, 3327 Intrinsic::ID IntrinsicID, 3328 Type *Ty, 3329 ArrayRef<Constant *> Operands, 3330 const TargetLibraryInfo *TLI, 3331 const CallBase *Call) { 3332 if (Operands.size() == 1) 3333 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call); 3334 3335 if (Operands.size() == 2) { 3336 if (Constant *FoldedLibCall = 3337 ConstantFoldLibCall2(Name, Ty, Operands, TLI)) { 3338 return FoldedLibCall; 3339 } 3340 return ConstantFoldIntrinsicCall2(IntrinsicID, Ty, Operands, Call); 3341 } 3342 3343 if (Operands.size() == 3) 3344 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call); 3345 3346 return nullptr; 3347 } 3348 3349 static Constant *ConstantFoldFixedVectorCall( 3350 StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy, 3351 ArrayRef<Constant *> Operands, const DataLayout &DL, 3352 const TargetLibraryInfo *TLI, const CallBase *Call) { 3353 SmallVector<Constant *, 4> Result(FVTy->getNumElements()); 3354 SmallVector<Constant *, 4> Lane(Operands.size()); 3355 Type *Ty = FVTy->getElementType(); 3356 3357 switch (IntrinsicID) { 3358 case Intrinsic::masked_load: { 3359 auto *SrcPtr = Operands[0]; 3360 auto *Mask = Operands[2]; 3361 auto *Passthru = Operands[3]; 3362 3363 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL); 3364 3365 SmallVector<Constant *, 32> NewElements; 3366 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) { 3367 auto *MaskElt = Mask->getAggregateElement(I); 3368 if (!MaskElt) 3369 break; 3370 auto *PassthruElt = Passthru->getAggregateElement(I); 3371 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr; 3372 if (isa<UndefValue>(MaskElt)) { 3373 if (PassthruElt) 3374 NewElements.push_back(PassthruElt); 3375 else if (VecElt) 3376 NewElements.push_back(VecElt); 3377 else 3378 return nullptr; 3379 } 3380 if (MaskElt->isNullValue()) { 3381 if (!PassthruElt) 3382 return nullptr; 3383 NewElements.push_back(PassthruElt); 3384 } else if (MaskElt->isOneValue()) { 3385 if (!VecElt) 3386 return nullptr; 3387 NewElements.push_back(VecElt); 3388 } else { 3389 return nullptr; 3390 } 3391 } 3392 if (NewElements.size() != FVTy->getNumElements()) 3393 return nullptr; 3394 return ConstantVector::get(NewElements); 3395 } 3396 case Intrinsic::arm_mve_vctp8: 3397 case Intrinsic::arm_mve_vctp16: 3398 case Intrinsic::arm_mve_vctp32: 3399 case Intrinsic::arm_mve_vctp64: { 3400 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) { 3401 unsigned Lanes = FVTy->getNumElements(); 3402 uint64_t Limit = Op->getZExtValue(); 3403 3404 SmallVector<Constant *, 16> NCs; 3405 for (unsigned i = 0; i < Lanes; i++) { 3406 if (i < Limit) 3407 NCs.push_back(ConstantInt::getTrue(Ty)); 3408 else 3409 NCs.push_back(ConstantInt::getFalse(Ty)); 3410 } 3411 return ConstantVector::get(NCs); 3412 } 3413 return nullptr; 3414 } 3415 case Intrinsic::get_active_lane_mask: { 3416 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]); 3417 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]); 3418 if (Op0 && Op1) { 3419 unsigned Lanes = FVTy->getNumElements(); 3420 uint64_t Base = Op0->getZExtValue(); 3421 uint64_t Limit = Op1->getZExtValue(); 3422 3423 SmallVector<Constant *, 16> NCs; 3424 for (unsigned i = 0; i < Lanes; i++) { 3425 if (Base + i < Limit) 3426 NCs.push_back(ConstantInt::getTrue(Ty)); 3427 else 3428 NCs.push_back(ConstantInt::getFalse(Ty)); 3429 } 3430 return ConstantVector::get(NCs); 3431 } 3432 return nullptr; 3433 } 3434 default: 3435 break; 3436 } 3437 3438 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) { 3439 // Gather a column of constants. 3440 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) { 3441 // Some intrinsics use a scalar type for certain arguments. 3442 if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, J)) { 3443 Lane[J] = Operands[J]; 3444 continue; 3445 } 3446 3447 Constant *Agg = Operands[J]->getAggregateElement(I); 3448 if (!Agg) 3449 return nullptr; 3450 3451 Lane[J] = Agg; 3452 } 3453 3454 // Use the regular scalar folding to simplify this column. 3455 Constant *Folded = 3456 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call); 3457 if (!Folded) 3458 return nullptr; 3459 Result[I] = Folded; 3460 } 3461 3462 return ConstantVector::get(Result); 3463 } 3464 3465 static Constant *ConstantFoldScalableVectorCall( 3466 StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy, 3467 ArrayRef<Constant *> Operands, const DataLayout &DL, 3468 const TargetLibraryInfo *TLI, const CallBase *Call) { 3469 switch (IntrinsicID) { 3470 case Intrinsic::aarch64_sve_convert_from_svbool: { 3471 auto *Src = dyn_cast<Constant>(Operands[0]); 3472 if (!Src || !Src->isNullValue()) 3473 break; 3474 3475 return ConstantInt::getFalse(SVTy); 3476 } 3477 default: 3478 break; 3479 } 3480 return nullptr; 3481 } 3482 3483 static std::pair<Constant *, Constant *> 3484 ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) { 3485 if (isa<PoisonValue>(Op)) 3486 return {Op, PoisonValue::get(IntTy)}; 3487 3488 auto *ConstFP = dyn_cast<ConstantFP>(Op); 3489 if (!ConstFP) 3490 return {}; 3491 3492 const APFloat &U = ConstFP->getValueAPF(); 3493 int FrexpExp; 3494 APFloat FrexpMant = frexp(U, FrexpExp, APFloat::rmNearestTiesToEven); 3495 Constant *Result0 = ConstantFP::get(ConstFP->getType(), FrexpMant); 3496 3497 // The exponent is an "unspecified value" for inf/nan. We use zero to avoid 3498 // using undef. 3499 Constant *Result1 = FrexpMant.isFinite() 3500 ? ConstantInt::getSigned(IntTy, FrexpExp) 3501 : ConstantInt::getNullValue(IntTy); 3502 return {Result0, Result1}; 3503 } 3504 3505 /// Handle intrinsics that return tuples, which may be tuples of vectors. 3506 static Constant * 3507 ConstantFoldStructCall(StringRef Name, Intrinsic::ID IntrinsicID, 3508 StructType *StTy, ArrayRef<Constant *> Operands, 3509 const DataLayout &DL, const TargetLibraryInfo *TLI, 3510 const CallBase *Call) { 3511 3512 switch (IntrinsicID) { 3513 case Intrinsic::frexp: { 3514 Type *Ty0 = StTy->getContainedType(0); 3515 Type *Ty1 = StTy->getContainedType(1)->getScalarType(); 3516 3517 if (auto *FVTy0 = dyn_cast<FixedVectorType>(Ty0)) { 3518 SmallVector<Constant *, 4> Results0(FVTy0->getNumElements()); 3519 SmallVector<Constant *, 4> Results1(FVTy0->getNumElements()); 3520 3521 for (unsigned I = 0, E = FVTy0->getNumElements(); I != E; ++I) { 3522 Constant *Lane = Operands[0]->getAggregateElement(I); 3523 std::tie(Results0[I], Results1[I]) = 3524 ConstantFoldScalarFrexpCall(Lane, Ty1); 3525 if (!Results0[I]) 3526 return nullptr; 3527 } 3528 3529 return ConstantStruct::get(StTy, ConstantVector::get(Results0), 3530 ConstantVector::get(Results1)); 3531 } 3532 3533 auto [Result0, Result1] = ConstantFoldScalarFrexpCall(Operands[0], Ty1); 3534 if (!Result0) 3535 return nullptr; 3536 return ConstantStruct::get(StTy, Result0, Result1); 3537 } 3538 case Intrinsic::sincos: { 3539 Type *Ty = StTy->getContainedType(0); 3540 Type *TyScalar = Ty->getScalarType(); 3541 3542 auto ConstantFoldScalarSincosCall = 3543 [&](Constant *Op) -> std::pair<Constant *, Constant *> { 3544 Constant *SinResult = 3545 ConstantFoldScalarCall(Name, Intrinsic::sin, TyScalar, Op, TLI, Call); 3546 Constant *CosResult = 3547 ConstantFoldScalarCall(Name, Intrinsic::cos, TyScalar, Op, TLI, Call); 3548 return std::make_pair(SinResult, CosResult); 3549 }; 3550 3551 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) { 3552 SmallVector<Constant *> SinResults(FVTy->getNumElements()); 3553 SmallVector<Constant *> CosResults(FVTy->getNumElements()); 3554 3555 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) { 3556 Constant *Lane = Operands[0]->getAggregateElement(I); 3557 std::tie(SinResults[I], CosResults[I]) = 3558 ConstantFoldScalarSincosCall(Lane); 3559 if (!SinResults[I] || !CosResults[I]) 3560 return nullptr; 3561 } 3562 3563 return ConstantStruct::get(StTy, ConstantVector::get(SinResults), 3564 ConstantVector::get(CosResults)); 3565 } 3566 3567 auto [SinResult, CosResult] = ConstantFoldScalarSincosCall(Operands[0]); 3568 if (!SinResult || !CosResult) 3569 return nullptr; 3570 return ConstantStruct::get(StTy, SinResult, CosResult); 3571 } 3572 default: 3573 // TODO: Constant folding of vector intrinsics that fall through here does 3574 // not work (e.g. overflow intrinsics) 3575 return ConstantFoldScalarCall(Name, IntrinsicID, StTy, Operands, TLI, Call); 3576 } 3577 3578 return nullptr; 3579 } 3580 3581 } // end anonymous namespace 3582 3583 Constant *llvm::ConstantFoldBinaryIntrinsic(Intrinsic::ID ID, Constant *LHS, 3584 Constant *RHS, Type *Ty, 3585 Instruction *FMFSource) { 3586 return ConstantFoldIntrinsicCall2(ID, Ty, {LHS, RHS}, 3587 dyn_cast_if_present<CallBase>(FMFSource)); 3588 } 3589 3590 Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F, 3591 ArrayRef<Constant *> Operands, 3592 const TargetLibraryInfo *TLI, 3593 bool AllowNonDeterministic) { 3594 if (Call->isNoBuiltin()) 3595 return nullptr; 3596 if (!F->hasName()) 3597 return nullptr; 3598 3599 // If this is not an intrinsic and not recognized as a library call, bail out. 3600 Intrinsic::ID IID = F->getIntrinsicID(); 3601 if (IID == Intrinsic::not_intrinsic) { 3602 if (!TLI) 3603 return nullptr; 3604 LibFunc LibF; 3605 if (!TLI->getLibFunc(*F, LibF)) 3606 return nullptr; 3607 } 3608 3609 // Conservatively assume that floating-point libcalls may be 3610 // non-deterministic. 3611 Type *Ty = F->getReturnType(); 3612 if (!AllowNonDeterministic && Ty->isFPOrFPVectorTy()) 3613 return nullptr; 3614 3615 StringRef Name = F->getName(); 3616 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) 3617 return ConstantFoldFixedVectorCall( 3618 Name, IID, FVTy, Operands, F->getDataLayout(), TLI, Call); 3619 3620 if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty)) 3621 return ConstantFoldScalableVectorCall( 3622 Name, IID, SVTy, Operands, F->getDataLayout(), TLI, Call); 3623 3624 if (auto *StTy = dyn_cast<StructType>(Ty)) 3625 return ConstantFoldStructCall(Name, IID, StTy, Operands, 3626 F->getDataLayout(), TLI, Call); 3627 3628 // TODO: If this is a library function, we already discovered that above, 3629 // so we should pass the LibFunc, not the name (and it might be better 3630 // still to separate intrinsic handling from libcalls). 3631 return ConstantFoldScalarCall(Name, IID, Ty, Operands, TLI, Call); 3632 } 3633 3634 bool llvm::isMathLibCallNoop(const CallBase *Call, 3635 const TargetLibraryInfo *TLI) { 3636 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap 3637 // (and to some extent ConstantFoldScalarCall). 3638 if (Call->isNoBuiltin() || Call->isStrictFP()) 3639 return false; 3640 Function *F = Call->getCalledFunction(); 3641 if (!F) 3642 return false; 3643 3644 LibFunc Func; 3645 if (!TLI || !TLI->getLibFunc(*F, Func)) 3646 return false; 3647 3648 if (Call->arg_size() == 1) { 3649 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) { 3650 const APFloat &Op = OpC->getValueAPF(); 3651 switch (Func) { 3652 case LibFunc_logl: 3653 case LibFunc_log: 3654 case LibFunc_logf: 3655 case LibFunc_log2l: 3656 case LibFunc_log2: 3657 case LibFunc_log2f: 3658 case LibFunc_log10l: 3659 case LibFunc_log10: 3660 case LibFunc_log10f: 3661 return Op.isNaN() || (!Op.isZero() && !Op.isNegative()); 3662 3663 case LibFunc_expl: 3664 case LibFunc_exp: 3665 case LibFunc_expf: 3666 // FIXME: These boundaries are slightly conservative. 3667 if (OpC->getType()->isDoubleTy()) 3668 return !(Op < APFloat(-745.0) || Op > APFloat(709.0)); 3669 if (OpC->getType()->isFloatTy()) 3670 return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f)); 3671 break; 3672 3673 case LibFunc_exp2l: 3674 case LibFunc_exp2: 3675 case LibFunc_exp2f: 3676 // FIXME: These boundaries are slightly conservative. 3677 if (OpC->getType()->isDoubleTy()) 3678 return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0)); 3679 if (OpC->getType()->isFloatTy()) 3680 return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f)); 3681 break; 3682 3683 case LibFunc_sinl: 3684 case LibFunc_sin: 3685 case LibFunc_sinf: 3686 case LibFunc_cosl: 3687 case LibFunc_cos: 3688 case LibFunc_cosf: 3689 return !Op.isInfinity(); 3690 3691 case LibFunc_tanl: 3692 case LibFunc_tan: 3693 case LibFunc_tanf: { 3694 // FIXME: Stop using the host math library. 3695 // FIXME: The computation isn't done in the right precision. 3696 Type *Ty = OpC->getType(); 3697 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) 3698 return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr; 3699 break; 3700 } 3701 3702 case LibFunc_atan: 3703 case LibFunc_atanf: 3704 case LibFunc_atanl: 3705 // Per POSIX, this MAY fail if Op is denormal. We choose not failing. 3706 return true; 3707 3708 case LibFunc_asinl: 3709 case LibFunc_asin: 3710 case LibFunc_asinf: 3711 case LibFunc_acosl: 3712 case LibFunc_acos: 3713 case LibFunc_acosf: 3714 return !(Op < APFloat::getOne(Op.getSemantics(), true) || 3715 Op > APFloat::getOne(Op.getSemantics())); 3716 3717 case LibFunc_sinh: 3718 case LibFunc_cosh: 3719 case LibFunc_sinhf: 3720 case LibFunc_coshf: 3721 case LibFunc_sinhl: 3722 case LibFunc_coshl: 3723 // FIXME: These boundaries are slightly conservative. 3724 if (OpC->getType()->isDoubleTy()) 3725 return !(Op < APFloat(-710.0) || Op > APFloat(710.0)); 3726 if (OpC->getType()->isFloatTy()) 3727 return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f)); 3728 break; 3729 3730 case LibFunc_sqrtl: 3731 case LibFunc_sqrt: 3732 case LibFunc_sqrtf: 3733 return Op.isNaN() || Op.isZero() || !Op.isNegative(); 3734 3735 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p, 3736 // maybe others? 3737 default: 3738 break; 3739 } 3740 } 3741 } 3742 3743 if (Call->arg_size() == 2) { 3744 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0)); 3745 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1)); 3746 if (Op0C && Op1C) { 3747 const APFloat &Op0 = Op0C->getValueAPF(); 3748 const APFloat &Op1 = Op1C->getValueAPF(); 3749 3750 switch (Func) { 3751 case LibFunc_powl: 3752 case LibFunc_pow: 3753 case LibFunc_powf: { 3754 // FIXME: Stop using the host math library. 3755 // FIXME: The computation isn't done in the right precision. 3756 Type *Ty = Op0C->getType(); 3757 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) { 3758 if (Ty == Op1C->getType()) 3759 return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr; 3760 } 3761 break; 3762 } 3763 3764 case LibFunc_fmodl: 3765 case LibFunc_fmod: 3766 case LibFunc_fmodf: 3767 case LibFunc_remainderl: 3768 case LibFunc_remainder: 3769 case LibFunc_remainderf: 3770 return Op0.isNaN() || Op1.isNaN() || 3771 (!Op0.isInfinity() && !Op1.isZero()); 3772 3773 case LibFunc_atan2: 3774 case LibFunc_atan2f: 3775 case LibFunc_atan2l: 3776 // Although IEEE-754 says atan2(+/-0.0, +/-0.0) are well-defined, and 3777 // GLIBC and MSVC do not appear to raise an error on those, we 3778 // cannot rely on that behavior. POSIX and C11 say that a domain error 3779 // may occur, so allow for that possibility. 3780 return !Op0.isZero() || !Op1.isZero(); 3781 3782 default: 3783 break; 3784 } 3785 } 3786 } 3787 3788 return false; 3789 } 3790 3791 void TargetFolder::anchor() {} 3792