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