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