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