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