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