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