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