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