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