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