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