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