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