1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===// 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 implements folding of constants for LLVM. This implements the 10 // (internal) ConstantFold.h interface, which is used by the 11 // ConstantExpr::get* methods to automatically fold constants when possible. 12 // 13 // The current constant folding implementation is implemented in two pieces: the 14 // pieces that don't need DataLayout, and the pieces that do. This is to avoid 15 // a dependence in IR on Target. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "ConstantFold.h" 20 #include "llvm/ADT/APSInt.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GetElementPtrTypeIterator.h" 26 #include "llvm/IR/GlobalAlias.h" 27 #include "llvm/IR/GlobalVariable.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/Operator.h" 31 #include "llvm/IR/PatternMatch.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/ManagedStatic.h" 34 #include "llvm/Support/MathExtras.h" 35 using namespace llvm; 36 using namespace llvm::PatternMatch; 37 38 //===----------------------------------------------------------------------===// 39 // ConstantFold*Instruction Implementations 40 //===----------------------------------------------------------------------===// 41 42 /// Convert the specified vector Constant node to the specified vector type. 43 /// At this point, we know that the elements of the input vector constant are 44 /// all simple integer or FP values. 45 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) { 46 47 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy); 48 if (CV->isNullValue()) return Constant::getNullValue(DstTy); 49 50 // Do not iterate on scalable vector. The num of elements is unknown at 51 // compile-time. 52 if (DstTy->isScalable()) 53 return nullptr; 54 55 // If this cast changes element count then we can't handle it here: 56 // doing so requires endianness information. This should be handled by 57 // Analysis/ConstantFolding.cpp 58 unsigned NumElts = DstTy->getNumElements(); 59 if (NumElts != CV->getType()->getVectorNumElements()) 60 return nullptr; 61 62 Type *DstEltTy = DstTy->getElementType(); 63 // Fast path for splatted constants. 64 if (Constant *Splat = CV->getSplatValue()) { 65 return ConstantVector::getSplat(DstTy->getVectorElementCount(), 66 ConstantExpr::getBitCast(Splat, DstEltTy)); 67 } 68 69 SmallVector<Constant*, 16> Result; 70 Type *Ty = IntegerType::get(CV->getContext(), 32); 71 for (unsigned i = 0; i != NumElts; ++i) { 72 Constant *C = 73 ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i)); 74 C = ConstantExpr::getBitCast(C, DstEltTy); 75 Result.push_back(C); 76 } 77 78 return ConstantVector::get(Result); 79 } 80 81 /// This function determines which opcode to use to fold two constant cast 82 /// expressions together. It uses CastInst::isEliminableCastPair to determine 83 /// the opcode. Consequently its just a wrapper around that function. 84 /// Determine if it is valid to fold a cast of a cast 85 static unsigned 86 foldConstantCastPair( 87 unsigned opc, ///< opcode of the second cast constant expression 88 ConstantExpr *Op, ///< the first cast constant expression 89 Type *DstTy ///< destination type of the first cast 90 ) { 91 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!"); 92 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type"); 93 assert(CastInst::isCast(opc) && "Invalid cast opcode"); 94 95 // The types and opcodes for the two Cast constant expressions 96 Type *SrcTy = Op->getOperand(0)->getType(); 97 Type *MidTy = Op->getType(); 98 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode()); 99 Instruction::CastOps secondOp = Instruction::CastOps(opc); 100 101 // Assume that pointers are never more than 64 bits wide, and only use this 102 // for the middle type. Otherwise we could end up folding away illegal 103 // bitcasts between address spaces with different sizes. 104 IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext()); 105 106 // Let CastInst::isEliminableCastPair do the heavy lifting. 107 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy, 108 nullptr, FakeIntPtrTy, nullptr); 109 } 110 111 static Constant *FoldBitCast(Constant *V, Type *DestTy) { 112 Type *SrcTy = V->getType(); 113 if (SrcTy == DestTy) 114 return V; // no-op cast 115 116 // Check to see if we are casting a pointer to an aggregate to a pointer to 117 // the first element. If so, return the appropriate GEP instruction. 118 if (PointerType *PTy = dyn_cast<PointerType>(V->getType())) 119 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy)) 120 if (PTy->getAddressSpace() == DPTy->getAddressSpace() 121 && PTy->getElementType()->isSized()) { 122 SmallVector<Value*, 8> IdxList; 123 Value *Zero = 124 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext())); 125 IdxList.push_back(Zero); 126 Type *ElTy = PTy->getElementType(); 127 while (ElTy && ElTy != DPTy->getElementType()) { 128 ElTy = GetElementPtrInst::getTypeAtIndex(ElTy, (uint64_t)0); 129 IdxList.push_back(Zero); 130 } 131 132 if (ElTy == DPTy->getElementType()) 133 // This GEP is inbounds because all indices are zero. 134 return ConstantExpr::getInBoundsGetElementPtr(PTy->getElementType(), 135 V, IdxList); 136 } 137 138 // Handle casts from one vector constant to another. We know that the src 139 // and dest type have the same size (otherwise its an illegal cast). 140 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) { 141 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) { 142 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() && 143 "Not cast between same sized vectors!"); 144 SrcTy = nullptr; 145 // First, check for null. Undef is already handled. 146 if (isa<ConstantAggregateZero>(V)) 147 return Constant::getNullValue(DestTy); 148 149 // Handle ConstantVector and ConstantAggregateVector. 150 return BitCastConstantVector(V, DestPTy); 151 } 152 153 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts 154 // This allows for other simplifications (although some of them 155 // can only be handled by Analysis/ConstantFolding.cpp). 156 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) 157 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy); 158 } 159 160 // Finally, implement bitcast folding now. The code below doesn't handle 161 // bitcast right. 162 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast. 163 return ConstantPointerNull::get(cast<PointerType>(DestTy)); 164 165 // Handle integral constant input. 166 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 167 if (DestTy->isIntegerTy()) 168 // Integral -> Integral. This is a no-op because the bit widths must 169 // be the same. Consequently, we just fold to V. 170 return V; 171 172 // See note below regarding the PPC_FP128 restriction. 173 if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty()) 174 return ConstantFP::get(DestTy->getContext(), 175 APFloat(DestTy->getFltSemantics(), 176 CI->getValue())); 177 178 // Otherwise, can't fold this (vector?) 179 return nullptr; 180 } 181 182 // Handle ConstantFP input: FP -> Integral. 183 if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) { 184 // PPC_FP128 is really the sum of two consecutive doubles, where the first 185 // double is always stored first in memory, regardless of the target 186 // endianness. The memory layout of i128, however, depends on the target 187 // endianness, and so we can't fold this without target endianness 188 // information. This should instead be handled by 189 // Analysis/ConstantFolding.cpp 190 if (FP->getType()->isPPC_FP128Ty()) 191 return nullptr; 192 193 // Make sure dest type is compatible with the folded integer constant. 194 if (!DestTy->isIntegerTy()) 195 return nullptr; 196 197 return ConstantInt::get(FP->getContext(), 198 FP->getValueAPF().bitcastToAPInt()); 199 } 200 201 return nullptr; 202 } 203 204 205 /// V is an integer constant which only has a subset of its bytes used. 206 /// The bytes used are indicated by ByteStart (which is the first byte used, 207 /// counting from the least significant byte) and ByteSize, which is the number 208 /// of bytes used. 209 /// 210 /// This function analyzes the specified constant to see if the specified byte 211 /// range can be returned as a simplified constant. If so, the constant is 212 /// returned, otherwise null is returned. 213 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart, 214 unsigned ByteSize) { 215 assert(C->getType()->isIntegerTy() && 216 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 && 217 "Non-byte sized integer input"); 218 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8; 219 assert(ByteSize && "Must be accessing some piece"); 220 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input"); 221 assert(ByteSize != CSize && "Should not extract everything"); 222 223 // Constant Integers are simple. 224 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) { 225 APInt V = CI->getValue(); 226 if (ByteStart) 227 V.lshrInPlace(ByteStart*8); 228 V = V.trunc(ByteSize*8); 229 return ConstantInt::get(CI->getContext(), V); 230 } 231 232 // In the input is a constant expr, we might be able to recursively simplify. 233 // If not, we definitely can't do anything. 234 ConstantExpr *CE = dyn_cast<ConstantExpr>(C); 235 if (!CE) return nullptr; 236 237 switch (CE->getOpcode()) { 238 default: return nullptr; 239 case Instruction::Or: { 240 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize); 241 if (!RHS) 242 return nullptr; 243 244 // X | -1 -> -1. 245 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) 246 if (RHSC->isMinusOne()) 247 return RHSC; 248 249 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize); 250 if (!LHS) 251 return nullptr; 252 return ConstantExpr::getOr(LHS, RHS); 253 } 254 case Instruction::And: { 255 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize); 256 if (!RHS) 257 return nullptr; 258 259 // X & 0 -> 0. 260 if (RHS->isNullValue()) 261 return RHS; 262 263 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize); 264 if (!LHS) 265 return nullptr; 266 return ConstantExpr::getAnd(LHS, RHS); 267 } 268 case Instruction::LShr: { 269 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1)); 270 if (!Amt) 271 return nullptr; 272 APInt ShAmt = Amt->getValue(); 273 // Cannot analyze non-byte shifts. 274 if ((ShAmt & 7) != 0) 275 return nullptr; 276 ShAmt.lshrInPlace(3); 277 278 // If the extract is known to be all zeros, return zero. 279 if (ShAmt.uge(CSize - ByteStart)) 280 return Constant::getNullValue( 281 IntegerType::get(CE->getContext(), ByteSize * 8)); 282 // If the extract is known to be fully in the input, extract it. 283 if (ShAmt.ule(CSize - (ByteStart + ByteSize))) 284 return ExtractConstantBytes(CE->getOperand(0), 285 ByteStart + ShAmt.getZExtValue(), ByteSize); 286 287 // TODO: Handle the 'partially zero' case. 288 return nullptr; 289 } 290 291 case Instruction::Shl: { 292 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1)); 293 if (!Amt) 294 return nullptr; 295 APInt ShAmt = Amt->getValue(); 296 // Cannot analyze non-byte shifts. 297 if ((ShAmt & 7) != 0) 298 return nullptr; 299 ShAmt.lshrInPlace(3); 300 301 // If the extract is known to be all zeros, return zero. 302 if (ShAmt.uge(ByteStart + ByteSize)) 303 return Constant::getNullValue( 304 IntegerType::get(CE->getContext(), ByteSize * 8)); 305 // If the extract is known to be fully in the input, extract it. 306 if (ShAmt.ule(ByteStart)) 307 return ExtractConstantBytes(CE->getOperand(0), 308 ByteStart - ShAmt.getZExtValue(), ByteSize); 309 310 // TODO: Handle the 'partially zero' case. 311 return nullptr; 312 } 313 314 case Instruction::ZExt: { 315 unsigned SrcBitSize = 316 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth(); 317 318 // If extracting something that is completely zero, return 0. 319 if (ByteStart*8 >= SrcBitSize) 320 return Constant::getNullValue(IntegerType::get(CE->getContext(), 321 ByteSize*8)); 322 323 // If exactly extracting the input, return it. 324 if (ByteStart == 0 && ByteSize*8 == SrcBitSize) 325 return CE->getOperand(0); 326 327 // If extracting something completely in the input, if the input is a 328 // multiple of 8 bits, recurse. 329 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize) 330 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize); 331 332 // Otherwise, if extracting a subset of the input, which is not multiple of 333 // 8 bits, do a shift and trunc to get the bits. 334 if ((ByteStart+ByteSize)*8 < SrcBitSize) { 335 assert((SrcBitSize&7) && "Shouldn't get byte sized case here"); 336 Constant *Res = CE->getOperand(0); 337 if (ByteStart) 338 Res = ConstantExpr::getLShr(Res, 339 ConstantInt::get(Res->getType(), ByteStart*8)); 340 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(), 341 ByteSize*8)); 342 } 343 344 // TODO: Handle the 'partially zero' case. 345 return nullptr; 346 } 347 } 348 } 349 350 /// Return a ConstantExpr with type DestTy for sizeof on Ty, with any known 351 /// factors factored out. If Folded is false, return null if no factoring was 352 /// possible, to avoid endlessly bouncing an unfoldable expression back into the 353 /// top-level folder. 354 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, bool Folded) { 355 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 356 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements()); 357 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true); 358 return ConstantExpr::getNUWMul(E, N); 359 } 360 361 if (StructType *STy = dyn_cast<StructType>(Ty)) 362 if (!STy->isPacked()) { 363 unsigned NumElems = STy->getNumElements(); 364 // An empty struct has size zero. 365 if (NumElems == 0) 366 return ConstantExpr::getNullValue(DestTy); 367 // Check for a struct with all members having the same size. 368 Constant *MemberSize = 369 getFoldedSizeOf(STy->getElementType(0), DestTy, true); 370 bool AllSame = true; 371 for (unsigned i = 1; i != NumElems; ++i) 372 if (MemberSize != 373 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) { 374 AllSame = false; 375 break; 376 } 377 if (AllSame) { 378 Constant *N = ConstantInt::get(DestTy, NumElems); 379 return ConstantExpr::getNUWMul(MemberSize, N); 380 } 381 } 382 383 // Pointer size doesn't depend on the pointee type, so canonicalize them 384 // to an arbitrary pointee. 385 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 386 if (!PTy->getElementType()->isIntegerTy(1)) 387 return 388 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1), 389 PTy->getAddressSpace()), 390 DestTy, true); 391 392 // If there's no interesting folding happening, bail so that we don't create 393 // a constant that looks like it needs folding but really doesn't. 394 if (!Folded) 395 return nullptr; 396 397 // Base case: Get a regular sizeof expression. 398 Constant *C = ConstantExpr::getSizeOf(Ty); 399 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 400 DestTy, false), 401 C, DestTy); 402 return C; 403 } 404 405 /// Return a ConstantExpr with type DestTy for alignof on Ty, with any known 406 /// factors factored out. If Folded is false, return null if no factoring was 407 /// possible, to avoid endlessly bouncing an unfoldable expression back into the 408 /// top-level folder. 409 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy, bool Folded) { 410 // The alignment of an array is equal to the alignment of the 411 // array element. Note that this is not always true for vectors. 412 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 413 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType()); 414 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 415 DestTy, 416 false), 417 C, DestTy); 418 return C; 419 } 420 421 if (StructType *STy = dyn_cast<StructType>(Ty)) { 422 // Packed structs always have an alignment of 1. 423 if (STy->isPacked()) 424 return ConstantInt::get(DestTy, 1); 425 426 // Otherwise, struct alignment is the maximum alignment of any member. 427 // Without target data, we can't compare much, but we can check to see 428 // if all the members have the same alignment. 429 unsigned NumElems = STy->getNumElements(); 430 // An empty struct has minimal alignment. 431 if (NumElems == 0) 432 return ConstantInt::get(DestTy, 1); 433 // Check for a struct with all members having the same alignment. 434 Constant *MemberAlign = 435 getFoldedAlignOf(STy->getElementType(0), DestTy, true); 436 bool AllSame = true; 437 for (unsigned i = 1; i != NumElems; ++i) 438 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) { 439 AllSame = false; 440 break; 441 } 442 if (AllSame) 443 return MemberAlign; 444 } 445 446 // Pointer alignment doesn't depend on the pointee type, so canonicalize them 447 // to an arbitrary pointee. 448 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 449 if (!PTy->getElementType()->isIntegerTy(1)) 450 return 451 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(), 452 1), 453 PTy->getAddressSpace()), 454 DestTy, true); 455 456 // If there's no interesting folding happening, bail so that we don't create 457 // a constant that looks like it needs folding but really doesn't. 458 if (!Folded) 459 return nullptr; 460 461 // Base case: Get a regular alignof expression. 462 Constant *C = ConstantExpr::getAlignOf(Ty); 463 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 464 DestTy, false), 465 C, DestTy); 466 return C; 467 } 468 469 /// Return a ConstantExpr with type DestTy for offsetof on Ty and FieldNo, with 470 /// any known factors factored out. If Folded is false, return null if no 471 /// factoring was possible, to avoid endlessly bouncing an unfoldable expression 472 /// back into the top-level folder. 473 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo, Type *DestTy, 474 bool Folded) { 475 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 476 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false, 477 DestTy, false), 478 FieldNo, DestTy); 479 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true); 480 return ConstantExpr::getNUWMul(E, N); 481 } 482 483 if (StructType *STy = dyn_cast<StructType>(Ty)) 484 if (!STy->isPacked()) { 485 unsigned NumElems = STy->getNumElements(); 486 // An empty struct has no members. 487 if (NumElems == 0) 488 return nullptr; 489 // Check for a struct with all members having the same size. 490 Constant *MemberSize = 491 getFoldedSizeOf(STy->getElementType(0), DestTy, true); 492 bool AllSame = true; 493 for (unsigned i = 1; i != NumElems; ++i) 494 if (MemberSize != 495 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) { 496 AllSame = false; 497 break; 498 } 499 if (AllSame) { 500 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, 501 false, 502 DestTy, 503 false), 504 FieldNo, DestTy); 505 return ConstantExpr::getNUWMul(MemberSize, N); 506 } 507 } 508 509 // If there's no interesting folding happening, bail so that we don't create 510 // a constant that looks like it needs folding but really doesn't. 511 if (!Folded) 512 return nullptr; 513 514 // Base case: Get a regular offsetof expression. 515 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo); 516 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 517 DestTy, false), 518 C, DestTy); 519 return C; 520 } 521 522 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V, 523 Type *DestTy) { 524 if (isa<UndefValue>(V)) { 525 // zext(undef) = 0, because the top bits will be zero. 526 // sext(undef) = 0, because the top bits will all be the same. 527 // [us]itofp(undef) = 0, because the result value is bounded. 528 if (opc == Instruction::ZExt || opc == Instruction::SExt || 529 opc == Instruction::UIToFP || opc == Instruction::SIToFP) 530 return Constant::getNullValue(DestTy); 531 return UndefValue::get(DestTy); 532 } 533 534 if (V->isNullValue() && !DestTy->isX86_MMXTy() && 535 opc != Instruction::AddrSpaceCast) 536 return Constant::getNullValue(DestTy); 537 538 // If the cast operand is a constant expression, there's a few things we can 539 // do to try to simplify it. 540 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 541 if (CE->isCast()) { 542 // Try hard to fold cast of cast because they are often eliminable. 543 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy)) 544 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy); 545 } else if (CE->getOpcode() == Instruction::GetElementPtr && 546 // Do not fold addrspacecast (gep 0, .., 0). It might make the 547 // addrspacecast uncanonicalized. 548 opc != Instruction::AddrSpaceCast && 549 // Do not fold bitcast (gep) with inrange index, as this loses 550 // information. 551 !cast<GEPOperator>(CE)->getInRangeIndex().hasValue() && 552 // Do not fold if the gep type is a vector, as bitcasting 553 // operand 0 of a vector gep will result in a bitcast between 554 // different sizes. 555 !CE->getType()->isVectorTy()) { 556 // If all of the indexes in the GEP are null values, there is no pointer 557 // adjustment going on. We might as well cast the source pointer. 558 bool isAllNull = true; 559 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) 560 if (!CE->getOperand(i)->isNullValue()) { 561 isAllNull = false; 562 break; 563 } 564 if (isAllNull) 565 // This is casting one pointer type to another, always BitCast 566 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy); 567 } 568 } 569 570 // If the cast operand is a constant vector, perform the cast by 571 // operating on each element. In the cast of bitcasts, the element 572 // count may be mismatched; don't attempt to handle that here. 573 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) && 574 DestTy->isVectorTy() && 575 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) { 576 VectorType *DestVecTy = cast<VectorType>(DestTy); 577 Type *DstEltTy = DestVecTy->getElementType(); 578 // Fast path for splatted constants. 579 if (Constant *Splat = V->getSplatValue()) { 580 return ConstantVector::getSplat( 581 DestTy->getVectorElementCount(), 582 ConstantExpr::getCast(opc, Splat, DstEltTy)); 583 } 584 SmallVector<Constant *, 16> res; 585 Type *Ty = IntegerType::get(V->getContext(), 32); 586 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) { 587 Constant *C = 588 ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i)); 589 res.push_back(ConstantExpr::getCast(opc, C, DstEltTy)); 590 } 591 return ConstantVector::get(res); 592 } 593 594 // We actually have to do a cast now. Perform the cast according to the 595 // opcode specified. 596 switch (opc) { 597 default: 598 llvm_unreachable("Failed to cast constant expression"); 599 case Instruction::FPTrunc: 600 case Instruction::FPExt: 601 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) { 602 bool ignored; 603 APFloat Val = FPC->getValueAPF(); 604 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf() : 605 DestTy->isFloatTy() ? APFloat::IEEEsingle() : 606 DestTy->isDoubleTy() ? APFloat::IEEEdouble() : 607 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended() : 608 DestTy->isFP128Ty() ? APFloat::IEEEquad() : 609 DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble() : 610 APFloat::Bogus(), 611 APFloat::rmNearestTiesToEven, &ignored); 612 return ConstantFP::get(V->getContext(), Val); 613 } 614 return nullptr; // Can't fold. 615 case Instruction::FPToUI: 616 case Instruction::FPToSI: 617 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) { 618 const APFloat &V = FPC->getValueAPF(); 619 bool ignored; 620 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 621 APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI); 622 if (APFloat::opInvalidOp == 623 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) { 624 // Undefined behavior invoked - the destination type can't represent 625 // the input constant. 626 return UndefValue::get(DestTy); 627 } 628 return ConstantInt::get(FPC->getContext(), IntVal); 629 } 630 return nullptr; // Can't fold. 631 case Instruction::IntToPtr: //always treated as unsigned 632 if (V->isNullValue()) // Is it an integral null value? 633 return ConstantPointerNull::get(cast<PointerType>(DestTy)); 634 return nullptr; // Other pointer types cannot be casted 635 case Instruction::PtrToInt: // always treated as unsigned 636 // Is it a null pointer value? 637 if (V->isNullValue()) 638 return ConstantInt::get(DestTy, 0); 639 // If this is a sizeof-like expression, pull out multiplications by 640 // known factors to expose them to subsequent folding. If it's an 641 // alignof-like expression, factor out known factors. 642 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 643 if (CE->getOpcode() == Instruction::GetElementPtr && 644 CE->getOperand(0)->isNullValue()) { 645 // FIXME: Looks like getFoldedSizeOf(), getFoldedOffsetOf() and 646 // getFoldedAlignOf() don't handle the case when DestTy is a vector of 647 // pointers yet. We end up in asserts in CastInst::getCastOpcode (see 648 // test/Analysis/ConstantFolding/cast-vector.ll). I've only seen this 649 // happen in one "real" C-code test case, so it does not seem to be an 650 // important optimization to handle vectors here. For now, simply bail 651 // out. 652 if (DestTy->isVectorTy()) 653 return nullptr; 654 GEPOperator *GEPO = cast<GEPOperator>(CE); 655 Type *Ty = GEPO->getSourceElementType(); 656 if (CE->getNumOperands() == 2) { 657 // Handle a sizeof-like expression. 658 Constant *Idx = CE->getOperand(1); 659 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne(); 660 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) { 661 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true, 662 DestTy, false), 663 Idx, DestTy); 664 return ConstantExpr::getMul(C, Idx); 665 } 666 } else if (CE->getNumOperands() == 3 && 667 CE->getOperand(1)->isNullValue()) { 668 // Handle an alignof-like expression. 669 if (StructType *STy = dyn_cast<StructType>(Ty)) 670 if (!STy->isPacked()) { 671 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2)); 672 if (CI->isOne() && 673 STy->getNumElements() == 2 && 674 STy->getElementType(0)->isIntegerTy(1)) { 675 return getFoldedAlignOf(STy->getElementType(1), DestTy, false); 676 } 677 } 678 // Handle an offsetof-like expression. 679 if (Ty->isStructTy() || Ty->isArrayTy()) { 680 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2), 681 DestTy, false)) 682 return C; 683 } 684 } 685 } 686 // Other pointer types cannot be casted 687 return nullptr; 688 case Instruction::UIToFP: 689 case Instruction::SIToFP: 690 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 691 const APInt &api = CI->getValue(); 692 APFloat apf(DestTy->getFltSemantics(), 693 APInt::getNullValue(DestTy->getPrimitiveSizeInBits())); 694 apf.convertFromAPInt(api, opc==Instruction::SIToFP, 695 APFloat::rmNearestTiesToEven); 696 return ConstantFP::get(V->getContext(), apf); 697 } 698 return nullptr; 699 case Instruction::ZExt: 700 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 701 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 702 return ConstantInt::get(V->getContext(), 703 CI->getValue().zext(BitWidth)); 704 } 705 return nullptr; 706 case Instruction::SExt: 707 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 708 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 709 return ConstantInt::get(V->getContext(), 710 CI->getValue().sext(BitWidth)); 711 } 712 return nullptr; 713 case Instruction::Trunc: { 714 if (V->getType()->isVectorTy()) 715 return nullptr; 716 717 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 718 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 719 return ConstantInt::get(V->getContext(), 720 CI->getValue().trunc(DestBitWidth)); 721 } 722 723 // The input must be a constantexpr. See if we can simplify this based on 724 // the bytes we are demanding. Only do this if the source and dest are an 725 // even multiple of a byte. 726 if ((DestBitWidth & 7) == 0 && 727 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0) 728 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8)) 729 return Res; 730 731 return nullptr; 732 } 733 case Instruction::BitCast: 734 return FoldBitCast(V, DestTy); 735 case Instruction::AddrSpaceCast: 736 return nullptr; 737 } 738 } 739 740 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond, 741 Constant *V1, Constant *V2) { 742 // Check for i1 and vector true/false conditions. 743 if (Cond->isNullValue()) return V2; 744 if (Cond->isAllOnesValue()) return V1; 745 746 // If the condition is a vector constant, fold the result elementwise. 747 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) { 748 SmallVector<Constant*, 16> Result; 749 Type *Ty = IntegerType::get(CondV->getContext(), 32); 750 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){ 751 Constant *V; 752 Constant *V1Element = ConstantExpr::getExtractElement(V1, 753 ConstantInt::get(Ty, i)); 754 Constant *V2Element = ConstantExpr::getExtractElement(V2, 755 ConstantInt::get(Ty, i)); 756 auto *Cond = cast<Constant>(CondV->getOperand(i)); 757 if (V1Element == V2Element) { 758 V = V1Element; 759 } else if (isa<UndefValue>(Cond)) { 760 V = isa<UndefValue>(V1Element) ? V1Element : V2Element; 761 } else { 762 if (!isa<ConstantInt>(Cond)) break; 763 V = Cond->isNullValue() ? V2Element : V1Element; 764 } 765 Result.push_back(V); 766 } 767 768 // If we were able to build the vector, return it. 769 if (Result.size() == V1->getType()->getVectorNumElements()) 770 return ConstantVector::get(Result); 771 } 772 773 if (isa<UndefValue>(Cond)) { 774 if (isa<UndefValue>(V1)) return V1; 775 return V2; 776 } 777 if (isa<UndefValue>(V1)) return V2; 778 if (isa<UndefValue>(V2)) return V1; 779 if (V1 == V2) return V1; 780 781 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) { 782 if (TrueVal->getOpcode() == Instruction::Select) 783 if (TrueVal->getOperand(0) == Cond) 784 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2); 785 } 786 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) { 787 if (FalseVal->getOpcode() == Instruction::Select) 788 if (FalseVal->getOperand(0) == Cond) 789 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2)); 790 } 791 792 return nullptr; 793 } 794 795 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val, 796 Constant *Idx) { 797 // extractelt undef, C -> undef 798 // extractelt C, undef -> undef 799 if (isa<UndefValue>(Val) || isa<UndefValue>(Idx)) 800 return UndefValue::get(Val->getType()->getVectorElementType()); 801 802 auto *CIdx = dyn_cast<ConstantInt>(Idx); 803 if (!CIdx) 804 return nullptr; 805 806 // ee({w,x,y,z}, wrong_value) -> undef 807 if (CIdx->uge(Val->getType()->getVectorNumElements())) 808 return UndefValue::get(Val->getType()->getVectorElementType()); 809 810 // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...) 811 if (auto *CE = dyn_cast<ConstantExpr>(Val)) { 812 if (CE->getOpcode() == Instruction::GetElementPtr) { 813 SmallVector<Constant *, 8> Ops; 814 Ops.reserve(CE->getNumOperands()); 815 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 816 Constant *Op = CE->getOperand(i); 817 if (Op->getType()->isVectorTy()) { 818 Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx); 819 if (!ScalarOp) 820 return nullptr; 821 Ops.push_back(ScalarOp); 822 } else 823 Ops.push_back(Op); 824 } 825 return CE->getWithOperands(Ops, CE->getType()->getVectorElementType(), 826 false, 827 Ops[0]->getType()->getPointerElementType()); 828 } 829 } 830 831 return Val->getAggregateElement(CIdx); 832 } 833 834 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val, 835 Constant *Elt, 836 Constant *Idx) { 837 if (isa<UndefValue>(Idx)) 838 return UndefValue::get(Val->getType()); 839 840 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx); 841 if (!CIdx) return nullptr; 842 843 // Do not iterate on scalable vector. The num of elements is unknown at 844 // compile-time. 845 VectorType *ValTy = cast<VectorType>(Val->getType()); 846 if (ValTy->isScalable()) 847 return nullptr; 848 849 unsigned NumElts = Val->getType()->getVectorNumElements(); 850 if (CIdx->uge(NumElts)) 851 return UndefValue::get(Val->getType()); 852 853 SmallVector<Constant*, 16> Result; 854 Result.reserve(NumElts); 855 auto *Ty = Type::getInt32Ty(Val->getContext()); 856 uint64_t IdxVal = CIdx->getZExtValue(); 857 for (unsigned i = 0; i != NumElts; ++i) { 858 if (i == IdxVal) { 859 Result.push_back(Elt); 860 continue; 861 } 862 863 Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i)); 864 Result.push_back(C); 865 } 866 867 return ConstantVector::get(Result); 868 } 869 870 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, 871 ArrayRef<int> Mask) { 872 unsigned MaskNumElts = Mask.size(); 873 ElementCount MaskEltCount = {MaskNumElts, 874 V1->getType()->getVectorIsScalable()}; 875 Type *EltTy = V1->getType()->getVectorElementType(); 876 877 // Undefined shuffle mask -> undefined value. 878 if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) { 879 return UndefValue::get(VectorType::get(EltTy, MaskNumElts)); 880 } 881 882 // If the mask is all zeros this is a splat, no need to go through all 883 // elements. 884 if (all_of(Mask, [](int Elt) { return Elt == 0; }) && 885 !MaskEltCount.Scalable) { 886 Type *Ty = IntegerType::get(V1->getContext(), 32); 887 Constant *Elt = 888 ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0)); 889 return ConstantVector::getSplat(MaskEltCount, Elt); 890 } 891 // Do not iterate on scalable vector. The num of elements is unknown at 892 // compile-time. 893 VectorType *ValTy = cast<VectorType>(V1->getType()); 894 if (ValTy->isScalable()) 895 return nullptr; 896 897 unsigned SrcNumElts = V1->getType()->getVectorNumElements(); 898 899 // Loop over the shuffle mask, evaluating each element. 900 SmallVector<Constant*, 32> Result; 901 for (unsigned i = 0; i != MaskNumElts; ++i) { 902 int Elt = Mask[i]; 903 if (Elt == -1) { 904 Result.push_back(UndefValue::get(EltTy)); 905 continue; 906 } 907 Constant *InElt; 908 if (unsigned(Elt) >= SrcNumElts*2) 909 InElt = UndefValue::get(EltTy); 910 else if (unsigned(Elt) >= SrcNumElts) { 911 Type *Ty = IntegerType::get(V2->getContext(), 32); 912 InElt = 913 ConstantExpr::getExtractElement(V2, 914 ConstantInt::get(Ty, Elt - SrcNumElts)); 915 } else { 916 Type *Ty = IntegerType::get(V1->getContext(), 32); 917 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt)); 918 } 919 Result.push_back(InElt); 920 } 921 922 return ConstantVector::get(Result); 923 } 924 925 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg, 926 ArrayRef<unsigned> Idxs) { 927 // Base case: no indices, so return the entire value. 928 if (Idxs.empty()) 929 return Agg; 930 931 if (Constant *C = Agg->getAggregateElement(Idxs[0])) 932 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1)); 933 934 return nullptr; 935 } 936 937 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg, 938 Constant *Val, 939 ArrayRef<unsigned> Idxs) { 940 // Base case: no indices, so replace the entire value. 941 if (Idxs.empty()) 942 return Val; 943 944 unsigned NumElts; 945 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 946 NumElts = ST->getNumElements(); 947 else 948 NumElts = cast<ArrayType>(Agg->getType())->getNumElements(); 949 950 SmallVector<Constant*, 32> Result; 951 for (unsigned i = 0; i != NumElts; ++i) { 952 Constant *C = Agg->getAggregateElement(i); 953 if (!C) return nullptr; 954 955 if (Idxs[0] == i) 956 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1)); 957 958 Result.push_back(C); 959 } 960 961 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 962 return ConstantStruct::get(ST, Result); 963 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result); 964 } 965 966 Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) { 967 assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected"); 968 969 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length 970 // vectors are always evaluated per element. 971 bool IsScalableVector = 972 C->getType()->isVectorTy() && C->getType()->getVectorIsScalable(); 973 bool HasScalarUndefOrScalableVectorUndef = 974 (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C); 975 976 if (HasScalarUndefOrScalableVectorUndef) { 977 switch (static_cast<Instruction::UnaryOps>(Opcode)) { 978 case Instruction::FNeg: 979 return C; // -undef -> undef 980 case Instruction::UnaryOpsEnd: 981 llvm_unreachable("Invalid UnaryOp"); 982 } 983 } 984 985 // Constant should not be UndefValue, unless these are vector constants. 986 assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue"); 987 // We only have FP UnaryOps right now. 988 assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp"); 989 990 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 991 const APFloat &CV = CFP->getValueAPF(); 992 switch (Opcode) { 993 default: 994 break; 995 case Instruction::FNeg: 996 return ConstantFP::get(C->getContext(), neg(CV)); 997 } 998 } else if (VectorType *VTy = dyn_cast<VectorType>(C->getType())) { 999 // Do not iterate on scalable vector. The number of elements is unknown at 1000 // compile-time. 1001 if (IsScalableVector) 1002 return nullptr; 1003 Type *Ty = IntegerType::get(VTy->getContext(), 32); 1004 // Fast path for splatted constants. 1005 if (Constant *Splat = C->getSplatValue()) { 1006 Constant *Elt = ConstantExpr::get(Opcode, Splat); 1007 return ConstantVector::getSplat(VTy->getElementCount(), Elt); 1008 } 1009 1010 // Fold each element and create a vector constant from those constants. 1011 SmallVector<Constant*, 16> Result; 1012 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 1013 Constant *ExtractIdx = ConstantInt::get(Ty, i); 1014 Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx); 1015 1016 Result.push_back(ConstantExpr::get(Opcode, Elt)); 1017 } 1018 1019 return ConstantVector::get(Result); 1020 } 1021 1022 // We don't know how to fold this. 1023 return nullptr; 1024 } 1025 1026 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1, 1027 Constant *C2) { 1028 assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected"); 1029 1030 // Simplify BinOps with their identity values first. They are no-ops and we 1031 // can always return the other value, including undef or poison values. 1032 // FIXME: remove unnecessary duplicated identity patterns below. 1033 // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops, 1034 // like X << 0 = X. 1035 Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, C1->getType()); 1036 if (Identity) { 1037 if (C1 == Identity) 1038 return C2; 1039 if (C2 == Identity) 1040 return C1; 1041 } 1042 1043 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length 1044 // vectors are always evaluated per element. 1045 bool IsScalableVector = 1046 C1->getType()->isVectorTy() && C1->getType()->getVectorIsScalable(); 1047 bool HasScalarUndefOrScalableVectorUndef = 1048 (!C1->getType()->isVectorTy() || IsScalableVector) && 1049 (isa<UndefValue>(C1) || isa<UndefValue>(C2)); 1050 if (HasScalarUndefOrScalableVectorUndef) { 1051 switch (static_cast<Instruction::BinaryOps>(Opcode)) { 1052 case Instruction::Xor: 1053 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 1054 // Handle undef ^ undef -> 0 special case. This is a common 1055 // idiom (misuse). 1056 return Constant::getNullValue(C1->getType()); 1057 LLVM_FALLTHROUGH; 1058 case Instruction::Add: 1059 case Instruction::Sub: 1060 return UndefValue::get(C1->getType()); 1061 case Instruction::And: 1062 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef 1063 return C1; 1064 return Constant::getNullValue(C1->getType()); // undef & X -> 0 1065 case Instruction::Mul: { 1066 // undef * undef -> undef 1067 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 1068 return C1; 1069 const APInt *CV; 1070 // X * undef -> undef if X is odd 1071 if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV))) 1072 if ((*CV)[0]) 1073 return UndefValue::get(C1->getType()); 1074 1075 // X * undef -> 0 otherwise 1076 return Constant::getNullValue(C1->getType()); 1077 } 1078 case Instruction::SDiv: 1079 case Instruction::UDiv: 1080 // X / undef -> undef 1081 if (isa<UndefValue>(C2)) 1082 return C2; 1083 // undef / 0 -> undef 1084 // undef / 1 -> undef 1085 if (match(C2, m_Zero()) || match(C2, m_One())) 1086 return C1; 1087 // undef / X -> 0 otherwise 1088 return Constant::getNullValue(C1->getType()); 1089 case Instruction::URem: 1090 case Instruction::SRem: 1091 // X % undef -> undef 1092 if (match(C2, m_Undef())) 1093 return C2; 1094 // undef % 0 -> undef 1095 if (match(C2, m_Zero())) 1096 return C1; 1097 // undef % X -> 0 otherwise 1098 return Constant::getNullValue(C1->getType()); 1099 case Instruction::Or: // X | undef -> -1 1100 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef 1101 return C1; 1102 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0 1103 case Instruction::LShr: 1104 // X >>l undef -> undef 1105 if (isa<UndefValue>(C2)) 1106 return C2; 1107 // undef >>l 0 -> undef 1108 if (match(C2, m_Zero())) 1109 return C1; 1110 // undef >>l X -> 0 1111 return Constant::getNullValue(C1->getType()); 1112 case Instruction::AShr: 1113 // X >>a undef -> undef 1114 if (isa<UndefValue>(C2)) 1115 return C2; 1116 // undef >>a 0 -> undef 1117 if (match(C2, m_Zero())) 1118 return C1; 1119 // TODO: undef >>a X -> undef if the shift is exact 1120 // undef >>a X -> 0 1121 return Constant::getNullValue(C1->getType()); 1122 case Instruction::Shl: 1123 // X << undef -> undef 1124 if (isa<UndefValue>(C2)) 1125 return C2; 1126 // undef << 0 -> undef 1127 if (match(C2, m_Zero())) 1128 return C1; 1129 // undef << X -> 0 1130 return Constant::getNullValue(C1->getType()); 1131 case Instruction::FSub: 1132 // -0.0 - undef --> undef (consistent with "fneg undef") 1133 if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2)) 1134 return C2; 1135 LLVM_FALLTHROUGH; 1136 case Instruction::FAdd: 1137 case Instruction::FMul: 1138 case Instruction::FDiv: 1139 case Instruction::FRem: 1140 // [any flop] undef, undef -> undef 1141 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 1142 return C1; 1143 // [any flop] C, undef -> NaN 1144 // [any flop] undef, C -> NaN 1145 // We could potentially specialize NaN/Inf constants vs. 'normal' 1146 // constants (possibly differently depending on opcode and operand). This 1147 // would allow returning undef sometimes. But it is always safe to fold to 1148 // NaN because we can choose the undef operand as NaN, and any FP opcode 1149 // with a NaN operand will propagate NaN. 1150 return ConstantFP::getNaN(C1->getType()); 1151 case Instruction::BinaryOpsEnd: 1152 llvm_unreachable("Invalid BinaryOp"); 1153 } 1154 } 1155 1156 // Neither constant should be UndefValue, unless these are vector constants. 1157 assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue"); 1158 1159 // Handle simplifications when the RHS is a constant int. 1160 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 1161 switch (Opcode) { 1162 case Instruction::Add: 1163 if (CI2->isZero()) return C1; // X + 0 == X 1164 break; 1165 case Instruction::Sub: 1166 if (CI2->isZero()) return C1; // X - 0 == X 1167 break; 1168 case Instruction::Mul: 1169 if (CI2->isZero()) return C2; // X * 0 == 0 1170 if (CI2->isOne()) 1171 return C1; // X * 1 == X 1172 break; 1173 case Instruction::UDiv: 1174 case Instruction::SDiv: 1175 if (CI2->isOne()) 1176 return C1; // X / 1 == X 1177 if (CI2->isZero()) 1178 return UndefValue::get(CI2->getType()); // X / 0 == undef 1179 break; 1180 case Instruction::URem: 1181 case Instruction::SRem: 1182 if (CI2->isOne()) 1183 return Constant::getNullValue(CI2->getType()); // X % 1 == 0 1184 if (CI2->isZero()) 1185 return UndefValue::get(CI2->getType()); // X % 0 == undef 1186 break; 1187 case Instruction::And: 1188 if (CI2->isZero()) return C2; // X & 0 == 0 1189 if (CI2->isMinusOne()) 1190 return C1; // X & -1 == X 1191 1192 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1193 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64) 1194 if (CE1->getOpcode() == Instruction::ZExt) { 1195 unsigned DstWidth = CI2->getType()->getBitWidth(); 1196 unsigned SrcWidth = 1197 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits(); 1198 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1199 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits) 1200 return C1; 1201 } 1202 1203 // If and'ing the address of a global with a constant, fold it. 1204 if (CE1->getOpcode() == Instruction::PtrToInt && 1205 isa<GlobalValue>(CE1->getOperand(0))) { 1206 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0)); 1207 1208 MaybeAlign GVAlign; 1209 1210 if (Module *TheModule = GV->getParent()) { 1211 GVAlign = GV->getPointerAlignment(TheModule->getDataLayout()); 1212 1213 // If the function alignment is not specified then assume that it 1214 // is 4. 1215 // This is dangerous; on x86, the alignment of the pointer 1216 // corresponds to the alignment of the function, but might be less 1217 // than 4 if it isn't explicitly specified. 1218 // However, a fix for this behaviour was reverted because it 1219 // increased code size (see https://reviews.llvm.org/D55115) 1220 // FIXME: This code should be deleted once existing targets have 1221 // appropriate defaults 1222 if (!GVAlign && isa<Function>(GV)) 1223 GVAlign = Align(4); 1224 } else if (isa<Function>(GV)) { 1225 // Without a datalayout we have to assume the worst case: that the 1226 // function pointer isn't aligned at all. 1227 GVAlign = llvm::None; 1228 } else { 1229 GVAlign = MaybeAlign(GV->getAlignment()); 1230 } 1231 1232 if (GVAlign && *GVAlign > 1) { 1233 unsigned DstWidth = CI2->getType()->getBitWidth(); 1234 unsigned SrcWidth = std::min(DstWidth, Log2(*GVAlign)); 1235 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1236 1237 // If checking bits we know are clear, return zero. 1238 if ((CI2->getValue() & BitsNotSet) == CI2->getValue()) 1239 return Constant::getNullValue(CI2->getType()); 1240 } 1241 } 1242 } 1243 break; 1244 case Instruction::Or: 1245 if (CI2->isZero()) return C1; // X | 0 == X 1246 if (CI2->isMinusOne()) 1247 return C2; // X | -1 == -1 1248 break; 1249 case Instruction::Xor: 1250 if (CI2->isZero()) return C1; // X ^ 0 == X 1251 1252 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1253 switch (CE1->getOpcode()) { 1254 default: break; 1255 case Instruction::ICmp: 1256 case Instruction::FCmp: 1257 // cmp pred ^ true -> cmp !pred 1258 assert(CI2->isOne()); 1259 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate(); 1260 pred = CmpInst::getInversePredicate(pred); 1261 return ConstantExpr::getCompare(pred, CE1->getOperand(0), 1262 CE1->getOperand(1)); 1263 } 1264 } 1265 break; 1266 case Instruction::AShr: 1267 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2 1268 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) 1269 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero. 1270 return ConstantExpr::getLShr(C1, C2); 1271 break; 1272 } 1273 } else if (isa<ConstantInt>(C1)) { 1274 // If C1 is a ConstantInt and C2 is not, swap the operands. 1275 if (Instruction::isCommutative(Opcode)) 1276 return ConstantExpr::get(Opcode, C2, C1); 1277 } 1278 1279 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) { 1280 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 1281 const APInt &C1V = CI1->getValue(); 1282 const APInt &C2V = CI2->getValue(); 1283 switch (Opcode) { 1284 default: 1285 break; 1286 case Instruction::Add: 1287 return ConstantInt::get(CI1->getContext(), C1V + C2V); 1288 case Instruction::Sub: 1289 return ConstantInt::get(CI1->getContext(), C1V - C2V); 1290 case Instruction::Mul: 1291 return ConstantInt::get(CI1->getContext(), C1V * C2V); 1292 case Instruction::UDiv: 1293 assert(!CI2->isZero() && "Div by zero handled above"); 1294 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V)); 1295 case Instruction::SDiv: 1296 assert(!CI2->isZero() && "Div by zero handled above"); 1297 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1298 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef 1299 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V)); 1300 case Instruction::URem: 1301 assert(!CI2->isZero() && "Div by zero handled above"); 1302 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V)); 1303 case Instruction::SRem: 1304 assert(!CI2->isZero() && "Div by zero handled above"); 1305 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1306 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef 1307 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V)); 1308 case Instruction::And: 1309 return ConstantInt::get(CI1->getContext(), C1V & C2V); 1310 case Instruction::Or: 1311 return ConstantInt::get(CI1->getContext(), C1V | C2V); 1312 case Instruction::Xor: 1313 return ConstantInt::get(CI1->getContext(), C1V ^ C2V); 1314 case Instruction::Shl: 1315 if (C2V.ult(C1V.getBitWidth())) 1316 return ConstantInt::get(CI1->getContext(), C1V.shl(C2V)); 1317 return UndefValue::get(C1->getType()); // too big shift is undef 1318 case Instruction::LShr: 1319 if (C2V.ult(C1V.getBitWidth())) 1320 return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V)); 1321 return UndefValue::get(C1->getType()); // too big shift is undef 1322 case Instruction::AShr: 1323 if (C2V.ult(C1V.getBitWidth())) 1324 return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V)); 1325 return UndefValue::get(C1->getType()); // too big shift is undef 1326 } 1327 } 1328 1329 switch (Opcode) { 1330 case Instruction::SDiv: 1331 case Instruction::UDiv: 1332 case Instruction::URem: 1333 case Instruction::SRem: 1334 case Instruction::LShr: 1335 case Instruction::AShr: 1336 case Instruction::Shl: 1337 if (CI1->isZero()) return C1; 1338 break; 1339 default: 1340 break; 1341 } 1342 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) { 1343 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) { 1344 const APFloat &C1V = CFP1->getValueAPF(); 1345 const APFloat &C2V = CFP2->getValueAPF(); 1346 APFloat C3V = C1V; // copy for modification 1347 switch (Opcode) { 1348 default: 1349 break; 1350 case Instruction::FAdd: 1351 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven); 1352 return ConstantFP::get(C1->getContext(), C3V); 1353 case Instruction::FSub: 1354 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven); 1355 return ConstantFP::get(C1->getContext(), C3V); 1356 case Instruction::FMul: 1357 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven); 1358 return ConstantFP::get(C1->getContext(), C3V); 1359 case Instruction::FDiv: 1360 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven); 1361 return ConstantFP::get(C1->getContext(), C3V); 1362 case Instruction::FRem: 1363 (void)C3V.mod(C2V); 1364 return ConstantFP::get(C1->getContext(), C3V); 1365 } 1366 } 1367 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) { 1368 // Do not iterate on scalable vector. The number of elements is unknown at 1369 // compile-time. 1370 if (IsScalableVector) 1371 return nullptr; 1372 // Fast path for splatted constants. 1373 if (Constant *C2Splat = C2->getSplatValue()) { 1374 if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue()) 1375 return UndefValue::get(VTy); 1376 if (Constant *C1Splat = C1->getSplatValue()) { 1377 return ConstantVector::getSplat( 1378 VTy->getVectorElementCount(), 1379 ConstantExpr::get(Opcode, C1Splat, C2Splat)); 1380 } 1381 } 1382 1383 // Fold each element and create a vector constant from those constants. 1384 SmallVector<Constant*, 16> Result; 1385 Type *Ty = IntegerType::get(VTy->getContext(), 32); 1386 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 1387 Constant *ExtractIdx = ConstantInt::get(Ty, i); 1388 Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx); 1389 Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx); 1390 1391 // If any element of a divisor vector is zero, the whole op is undef. 1392 if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue()) 1393 return UndefValue::get(VTy); 1394 1395 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS)); 1396 } 1397 1398 return ConstantVector::get(Result); 1399 } 1400 1401 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1402 // There are many possible foldings we could do here. We should probably 1403 // at least fold add of a pointer with an integer into the appropriate 1404 // getelementptr. This will improve alias analysis a bit. 1405 1406 // Given ((a + b) + c), if (b + c) folds to something interesting, return 1407 // (a + (b + c)). 1408 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) { 1409 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2); 1410 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode) 1411 return ConstantExpr::get(Opcode, CE1->getOperand(0), T); 1412 } 1413 } else if (isa<ConstantExpr>(C2)) { 1414 // If C2 is a constant expr and C1 isn't, flop them around and fold the 1415 // other way if possible. 1416 if (Instruction::isCommutative(Opcode)) 1417 return ConstantFoldBinaryInstruction(Opcode, C2, C1); 1418 } 1419 1420 // i1 can be simplified in many cases. 1421 if (C1->getType()->isIntegerTy(1)) { 1422 switch (Opcode) { 1423 case Instruction::Add: 1424 case Instruction::Sub: 1425 return ConstantExpr::getXor(C1, C2); 1426 case Instruction::Mul: 1427 return ConstantExpr::getAnd(C1, C2); 1428 case Instruction::Shl: 1429 case Instruction::LShr: 1430 case Instruction::AShr: 1431 // We can assume that C2 == 0. If it were one the result would be 1432 // undefined because the shift value is as large as the bitwidth. 1433 return C1; 1434 case Instruction::SDiv: 1435 case Instruction::UDiv: 1436 // We can assume that C2 == 1. If it were zero the result would be 1437 // undefined through division by zero. 1438 return C1; 1439 case Instruction::URem: 1440 case Instruction::SRem: 1441 // We can assume that C2 == 1. If it were zero the result would be 1442 // undefined through division by zero. 1443 return ConstantInt::getFalse(C1->getContext()); 1444 default: 1445 break; 1446 } 1447 } 1448 1449 // We don't know how to fold this. 1450 return nullptr; 1451 } 1452 1453 /// This type is zero-sized if it's an array or structure of zero-sized types. 1454 /// The only leaf zero-sized type is an empty structure. 1455 static bool isMaybeZeroSizedType(Type *Ty) { 1456 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1457 if (STy->isOpaque()) return true; // Can't say. 1458 1459 // If all of elements have zero size, this does too. 1460 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1461 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false; 1462 return true; 1463 1464 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1465 return isMaybeZeroSizedType(ATy->getElementType()); 1466 } 1467 return false; 1468 } 1469 1470 /// Compare the two constants as though they were getelementptr indices. 1471 /// This allows coercion of the types to be the same thing. 1472 /// 1473 /// If the two constants are the "same" (after coercion), return 0. If the 1474 /// first is less than the second, return -1, if the second is less than the 1475 /// first, return 1. If the constants are not integral, return -2. 1476 /// 1477 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) { 1478 if (C1 == C2) return 0; 1479 1480 // Ok, we found a different index. If they are not ConstantInt, we can't do 1481 // anything with them. 1482 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2)) 1483 return -2; // don't know! 1484 1485 // We cannot compare the indices if they don't fit in an int64_t. 1486 if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 || 1487 cast<ConstantInt>(C2)->getValue().getActiveBits() > 64) 1488 return -2; // don't know! 1489 1490 // Ok, we have two differing integer indices. Sign extend them to be the same 1491 // type. 1492 int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue(); 1493 int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue(); 1494 1495 if (C1Val == C2Val) return 0; // They are equal 1496 1497 // If the type being indexed over is really just a zero sized type, there is 1498 // no pointer difference being made here. 1499 if (isMaybeZeroSizedType(ElTy)) 1500 return -2; // dunno. 1501 1502 // If they are really different, now that they are the same type, then we 1503 // found a difference! 1504 if (C1Val < C2Val) 1505 return -1; 1506 else 1507 return 1; 1508 } 1509 1510 /// This function determines if there is anything we can decide about the two 1511 /// constants provided. This doesn't need to handle simple things like 1512 /// ConstantFP comparisons, but should instead handle ConstantExprs. 1513 /// If we can determine that the two constants have a particular relation to 1514 /// each other, we should return the corresponding FCmpInst predicate, 1515 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in 1516 /// ConstantFoldCompareInstruction. 1517 /// 1518 /// To simplify this code we canonicalize the relation so that the first 1519 /// operand is always the most "complex" of the two. We consider ConstantFP 1520 /// to be the simplest, and ConstantExprs to be the most complex. 1521 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) { 1522 assert(V1->getType() == V2->getType() && 1523 "Cannot compare values of different types!"); 1524 1525 // We do not know if a constant expression will evaluate to a number or NaN. 1526 // Therefore, we can only say that the relation is unordered or equal. 1527 if (V1 == V2) return FCmpInst::FCMP_UEQ; 1528 1529 if (!isa<ConstantExpr>(V1)) { 1530 if (!isa<ConstantExpr>(V2)) { 1531 // Simple case, use the standard constant folder. 1532 ConstantInt *R = nullptr; 1533 R = dyn_cast<ConstantInt>( 1534 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2)); 1535 if (R && !R->isZero()) 1536 return FCmpInst::FCMP_OEQ; 1537 R = dyn_cast<ConstantInt>( 1538 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2)); 1539 if (R && !R->isZero()) 1540 return FCmpInst::FCMP_OLT; 1541 R = dyn_cast<ConstantInt>( 1542 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2)); 1543 if (R && !R->isZero()) 1544 return FCmpInst::FCMP_OGT; 1545 1546 // Nothing more we can do 1547 return FCmpInst::BAD_FCMP_PREDICATE; 1548 } 1549 1550 // If the first operand is simple and second is ConstantExpr, swap operands. 1551 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1); 1552 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE) 1553 return FCmpInst::getSwappedPredicate(SwappedRelation); 1554 } else { 1555 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1556 // constantexpr or a simple constant. 1557 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1558 switch (CE1->getOpcode()) { 1559 case Instruction::FPTrunc: 1560 case Instruction::FPExt: 1561 case Instruction::UIToFP: 1562 case Instruction::SIToFP: 1563 // We might be able to do something with these but we don't right now. 1564 break; 1565 default: 1566 break; 1567 } 1568 } 1569 // There are MANY other foldings that we could perform here. They will 1570 // probably be added on demand, as they seem needed. 1571 return FCmpInst::BAD_FCMP_PREDICATE; 1572 } 1573 1574 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, 1575 const GlobalValue *GV2) { 1576 auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) { 1577 if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage()) 1578 return true; 1579 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) { 1580 Type *Ty = GVar->getValueType(); 1581 // A global with opaque type might end up being zero sized. 1582 if (!Ty->isSized()) 1583 return true; 1584 // A global with an empty type might lie at the address of any other 1585 // global. 1586 if (Ty->isEmptyTy()) 1587 return true; 1588 } 1589 return false; 1590 }; 1591 // Don't try to decide equality of aliases. 1592 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2)) 1593 if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2)) 1594 return ICmpInst::ICMP_NE; 1595 return ICmpInst::BAD_ICMP_PREDICATE; 1596 } 1597 1598 /// This function determines if there is anything we can decide about the two 1599 /// constants provided. This doesn't need to handle simple things like integer 1600 /// comparisons, but should instead handle ConstantExprs and GlobalValues. 1601 /// If we can determine that the two constants have a particular relation to 1602 /// each other, we should return the corresponding ICmp predicate, otherwise 1603 /// return ICmpInst::BAD_ICMP_PREDICATE. 1604 /// 1605 /// To simplify this code we canonicalize the relation so that the first 1606 /// operand is always the most "complex" of the two. We consider simple 1607 /// constants (like ConstantInt) to be the simplest, followed by 1608 /// GlobalValues, followed by ConstantExpr's (the most complex). 1609 /// 1610 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, 1611 bool isSigned) { 1612 assert(V1->getType() == V2->getType() && 1613 "Cannot compare different types of values!"); 1614 if (V1 == V2) return ICmpInst::ICMP_EQ; 1615 1616 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) && 1617 !isa<BlockAddress>(V1)) { 1618 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) && 1619 !isa<BlockAddress>(V2)) { 1620 // We distilled this down to a simple case, use the standard constant 1621 // folder. 1622 ConstantInt *R = nullptr; 1623 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ; 1624 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1625 if (R && !R->isZero()) 1626 return pred; 1627 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1628 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1629 if (R && !R->isZero()) 1630 return pred; 1631 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1632 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1633 if (R && !R->isZero()) 1634 return pred; 1635 1636 // If we couldn't figure it out, bail. 1637 return ICmpInst::BAD_ICMP_PREDICATE; 1638 } 1639 1640 // If the first operand is simple, swap operands. 1641 ICmpInst::Predicate SwappedRelation = 1642 evaluateICmpRelation(V2, V1, isSigned); 1643 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1644 return ICmpInst::getSwappedPredicate(SwappedRelation); 1645 1646 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) { 1647 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1648 ICmpInst::Predicate SwappedRelation = 1649 evaluateICmpRelation(V2, V1, isSigned); 1650 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1651 return ICmpInst::getSwappedPredicate(SwappedRelation); 1652 return ICmpInst::BAD_ICMP_PREDICATE; 1653 } 1654 1655 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1656 // constant (which, since the types must match, means that it's a 1657 // ConstantPointerNull). 1658 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1659 return areGlobalsPotentiallyEqual(GV, GV2); 1660 } else if (isa<BlockAddress>(V2)) { 1661 return ICmpInst::ICMP_NE; // Globals never equal labels. 1662 } else { 1663 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!"); 1664 // GlobalVals can never be null unless they have external weak linkage. 1665 // We don't try to evaluate aliases here. 1666 // NOTE: We should not be doing this constant folding if null pointer 1667 // is considered valid for the function. But currently there is no way to 1668 // query it from the Constant type. 1669 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) && 1670 !NullPointerIsDefined(nullptr /* F */, 1671 GV->getType()->getAddressSpace())) 1672 return ICmpInst::ICMP_NE; 1673 } 1674 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) { 1675 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1676 ICmpInst::Predicate SwappedRelation = 1677 evaluateICmpRelation(V2, V1, isSigned); 1678 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1679 return ICmpInst::getSwappedPredicate(SwappedRelation); 1680 return ICmpInst::BAD_ICMP_PREDICATE; 1681 } 1682 1683 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1684 // constant (which, since the types must match, means that it is a 1685 // ConstantPointerNull). 1686 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) { 1687 // Block address in another function can't equal this one, but block 1688 // addresses in the current function might be the same if blocks are 1689 // empty. 1690 if (BA2->getFunction() != BA->getFunction()) 1691 return ICmpInst::ICMP_NE; 1692 } else { 1693 // Block addresses aren't null, don't equal the address of globals. 1694 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) && 1695 "Canonicalization guarantee!"); 1696 return ICmpInst::ICMP_NE; 1697 } 1698 } else { 1699 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1700 // constantexpr, a global, block address, or a simple constant. 1701 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1702 Constant *CE1Op0 = CE1->getOperand(0); 1703 1704 switch (CE1->getOpcode()) { 1705 case Instruction::Trunc: 1706 case Instruction::FPTrunc: 1707 case Instruction::FPExt: 1708 case Instruction::FPToUI: 1709 case Instruction::FPToSI: 1710 break; // We can't evaluate floating point casts or truncations. 1711 1712 case Instruction::UIToFP: 1713 case Instruction::SIToFP: 1714 case Instruction::BitCast: 1715 case Instruction::ZExt: 1716 case Instruction::SExt: 1717 // We can't evaluate floating point casts or truncations. 1718 if (CE1Op0->getType()->isFPOrFPVectorTy()) 1719 break; 1720 1721 // If the cast is not actually changing bits, and the second operand is a 1722 // null pointer, do the comparison with the pre-casted value. 1723 if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) { 1724 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false; 1725 if (CE1->getOpcode() == Instruction::SExt) isSigned = true; 1726 return evaluateICmpRelation(CE1Op0, 1727 Constant::getNullValue(CE1Op0->getType()), 1728 isSigned); 1729 } 1730 break; 1731 1732 case Instruction::GetElementPtr: { 1733 GEPOperator *CE1GEP = cast<GEPOperator>(CE1); 1734 // Ok, since this is a getelementptr, we know that the constant has a 1735 // pointer type. Check the various cases. 1736 if (isa<ConstantPointerNull>(V2)) { 1737 // If we are comparing a GEP to a null pointer, check to see if the base 1738 // of the GEP equals the null pointer. 1739 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1740 if (GV->hasExternalWeakLinkage()) 1741 // Weak linkage GVals could be zero or not. We're comparing that 1742 // to null pointer so its greater-or-equal 1743 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 1744 else 1745 // If its not weak linkage, the GVal must have a non-zero address 1746 // so the result is greater-than 1747 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1748 } else if (isa<ConstantPointerNull>(CE1Op0)) { 1749 // If we are indexing from a null pointer, check to see if we have any 1750 // non-zero indices. 1751 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i) 1752 if (!CE1->getOperand(i)->isNullValue()) 1753 // Offsetting from null, must not be equal. 1754 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1755 // Only zero indexes from null, must still be zero. 1756 return ICmpInst::ICMP_EQ; 1757 } 1758 // Otherwise, we can't really say if the first operand is null or not. 1759 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1760 if (isa<ConstantPointerNull>(CE1Op0)) { 1761 if (GV2->hasExternalWeakLinkage()) 1762 // Weak linkage GVals could be zero or not. We're comparing it to 1763 // a null pointer, so its less-or-equal 1764 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1765 else 1766 // If its not weak linkage, the GVal must have a non-zero address 1767 // so the result is less-than 1768 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1769 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1770 if (GV == GV2) { 1771 // If this is a getelementptr of the same global, then it must be 1772 // different. Because the types must match, the getelementptr could 1773 // only have at most one index, and because we fold getelementptr's 1774 // with a single zero index, it must be nonzero. 1775 assert(CE1->getNumOperands() == 2 && 1776 !CE1->getOperand(1)->isNullValue() && 1777 "Surprising getelementptr!"); 1778 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1779 } else { 1780 if (CE1GEP->hasAllZeroIndices()) 1781 return areGlobalsPotentiallyEqual(GV, GV2); 1782 return ICmpInst::BAD_ICMP_PREDICATE; 1783 } 1784 } 1785 } else { 1786 ConstantExpr *CE2 = cast<ConstantExpr>(V2); 1787 Constant *CE2Op0 = CE2->getOperand(0); 1788 1789 // There are MANY other foldings that we could perform here. They will 1790 // probably be added on demand, as they seem needed. 1791 switch (CE2->getOpcode()) { 1792 default: break; 1793 case Instruction::GetElementPtr: 1794 // By far the most common case to handle is when the base pointers are 1795 // obviously to the same global. 1796 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) { 1797 // Don't know relative ordering, but check for inequality. 1798 if (CE1Op0 != CE2Op0) { 1799 GEPOperator *CE2GEP = cast<GEPOperator>(CE2); 1800 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices()) 1801 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0), 1802 cast<GlobalValue>(CE2Op0)); 1803 return ICmpInst::BAD_ICMP_PREDICATE; 1804 } 1805 // Ok, we know that both getelementptr instructions are based on the 1806 // same global. From this, we can precisely determine the relative 1807 // ordering of the resultant pointers. 1808 unsigned i = 1; 1809 1810 // The logic below assumes that the result of the comparison 1811 // can be determined by finding the first index that differs. 1812 // This doesn't work if there is over-indexing in any 1813 // subsequent indices, so check for that case first. 1814 if (!CE1->isGEPWithNoNotionalOverIndexing() || 1815 !CE2->isGEPWithNoNotionalOverIndexing()) 1816 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1817 1818 // Compare all of the operands the GEP's have in common. 1819 gep_type_iterator GTI = gep_type_begin(CE1); 1820 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); 1821 ++i, ++GTI) 1822 switch (IdxCompare(CE1->getOperand(i), 1823 CE2->getOperand(i), GTI.getIndexedType())) { 1824 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT; 1825 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT; 1826 case -2: return ICmpInst::BAD_ICMP_PREDICATE; 1827 } 1828 1829 // Ok, we ran out of things they have in common. If any leftovers 1830 // are non-zero then we have a difference, otherwise we are equal. 1831 for (; i < CE1->getNumOperands(); ++i) 1832 if (!CE1->getOperand(i)->isNullValue()) { 1833 if (isa<ConstantInt>(CE1->getOperand(i))) 1834 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1835 else 1836 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1837 } 1838 1839 for (; i < CE2->getNumOperands(); ++i) 1840 if (!CE2->getOperand(i)->isNullValue()) { 1841 if (isa<ConstantInt>(CE2->getOperand(i))) 1842 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1843 else 1844 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1845 } 1846 return ICmpInst::ICMP_EQ; 1847 } 1848 } 1849 } 1850 break; 1851 } 1852 default: 1853 break; 1854 } 1855 } 1856 1857 return ICmpInst::BAD_ICMP_PREDICATE; 1858 } 1859 1860 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 1861 Constant *C1, Constant *C2) { 1862 Type *ResultTy; 1863 if (VectorType *VT = dyn_cast<VectorType>(C1->getType())) 1864 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()), 1865 VT->getElementCount()); 1866 else 1867 ResultTy = Type::getInt1Ty(C1->getContext()); 1868 1869 // Fold FCMP_FALSE/FCMP_TRUE unconditionally. 1870 if (pred == FCmpInst::FCMP_FALSE) 1871 return Constant::getNullValue(ResultTy); 1872 1873 if (pred == FCmpInst::FCMP_TRUE) 1874 return Constant::getAllOnesValue(ResultTy); 1875 1876 // Handle some degenerate cases first 1877 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 1878 CmpInst::Predicate Predicate = CmpInst::Predicate(pred); 1879 bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate); 1880 // For EQ and NE, we can always pick a value for the undef to make the 1881 // predicate pass or fail, so we can return undef. 1882 // Also, if both operands are undef, we can return undef for int comparison. 1883 if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2)) 1884 return UndefValue::get(ResultTy); 1885 1886 // Otherwise, for integer compare, pick the same value as the non-undef 1887 // operand, and fold it to true or false. 1888 if (isIntegerPredicate) 1889 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate)); 1890 1891 // Choosing NaN for the undef will always make unordered comparison succeed 1892 // and ordered comparison fails. 1893 return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate)); 1894 } 1895 1896 // icmp eq/ne(null,GV) -> false/true 1897 if (C1->isNullValue()) { 1898 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2)) 1899 // Don't try to evaluate aliases. External weak GV can be null. 1900 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() && 1901 !NullPointerIsDefined(nullptr /* F */, 1902 GV->getType()->getAddressSpace())) { 1903 if (pred == ICmpInst::ICMP_EQ) 1904 return ConstantInt::getFalse(C1->getContext()); 1905 else if (pred == ICmpInst::ICMP_NE) 1906 return ConstantInt::getTrue(C1->getContext()); 1907 } 1908 // icmp eq/ne(GV,null) -> false/true 1909 } else if (C2->isNullValue()) { 1910 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) 1911 // Don't try to evaluate aliases. External weak GV can be null. 1912 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() && 1913 !NullPointerIsDefined(nullptr /* F */, 1914 GV->getType()->getAddressSpace())) { 1915 if (pred == ICmpInst::ICMP_EQ) 1916 return ConstantInt::getFalse(C1->getContext()); 1917 else if (pred == ICmpInst::ICMP_NE) 1918 return ConstantInt::getTrue(C1->getContext()); 1919 } 1920 } 1921 1922 // If the comparison is a comparison between two i1's, simplify it. 1923 if (C1->getType()->isIntegerTy(1)) { 1924 switch(pred) { 1925 case ICmpInst::ICMP_EQ: 1926 if (isa<ConstantInt>(C2)) 1927 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2)); 1928 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2); 1929 case ICmpInst::ICMP_NE: 1930 return ConstantExpr::getXor(C1, C2); 1931 default: 1932 break; 1933 } 1934 } 1935 1936 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) { 1937 const APInt &V1 = cast<ConstantInt>(C1)->getValue(); 1938 const APInt &V2 = cast<ConstantInt>(C2)->getValue(); 1939 switch (pred) { 1940 default: llvm_unreachable("Invalid ICmp Predicate"); 1941 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2); 1942 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2); 1943 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2)); 1944 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2)); 1945 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2)); 1946 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2)); 1947 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2)); 1948 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2)); 1949 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2)); 1950 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2)); 1951 } 1952 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) { 1953 const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF(); 1954 const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF(); 1955 APFloat::cmpResult R = C1V.compare(C2V); 1956 switch (pred) { 1957 default: llvm_unreachable("Invalid FCmp Predicate"); 1958 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy); 1959 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy); 1960 case FCmpInst::FCMP_UNO: 1961 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered); 1962 case FCmpInst::FCMP_ORD: 1963 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered); 1964 case FCmpInst::FCMP_UEQ: 1965 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1966 R==APFloat::cmpEqual); 1967 case FCmpInst::FCMP_OEQ: 1968 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual); 1969 case FCmpInst::FCMP_UNE: 1970 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual); 1971 case FCmpInst::FCMP_ONE: 1972 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1973 R==APFloat::cmpGreaterThan); 1974 case FCmpInst::FCMP_ULT: 1975 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1976 R==APFloat::cmpLessThan); 1977 case FCmpInst::FCMP_OLT: 1978 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan); 1979 case FCmpInst::FCMP_UGT: 1980 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1981 R==APFloat::cmpGreaterThan); 1982 case FCmpInst::FCMP_OGT: 1983 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan); 1984 case FCmpInst::FCMP_ULE: 1985 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan); 1986 case FCmpInst::FCMP_OLE: 1987 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1988 R==APFloat::cmpEqual); 1989 case FCmpInst::FCMP_UGE: 1990 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan); 1991 case FCmpInst::FCMP_OGE: 1992 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan || 1993 R==APFloat::cmpEqual); 1994 } 1995 } else if (C1->getType()->isVectorTy()) { 1996 // Do not iterate on scalable vector. The number of elements is unknown at 1997 // compile-time. 1998 if (C1->getType()->getVectorIsScalable()) 1999 return nullptr; 2000 // Fast path for splatted constants. 2001 if (Constant *C1Splat = C1->getSplatValue()) 2002 if (Constant *C2Splat = C2->getSplatValue()) 2003 return ConstantVector::getSplat( 2004 C1->getType()->getVectorElementCount(), 2005 ConstantExpr::getCompare(pred, C1Splat, C2Splat)); 2006 2007 // If we can constant fold the comparison of each element, constant fold 2008 // the whole vector comparison. 2009 SmallVector<Constant*, 4> ResElts; 2010 Type *Ty = IntegerType::get(C1->getContext(), 32); 2011 // Compare the elements, producing an i1 result or constant expr. 2012 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){ 2013 Constant *C1E = 2014 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 2015 Constant *C2E = 2016 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 2017 2018 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E)); 2019 } 2020 2021 return ConstantVector::get(ResElts); 2022 } 2023 2024 if (C1->getType()->isFloatingPointTy() && 2025 // Only call evaluateFCmpRelation if we have a constant expr to avoid 2026 // infinite recursive loop 2027 (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) { 2028 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 2029 switch (evaluateFCmpRelation(C1, C2)) { 2030 default: llvm_unreachable("Unknown relation!"); 2031 case FCmpInst::FCMP_UNO: 2032 case FCmpInst::FCMP_ORD: 2033 case FCmpInst::FCMP_UNE: 2034 case FCmpInst::FCMP_ULT: 2035 case FCmpInst::FCMP_UGT: 2036 case FCmpInst::FCMP_ULE: 2037 case FCmpInst::FCMP_UGE: 2038 case FCmpInst::FCMP_TRUE: 2039 case FCmpInst::FCMP_FALSE: 2040 case FCmpInst::BAD_FCMP_PREDICATE: 2041 break; // Couldn't determine anything about these constants. 2042 case FCmpInst::FCMP_OEQ: // We know that C1 == C2 2043 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ || 2044 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE || 2045 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 2046 break; 2047 case FCmpInst::FCMP_OLT: // We know that C1 < C2 2048 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 2049 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT || 2050 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE); 2051 break; 2052 case FCmpInst::FCMP_OGT: // We know that C1 > C2 2053 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 2054 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT || 2055 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 2056 break; 2057 case FCmpInst::FCMP_OLE: // We know that C1 <= C2 2058 // We can only partially decide this relation. 2059 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 2060 Result = 0; 2061 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 2062 Result = 1; 2063 break; 2064 case FCmpInst::FCMP_OGE: // We known that C1 >= C2 2065 // We can only partially decide this relation. 2066 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 2067 Result = 0; 2068 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 2069 Result = 1; 2070 break; 2071 case FCmpInst::FCMP_ONE: // We know that C1 != C2 2072 // We can only partially decide this relation. 2073 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 2074 Result = 0; 2075 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 2076 Result = 1; 2077 break; 2078 case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2). 2079 // We can only partially decide this relation. 2080 if (pred == FCmpInst::FCMP_ONE) 2081 Result = 0; 2082 else if (pred == FCmpInst::FCMP_UEQ) 2083 Result = 1; 2084 break; 2085 } 2086 2087 // If we evaluated the result, return it now. 2088 if (Result != -1) 2089 return ConstantInt::get(ResultTy, Result); 2090 2091 } else { 2092 // Evaluate the relation between the two constants, per the predicate. 2093 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 2094 switch (evaluateICmpRelation(C1, C2, 2095 CmpInst::isSigned((CmpInst::Predicate)pred))) { 2096 default: llvm_unreachable("Unknown relational!"); 2097 case ICmpInst::BAD_ICMP_PREDICATE: 2098 break; // Couldn't determine anything about these constants. 2099 case ICmpInst::ICMP_EQ: // We know the constants are equal! 2100 // If we know the constants are equal, we can decide the result of this 2101 // computation precisely. 2102 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred); 2103 break; 2104 case ICmpInst::ICMP_ULT: 2105 switch (pred) { 2106 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE: 2107 Result = 1; break; 2108 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE: 2109 Result = 0; break; 2110 } 2111 break; 2112 case ICmpInst::ICMP_SLT: 2113 switch (pred) { 2114 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE: 2115 Result = 1; break; 2116 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE: 2117 Result = 0; break; 2118 } 2119 break; 2120 case ICmpInst::ICMP_UGT: 2121 switch (pred) { 2122 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE: 2123 Result = 1; break; 2124 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE: 2125 Result = 0; break; 2126 } 2127 break; 2128 case ICmpInst::ICMP_SGT: 2129 switch (pred) { 2130 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE: 2131 Result = 1; break; 2132 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE: 2133 Result = 0; break; 2134 } 2135 break; 2136 case ICmpInst::ICMP_ULE: 2137 if (pred == ICmpInst::ICMP_UGT) Result = 0; 2138 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1; 2139 break; 2140 case ICmpInst::ICMP_SLE: 2141 if (pred == ICmpInst::ICMP_SGT) Result = 0; 2142 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1; 2143 break; 2144 case ICmpInst::ICMP_UGE: 2145 if (pred == ICmpInst::ICMP_ULT) Result = 0; 2146 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1; 2147 break; 2148 case ICmpInst::ICMP_SGE: 2149 if (pred == ICmpInst::ICMP_SLT) Result = 0; 2150 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1; 2151 break; 2152 case ICmpInst::ICMP_NE: 2153 if (pred == ICmpInst::ICMP_EQ) Result = 0; 2154 if (pred == ICmpInst::ICMP_NE) Result = 1; 2155 break; 2156 } 2157 2158 // If we evaluated the result, return it now. 2159 if (Result != -1) 2160 return ConstantInt::get(ResultTy, Result); 2161 2162 // If the right hand side is a bitcast, try using its inverse to simplify 2163 // it by moving it to the left hand side. We can't do this if it would turn 2164 // a vector compare into a scalar compare or visa versa, or if it would turn 2165 // the operands into FP values. 2166 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) { 2167 Constant *CE2Op0 = CE2->getOperand(0); 2168 if (CE2->getOpcode() == Instruction::BitCast && 2169 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() && 2170 !CE2Op0->getType()->isFPOrFPVectorTy()) { 2171 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType()); 2172 return ConstantExpr::getICmp(pred, Inverse, CE2Op0); 2173 } 2174 } 2175 2176 // If the left hand side is an extension, try eliminating it. 2177 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 2178 if ((CE1->getOpcode() == Instruction::SExt && 2179 ICmpInst::isSigned((ICmpInst::Predicate)pred)) || 2180 (CE1->getOpcode() == Instruction::ZExt && 2181 !ICmpInst::isSigned((ICmpInst::Predicate)pred))){ 2182 Constant *CE1Op0 = CE1->getOperand(0); 2183 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType()); 2184 if (CE1Inverse == CE1Op0) { 2185 // Check whether we can safely truncate the right hand side. 2186 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType()); 2187 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse, 2188 C2->getType()) == C2) 2189 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse); 2190 } 2191 } 2192 } 2193 2194 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) || 2195 (C1->isNullValue() && !C2->isNullValue())) { 2196 // If C2 is a constant expr and C1 isn't, flip them around and fold the 2197 // other way if possible. 2198 // Also, if C1 is null and C2 isn't, flip them around. 2199 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred); 2200 return ConstantExpr::getICmp(pred, C2, C1); 2201 } 2202 } 2203 return nullptr; 2204 } 2205 2206 /// Test whether the given sequence of *normalized* indices is "inbounds". 2207 template<typename IndexTy> 2208 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) { 2209 // No indices means nothing that could be out of bounds. 2210 if (Idxs.empty()) return true; 2211 2212 // If the first index is zero, it's in bounds. 2213 if (cast<Constant>(Idxs[0])->isNullValue()) return true; 2214 2215 // If the first index is one and all the rest are zero, it's in bounds, 2216 // by the one-past-the-end rule. 2217 if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) { 2218 if (!CI->isOne()) 2219 return false; 2220 } else { 2221 auto *CV = cast<ConstantDataVector>(Idxs[0]); 2222 CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue()); 2223 if (!CI || !CI->isOne()) 2224 return false; 2225 } 2226 2227 for (unsigned i = 1, e = Idxs.size(); i != e; ++i) 2228 if (!cast<Constant>(Idxs[i])->isNullValue()) 2229 return false; 2230 return true; 2231 } 2232 2233 /// Test whether a given ConstantInt is in-range for a SequentialType. 2234 static bool isIndexInRangeOfArrayType(uint64_t NumElements, 2235 const ConstantInt *CI) { 2236 // We cannot bounds check the index if it doesn't fit in an int64_t. 2237 if (CI->getValue().getMinSignedBits() > 64) 2238 return false; 2239 2240 // A negative index or an index past the end of our sequential type is 2241 // considered out-of-range. 2242 int64_t IndexVal = CI->getSExtValue(); 2243 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements)) 2244 return false; 2245 2246 // Otherwise, it is in-range. 2247 return true; 2248 } 2249 2250 Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C, 2251 bool InBounds, 2252 Optional<unsigned> InRangeIndex, 2253 ArrayRef<Value *> Idxs) { 2254 if (Idxs.empty()) return C; 2255 2256 Type *GEPTy = GetElementPtrInst::getGEPReturnType( 2257 PointeeTy, C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size())); 2258 2259 if (isa<UndefValue>(C)) 2260 return UndefValue::get(GEPTy); 2261 2262 Constant *Idx0 = cast<Constant>(Idxs[0]); 2263 if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0))) 2264 return GEPTy->isVectorTy() && !C->getType()->isVectorTy() 2265 ? ConstantVector::getSplat(GEPTy->getVectorElementCount(), C) 2266 : C; 2267 2268 if (C->isNullValue()) { 2269 bool isNull = true; 2270 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2271 if (!isa<UndefValue>(Idxs[i]) && 2272 !cast<Constant>(Idxs[i])->isNullValue()) { 2273 isNull = false; 2274 break; 2275 } 2276 if (isNull) { 2277 PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType()); 2278 Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs); 2279 2280 assert(Ty && "Invalid indices for GEP!"); 2281 Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace()); 2282 Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace()); 2283 if (VectorType *VT = dyn_cast<VectorType>(C->getType())) 2284 GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements()); 2285 2286 // The GEP returns a vector of pointers when one of more of 2287 // its arguments is a vector. 2288 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 2289 if (auto *VT = dyn_cast<VectorType>(Idxs[i]->getType())) { 2290 GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements()); 2291 break; 2292 } 2293 } 2294 2295 return Constant::getNullValue(GEPTy); 2296 } 2297 } 2298 2299 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2300 // Combine Indices - If the source pointer to this getelementptr instruction 2301 // is a getelementptr instruction, combine the indices of the two 2302 // getelementptr instructions into a single instruction. 2303 // 2304 if (CE->getOpcode() == Instruction::GetElementPtr) { 2305 gep_type_iterator LastI = gep_type_end(CE); 2306 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); 2307 I != E; ++I) 2308 LastI = I; 2309 2310 // We cannot combine indices if doing so would take us outside of an 2311 // array or vector. Doing otherwise could trick us if we evaluated such a 2312 // GEP as part of a load. 2313 // 2314 // e.g. Consider if the original GEP was: 2315 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2316 // i32 0, i32 0, i64 0) 2317 // 2318 // If we then tried to offset it by '8' to get to the third element, 2319 // an i8, we should *not* get: 2320 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2321 // i32 0, i32 0, i64 8) 2322 // 2323 // This GEP tries to index array element '8 which runs out-of-bounds. 2324 // Subsequent evaluation would get confused and produce erroneous results. 2325 // 2326 // The following prohibits such a GEP from being formed by checking to see 2327 // if the index is in-range with respect to an array. 2328 // TODO: This code may be extended to handle vectors as well. 2329 bool PerformFold = false; 2330 if (Idx0->isNullValue()) 2331 PerformFold = true; 2332 else if (LastI.isSequential()) 2333 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0)) 2334 PerformFold = (!LastI.isBoundedSequential() || 2335 isIndexInRangeOfArrayType( 2336 LastI.getSequentialNumElements(), CI)) && 2337 !CE->getOperand(CE->getNumOperands() - 1) 2338 ->getType() 2339 ->isVectorTy(); 2340 2341 if (PerformFold) { 2342 SmallVector<Value*, 16> NewIndices; 2343 NewIndices.reserve(Idxs.size() + CE->getNumOperands()); 2344 NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1); 2345 2346 // Add the last index of the source with the first index of the new GEP. 2347 // Make sure to handle the case when they are actually different types. 2348 Constant *Combined = CE->getOperand(CE->getNumOperands()-1); 2349 // Otherwise it must be an array. 2350 if (!Idx0->isNullValue()) { 2351 Type *IdxTy = Combined->getType(); 2352 if (IdxTy != Idx0->getType()) { 2353 unsigned CommonExtendedWidth = 2354 std::max(IdxTy->getIntegerBitWidth(), 2355 Idx0->getType()->getIntegerBitWidth()); 2356 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U); 2357 2358 Type *CommonTy = 2359 Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth); 2360 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy); 2361 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy); 2362 Combined = ConstantExpr::get(Instruction::Add, C1, C2); 2363 } else { 2364 Combined = 2365 ConstantExpr::get(Instruction::Add, Idx0, Combined); 2366 } 2367 } 2368 2369 NewIndices.push_back(Combined); 2370 NewIndices.append(Idxs.begin() + 1, Idxs.end()); 2371 2372 // The combined GEP normally inherits its index inrange attribute from 2373 // the inner GEP, but if the inner GEP's last index was adjusted by the 2374 // outer GEP, any inbounds attribute on that index is invalidated. 2375 Optional<unsigned> IRIndex = cast<GEPOperator>(CE)->getInRangeIndex(); 2376 if (IRIndex && *IRIndex == CE->getNumOperands() - 2 && !Idx0->isNullValue()) 2377 IRIndex = None; 2378 2379 return ConstantExpr::getGetElementPtr( 2380 cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0), 2381 NewIndices, InBounds && cast<GEPOperator>(CE)->isInBounds(), 2382 IRIndex); 2383 } 2384 } 2385 2386 // Attempt to fold casts to the same type away. For example, folding: 2387 // 2388 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*), 2389 // i64 0, i64 0) 2390 // into: 2391 // 2392 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0) 2393 // 2394 // Don't fold if the cast is changing address spaces. 2395 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) { 2396 PointerType *SrcPtrTy = 2397 dyn_cast<PointerType>(CE->getOperand(0)->getType()); 2398 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType()); 2399 if (SrcPtrTy && DstPtrTy) { 2400 ArrayType *SrcArrayTy = 2401 dyn_cast<ArrayType>(SrcPtrTy->getElementType()); 2402 ArrayType *DstArrayTy = 2403 dyn_cast<ArrayType>(DstPtrTy->getElementType()); 2404 if (SrcArrayTy && DstArrayTy 2405 && SrcArrayTy->getElementType() == DstArrayTy->getElementType() 2406 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 2407 return ConstantExpr::getGetElementPtr(SrcArrayTy, 2408 (Constant *)CE->getOperand(0), 2409 Idxs, InBounds, InRangeIndex); 2410 } 2411 } 2412 } 2413 2414 // Check to see if any array indices are not within the corresponding 2415 // notional array or vector bounds. If so, try to determine if they can be 2416 // factored out into preceding dimensions. 2417 SmallVector<Constant *, 8> NewIdxs; 2418 Type *Ty = PointeeTy; 2419 Type *Prev = C->getType(); 2420 auto GEPIter = gep_type_begin(PointeeTy, Idxs); 2421 bool Unknown = 2422 !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]); 2423 for (unsigned i = 1, e = Idxs.size(); i != e; 2424 Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) { 2425 if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) { 2426 // We don't know if it's in range or not. 2427 Unknown = true; 2428 continue; 2429 } 2430 if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1])) 2431 // Skip if the type of the previous index is not supported. 2432 continue; 2433 if (InRangeIndex && i == *InRangeIndex + 1) { 2434 // If an index is marked inrange, we cannot apply this canonicalization to 2435 // the following index, as that will cause the inrange index to point to 2436 // the wrong element. 2437 continue; 2438 } 2439 if (isa<StructType>(Ty)) { 2440 // The verify makes sure that GEPs into a struct are in range. 2441 continue; 2442 } 2443 if (isa<VectorType>(Ty)) { 2444 // There can be awkward padding in after a non-power of two vector. 2445 Unknown = true; 2446 continue; 2447 } 2448 auto *STy = cast<ArrayType>(Ty); 2449 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) { 2450 if (isIndexInRangeOfArrayType(STy->getNumElements(), CI)) 2451 // It's in range, skip to the next index. 2452 continue; 2453 if (CI->getSExtValue() < 0) { 2454 // It's out of range and negative, don't try to factor it. 2455 Unknown = true; 2456 continue; 2457 } 2458 } else { 2459 auto *CV = cast<ConstantDataVector>(Idxs[i]); 2460 bool InRange = true; 2461 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) { 2462 auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I)); 2463 InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI); 2464 if (CI->getSExtValue() < 0) { 2465 Unknown = true; 2466 break; 2467 } 2468 } 2469 if (InRange || Unknown) 2470 // It's in range, skip to the next index. 2471 // It's out of range and negative, don't try to factor it. 2472 continue; 2473 } 2474 if (isa<StructType>(Prev)) { 2475 // It's out of range, but the prior dimension is a struct 2476 // so we can't do anything about it. 2477 Unknown = true; 2478 continue; 2479 } 2480 // It's out of range, but we can factor it into the prior 2481 // dimension. 2482 NewIdxs.resize(Idxs.size()); 2483 // Determine the number of elements in our sequential type. 2484 uint64_t NumElements = STy->getArrayNumElements(); 2485 2486 // Expand the current index or the previous index to a vector from a scalar 2487 // if necessary. 2488 Constant *CurrIdx = cast<Constant>(Idxs[i]); 2489 auto *PrevIdx = 2490 NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]); 2491 bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy(); 2492 bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy(); 2493 bool UseVector = IsCurrIdxVector || IsPrevIdxVector; 2494 2495 if (!IsCurrIdxVector && IsPrevIdxVector) 2496 CurrIdx = ConstantDataVector::getSplat( 2497 PrevIdx->getType()->getVectorNumElements(), CurrIdx); 2498 2499 if (!IsPrevIdxVector && IsCurrIdxVector) 2500 PrevIdx = ConstantDataVector::getSplat( 2501 CurrIdx->getType()->getVectorNumElements(), PrevIdx); 2502 2503 Constant *Factor = 2504 ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements); 2505 if (UseVector) 2506 Factor = ConstantDataVector::getSplat( 2507 IsPrevIdxVector ? PrevIdx->getType()->getVectorNumElements() 2508 : CurrIdx->getType()->getVectorNumElements(), 2509 Factor); 2510 2511 NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor); 2512 2513 Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor); 2514 2515 unsigned CommonExtendedWidth = 2516 std::max(PrevIdx->getType()->getScalarSizeInBits(), 2517 Div->getType()->getScalarSizeInBits()); 2518 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U); 2519 2520 // Before adding, extend both operands to i64 to avoid 2521 // overflow trouble. 2522 Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth); 2523 if (UseVector) 2524 ExtendedTy = VectorType::get( 2525 ExtendedTy, IsPrevIdxVector 2526 ? PrevIdx->getType()->getVectorNumElements() 2527 : CurrIdx->getType()->getVectorNumElements()); 2528 2529 if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth)) 2530 PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy); 2531 2532 if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth)) 2533 Div = ConstantExpr::getSExt(Div, ExtendedTy); 2534 2535 NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div); 2536 } 2537 2538 // If we did any factoring, start over with the adjusted indices. 2539 if (!NewIdxs.empty()) { 2540 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2541 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]); 2542 return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds, 2543 InRangeIndex); 2544 } 2545 2546 // If all indices are known integers and normalized, we can do a simple 2547 // check for the "inbounds" property. 2548 if (!Unknown && !InBounds) 2549 if (auto *GV = dyn_cast<GlobalVariable>(C)) 2550 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs)) 2551 return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs, 2552 /*InBounds=*/true, InRangeIndex); 2553 2554 return nullptr; 2555 } 2556