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