| 1 | //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// |
| 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 the Expr constant evaluator. |
| 10 | // |
| 11 | // Constant expression evaluation produces four main results: |
| 12 | // |
| 13 | // * A success/failure flag indicating whether constant folding was successful. |
| 14 | // This is the 'bool' return value used by most of the code in this file. A |
| 15 | // 'false' return value indicates that constant folding has failed, and any |
| 16 | // appropriate diagnostic has already been produced. |
| 17 | // |
| 18 | // * An evaluated result, valid only if constant folding has not failed. |
| 19 | // |
| 20 | // * A flag indicating if evaluation encountered (unevaluated) side-effects. |
| 21 | // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), |
| 22 | // where it is possible to determine the evaluated result regardless. |
| 23 | // |
| 24 | // * A set of notes indicating why the evaluation was not a constant expression |
| 25 | // (under the C++11 / C++1y rules only, at the moment), or, if folding failed |
| 26 | // too, why the expression could not be folded. |
| 27 | // |
| 28 | // If we are checking for a potential constant expression, failure to constant |
| 29 | // fold a potential constant sub-expression will be indicated by a 'false' |
| 30 | // return value (the expression could not be folded) and no diagnostic (the |
| 31 | // expression is not necessarily non-constant). |
| 32 | // |
| 33 | //===----------------------------------------------------------------------===// |
| 34 | |
| 35 | #include "ByteCode/Context.h" |
| 36 | #include "ByteCode/Frame.h" |
| 37 | #include "ByteCode/State.h" |
| 38 | #include "ExprConstShared.h" |
| 39 | #include "clang/AST/APValue.h" |
| 40 | #include "clang/AST/ASTContext.h" |
| 41 | #include "clang/AST/ASTLambda.h" |
| 42 | #include "clang/AST/Attr.h" |
| 43 | #include "clang/AST/CXXInheritance.h" |
| 44 | #include "clang/AST/CharUnits.h" |
| 45 | #include "clang/AST/CurrentSourceLocExprScope.h" |
| 46 | #include "clang/AST/Expr.h" |
| 47 | #include "clang/AST/OSLog.h" |
| 48 | #include "clang/AST/OptionalDiagnostic.h" |
| 49 | #include "clang/AST/RecordLayout.h" |
| 50 | #include "clang/AST/StmtVisitor.h" |
| 51 | #include "clang/AST/TypeLoc.h" |
| 52 | #include "clang/Basic/Builtins.h" |
| 53 | #include "clang/Basic/DiagnosticSema.h" |
| 54 | #include "clang/Basic/TargetBuiltins.h" |
| 55 | #include "clang/Basic/TargetInfo.h" |
| 56 | #include "llvm/ADT/APFixedPoint.h" |
| 57 | #include "llvm/ADT/Sequence.h" |
| 58 | #include "llvm/ADT/SmallBitVector.h" |
| 59 | #include "llvm/ADT/StringExtras.h" |
| 60 | #include "llvm/Support/Casting.h" |
| 61 | #include "llvm/Support/Debug.h" |
| 62 | #include "llvm/Support/SaveAndRestore.h" |
| 63 | #include "llvm/Support/SipHash.h" |
| 64 | #include "llvm/Support/TimeProfiler.h" |
| 65 | #include "llvm/Support/raw_ostream.h" |
| 66 | #include <cstring> |
| 67 | #include <functional> |
| 68 | #include <optional> |
| 69 | |
| 70 | #define DEBUG_TYPE "exprconstant" |
| 71 | |
| 72 | using namespace clang; |
| 73 | using llvm::APFixedPoint; |
| 74 | using llvm::APInt; |
| 75 | using llvm::APSInt; |
| 76 | using llvm::APFloat; |
| 77 | using llvm::FixedPointSemantics; |
| 78 | |
| 79 | namespace { |
| 80 | struct LValue; |
| 81 | class CallStackFrame; |
| 82 | class EvalInfo; |
| 83 | |
| 84 | using SourceLocExprScopeGuard = |
| 85 | CurrentSourceLocExprScope::SourceLocExprScopeGuard; |
| 86 | |
| 87 | static QualType getType(APValue::LValueBase B) { |
| 88 | return B.getType(); |
| 89 | } |
| 90 | |
| 91 | /// Get an LValue path entry, which is known to not be an array index, as a |
| 92 | /// field declaration. |
| 93 | static const FieldDecl *getAsField(APValue::LValuePathEntry E) { |
| 94 | return dyn_cast_or_null<FieldDecl>(Val: E.getAsBaseOrMember().getPointer()); |
| 95 | } |
| 96 | /// Get an LValue path entry, which is known to not be an array index, as a |
| 97 | /// base class declaration. |
| 98 | static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { |
| 99 | return dyn_cast_or_null<CXXRecordDecl>(Val: E.getAsBaseOrMember().getPointer()); |
| 100 | } |
| 101 | /// Determine whether this LValue path entry for a base class names a virtual |
| 102 | /// base class. |
| 103 | static bool isVirtualBaseClass(APValue::LValuePathEntry E) { |
| 104 | return E.getAsBaseOrMember().getInt(); |
| 105 | } |
| 106 | |
| 107 | /// Given an expression, determine the type used to store the result of |
| 108 | /// evaluating that expression. |
| 109 | static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { |
| 110 | if (E->isPRValue()) |
| 111 | return E->getType(); |
| 112 | return Ctx.getLValueReferenceType(T: E->getType()); |
| 113 | } |
| 114 | |
| 115 | /// Given a CallExpr, try to get the alloc_size attribute. May return null. |
| 116 | static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { |
| 117 | if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) |
| 118 | return DirectCallee->getAttr<AllocSizeAttr>(); |
| 119 | if (const Decl *IndirectCallee = CE->getCalleeDecl()) |
| 120 | return IndirectCallee->getAttr<AllocSizeAttr>(); |
| 121 | return nullptr; |
| 122 | } |
| 123 | |
| 124 | /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. |
| 125 | /// This will look through a single cast. |
| 126 | /// |
| 127 | /// Returns null if we couldn't unwrap a function with alloc_size. |
| 128 | static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { |
| 129 | if (!E->getType()->isPointerType()) |
| 130 | return nullptr; |
| 131 | |
| 132 | E = E->IgnoreParens(); |
| 133 | // If we're doing a variable assignment from e.g. malloc(N), there will |
| 134 | // probably be a cast of some kind. In exotic cases, we might also see a |
| 135 | // top-level ExprWithCleanups. Ignore them either way. |
| 136 | if (const auto *FE = dyn_cast<FullExpr>(Val: E)) |
| 137 | E = FE->getSubExpr()->IgnoreParens(); |
| 138 | |
| 139 | if (const auto *Cast = dyn_cast<CastExpr>(Val: E)) |
| 140 | E = Cast->getSubExpr()->IgnoreParens(); |
| 141 | |
| 142 | if (const auto *CE = dyn_cast<CallExpr>(Val: E)) |
| 143 | return getAllocSizeAttr(CE) ? CE : nullptr; |
| 144 | return nullptr; |
| 145 | } |
| 146 | |
| 147 | /// Determines whether or not the given Base contains a call to a function |
| 148 | /// with the alloc_size attribute. |
| 149 | static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { |
| 150 | const auto *E = Base.dyn_cast<const Expr *>(); |
| 151 | return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); |
| 152 | } |
| 153 | |
| 154 | /// Determines whether the given kind of constant expression is only ever |
| 155 | /// used for name mangling. If so, it's permitted to reference things that we |
| 156 | /// can't generate code for (in particular, dllimported functions). |
| 157 | static bool isForManglingOnly(ConstantExprKind Kind) { |
| 158 | switch (Kind) { |
| 159 | case ConstantExprKind::Normal: |
| 160 | case ConstantExprKind::ClassTemplateArgument: |
| 161 | case ConstantExprKind::ImmediateInvocation: |
| 162 | // Note that non-type template arguments of class type are emitted as |
| 163 | // template parameter objects. |
| 164 | return false; |
| 165 | |
| 166 | case ConstantExprKind::NonClassTemplateArgument: |
| 167 | return true; |
| 168 | } |
| 169 | llvm_unreachable("unknown ConstantExprKind" ); |
| 170 | } |
| 171 | |
| 172 | static bool isTemplateArgument(ConstantExprKind Kind) { |
| 173 | switch (Kind) { |
| 174 | case ConstantExprKind::Normal: |
| 175 | case ConstantExprKind::ImmediateInvocation: |
| 176 | return false; |
| 177 | |
| 178 | case ConstantExprKind::ClassTemplateArgument: |
| 179 | case ConstantExprKind::NonClassTemplateArgument: |
| 180 | return true; |
| 181 | } |
| 182 | llvm_unreachable("unknown ConstantExprKind" ); |
| 183 | } |
| 184 | |
| 185 | /// The bound to claim that an array of unknown bound has. |
| 186 | /// The value in MostDerivedArraySize is undefined in this case. So, set it |
| 187 | /// to an arbitrary value that's likely to loudly break things if it's used. |
| 188 | static const uint64_t AssumedSizeForUnsizedArray = |
| 189 | std::numeric_limits<uint64_t>::max() / 2; |
| 190 | |
| 191 | /// Determines if an LValue with the given LValueBase will have an unsized |
| 192 | /// array in its designator. |
| 193 | /// Find the path length and type of the most-derived subobject in the given |
| 194 | /// path, and find the size of the containing array, if any. |
| 195 | static unsigned |
| 196 | findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, |
| 197 | ArrayRef<APValue::LValuePathEntry> Path, |
| 198 | uint64_t &ArraySize, QualType &Type, bool &IsArray, |
| 199 | bool &FirstEntryIsUnsizedArray) { |
| 200 | // This only accepts LValueBases from APValues, and APValues don't support |
| 201 | // arrays that lack size info. |
| 202 | assert(!isBaseAnAllocSizeCall(Base) && |
| 203 | "Unsized arrays shouldn't appear here" ); |
| 204 | unsigned MostDerivedLength = 0; |
| 205 | Type = getType(B: Base); |
| 206 | |
| 207 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { |
| 208 | if (Type->isArrayType()) { |
| 209 | const ArrayType *AT = Ctx.getAsArrayType(T: Type); |
| 210 | Type = AT->getElementType(); |
| 211 | MostDerivedLength = I + 1; |
| 212 | IsArray = true; |
| 213 | |
| 214 | if (auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) { |
| 215 | ArraySize = CAT->getZExtSize(); |
| 216 | } else { |
| 217 | assert(I == 0 && "unexpected unsized array designator" ); |
| 218 | FirstEntryIsUnsizedArray = true; |
| 219 | ArraySize = AssumedSizeForUnsizedArray; |
| 220 | } |
| 221 | } else if (Type->isAnyComplexType()) { |
| 222 | const ComplexType *CT = Type->castAs<ComplexType>(); |
| 223 | Type = CT->getElementType(); |
| 224 | ArraySize = 2; |
| 225 | MostDerivedLength = I + 1; |
| 226 | IsArray = true; |
| 227 | } else if (const auto *VT = Type->getAs<VectorType>()) { |
| 228 | Type = VT->getElementType(); |
| 229 | ArraySize = VT->getNumElements(); |
| 230 | MostDerivedLength = I + 1; |
| 231 | IsArray = true; |
| 232 | } else if (const FieldDecl *FD = getAsField(E: Path[I])) { |
| 233 | Type = FD->getType(); |
| 234 | ArraySize = 0; |
| 235 | MostDerivedLength = I + 1; |
| 236 | IsArray = false; |
| 237 | } else { |
| 238 | // Path[I] describes a base class. |
| 239 | ArraySize = 0; |
| 240 | IsArray = false; |
| 241 | } |
| 242 | } |
| 243 | return MostDerivedLength; |
| 244 | } |
| 245 | |
| 246 | /// A path from a glvalue to a subobject of that glvalue. |
| 247 | struct SubobjectDesignator { |
| 248 | /// True if the subobject was named in a manner not supported by C++11. Such |
| 249 | /// lvalues can still be folded, but they are not core constant expressions |
| 250 | /// and we cannot perform lvalue-to-rvalue conversions on them. |
| 251 | LLVM_PREFERRED_TYPE(bool) |
| 252 | unsigned Invalid : 1; |
| 253 | |
| 254 | /// Is this a pointer one past the end of an object? |
| 255 | LLVM_PREFERRED_TYPE(bool) |
| 256 | unsigned IsOnePastTheEnd : 1; |
| 257 | |
| 258 | /// Indicator of whether the first entry is an unsized array. |
| 259 | LLVM_PREFERRED_TYPE(bool) |
| 260 | unsigned FirstEntryIsAnUnsizedArray : 1; |
| 261 | |
| 262 | /// Indicator of whether the most-derived object is an array element. |
| 263 | LLVM_PREFERRED_TYPE(bool) |
| 264 | unsigned MostDerivedIsArrayElement : 1; |
| 265 | |
| 266 | /// The length of the path to the most-derived object of which this is a |
| 267 | /// subobject. |
| 268 | unsigned MostDerivedPathLength : 28; |
| 269 | |
| 270 | /// The size of the array of which the most-derived object is an element. |
| 271 | /// This will always be 0 if the most-derived object is not an array |
| 272 | /// element. 0 is not an indicator of whether or not the most-derived object |
| 273 | /// is an array, however, because 0-length arrays are allowed. |
| 274 | /// |
| 275 | /// If the current array is an unsized array, the value of this is |
| 276 | /// undefined. |
| 277 | uint64_t MostDerivedArraySize; |
| 278 | /// The type of the most derived object referred to by this address. |
| 279 | QualType MostDerivedType; |
| 280 | |
| 281 | typedef APValue::LValuePathEntry PathEntry; |
| 282 | |
| 283 | /// The entries on the path from the glvalue to the designated subobject. |
| 284 | SmallVector<PathEntry, 8> Entries; |
| 285 | |
| 286 | SubobjectDesignator() : Invalid(true) {} |
| 287 | |
| 288 | explicit SubobjectDesignator(QualType T) |
| 289 | : Invalid(false), IsOnePastTheEnd(false), |
| 290 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), |
| 291 | MostDerivedPathLength(0), MostDerivedArraySize(0), |
| 292 | MostDerivedType(T) {} |
| 293 | |
| 294 | SubobjectDesignator(ASTContext &Ctx, const APValue &V) |
| 295 | : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), |
| 296 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), |
| 297 | MostDerivedPathLength(0), MostDerivedArraySize(0) { |
| 298 | assert(V.isLValue() && "Non-LValue used to make an LValue designator?" ); |
| 299 | if (!Invalid) { |
| 300 | IsOnePastTheEnd = V.isLValueOnePastTheEnd(); |
| 301 | llvm::append_range(C&: Entries, R: V.getLValuePath()); |
| 302 | if (V.getLValueBase()) { |
| 303 | bool IsArray = false; |
| 304 | bool FirstIsUnsizedArray = false; |
| 305 | MostDerivedPathLength = findMostDerivedSubobject( |
| 306 | Ctx, Base: V.getLValueBase(), Path: V.getLValuePath(), ArraySize&: MostDerivedArraySize, |
| 307 | Type&: MostDerivedType, IsArray, FirstEntryIsUnsizedArray&: FirstIsUnsizedArray); |
| 308 | MostDerivedIsArrayElement = IsArray; |
| 309 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | void truncate(ASTContext &Ctx, APValue::LValueBase Base, |
| 315 | unsigned NewLength) { |
| 316 | if (Invalid) |
| 317 | return; |
| 318 | |
| 319 | assert(Base && "cannot truncate path for null pointer" ); |
| 320 | assert(NewLength <= Entries.size() && "not a truncation" ); |
| 321 | |
| 322 | if (NewLength == Entries.size()) |
| 323 | return; |
| 324 | Entries.resize(N: NewLength); |
| 325 | |
| 326 | bool IsArray = false; |
| 327 | bool FirstIsUnsizedArray = false; |
| 328 | MostDerivedPathLength = findMostDerivedSubobject( |
| 329 | Ctx, Base, Path: Entries, ArraySize&: MostDerivedArraySize, Type&: MostDerivedType, IsArray, |
| 330 | FirstEntryIsUnsizedArray&: FirstIsUnsizedArray); |
| 331 | MostDerivedIsArrayElement = IsArray; |
| 332 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; |
| 333 | } |
| 334 | |
| 335 | void setInvalid() { |
| 336 | Invalid = true; |
| 337 | Entries.clear(); |
| 338 | } |
| 339 | |
| 340 | /// Determine whether the most derived subobject is an array without a |
| 341 | /// known bound. |
| 342 | bool isMostDerivedAnUnsizedArray() const { |
| 343 | assert(!Invalid && "Calling this makes no sense on invalid designators" ); |
| 344 | return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; |
| 345 | } |
| 346 | |
| 347 | /// Determine what the most derived array's size is. Results in an assertion |
| 348 | /// failure if the most derived array lacks a size. |
| 349 | uint64_t getMostDerivedArraySize() const { |
| 350 | assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size" ); |
| 351 | return MostDerivedArraySize; |
| 352 | } |
| 353 | |
| 354 | /// Determine whether this is a one-past-the-end pointer. |
| 355 | bool isOnePastTheEnd() const { |
| 356 | assert(!Invalid); |
| 357 | if (IsOnePastTheEnd) |
| 358 | return true; |
| 359 | if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && |
| 360 | Entries[MostDerivedPathLength - 1].getAsArrayIndex() == |
| 361 | MostDerivedArraySize) |
| 362 | return true; |
| 363 | return false; |
| 364 | } |
| 365 | |
| 366 | /// Get the range of valid index adjustments in the form |
| 367 | /// {maximum value that can be subtracted from this pointer, |
| 368 | /// maximum value that can be added to this pointer} |
| 369 | std::pair<uint64_t, uint64_t> validIndexAdjustments() { |
| 370 | if (Invalid || isMostDerivedAnUnsizedArray()) |
| 371 | return {0, 0}; |
| 372 | |
| 373 | // [expr.add]p4: For the purposes of these operators, a pointer to a |
| 374 | // nonarray object behaves the same as a pointer to the first element of |
| 375 | // an array of length one with the type of the object as its element type. |
| 376 | bool IsArray = MostDerivedPathLength == Entries.size() && |
| 377 | MostDerivedIsArrayElement; |
| 378 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() |
| 379 | : (uint64_t)IsOnePastTheEnd; |
| 380 | uint64_t ArraySize = |
| 381 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; |
| 382 | return {ArrayIndex, ArraySize - ArrayIndex}; |
| 383 | } |
| 384 | |
| 385 | /// Check that this refers to a valid subobject. |
| 386 | bool isValidSubobject() const { |
| 387 | if (Invalid) |
| 388 | return false; |
| 389 | return !isOnePastTheEnd(); |
| 390 | } |
| 391 | /// Check that this refers to a valid subobject, and if not, produce a |
| 392 | /// relevant diagnostic and set the designator as invalid. |
| 393 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); |
| 394 | |
| 395 | /// Get the type of the designated object. |
| 396 | QualType getType(ASTContext &Ctx) const { |
| 397 | assert(!Invalid && "invalid designator has no subobject type" ); |
| 398 | return MostDerivedPathLength == Entries.size() |
| 399 | ? MostDerivedType |
| 400 | : Ctx.getRecordType(Decl: getAsBaseClass(E: Entries.back())); |
| 401 | } |
| 402 | |
| 403 | /// Update this designator to refer to the first element within this array. |
| 404 | void addArrayUnchecked(const ConstantArrayType *CAT) { |
| 405 | Entries.push_back(Elt: PathEntry::ArrayIndex(Index: 0)); |
| 406 | |
| 407 | // This is a most-derived object. |
| 408 | MostDerivedType = CAT->getElementType(); |
| 409 | MostDerivedIsArrayElement = true; |
| 410 | MostDerivedArraySize = CAT->getZExtSize(); |
| 411 | MostDerivedPathLength = Entries.size(); |
| 412 | } |
| 413 | /// Update this designator to refer to the first element within the array of |
| 414 | /// elements of type T. This is an array of unknown size. |
| 415 | void addUnsizedArrayUnchecked(QualType ElemTy) { |
| 416 | Entries.push_back(Elt: PathEntry::ArrayIndex(Index: 0)); |
| 417 | |
| 418 | MostDerivedType = ElemTy; |
| 419 | MostDerivedIsArrayElement = true; |
| 420 | // The value in MostDerivedArraySize is undefined in this case. So, set it |
| 421 | // to an arbitrary value that's likely to loudly break things if it's |
| 422 | // used. |
| 423 | MostDerivedArraySize = AssumedSizeForUnsizedArray; |
| 424 | MostDerivedPathLength = Entries.size(); |
| 425 | } |
| 426 | /// Update this designator to refer to the given base or member of this |
| 427 | /// object. |
| 428 | void addDeclUnchecked(const Decl *D, bool Virtual = false) { |
| 429 | Entries.push_back(Elt: APValue::BaseOrMemberType(D, Virtual)); |
| 430 | |
| 431 | // If this isn't a base class, it's a new most-derived object. |
| 432 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D)) { |
| 433 | MostDerivedType = FD->getType(); |
| 434 | MostDerivedIsArrayElement = false; |
| 435 | MostDerivedArraySize = 0; |
| 436 | MostDerivedPathLength = Entries.size(); |
| 437 | } |
| 438 | } |
| 439 | /// Update this designator to refer to the given complex component. |
| 440 | void addComplexUnchecked(QualType EltTy, bool Imag) { |
| 441 | Entries.push_back(Elt: PathEntry::ArrayIndex(Index: Imag)); |
| 442 | |
| 443 | // This is technically a most-derived object, though in practice this |
| 444 | // is unlikely to matter. |
| 445 | MostDerivedType = EltTy; |
| 446 | MostDerivedIsArrayElement = true; |
| 447 | MostDerivedArraySize = 2; |
| 448 | MostDerivedPathLength = Entries.size(); |
| 449 | } |
| 450 | |
| 451 | void addVectorElementUnchecked(QualType EltTy, uint64_t Size, |
| 452 | uint64_t Idx) { |
| 453 | Entries.push_back(Elt: PathEntry::ArrayIndex(Index: Idx)); |
| 454 | MostDerivedType = EltTy; |
| 455 | MostDerivedPathLength = Entries.size(); |
| 456 | MostDerivedArraySize = 0; |
| 457 | MostDerivedIsArrayElement = false; |
| 458 | } |
| 459 | |
| 460 | void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); |
| 461 | void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, |
| 462 | const APSInt &N); |
| 463 | /// Add N to the address of this subobject. |
| 464 | void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { |
| 465 | if (Invalid || !N) return; |
| 466 | uint64_t TruncatedN = N.extOrTrunc(width: 64).getZExtValue(); |
| 467 | if (isMostDerivedAnUnsizedArray()) { |
| 468 | diagnoseUnsizedArrayPointerArithmetic(Info, E); |
| 469 | // Can't verify -- trust that the user is doing the right thing (or if |
| 470 | // not, trust that the caller will catch the bad behavior). |
| 471 | // FIXME: Should we reject if this overflows, at least? |
| 472 | Entries.back() = PathEntry::ArrayIndex( |
| 473 | Index: Entries.back().getAsArrayIndex() + TruncatedN); |
| 474 | return; |
| 475 | } |
| 476 | |
| 477 | // [expr.add]p4: For the purposes of these operators, a pointer to a |
| 478 | // nonarray object behaves the same as a pointer to the first element of |
| 479 | // an array of length one with the type of the object as its element type. |
| 480 | bool IsArray = MostDerivedPathLength == Entries.size() && |
| 481 | MostDerivedIsArrayElement; |
| 482 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() |
| 483 | : (uint64_t)IsOnePastTheEnd; |
| 484 | uint64_t ArraySize = |
| 485 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; |
| 486 | |
| 487 | if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { |
| 488 | // Calculate the actual index in a wide enough type, so we can include |
| 489 | // it in the note. |
| 490 | N = N.extend(width: std::max<unsigned>(a: N.getBitWidth() + 1, b: 65)); |
| 491 | (llvm::APInt&)N += ArrayIndex; |
| 492 | assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index" ); |
| 493 | diagnosePointerArithmetic(Info, E, N); |
| 494 | setInvalid(); |
| 495 | return; |
| 496 | } |
| 497 | |
| 498 | ArrayIndex += TruncatedN; |
| 499 | assert(ArrayIndex <= ArraySize && |
| 500 | "bounds check succeeded for out-of-bounds index" ); |
| 501 | |
| 502 | if (IsArray) |
| 503 | Entries.back() = PathEntry::ArrayIndex(Index: ArrayIndex); |
| 504 | else |
| 505 | IsOnePastTheEnd = (ArrayIndex != 0); |
| 506 | } |
| 507 | }; |
| 508 | |
| 509 | /// A scope at the end of which an object can need to be destroyed. |
| 510 | enum class ScopeKind { |
| 511 | Block, |
| 512 | FullExpression, |
| 513 | Call |
| 514 | }; |
| 515 | |
| 516 | /// A reference to a particular call and its arguments. |
| 517 | struct CallRef { |
| 518 | CallRef() : OrigCallee(), CallIndex(0), Version() {} |
| 519 | CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) |
| 520 | : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} |
| 521 | |
| 522 | explicit operator bool() const { return OrigCallee; } |
| 523 | |
| 524 | /// Get the parameter that the caller initialized, corresponding to the |
| 525 | /// given parameter in the callee. |
| 526 | const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { |
| 527 | return OrigCallee ? OrigCallee->getParamDecl(i: PVD->getFunctionScopeIndex()) |
| 528 | : PVD; |
| 529 | } |
| 530 | |
| 531 | /// The callee at the point where the arguments were evaluated. This might |
| 532 | /// be different from the actual callee (a different redeclaration, or a |
| 533 | /// virtual override), but this function's parameters are the ones that |
| 534 | /// appear in the parameter map. |
| 535 | const FunctionDecl *OrigCallee; |
| 536 | /// The call index of the frame that holds the argument values. |
| 537 | unsigned CallIndex; |
| 538 | /// The version of the parameters corresponding to this call. |
| 539 | unsigned Version; |
| 540 | }; |
| 541 | |
| 542 | /// A stack frame in the constexpr call stack. |
| 543 | class CallStackFrame : public interp::Frame { |
| 544 | public: |
| 545 | EvalInfo &Info; |
| 546 | |
| 547 | /// Parent - The caller of this stack frame. |
| 548 | CallStackFrame *Caller; |
| 549 | |
| 550 | /// Callee - The function which was called. |
| 551 | const FunctionDecl *Callee; |
| 552 | |
| 553 | /// This - The binding for the this pointer in this call, if any. |
| 554 | const LValue *This; |
| 555 | |
| 556 | /// CallExpr - The syntactical structure of member function calls |
| 557 | const Expr *CallExpr; |
| 558 | |
| 559 | /// Information on how to find the arguments to this call. Our arguments |
| 560 | /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a |
| 561 | /// key and this value as the version. |
| 562 | CallRef Arguments; |
| 563 | |
| 564 | /// Source location information about the default argument or default |
| 565 | /// initializer expression we're evaluating, if any. |
| 566 | CurrentSourceLocExprScope CurSourceLocExprScope; |
| 567 | |
| 568 | // Note that we intentionally use std::map here so that references to |
| 569 | // values are stable. |
| 570 | typedef std::pair<const void *, unsigned> MapKeyTy; |
| 571 | typedef std::map<MapKeyTy, APValue> MapTy; |
| 572 | /// Temporaries - Temporary lvalues materialized within this stack frame. |
| 573 | MapTy Temporaries; |
| 574 | MapTy ConstexprUnknownAPValues; |
| 575 | |
| 576 | /// CallRange - The source range of the call expression for this call. |
| 577 | SourceRange CallRange; |
| 578 | |
| 579 | /// Index - The call index of this call. |
| 580 | unsigned Index; |
| 581 | |
| 582 | /// The stack of integers for tracking version numbers for temporaries. |
| 583 | SmallVector<unsigned, 2> TempVersionStack = {1}; |
| 584 | unsigned CurTempVersion = TempVersionStack.back(); |
| 585 | |
| 586 | unsigned getTempVersion() const { return TempVersionStack.back(); } |
| 587 | |
| 588 | void pushTempVersion() { |
| 589 | TempVersionStack.push_back(Elt: ++CurTempVersion); |
| 590 | } |
| 591 | |
| 592 | void popTempVersion() { |
| 593 | TempVersionStack.pop_back(); |
| 594 | } |
| 595 | |
| 596 | CallRef createCall(const FunctionDecl *Callee) { |
| 597 | return {Callee, Index, ++CurTempVersion}; |
| 598 | } |
| 599 | |
| 600 | // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact |
| 601 | // on the overall stack usage of deeply-recursing constexpr evaluations. |
| 602 | // (We should cache this map rather than recomputing it repeatedly.) |
| 603 | // But let's try this and see how it goes; we can look into caching the map |
| 604 | // as a later change. |
| 605 | |
| 606 | /// LambdaCaptureFields - Mapping from captured variables/this to |
| 607 | /// corresponding data members in the closure class. |
| 608 | llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; |
| 609 | FieldDecl *LambdaThisCaptureField = nullptr; |
| 610 | |
| 611 | CallStackFrame(EvalInfo &Info, SourceRange CallRange, |
| 612 | const FunctionDecl *Callee, const LValue *This, |
| 613 | const Expr *CallExpr, CallRef Arguments); |
| 614 | ~CallStackFrame(); |
| 615 | |
| 616 | // Return the temporary for Key whose version number is Version. |
| 617 | APValue *getTemporary(const void *Key, unsigned Version) { |
| 618 | MapKeyTy KV(Key, Version); |
| 619 | auto LB = Temporaries.lower_bound(x: KV); |
| 620 | if (LB != Temporaries.end() && LB->first == KV) |
| 621 | return &LB->second; |
| 622 | return nullptr; |
| 623 | } |
| 624 | |
| 625 | // Return the current temporary for Key in the map. |
| 626 | APValue *getCurrentTemporary(const void *Key) { |
| 627 | auto UB = Temporaries.upper_bound(x: MapKeyTy(Key, UINT_MAX)); |
| 628 | if (UB != Temporaries.begin() && std::prev(x: UB)->first.first == Key) |
| 629 | return &std::prev(x: UB)->second; |
| 630 | return nullptr; |
| 631 | } |
| 632 | |
| 633 | // Return the version number of the current temporary for Key. |
| 634 | unsigned getCurrentTemporaryVersion(const void *Key) const { |
| 635 | auto UB = Temporaries.upper_bound(x: MapKeyTy(Key, UINT_MAX)); |
| 636 | if (UB != Temporaries.begin() && std::prev(x: UB)->first.first == Key) |
| 637 | return std::prev(x: UB)->first.second; |
| 638 | return 0; |
| 639 | } |
| 640 | |
| 641 | /// Allocate storage for an object of type T in this stack frame. |
| 642 | /// Populates LV with a handle to the created object. Key identifies |
| 643 | /// the temporary within the stack frame, and must not be reused without |
| 644 | /// bumping the temporary version number. |
| 645 | template<typename KeyT> |
| 646 | APValue &createTemporary(const KeyT *Key, QualType T, |
| 647 | ScopeKind Scope, LValue &LV); |
| 648 | |
| 649 | APValue &createConstexprUnknownAPValues(const VarDecl *Key, |
| 650 | APValue::LValueBase Base); |
| 651 | |
| 652 | /// Allocate storage for a parameter of a function call made in this frame. |
| 653 | APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); |
| 654 | |
| 655 | void describe(llvm::raw_ostream &OS) const override; |
| 656 | |
| 657 | Frame *getCaller() const override { return Caller; } |
| 658 | SourceRange getCallRange() const override { return CallRange; } |
| 659 | const FunctionDecl *getCallee() const override { return Callee; } |
| 660 | |
| 661 | bool isStdFunction() const { |
| 662 | for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) |
| 663 | if (DC->isStdNamespace()) |
| 664 | return true; |
| 665 | return false; |
| 666 | } |
| 667 | |
| 668 | /// Whether we're in a context where [[msvc::constexpr]] evaluation is |
| 669 | /// permitted. See MSConstexprDocs for description of permitted contexts. |
| 670 | bool CanEvalMSConstexpr = false; |
| 671 | |
| 672 | private: |
| 673 | APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, |
| 674 | ScopeKind Scope); |
| 675 | }; |
| 676 | |
| 677 | /// Temporarily override 'this'. |
| 678 | class ThisOverrideRAII { |
| 679 | public: |
| 680 | ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) |
| 681 | : Frame(Frame), OldThis(Frame.This) { |
| 682 | if (Enable) |
| 683 | Frame.This = NewThis; |
| 684 | } |
| 685 | ~ThisOverrideRAII() { |
| 686 | Frame.This = OldThis; |
| 687 | } |
| 688 | private: |
| 689 | CallStackFrame &Frame; |
| 690 | const LValue *OldThis; |
| 691 | }; |
| 692 | |
| 693 | // A shorthand time trace scope struct, prints source range, for example |
| 694 | // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}} |
| 695 | class ExprTimeTraceScope { |
| 696 | public: |
| 697 | ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name) |
| 698 | : TimeScope(Name, [E, &Ctx] { |
| 699 | return E->getSourceRange().printToString(SM: Ctx.getSourceManager()); |
| 700 | }) {} |
| 701 | |
| 702 | private: |
| 703 | llvm::TimeTraceScope TimeScope; |
| 704 | }; |
| 705 | |
| 706 | /// RAII object used to change the current ability of |
| 707 | /// [[msvc::constexpr]] evaulation. |
| 708 | struct { |
| 709 | CallStackFrame &; |
| 710 | bool ; |
| 711 | explicit (CallStackFrame &Frame, bool Value) |
| 712 | : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) { |
| 713 | Frame.CanEvalMSConstexpr = Value; |
| 714 | } |
| 715 | |
| 716 | () { Frame.CanEvalMSConstexpr = OldValue; } |
| 717 | }; |
| 718 | } |
| 719 | |
| 720 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, |
| 721 | const LValue &This, QualType ThisType); |
| 722 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, |
| 723 | APValue::LValueBase LVBase, APValue &Value, |
| 724 | QualType T); |
| 725 | |
| 726 | namespace { |
| 727 | /// A cleanup, and a flag indicating whether it is lifetime-extended. |
| 728 | class Cleanup { |
| 729 | llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; |
| 730 | APValue::LValueBase Base; |
| 731 | QualType T; |
| 732 | |
| 733 | public: |
| 734 | Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, |
| 735 | ScopeKind Scope) |
| 736 | : Value(Val, Scope), Base(Base), T(T) {} |
| 737 | |
| 738 | /// Determine whether this cleanup should be performed at the end of the |
| 739 | /// given kind of scope. |
| 740 | bool isDestroyedAtEndOf(ScopeKind K) const { |
| 741 | return (int)Value.getInt() >= (int)K; |
| 742 | } |
| 743 | bool endLifetime(EvalInfo &Info, bool RunDestructors) { |
| 744 | if (RunDestructors) { |
| 745 | SourceLocation Loc; |
| 746 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) |
| 747 | Loc = VD->getLocation(); |
| 748 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) |
| 749 | Loc = E->getExprLoc(); |
| 750 | return HandleDestruction(Info, Loc, LVBase: Base, Value&: *Value.getPointer(), T); |
| 751 | } |
| 752 | *Value.getPointer() = APValue(); |
| 753 | return true; |
| 754 | } |
| 755 | |
| 756 | bool hasSideEffect() { |
| 757 | return T.isDestructedType(); |
| 758 | } |
| 759 | }; |
| 760 | |
| 761 | /// A reference to an object whose construction we are currently evaluating. |
| 762 | struct ObjectUnderConstruction { |
| 763 | APValue::LValueBase Base; |
| 764 | ArrayRef<APValue::LValuePathEntry> Path; |
| 765 | friend bool operator==(const ObjectUnderConstruction &LHS, |
| 766 | const ObjectUnderConstruction &RHS) { |
| 767 | return LHS.Base == RHS.Base && LHS.Path == RHS.Path; |
| 768 | } |
| 769 | friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { |
| 770 | return llvm::hash_combine(args: Obj.Base, args: Obj.Path); |
| 771 | } |
| 772 | }; |
| 773 | enum class ConstructionPhase { |
| 774 | None, |
| 775 | Bases, |
| 776 | AfterBases, |
| 777 | AfterFields, |
| 778 | Destroying, |
| 779 | DestroyingBases |
| 780 | }; |
| 781 | } |
| 782 | |
| 783 | namespace llvm { |
| 784 | template<> struct DenseMapInfo<ObjectUnderConstruction> { |
| 785 | using Base = DenseMapInfo<APValue::LValueBase>; |
| 786 | static ObjectUnderConstruction getEmptyKey() { |
| 787 | return {.Base: Base::getEmptyKey(), .Path: {}}; } |
| 788 | static ObjectUnderConstruction getTombstoneKey() { |
| 789 | return {.Base: Base::getTombstoneKey(), .Path: {}}; |
| 790 | } |
| 791 | static unsigned getHashValue(const ObjectUnderConstruction &Object) { |
| 792 | return hash_value(Obj: Object); |
| 793 | } |
| 794 | static bool isEqual(const ObjectUnderConstruction &LHS, |
| 795 | const ObjectUnderConstruction &RHS) { |
| 796 | return LHS == RHS; |
| 797 | } |
| 798 | }; |
| 799 | } |
| 800 | |
| 801 | namespace { |
| 802 | /// A dynamically-allocated heap object. |
| 803 | struct DynAlloc { |
| 804 | /// The value of this heap-allocated object. |
| 805 | APValue Value; |
| 806 | /// The allocating expression; used for diagnostics. Either a CXXNewExpr |
| 807 | /// or a CallExpr (the latter is for direct calls to operator new inside |
| 808 | /// std::allocator<T>::allocate). |
| 809 | const Expr *AllocExpr = nullptr; |
| 810 | |
| 811 | enum Kind { |
| 812 | New, |
| 813 | ArrayNew, |
| 814 | StdAllocator |
| 815 | }; |
| 816 | |
| 817 | /// Get the kind of the allocation. This must match between allocation |
| 818 | /// and deallocation. |
| 819 | Kind getKind() const { |
| 820 | if (auto *NE = dyn_cast<CXXNewExpr>(Val: AllocExpr)) |
| 821 | return NE->isArray() ? ArrayNew : New; |
| 822 | assert(isa<CallExpr>(AllocExpr)); |
| 823 | return StdAllocator; |
| 824 | } |
| 825 | }; |
| 826 | |
| 827 | struct DynAllocOrder { |
| 828 | bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { |
| 829 | return L.getIndex() < R.getIndex(); |
| 830 | } |
| 831 | }; |
| 832 | |
| 833 | /// EvalInfo - This is a private struct used by the evaluator to capture |
| 834 | /// information about a subexpression as it is folded. It retains information |
| 835 | /// about the AST context, but also maintains information about the folded |
| 836 | /// expression. |
| 837 | /// |
| 838 | /// If an expression could be evaluated, it is still possible it is not a C |
| 839 | /// "integer constant expression" or constant expression. If not, this struct |
| 840 | /// captures information about how and why not. |
| 841 | /// |
| 842 | /// One bit of information passed *into* the request for constant folding |
| 843 | /// indicates whether the subexpression is "evaluated" or not according to C |
| 844 | /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can |
| 845 | /// evaluate the expression regardless of what the RHS is, but C only allows |
| 846 | /// certain things in certain situations. |
| 847 | class EvalInfo : public interp::State { |
| 848 | public: |
| 849 | ASTContext &Ctx; |
| 850 | |
| 851 | /// EvalStatus - Contains information about the evaluation. |
| 852 | Expr::EvalStatus &EvalStatus; |
| 853 | |
| 854 | /// CurrentCall - The top of the constexpr call stack. |
| 855 | CallStackFrame *CurrentCall; |
| 856 | |
| 857 | /// CallStackDepth - The number of calls in the call stack right now. |
| 858 | unsigned CallStackDepth; |
| 859 | |
| 860 | /// NextCallIndex - The next call index to assign. |
| 861 | unsigned NextCallIndex; |
| 862 | |
| 863 | /// StepsLeft - The remaining number of evaluation steps we're permitted |
| 864 | /// to perform. This is essentially a limit for the number of statements |
| 865 | /// we will evaluate. |
| 866 | unsigned StepsLeft; |
| 867 | |
| 868 | /// Enable the experimental new constant interpreter. If an expression is |
| 869 | /// not supported by the interpreter, an error is triggered. |
| 870 | bool EnableNewConstInterp; |
| 871 | |
| 872 | /// BottomFrame - The frame in which evaluation started. This must be |
| 873 | /// initialized after CurrentCall and CallStackDepth. |
| 874 | CallStackFrame BottomFrame; |
| 875 | |
| 876 | /// A stack of values whose lifetimes end at the end of some surrounding |
| 877 | /// evaluation frame. |
| 878 | llvm::SmallVector<Cleanup, 16> CleanupStack; |
| 879 | |
| 880 | /// EvaluatingDecl - This is the declaration whose initializer is being |
| 881 | /// evaluated, if any. |
| 882 | APValue::LValueBase EvaluatingDecl; |
| 883 | |
| 884 | enum class EvaluatingDeclKind { |
| 885 | None, |
| 886 | /// We're evaluating the construction of EvaluatingDecl. |
| 887 | Ctor, |
| 888 | /// We're evaluating the destruction of EvaluatingDecl. |
| 889 | Dtor, |
| 890 | }; |
| 891 | EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; |
| 892 | |
| 893 | /// EvaluatingDeclValue - This is the value being constructed for the |
| 894 | /// declaration whose initializer is being evaluated, if any. |
| 895 | APValue *EvaluatingDeclValue; |
| 896 | |
| 897 | /// Set of objects that are currently being constructed. |
| 898 | llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> |
| 899 | ObjectsUnderConstruction; |
| 900 | |
| 901 | /// Current heap allocations, along with the location where each was |
| 902 | /// allocated. We use std::map here because we need stable addresses |
| 903 | /// for the stored APValues. |
| 904 | std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; |
| 905 | |
| 906 | /// The number of heap allocations performed so far in this evaluation. |
| 907 | unsigned NumHeapAllocs = 0; |
| 908 | |
| 909 | struct EvaluatingConstructorRAII { |
| 910 | EvalInfo &EI; |
| 911 | ObjectUnderConstruction Object; |
| 912 | bool DidInsert; |
| 913 | EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, |
| 914 | bool HasBases) |
| 915 | : EI(EI), Object(Object) { |
| 916 | DidInsert = |
| 917 | EI.ObjectsUnderConstruction |
| 918 | .insert(KV: {Object, HasBases ? ConstructionPhase::Bases |
| 919 | : ConstructionPhase::AfterBases}) |
| 920 | .second; |
| 921 | } |
| 922 | void finishedConstructingBases() { |
| 923 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; |
| 924 | } |
| 925 | void finishedConstructingFields() { |
| 926 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; |
| 927 | } |
| 928 | ~EvaluatingConstructorRAII() { |
| 929 | if (DidInsert) EI.ObjectsUnderConstruction.erase(Val: Object); |
| 930 | } |
| 931 | }; |
| 932 | |
| 933 | struct EvaluatingDestructorRAII { |
| 934 | EvalInfo &EI; |
| 935 | ObjectUnderConstruction Object; |
| 936 | bool DidInsert; |
| 937 | EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) |
| 938 | : EI(EI), Object(Object) { |
| 939 | DidInsert = EI.ObjectsUnderConstruction |
| 940 | .insert(KV: {Object, ConstructionPhase::Destroying}) |
| 941 | .second; |
| 942 | } |
| 943 | void startedDestroyingBases() { |
| 944 | EI.ObjectsUnderConstruction[Object] = |
| 945 | ConstructionPhase::DestroyingBases; |
| 946 | } |
| 947 | ~EvaluatingDestructorRAII() { |
| 948 | if (DidInsert) |
| 949 | EI.ObjectsUnderConstruction.erase(Val: Object); |
| 950 | } |
| 951 | }; |
| 952 | |
| 953 | ConstructionPhase |
| 954 | isEvaluatingCtorDtor(APValue::LValueBase Base, |
| 955 | ArrayRef<APValue::LValuePathEntry> Path) { |
| 956 | return ObjectsUnderConstruction.lookup(Val: {.Base: Base, .Path: Path}); |
| 957 | } |
| 958 | |
| 959 | /// If we're currently speculatively evaluating, the outermost call stack |
| 960 | /// depth at which we can mutate state, otherwise 0. |
| 961 | unsigned SpeculativeEvaluationDepth = 0; |
| 962 | |
| 963 | /// The current array initialization index, if we're performing array |
| 964 | /// initialization. |
| 965 | uint64_t ArrayInitIndex = -1; |
| 966 | |
| 967 | /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further |
| 968 | /// notes attached to it will also be stored, otherwise they will not be. |
| 969 | bool HasActiveDiagnostic; |
| 970 | |
| 971 | /// Have we emitted a diagnostic explaining why we couldn't constant |
| 972 | /// fold (not just why it's not strictly a constant expression)? |
| 973 | bool HasFoldFailureDiagnostic; |
| 974 | |
| 975 | /// Whether we're checking that an expression is a potential constant |
| 976 | /// expression. If so, do not fail on constructs that could become constant |
| 977 | /// later on (such as a use of an undefined global). |
| 978 | bool CheckingPotentialConstantExpression = false; |
| 979 | |
| 980 | /// Whether we're checking for an expression that has undefined behavior. |
| 981 | /// If so, we will produce warnings if we encounter an operation that is |
| 982 | /// always undefined. |
| 983 | /// |
| 984 | /// Note that we still need to evaluate the expression normally when this |
| 985 | /// is set; this is used when evaluating ICEs in C. |
| 986 | bool CheckingForUndefinedBehavior = false; |
| 987 | |
| 988 | enum EvaluationMode { |
| 989 | /// Evaluate as a constant expression. Stop if we find that the expression |
| 990 | /// is not a constant expression. |
| 991 | EM_ConstantExpression, |
| 992 | |
| 993 | /// Evaluate as a constant expression. Stop if we find that the expression |
| 994 | /// is not a constant expression. Some expressions can be retried in the |
| 995 | /// optimizer if we don't constant fold them here, but in an unevaluated |
| 996 | /// context we try to fold them immediately since the optimizer never |
| 997 | /// gets a chance to look at it. |
| 998 | EM_ConstantExpressionUnevaluated, |
| 999 | |
| 1000 | /// Fold the expression to a constant. Stop if we hit a side-effect that |
| 1001 | /// we can't model. |
| 1002 | EM_ConstantFold, |
| 1003 | |
| 1004 | /// Evaluate in any way we know how. Don't worry about side-effects that |
| 1005 | /// can't be modeled. |
| 1006 | EM_IgnoreSideEffects, |
| 1007 | } EvalMode; |
| 1008 | |
| 1009 | /// Are we checking whether the expression is a potential constant |
| 1010 | /// expression? |
| 1011 | bool checkingPotentialConstantExpression() const override { |
| 1012 | return CheckingPotentialConstantExpression; |
| 1013 | } |
| 1014 | |
| 1015 | /// Are we checking an expression for overflow? |
| 1016 | // FIXME: We should check for any kind of undefined or suspicious behavior |
| 1017 | // in such constructs, not just overflow. |
| 1018 | bool checkingForUndefinedBehavior() const override { |
| 1019 | return CheckingForUndefinedBehavior; |
| 1020 | } |
| 1021 | |
| 1022 | EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) |
| 1023 | : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), |
| 1024 | CallStackDepth(0), NextCallIndex(1), |
| 1025 | StepsLeft(C.getLangOpts().ConstexprStepLimit), |
| 1026 | EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), |
| 1027 | BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr, |
| 1028 | /*This=*/nullptr, |
| 1029 | /*CallExpr=*/nullptr, CallRef()), |
| 1030 | EvaluatingDecl((const ValueDecl *)nullptr), |
| 1031 | EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), |
| 1032 | HasFoldFailureDiagnostic(false), EvalMode(Mode) {} |
| 1033 | |
| 1034 | ~EvalInfo() { |
| 1035 | discardCleanups(); |
| 1036 | } |
| 1037 | |
| 1038 | ASTContext &getASTContext() const override { return Ctx; } |
| 1039 | |
| 1040 | void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, |
| 1041 | EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { |
| 1042 | EvaluatingDecl = Base; |
| 1043 | IsEvaluatingDecl = EDK; |
| 1044 | EvaluatingDeclValue = &Value; |
| 1045 | } |
| 1046 | |
| 1047 | bool CheckCallLimit(SourceLocation Loc) { |
| 1048 | // Don't perform any constexpr calls (other than the call we're checking) |
| 1049 | // when checking a potential constant expression. |
| 1050 | if (checkingPotentialConstantExpression() && CallStackDepth > 1) |
| 1051 | return false; |
| 1052 | if (NextCallIndex == 0) { |
| 1053 | // NextCallIndex has wrapped around. |
| 1054 | FFDiag(Loc, DiagId: diag::note_constexpr_call_limit_exceeded); |
| 1055 | return false; |
| 1056 | } |
| 1057 | if (CallStackDepth <= getLangOpts().ConstexprCallDepth) |
| 1058 | return true; |
| 1059 | FFDiag(Loc, DiagId: diag::note_constexpr_depth_limit_exceeded) |
| 1060 | << getLangOpts().ConstexprCallDepth; |
| 1061 | return false; |
| 1062 | } |
| 1063 | |
| 1064 | bool CheckArraySize(SourceLocation Loc, unsigned BitWidth, |
| 1065 | uint64_t ElemCount, bool Diag) { |
| 1066 | // FIXME: GH63562 |
| 1067 | // APValue stores array extents as unsigned, |
| 1068 | // so anything that is greater that unsigned would overflow when |
| 1069 | // constructing the array, we catch this here. |
| 1070 | if (BitWidth > ConstantArrayType::getMaxSizeBits(Context: Ctx) || |
| 1071 | ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) { |
| 1072 | if (Diag) |
| 1073 | FFDiag(Loc, DiagId: diag::note_constexpr_new_too_large) << ElemCount; |
| 1074 | return false; |
| 1075 | } |
| 1076 | |
| 1077 | // FIXME: GH63562 |
| 1078 | // Arrays allocate an APValue per element. |
| 1079 | // We use the number of constexpr steps as a proxy for the maximum size |
| 1080 | // of arrays to avoid exhausting the system resources, as initialization |
| 1081 | // of each element is likely to take some number of steps anyway. |
| 1082 | uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit; |
| 1083 | if (ElemCount > Limit) { |
| 1084 | if (Diag) |
| 1085 | FFDiag(Loc, DiagId: diag::note_constexpr_new_exceeds_limits) |
| 1086 | << ElemCount << Limit; |
| 1087 | return false; |
| 1088 | } |
| 1089 | return true; |
| 1090 | } |
| 1091 | |
| 1092 | std::pair<CallStackFrame *, unsigned> |
| 1093 | getCallFrameAndDepth(unsigned CallIndex) { |
| 1094 | assert(CallIndex && "no call index in getCallFrameAndDepth" ); |
| 1095 | // We will eventually hit BottomFrame, which has Index 1, so Frame can't |
| 1096 | // be null in this loop. |
| 1097 | unsigned Depth = CallStackDepth; |
| 1098 | CallStackFrame *Frame = CurrentCall; |
| 1099 | while (Frame->Index > CallIndex) { |
| 1100 | Frame = Frame->Caller; |
| 1101 | --Depth; |
| 1102 | } |
| 1103 | if (Frame->Index == CallIndex) |
| 1104 | return {Frame, Depth}; |
| 1105 | return {nullptr, 0}; |
| 1106 | } |
| 1107 | |
| 1108 | bool nextStep(const Stmt *S) { |
| 1109 | if (!StepsLeft) { |
| 1110 | FFDiag(Loc: S->getBeginLoc(), DiagId: diag::note_constexpr_step_limit_exceeded); |
| 1111 | return false; |
| 1112 | } |
| 1113 | --StepsLeft; |
| 1114 | return true; |
| 1115 | } |
| 1116 | |
| 1117 | APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); |
| 1118 | |
| 1119 | std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) { |
| 1120 | std::optional<DynAlloc *> Result; |
| 1121 | auto It = HeapAllocs.find(x: DA); |
| 1122 | if (It != HeapAllocs.end()) |
| 1123 | Result = &It->second; |
| 1124 | return Result; |
| 1125 | } |
| 1126 | |
| 1127 | /// Get the allocated storage for the given parameter of the given call. |
| 1128 | APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { |
| 1129 | CallStackFrame *Frame = getCallFrameAndDepth(CallIndex: Call.CallIndex).first; |
| 1130 | return Frame ? Frame->getTemporary(Key: Call.getOrigParam(PVD), Version: Call.Version) |
| 1131 | : nullptr; |
| 1132 | } |
| 1133 | |
| 1134 | /// Information about a stack frame for std::allocator<T>::[de]allocate. |
| 1135 | struct StdAllocatorCaller { |
| 1136 | unsigned FrameIndex; |
| 1137 | QualType ElemType; |
| 1138 | const Expr *Call; |
| 1139 | explicit operator bool() const { return FrameIndex != 0; }; |
| 1140 | }; |
| 1141 | |
| 1142 | StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { |
| 1143 | for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; |
| 1144 | Call = Call->Caller) { |
| 1145 | const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Call->Callee); |
| 1146 | if (!MD) |
| 1147 | continue; |
| 1148 | const IdentifierInfo *FnII = MD->getIdentifier(); |
| 1149 | if (!FnII || !FnII->isStr(Str: FnName)) |
| 1150 | continue; |
| 1151 | |
| 1152 | const auto *CTSD = |
| 1153 | dyn_cast<ClassTemplateSpecializationDecl>(Val: MD->getParent()); |
| 1154 | if (!CTSD) |
| 1155 | continue; |
| 1156 | |
| 1157 | const IdentifierInfo *ClassII = CTSD->getIdentifier(); |
| 1158 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); |
| 1159 | if (CTSD->isInStdNamespace() && ClassII && |
| 1160 | ClassII->isStr(Str: "allocator" ) && TAL.size() >= 1 && |
| 1161 | TAL[0].getKind() == TemplateArgument::Type) |
| 1162 | return {.FrameIndex: Call->Index, .ElemType: TAL[0].getAsType(), .Call: Call->CallExpr}; |
| 1163 | } |
| 1164 | |
| 1165 | return {}; |
| 1166 | } |
| 1167 | |
| 1168 | void performLifetimeExtension() { |
| 1169 | // Disable the cleanups for lifetime-extended temporaries. |
| 1170 | llvm::erase_if(C&: CleanupStack, P: [](Cleanup &C) { |
| 1171 | return !C.isDestroyedAtEndOf(K: ScopeKind::FullExpression); |
| 1172 | }); |
| 1173 | } |
| 1174 | |
| 1175 | /// Throw away any remaining cleanups at the end of evaluation. If any |
| 1176 | /// cleanups would have had a side-effect, note that as an unmodeled |
| 1177 | /// side-effect and return false. Otherwise, return true. |
| 1178 | bool discardCleanups() { |
| 1179 | for (Cleanup &C : CleanupStack) { |
| 1180 | if (C.hasSideEffect() && !noteSideEffect()) { |
| 1181 | CleanupStack.clear(); |
| 1182 | return false; |
| 1183 | } |
| 1184 | } |
| 1185 | CleanupStack.clear(); |
| 1186 | return true; |
| 1187 | } |
| 1188 | |
| 1189 | private: |
| 1190 | interp::Frame *getCurrentFrame() override { return CurrentCall; } |
| 1191 | const interp::Frame *getBottomFrame() const override { return &BottomFrame; } |
| 1192 | |
| 1193 | bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } |
| 1194 | void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } |
| 1195 | |
| 1196 | void setFoldFailureDiagnostic(bool Flag) override { |
| 1197 | HasFoldFailureDiagnostic = Flag; |
| 1198 | } |
| 1199 | |
| 1200 | Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } |
| 1201 | |
| 1202 | // If we have a prior diagnostic, it will be noting that the expression |
| 1203 | // isn't a constant expression. This diagnostic is more important, |
| 1204 | // unless we require this evaluation to produce a constant expression. |
| 1205 | // |
| 1206 | // FIXME: We might want to show both diagnostics to the user in |
| 1207 | // EM_ConstantFold mode. |
| 1208 | bool hasPriorDiagnostic() override { |
| 1209 | if (!EvalStatus.Diag->empty()) { |
| 1210 | switch (EvalMode) { |
| 1211 | case EM_ConstantFold: |
| 1212 | case EM_IgnoreSideEffects: |
| 1213 | if (!HasFoldFailureDiagnostic) |
| 1214 | break; |
| 1215 | // We've already failed to fold something. Keep that diagnostic. |
| 1216 | [[fallthrough]]; |
| 1217 | case EM_ConstantExpression: |
| 1218 | case EM_ConstantExpressionUnevaluated: |
| 1219 | setActiveDiagnostic(false); |
| 1220 | return true; |
| 1221 | } |
| 1222 | } |
| 1223 | return false; |
| 1224 | } |
| 1225 | |
| 1226 | unsigned getCallStackDepth() override { return CallStackDepth; } |
| 1227 | |
| 1228 | public: |
| 1229 | /// Should we continue evaluation after encountering a side-effect that we |
| 1230 | /// couldn't model? |
| 1231 | bool keepEvaluatingAfterSideEffect() const override { |
| 1232 | switch (EvalMode) { |
| 1233 | case EM_IgnoreSideEffects: |
| 1234 | return true; |
| 1235 | |
| 1236 | case EM_ConstantExpression: |
| 1237 | case EM_ConstantExpressionUnevaluated: |
| 1238 | case EM_ConstantFold: |
| 1239 | // By default, assume any side effect might be valid in some other |
| 1240 | // evaluation of this expression from a different context. |
| 1241 | return checkingPotentialConstantExpression() || |
| 1242 | checkingForUndefinedBehavior(); |
| 1243 | } |
| 1244 | llvm_unreachable("Missed EvalMode case" ); |
| 1245 | } |
| 1246 | |
| 1247 | /// Note that we have had a side-effect, and determine whether we should |
| 1248 | /// keep evaluating. |
| 1249 | bool noteSideEffect() override { |
| 1250 | EvalStatus.HasSideEffects = true; |
| 1251 | return keepEvaluatingAfterSideEffect(); |
| 1252 | } |
| 1253 | |
| 1254 | /// Should we continue evaluation after encountering undefined behavior? |
| 1255 | bool keepEvaluatingAfterUndefinedBehavior() { |
| 1256 | switch (EvalMode) { |
| 1257 | case EM_IgnoreSideEffects: |
| 1258 | case EM_ConstantFold: |
| 1259 | return true; |
| 1260 | |
| 1261 | case EM_ConstantExpression: |
| 1262 | case EM_ConstantExpressionUnevaluated: |
| 1263 | return checkingForUndefinedBehavior(); |
| 1264 | } |
| 1265 | llvm_unreachable("Missed EvalMode case" ); |
| 1266 | } |
| 1267 | |
| 1268 | /// Note that we hit something that was technically undefined behavior, but |
| 1269 | /// that we can evaluate past it (such as signed overflow or floating-point |
| 1270 | /// division by zero.) |
| 1271 | bool noteUndefinedBehavior() override { |
| 1272 | EvalStatus.HasUndefinedBehavior = true; |
| 1273 | return keepEvaluatingAfterUndefinedBehavior(); |
| 1274 | } |
| 1275 | |
| 1276 | /// Should we continue evaluation as much as possible after encountering a |
| 1277 | /// construct which can't be reduced to a value? |
| 1278 | bool keepEvaluatingAfterFailure() const override { |
| 1279 | if (!StepsLeft) |
| 1280 | return false; |
| 1281 | |
| 1282 | switch (EvalMode) { |
| 1283 | case EM_ConstantExpression: |
| 1284 | case EM_ConstantExpressionUnevaluated: |
| 1285 | case EM_ConstantFold: |
| 1286 | case EM_IgnoreSideEffects: |
| 1287 | return checkingPotentialConstantExpression() || |
| 1288 | checkingForUndefinedBehavior(); |
| 1289 | } |
| 1290 | llvm_unreachable("Missed EvalMode case" ); |
| 1291 | } |
| 1292 | |
| 1293 | /// Notes that we failed to evaluate an expression that other expressions |
| 1294 | /// directly depend on, and determine if we should keep evaluating. This |
| 1295 | /// should only be called if we actually intend to keep evaluating. |
| 1296 | /// |
| 1297 | /// Call noteSideEffect() instead if we may be able to ignore the value that |
| 1298 | /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: |
| 1299 | /// |
| 1300 | /// (Foo(), 1) // use noteSideEffect |
| 1301 | /// (Foo() || true) // use noteSideEffect |
| 1302 | /// Foo() + 1 // use noteFailure |
| 1303 | [[nodiscard]] bool noteFailure() { |
| 1304 | // Failure when evaluating some expression often means there is some |
| 1305 | // subexpression whose evaluation was skipped. Therefore, (because we |
| 1306 | // don't track whether we skipped an expression when unwinding after an |
| 1307 | // evaluation failure) every evaluation failure that bubbles up from a |
| 1308 | // subexpression implies that a side-effect has potentially happened. We |
| 1309 | // skip setting the HasSideEffects flag to true until we decide to |
| 1310 | // continue evaluating after that point, which happens here. |
| 1311 | bool KeepGoing = keepEvaluatingAfterFailure(); |
| 1312 | EvalStatus.HasSideEffects |= KeepGoing; |
| 1313 | return KeepGoing; |
| 1314 | } |
| 1315 | |
| 1316 | class ArrayInitLoopIndex { |
| 1317 | EvalInfo &Info; |
| 1318 | uint64_t OuterIndex; |
| 1319 | |
| 1320 | public: |
| 1321 | ArrayInitLoopIndex(EvalInfo &Info) |
| 1322 | : Info(Info), OuterIndex(Info.ArrayInitIndex) { |
| 1323 | Info.ArrayInitIndex = 0; |
| 1324 | } |
| 1325 | ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } |
| 1326 | |
| 1327 | operator uint64_t&() { return Info.ArrayInitIndex; } |
| 1328 | }; |
| 1329 | }; |
| 1330 | |
| 1331 | /// Object used to treat all foldable expressions as constant expressions. |
| 1332 | struct FoldConstant { |
| 1333 | EvalInfo &Info; |
| 1334 | bool Enabled; |
| 1335 | bool HadNoPriorDiags; |
| 1336 | EvalInfo::EvaluationMode OldMode; |
| 1337 | |
| 1338 | explicit FoldConstant(EvalInfo &Info, bool Enabled) |
| 1339 | : Info(Info), |
| 1340 | Enabled(Enabled), |
| 1341 | HadNoPriorDiags(Info.EvalStatus.Diag && |
| 1342 | Info.EvalStatus.Diag->empty() && |
| 1343 | !Info.EvalStatus.HasSideEffects), |
| 1344 | OldMode(Info.EvalMode) { |
| 1345 | if (Enabled) |
| 1346 | Info.EvalMode = EvalInfo::EM_ConstantFold; |
| 1347 | } |
| 1348 | void keepDiagnostics() { Enabled = false; } |
| 1349 | ~FoldConstant() { |
| 1350 | if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && |
| 1351 | !Info.EvalStatus.HasSideEffects) |
| 1352 | Info.EvalStatus.Diag->clear(); |
| 1353 | Info.EvalMode = OldMode; |
| 1354 | } |
| 1355 | }; |
| 1356 | |
| 1357 | /// RAII object used to set the current evaluation mode to ignore |
| 1358 | /// side-effects. |
| 1359 | struct IgnoreSideEffectsRAII { |
| 1360 | EvalInfo &Info; |
| 1361 | EvalInfo::EvaluationMode OldMode; |
| 1362 | explicit IgnoreSideEffectsRAII(EvalInfo &Info) |
| 1363 | : Info(Info), OldMode(Info.EvalMode) { |
| 1364 | Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; |
| 1365 | } |
| 1366 | |
| 1367 | ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } |
| 1368 | }; |
| 1369 | |
| 1370 | /// RAII object used to optionally suppress diagnostics and side-effects from |
| 1371 | /// a speculative evaluation. |
| 1372 | class SpeculativeEvaluationRAII { |
| 1373 | EvalInfo *Info = nullptr; |
| 1374 | Expr::EvalStatus OldStatus; |
| 1375 | unsigned OldSpeculativeEvaluationDepth = 0; |
| 1376 | |
| 1377 | void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { |
| 1378 | Info = Other.Info; |
| 1379 | OldStatus = Other.OldStatus; |
| 1380 | OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; |
| 1381 | Other.Info = nullptr; |
| 1382 | } |
| 1383 | |
| 1384 | void maybeRestoreState() { |
| 1385 | if (!Info) |
| 1386 | return; |
| 1387 | |
| 1388 | Info->EvalStatus = OldStatus; |
| 1389 | Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; |
| 1390 | } |
| 1391 | |
| 1392 | public: |
| 1393 | SpeculativeEvaluationRAII() = default; |
| 1394 | |
| 1395 | SpeculativeEvaluationRAII( |
| 1396 | EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) |
| 1397 | : Info(&Info), OldStatus(Info.EvalStatus), |
| 1398 | OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { |
| 1399 | Info.EvalStatus.Diag = NewDiag; |
| 1400 | Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; |
| 1401 | } |
| 1402 | |
| 1403 | SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; |
| 1404 | SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { |
| 1405 | moveFromAndCancel(Other: std::move(Other)); |
| 1406 | } |
| 1407 | |
| 1408 | SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { |
| 1409 | maybeRestoreState(); |
| 1410 | moveFromAndCancel(Other: std::move(Other)); |
| 1411 | return *this; |
| 1412 | } |
| 1413 | |
| 1414 | ~SpeculativeEvaluationRAII() { maybeRestoreState(); } |
| 1415 | }; |
| 1416 | |
| 1417 | /// RAII object wrapping a full-expression or block scope, and handling |
| 1418 | /// the ending of the lifetime of temporaries created within it. |
| 1419 | template<ScopeKind Kind> |
| 1420 | class ScopeRAII { |
| 1421 | EvalInfo &Info; |
| 1422 | unsigned OldStackSize; |
| 1423 | public: |
| 1424 | ScopeRAII(EvalInfo &Info) |
| 1425 | : Info(Info), OldStackSize(Info.CleanupStack.size()) { |
| 1426 | // Push a new temporary version. This is needed to distinguish between |
| 1427 | // temporaries created in different iterations of a loop. |
| 1428 | Info.CurrentCall->pushTempVersion(); |
| 1429 | } |
| 1430 | bool destroy(bool RunDestructors = true) { |
| 1431 | bool OK = cleanup(Info, RunDestructors, OldStackSize); |
| 1432 | OldStackSize = -1U; |
| 1433 | return OK; |
| 1434 | } |
| 1435 | ~ScopeRAII() { |
| 1436 | if (OldStackSize != -1U) |
| 1437 | destroy(RunDestructors: false); |
| 1438 | // Body moved to a static method to encourage the compiler to inline away |
| 1439 | // instances of this class. |
| 1440 | Info.CurrentCall->popTempVersion(); |
| 1441 | } |
| 1442 | private: |
| 1443 | static bool cleanup(EvalInfo &Info, bool RunDestructors, |
| 1444 | unsigned OldStackSize) { |
| 1445 | assert(OldStackSize <= Info.CleanupStack.size() && |
| 1446 | "running cleanups out of order?" ); |
| 1447 | |
| 1448 | // Run all cleanups for a block scope, and non-lifetime-extended cleanups |
| 1449 | // for a full-expression scope. |
| 1450 | bool Success = true; |
| 1451 | for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { |
| 1452 | if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(K: Kind)) { |
| 1453 | if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { |
| 1454 | Success = false; |
| 1455 | break; |
| 1456 | } |
| 1457 | } |
| 1458 | } |
| 1459 | |
| 1460 | // Compact any retained cleanups. |
| 1461 | auto NewEnd = Info.CleanupStack.begin() + OldStackSize; |
| 1462 | if (Kind != ScopeKind::Block) |
| 1463 | NewEnd = |
| 1464 | std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { |
| 1465 | return C.isDestroyedAtEndOf(K: Kind); |
| 1466 | }); |
| 1467 | Info.CleanupStack.erase(CS: NewEnd, CE: Info.CleanupStack.end()); |
| 1468 | return Success; |
| 1469 | } |
| 1470 | }; |
| 1471 | typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; |
| 1472 | typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; |
| 1473 | typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; |
| 1474 | } |
| 1475 | |
| 1476 | bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, |
| 1477 | CheckSubobjectKind CSK) { |
| 1478 | if (Invalid) |
| 1479 | return false; |
| 1480 | if (isOnePastTheEnd()) { |
| 1481 | Info.CCEDiag(E, DiagId: diag::note_constexpr_past_end_subobject) |
| 1482 | << CSK; |
| 1483 | setInvalid(); |
| 1484 | return false; |
| 1485 | } |
| 1486 | // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there |
| 1487 | // must actually be at least one array element; even a VLA cannot have a |
| 1488 | // bound of zero. And if our index is nonzero, we already had a CCEDiag. |
| 1489 | return true; |
| 1490 | } |
| 1491 | |
| 1492 | void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, |
| 1493 | const Expr *E) { |
| 1494 | Info.CCEDiag(E, DiagId: diag::note_constexpr_unsized_array_indexed); |
| 1495 | // Do not set the designator as invalid: we can represent this situation, |
| 1496 | // and correct handling of __builtin_object_size requires us to do so. |
| 1497 | } |
| 1498 | |
| 1499 | void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, |
| 1500 | const Expr *E, |
| 1501 | const APSInt &N) { |
| 1502 | // If we're complaining, we must be able to statically determine the size of |
| 1503 | // the most derived array. |
| 1504 | if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) |
| 1505 | Info.CCEDiag(E, DiagId: diag::note_constexpr_array_index) |
| 1506 | << N << /*array*/ 0 |
| 1507 | << static_cast<unsigned>(getMostDerivedArraySize()); |
| 1508 | else |
| 1509 | Info.CCEDiag(E, DiagId: diag::note_constexpr_array_index) |
| 1510 | << N << /*non-array*/ 1; |
| 1511 | setInvalid(); |
| 1512 | } |
| 1513 | |
| 1514 | CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange, |
| 1515 | const FunctionDecl *Callee, const LValue *This, |
| 1516 | const Expr *CallExpr, CallRef Call) |
| 1517 | : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), |
| 1518 | CallExpr(CallExpr), Arguments(Call), CallRange(CallRange), |
| 1519 | Index(Info.NextCallIndex++) { |
| 1520 | Info.CurrentCall = this; |
| 1521 | ++Info.CallStackDepth; |
| 1522 | } |
| 1523 | |
| 1524 | CallStackFrame::~CallStackFrame() { |
| 1525 | assert(Info.CurrentCall == this && "calls retired out of order" ); |
| 1526 | --Info.CallStackDepth; |
| 1527 | Info.CurrentCall = Caller; |
| 1528 | } |
| 1529 | |
| 1530 | static bool isRead(AccessKinds AK) { |
| 1531 | return AK == AK_Read || AK == AK_ReadObjectRepresentation || |
| 1532 | AK == AK_IsWithinLifetime; |
| 1533 | } |
| 1534 | |
| 1535 | static bool isModification(AccessKinds AK) { |
| 1536 | switch (AK) { |
| 1537 | case AK_Read: |
| 1538 | case AK_ReadObjectRepresentation: |
| 1539 | case AK_MemberCall: |
| 1540 | case AK_DynamicCast: |
| 1541 | case AK_TypeId: |
| 1542 | case AK_IsWithinLifetime: |
| 1543 | return false; |
| 1544 | case AK_Assign: |
| 1545 | case AK_Increment: |
| 1546 | case AK_Decrement: |
| 1547 | case AK_Construct: |
| 1548 | case AK_Destroy: |
| 1549 | return true; |
| 1550 | } |
| 1551 | llvm_unreachable("unknown access kind" ); |
| 1552 | } |
| 1553 | |
| 1554 | static bool isAnyAccess(AccessKinds AK) { |
| 1555 | return isRead(AK) || isModification(AK); |
| 1556 | } |
| 1557 | |
| 1558 | /// Is this an access per the C++ definition? |
| 1559 | static bool isFormalAccess(AccessKinds AK) { |
| 1560 | return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy && |
| 1561 | AK != AK_IsWithinLifetime; |
| 1562 | } |
| 1563 | |
| 1564 | /// Is this kind of axcess valid on an indeterminate object value? |
| 1565 | static bool isValidIndeterminateAccess(AccessKinds AK) { |
| 1566 | switch (AK) { |
| 1567 | case AK_Read: |
| 1568 | case AK_Increment: |
| 1569 | case AK_Decrement: |
| 1570 | // These need the object's value. |
| 1571 | return false; |
| 1572 | |
| 1573 | case AK_IsWithinLifetime: |
| 1574 | case AK_ReadObjectRepresentation: |
| 1575 | case AK_Assign: |
| 1576 | case AK_Construct: |
| 1577 | case AK_Destroy: |
| 1578 | // Construction and destruction don't need the value. |
| 1579 | return true; |
| 1580 | |
| 1581 | case AK_MemberCall: |
| 1582 | case AK_DynamicCast: |
| 1583 | case AK_TypeId: |
| 1584 | // These aren't really meaningful on scalars. |
| 1585 | return true; |
| 1586 | } |
| 1587 | llvm_unreachable("unknown access kind" ); |
| 1588 | } |
| 1589 | |
| 1590 | namespace { |
| 1591 | struct ComplexValue { |
| 1592 | private: |
| 1593 | bool IsInt; |
| 1594 | |
| 1595 | public: |
| 1596 | APSInt IntReal, IntImag; |
| 1597 | APFloat FloatReal, FloatImag; |
| 1598 | |
| 1599 | ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} |
| 1600 | |
| 1601 | void makeComplexFloat() { IsInt = false; } |
| 1602 | bool isComplexFloat() const { return !IsInt; } |
| 1603 | APFloat &getComplexFloatReal() { return FloatReal; } |
| 1604 | APFloat &getComplexFloatImag() { return FloatImag; } |
| 1605 | |
| 1606 | void makeComplexInt() { IsInt = true; } |
| 1607 | bool isComplexInt() const { return IsInt; } |
| 1608 | APSInt &getComplexIntReal() { return IntReal; } |
| 1609 | APSInt &getComplexIntImag() { return IntImag; } |
| 1610 | |
| 1611 | void moveInto(APValue &v) const { |
| 1612 | if (isComplexFloat()) |
| 1613 | v = APValue(FloatReal, FloatImag); |
| 1614 | else |
| 1615 | v = APValue(IntReal, IntImag); |
| 1616 | } |
| 1617 | void setFrom(const APValue &v) { |
| 1618 | assert(v.isComplexFloat() || v.isComplexInt()); |
| 1619 | if (v.isComplexFloat()) { |
| 1620 | makeComplexFloat(); |
| 1621 | FloatReal = v.getComplexFloatReal(); |
| 1622 | FloatImag = v.getComplexFloatImag(); |
| 1623 | } else { |
| 1624 | makeComplexInt(); |
| 1625 | IntReal = v.getComplexIntReal(); |
| 1626 | IntImag = v.getComplexIntImag(); |
| 1627 | } |
| 1628 | } |
| 1629 | }; |
| 1630 | |
| 1631 | struct LValue { |
| 1632 | APValue::LValueBase Base; |
| 1633 | CharUnits Offset; |
| 1634 | SubobjectDesignator Designator; |
| 1635 | bool IsNullPtr : 1; |
| 1636 | bool InvalidBase : 1; |
| 1637 | // P2280R4 track if we have an unknown reference or pointer. |
| 1638 | bool AllowConstexprUnknown = false; |
| 1639 | |
| 1640 | const APValue::LValueBase getLValueBase() const { return Base; } |
| 1641 | bool allowConstexprUnknown() const { return AllowConstexprUnknown; } |
| 1642 | CharUnits &getLValueOffset() { return Offset; } |
| 1643 | const CharUnits &getLValueOffset() const { return Offset; } |
| 1644 | SubobjectDesignator &getLValueDesignator() { return Designator; } |
| 1645 | const SubobjectDesignator &getLValueDesignator() const { return Designator;} |
| 1646 | bool isNullPointer() const { return IsNullPtr;} |
| 1647 | |
| 1648 | unsigned getLValueCallIndex() const { return Base.getCallIndex(); } |
| 1649 | unsigned getLValueVersion() const { return Base.getVersion(); } |
| 1650 | |
| 1651 | void moveInto(APValue &V) const { |
| 1652 | if (Designator.Invalid) |
| 1653 | V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); |
| 1654 | else { |
| 1655 | assert(!InvalidBase && "APValues can't handle invalid LValue bases" ); |
| 1656 | V = APValue(Base, Offset, Designator.Entries, |
| 1657 | Designator.IsOnePastTheEnd, IsNullPtr); |
| 1658 | } |
| 1659 | if (AllowConstexprUnknown) |
| 1660 | V.setConstexprUnknown(); |
| 1661 | } |
| 1662 | void setFrom(ASTContext &Ctx, const APValue &V) { |
| 1663 | assert(V.isLValue() && "Setting LValue from a non-LValue?" ); |
| 1664 | Base = V.getLValueBase(); |
| 1665 | Offset = V.getLValueOffset(); |
| 1666 | InvalidBase = false; |
| 1667 | Designator = SubobjectDesignator(Ctx, V); |
| 1668 | IsNullPtr = V.isNullPointer(); |
| 1669 | AllowConstexprUnknown = V.allowConstexprUnknown(); |
| 1670 | } |
| 1671 | |
| 1672 | void set(APValue::LValueBase B, bool BInvalid = false) { |
| 1673 | #ifndef NDEBUG |
| 1674 | // We only allow a few types of invalid bases. Enforce that here. |
| 1675 | if (BInvalid) { |
| 1676 | const auto *E = B.get<const Expr *>(); |
| 1677 | assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && |
| 1678 | "Unexpected type of invalid base" ); |
| 1679 | } |
| 1680 | #endif |
| 1681 | |
| 1682 | Base = B; |
| 1683 | Offset = CharUnits::fromQuantity(Quantity: 0); |
| 1684 | InvalidBase = BInvalid; |
| 1685 | Designator = SubobjectDesignator(getType(B)); |
| 1686 | IsNullPtr = false; |
| 1687 | AllowConstexprUnknown = false; |
| 1688 | } |
| 1689 | |
| 1690 | void setNull(ASTContext &Ctx, QualType PointerTy) { |
| 1691 | Base = (const ValueDecl *)nullptr; |
| 1692 | Offset = |
| 1693 | CharUnits::fromQuantity(Quantity: Ctx.getTargetNullPointerValue(QT: PointerTy)); |
| 1694 | InvalidBase = false; |
| 1695 | Designator = SubobjectDesignator(PointerTy->getPointeeType()); |
| 1696 | IsNullPtr = true; |
| 1697 | AllowConstexprUnknown = false; |
| 1698 | } |
| 1699 | |
| 1700 | void setInvalid(APValue::LValueBase B, unsigned I = 0) { |
| 1701 | set(B, BInvalid: true); |
| 1702 | } |
| 1703 | |
| 1704 | std::string toString(ASTContext &Ctx, QualType T) const { |
| 1705 | APValue Printable; |
| 1706 | moveInto(V&: Printable); |
| 1707 | return Printable.getAsString(Ctx, Ty: T); |
| 1708 | } |
| 1709 | |
| 1710 | private: |
| 1711 | // Check that this LValue is not based on a null pointer. If it is, produce |
| 1712 | // a diagnostic and mark the designator as invalid. |
| 1713 | template <typename GenDiagType> |
| 1714 | bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { |
| 1715 | if (Designator.Invalid) |
| 1716 | return false; |
| 1717 | if (IsNullPtr) { |
| 1718 | GenDiag(); |
| 1719 | Designator.setInvalid(); |
| 1720 | return false; |
| 1721 | } |
| 1722 | return true; |
| 1723 | } |
| 1724 | |
| 1725 | public: |
| 1726 | bool checkNullPointer(EvalInfo &Info, const Expr *E, |
| 1727 | CheckSubobjectKind CSK) { |
| 1728 | return checkNullPointerDiagnosingWith(GenDiag: [&Info, E, CSK] { |
| 1729 | Info.CCEDiag(E, DiagId: diag::note_constexpr_null_subobject) << CSK; |
| 1730 | }); |
| 1731 | } |
| 1732 | |
| 1733 | bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, |
| 1734 | AccessKinds AK) { |
| 1735 | return checkNullPointerDiagnosingWith(GenDiag: [&Info, E, AK] { |
| 1736 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_null) << AK; |
| 1737 | }); |
| 1738 | } |
| 1739 | |
| 1740 | // Check this LValue refers to an object. If not, set the designator to be |
| 1741 | // invalid and emit a diagnostic. |
| 1742 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { |
| 1743 | return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && |
| 1744 | Designator.checkSubobject(Info, E, CSK); |
| 1745 | } |
| 1746 | |
| 1747 | void addDecl(EvalInfo &Info, const Expr *E, |
| 1748 | const Decl *D, bool Virtual = false) { |
| 1749 | if (checkSubobject(Info, E, CSK: isa<FieldDecl>(Val: D) ? CSK_Field : CSK_Base)) |
| 1750 | Designator.addDeclUnchecked(D, Virtual); |
| 1751 | } |
| 1752 | void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { |
| 1753 | if (!Designator.Entries.empty()) { |
| 1754 | Info.CCEDiag(E, DiagId: diag::note_constexpr_unsupported_unsized_array); |
| 1755 | Designator.setInvalid(); |
| 1756 | return; |
| 1757 | } |
| 1758 | if (checkSubobject(Info, E, CSK: CSK_ArrayToPointer)) { |
| 1759 | assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); |
| 1760 | Designator.FirstEntryIsAnUnsizedArray = true; |
| 1761 | Designator.addUnsizedArrayUnchecked(ElemTy); |
| 1762 | } |
| 1763 | } |
| 1764 | void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { |
| 1765 | if (checkSubobject(Info, E, CSK: CSK_ArrayToPointer)) |
| 1766 | Designator.addArrayUnchecked(CAT); |
| 1767 | } |
| 1768 | void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { |
| 1769 | if (checkSubobject(Info, E, CSK: Imag ? CSK_Imag : CSK_Real)) |
| 1770 | Designator.addComplexUnchecked(EltTy, Imag); |
| 1771 | } |
| 1772 | void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy, |
| 1773 | uint64_t Size, uint64_t Idx) { |
| 1774 | if (checkSubobject(Info, E, CSK: CSK_VectorElement)) |
| 1775 | Designator.addVectorElementUnchecked(EltTy, Size, Idx); |
| 1776 | } |
| 1777 | void clearIsNullPointer() { |
| 1778 | IsNullPtr = false; |
| 1779 | } |
| 1780 | void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, |
| 1781 | const APSInt &Index, CharUnits ElementSize) { |
| 1782 | // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, |
| 1783 | // but we're not required to diagnose it and it's valid in C++.) |
| 1784 | if (!Index) |
| 1785 | return; |
| 1786 | |
| 1787 | // Compute the new offset in the appropriate width, wrapping at 64 bits. |
| 1788 | // FIXME: When compiling for a 32-bit target, we should use 32-bit |
| 1789 | // offsets. |
| 1790 | uint64_t Offset64 = Offset.getQuantity(); |
| 1791 | uint64_t ElemSize64 = ElementSize.getQuantity(); |
| 1792 | uint64_t Index64 = Index.extOrTrunc(width: 64).getZExtValue(); |
| 1793 | Offset = CharUnits::fromQuantity(Quantity: Offset64 + ElemSize64 * Index64); |
| 1794 | |
| 1795 | if (checkNullPointer(Info, E, CSK: CSK_ArrayIndex)) |
| 1796 | Designator.adjustIndex(Info, E, N: Index); |
| 1797 | clearIsNullPointer(); |
| 1798 | } |
| 1799 | void adjustOffset(CharUnits N) { |
| 1800 | Offset += N; |
| 1801 | if (N.getQuantity()) |
| 1802 | clearIsNullPointer(); |
| 1803 | } |
| 1804 | }; |
| 1805 | |
| 1806 | struct MemberPtr { |
| 1807 | MemberPtr() {} |
| 1808 | explicit MemberPtr(const ValueDecl *Decl) |
| 1809 | : DeclAndIsDerivedMember(Decl, false) {} |
| 1810 | |
| 1811 | /// The member or (direct or indirect) field referred to by this member |
| 1812 | /// pointer, or 0 if this is a null member pointer. |
| 1813 | const ValueDecl *getDecl() const { |
| 1814 | return DeclAndIsDerivedMember.getPointer(); |
| 1815 | } |
| 1816 | /// Is this actually a member of some type derived from the relevant class? |
| 1817 | bool isDerivedMember() const { |
| 1818 | return DeclAndIsDerivedMember.getInt(); |
| 1819 | } |
| 1820 | /// Get the class which the declaration actually lives in. |
| 1821 | const CXXRecordDecl *getContainingRecord() const { |
| 1822 | return cast<CXXRecordDecl>( |
| 1823 | Val: DeclAndIsDerivedMember.getPointer()->getDeclContext()); |
| 1824 | } |
| 1825 | |
| 1826 | void moveInto(APValue &V) const { |
| 1827 | V = APValue(getDecl(), isDerivedMember(), Path); |
| 1828 | } |
| 1829 | void setFrom(const APValue &V) { |
| 1830 | assert(V.isMemberPointer()); |
| 1831 | DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); |
| 1832 | DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); |
| 1833 | Path.clear(); |
| 1834 | llvm::append_range(C&: Path, R: V.getMemberPointerPath()); |
| 1835 | } |
| 1836 | |
| 1837 | /// DeclAndIsDerivedMember - The member declaration, and a flag indicating |
| 1838 | /// whether the member is a member of some class derived from the class type |
| 1839 | /// of the member pointer. |
| 1840 | llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; |
| 1841 | /// Path - The path of base/derived classes from the member declaration's |
| 1842 | /// class (exclusive) to the class type of the member pointer (inclusive). |
| 1843 | SmallVector<const CXXRecordDecl*, 4> Path; |
| 1844 | |
| 1845 | /// Perform a cast towards the class of the Decl (either up or down the |
| 1846 | /// hierarchy). |
| 1847 | bool castBack(const CXXRecordDecl *Class) { |
| 1848 | assert(!Path.empty()); |
| 1849 | const CXXRecordDecl *Expected; |
| 1850 | if (Path.size() >= 2) |
| 1851 | Expected = Path[Path.size() - 2]; |
| 1852 | else |
| 1853 | Expected = getContainingRecord(); |
| 1854 | if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { |
| 1855 | // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), |
| 1856 | // if B does not contain the original member and is not a base or |
| 1857 | // derived class of the class containing the original member, the result |
| 1858 | // of the cast is undefined. |
| 1859 | // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to |
| 1860 | // (D::*). We consider that to be a language defect. |
| 1861 | return false; |
| 1862 | } |
| 1863 | Path.pop_back(); |
| 1864 | return true; |
| 1865 | } |
| 1866 | /// Perform a base-to-derived member pointer cast. |
| 1867 | bool castToDerived(const CXXRecordDecl *Derived) { |
| 1868 | if (!getDecl()) |
| 1869 | return true; |
| 1870 | if (!isDerivedMember()) { |
| 1871 | Path.push_back(Elt: Derived); |
| 1872 | return true; |
| 1873 | } |
| 1874 | if (!castBack(Class: Derived)) |
| 1875 | return false; |
| 1876 | if (Path.empty()) |
| 1877 | DeclAndIsDerivedMember.setInt(false); |
| 1878 | return true; |
| 1879 | } |
| 1880 | /// Perform a derived-to-base member pointer cast. |
| 1881 | bool castToBase(const CXXRecordDecl *Base) { |
| 1882 | if (!getDecl()) |
| 1883 | return true; |
| 1884 | if (Path.empty()) |
| 1885 | DeclAndIsDerivedMember.setInt(true); |
| 1886 | if (isDerivedMember()) { |
| 1887 | Path.push_back(Elt: Base); |
| 1888 | return true; |
| 1889 | } |
| 1890 | return castBack(Class: Base); |
| 1891 | } |
| 1892 | }; |
| 1893 | |
| 1894 | /// Compare two member pointers, which are assumed to be of the same type. |
| 1895 | static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { |
| 1896 | if (!LHS.getDecl() || !RHS.getDecl()) |
| 1897 | return !LHS.getDecl() && !RHS.getDecl(); |
| 1898 | if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) |
| 1899 | return false; |
| 1900 | return LHS.Path == RHS.Path; |
| 1901 | } |
| 1902 | } |
| 1903 | |
| 1904 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); |
| 1905 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, |
| 1906 | const LValue &This, const Expr *E, |
| 1907 | bool AllowNonLiteralTypes = false); |
| 1908 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, |
| 1909 | bool InvalidBaseOK = false); |
| 1910 | static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, |
| 1911 | bool InvalidBaseOK = false); |
| 1912 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, |
| 1913 | EvalInfo &Info); |
| 1914 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); |
| 1915 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); |
| 1916 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, |
| 1917 | EvalInfo &Info); |
| 1918 | static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); |
| 1919 | static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); |
| 1920 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, |
| 1921 | EvalInfo &Info); |
| 1922 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); |
| 1923 | static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, |
| 1924 | EvalInfo &Info, |
| 1925 | std::string *StringResult = nullptr); |
| 1926 | |
| 1927 | /// Evaluate an integer or fixed point expression into an APResult. |
| 1928 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, |
| 1929 | EvalInfo &Info); |
| 1930 | |
| 1931 | /// Evaluate only a fixed point expression into an APResult. |
| 1932 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, |
| 1933 | EvalInfo &Info); |
| 1934 | |
| 1935 | //===----------------------------------------------------------------------===// |
| 1936 | // Misc utilities |
| 1937 | //===----------------------------------------------------------------------===// |
| 1938 | |
| 1939 | /// Negate an APSInt in place, converting it to a signed form if necessary, and |
| 1940 | /// preserving its value (by extending by up to one bit as needed). |
| 1941 | static void negateAsSigned(APSInt &Int) { |
| 1942 | if (Int.isUnsigned() || Int.isMinSignedValue()) { |
| 1943 | Int = Int.extend(width: Int.getBitWidth() + 1); |
| 1944 | Int.setIsSigned(true); |
| 1945 | } |
| 1946 | Int = -Int; |
| 1947 | } |
| 1948 | |
| 1949 | template<typename KeyT> |
| 1950 | APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, |
| 1951 | ScopeKind Scope, LValue &LV) { |
| 1952 | unsigned Version = getTempVersion(); |
| 1953 | APValue::LValueBase Base(Key, Index, Version); |
| 1954 | LV.set(B: Base); |
| 1955 | return createLocal(Base, Key, T, Scope); |
| 1956 | } |
| 1957 | |
| 1958 | APValue & |
| 1959 | CallStackFrame::createConstexprUnknownAPValues(const VarDecl *Key, |
| 1960 | APValue::LValueBase Base) { |
| 1961 | APValue &Result = ConstexprUnknownAPValues[MapKeyTy(Key, Base.getVersion())]; |
| 1962 | Result = APValue(Base, CharUnits::Zero(), APValue::ConstexprUnknown{}); |
| 1963 | |
| 1964 | return Result; |
| 1965 | } |
| 1966 | |
| 1967 | /// Allocate storage for a parameter of a function call made in this frame. |
| 1968 | APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, |
| 1969 | LValue &LV) { |
| 1970 | assert(Args.CallIndex == Index && "creating parameter in wrong frame" ); |
| 1971 | APValue::LValueBase Base(PVD, Index, Args.Version); |
| 1972 | LV.set(B: Base); |
| 1973 | // We always destroy parameters at the end of the call, even if we'd allow |
| 1974 | // them to live to the end of the full-expression at runtime, in order to |
| 1975 | // give portable results and match other compilers. |
| 1976 | return createLocal(Base, Key: PVD, T: PVD->getType(), Scope: ScopeKind::Call); |
| 1977 | } |
| 1978 | |
| 1979 | APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, |
| 1980 | QualType T, ScopeKind Scope) { |
| 1981 | assert(Base.getCallIndex() == Index && "lvalue for wrong frame" ); |
| 1982 | unsigned Version = Base.getVersion(); |
| 1983 | APValue &Result = Temporaries[MapKeyTy(Key, Version)]; |
| 1984 | assert(Result.isAbsent() && "local created multiple times" ); |
| 1985 | |
| 1986 | // If we're creating a local immediately in the operand of a speculative |
| 1987 | // evaluation, don't register a cleanup to be run outside the speculative |
| 1988 | // evaluation context, since we won't actually be able to initialize this |
| 1989 | // object. |
| 1990 | if (Index <= Info.SpeculativeEvaluationDepth) { |
| 1991 | if (T.isDestructedType()) |
| 1992 | Info.noteSideEffect(); |
| 1993 | } else { |
| 1994 | Info.CleanupStack.push_back(Elt: Cleanup(&Result, Base, T, Scope)); |
| 1995 | } |
| 1996 | return Result; |
| 1997 | } |
| 1998 | |
| 1999 | APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { |
| 2000 | if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { |
| 2001 | FFDiag(E, DiagId: diag::note_constexpr_heap_alloc_limit_exceeded); |
| 2002 | return nullptr; |
| 2003 | } |
| 2004 | |
| 2005 | DynamicAllocLValue DA(NumHeapAllocs++); |
| 2006 | LV.set(B: APValue::LValueBase::getDynamicAlloc(LV: DA, Type: T)); |
| 2007 | auto Result = HeapAllocs.emplace(args: std::piecewise_construct, |
| 2008 | args: std::forward_as_tuple(args&: DA), args: std::tuple<>()); |
| 2009 | assert(Result.second && "reused a heap alloc index?" ); |
| 2010 | Result.first->second.AllocExpr = E; |
| 2011 | return &Result.first->second.Value; |
| 2012 | } |
| 2013 | |
| 2014 | /// Produce a string describing the given constexpr call. |
| 2015 | void CallStackFrame::describe(raw_ostream &Out) const { |
| 2016 | unsigned ArgIndex = 0; |
| 2017 | bool IsMemberCall = |
| 2018 | isa<CXXMethodDecl>(Val: Callee) && !isa<CXXConstructorDecl>(Val: Callee) && |
| 2019 | cast<CXXMethodDecl>(Val: Callee)->isImplicitObjectMemberFunction(); |
| 2020 | |
| 2021 | if (!IsMemberCall) |
| 2022 | Callee->getNameForDiagnostic(OS&: Out, Policy: Info.Ctx.getPrintingPolicy(), |
| 2023 | /*Qualified=*/false); |
| 2024 | |
| 2025 | if (This && IsMemberCall) { |
| 2026 | if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(Val: CallExpr)) { |
| 2027 | const Expr *Object = MCE->getImplicitObjectArgument(); |
| 2028 | Object->printPretty(OS&: Out, /*Helper=*/nullptr, Policy: Info.Ctx.getPrintingPolicy(), |
| 2029 | /*Indentation=*/0); |
| 2030 | if (Object->getType()->isPointerType()) |
| 2031 | Out << "->" ; |
| 2032 | else |
| 2033 | Out << "." ; |
| 2034 | } else if (const auto *OCE = |
| 2035 | dyn_cast_if_present<CXXOperatorCallExpr>(Val: CallExpr)) { |
| 2036 | OCE->getArg(Arg: 0)->printPretty(OS&: Out, /*Helper=*/nullptr, |
| 2037 | Policy: Info.Ctx.getPrintingPolicy(), |
| 2038 | /*Indentation=*/0); |
| 2039 | Out << "." ; |
| 2040 | } else { |
| 2041 | APValue Val; |
| 2042 | This->moveInto(V&: Val); |
| 2043 | Val.printPretty( |
| 2044 | OS&: Out, Ctx: Info.Ctx, |
| 2045 | Ty: Info.Ctx.getLValueReferenceType(T: This->Designator.MostDerivedType)); |
| 2046 | Out << "." ; |
| 2047 | } |
| 2048 | Callee->getNameForDiagnostic(OS&: Out, Policy: Info.Ctx.getPrintingPolicy(), |
| 2049 | /*Qualified=*/false); |
| 2050 | IsMemberCall = false; |
| 2051 | } |
| 2052 | |
| 2053 | Out << '('; |
| 2054 | |
| 2055 | for (FunctionDecl::param_const_iterator I = Callee->param_begin(), |
| 2056 | E = Callee->param_end(); I != E; ++I, ++ArgIndex) { |
| 2057 | if (ArgIndex > (unsigned)IsMemberCall) |
| 2058 | Out << ", " ; |
| 2059 | |
| 2060 | const ParmVarDecl *Param = *I; |
| 2061 | APValue *V = Info.getParamSlot(Call: Arguments, PVD: Param); |
| 2062 | if (V) |
| 2063 | V->printPretty(OS&: Out, Ctx: Info.Ctx, Ty: Param->getType()); |
| 2064 | else |
| 2065 | Out << "<...>" ; |
| 2066 | |
| 2067 | if (ArgIndex == 0 && IsMemberCall) |
| 2068 | Out << "->" << *Callee << '('; |
| 2069 | } |
| 2070 | |
| 2071 | Out << ')'; |
| 2072 | } |
| 2073 | |
| 2074 | /// Evaluate an expression to see if it had side-effects, and discard its |
| 2075 | /// result. |
| 2076 | /// \return \c true if the caller should keep evaluating. |
| 2077 | static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { |
| 2078 | assert(!E->isValueDependent()); |
| 2079 | APValue Scratch; |
| 2080 | if (!Evaluate(Result&: Scratch, Info, E)) |
| 2081 | // We don't need the value, but we might have skipped a side effect here. |
| 2082 | return Info.noteSideEffect(); |
| 2083 | return true; |
| 2084 | } |
| 2085 | |
| 2086 | /// Should this call expression be treated as forming an opaque constant? |
| 2087 | static bool IsOpaqueConstantCall(const CallExpr *E) { |
| 2088 | unsigned Builtin = E->getBuiltinCallee(); |
| 2089 | return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || |
| 2090 | Builtin == Builtin::BI__builtin___NSStringMakeConstantString || |
| 2091 | Builtin == Builtin::BI__builtin_ptrauth_sign_constant || |
| 2092 | Builtin == Builtin::BI__builtin_function_start); |
| 2093 | } |
| 2094 | |
| 2095 | static bool IsOpaqueConstantCall(const LValue &LVal) { |
| 2096 | const auto *BaseExpr = |
| 2097 | llvm::dyn_cast_if_present<CallExpr>(Val: LVal.Base.dyn_cast<const Expr *>()); |
| 2098 | return BaseExpr && IsOpaqueConstantCall(E: BaseExpr); |
| 2099 | } |
| 2100 | |
| 2101 | static bool IsGlobalLValue(APValue::LValueBase B) { |
| 2102 | // C++11 [expr.const]p3 An address constant expression is a prvalue core |
| 2103 | // constant expression of pointer type that evaluates to... |
| 2104 | |
| 2105 | // ... a null pointer value, or a prvalue core constant expression of type |
| 2106 | // std::nullptr_t. |
| 2107 | if (!B) |
| 2108 | return true; |
| 2109 | |
| 2110 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { |
| 2111 | // ... the address of an object with static storage duration, |
| 2112 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) |
| 2113 | return VD->hasGlobalStorage(); |
| 2114 | if (isa<TemplateParamObjectDecl>(Val: D)) |
| 2115 | return true; |
| 2116 | // ... the address of a function, |
| 2117 | // ... the address of a GUID [MS extension], |
| 2118 | // ... the address of an unnamed global constant |
| 2119 | return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(Val: D); |
| 2120 | } |
| 2121 | |
| 2122 | if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) |
| 2123 | return true; |
| 2124 | |
| 2125 | const Expr *E = B.get<const Expr*>(); |
| 2126 | switch (E->getStmtClass()) { |
| 2127 | default: |
| 2128 | return false; |
| 2129 | case Expr::CompoundLiteralExprClass: { |
| 2130 | const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(Val: E); |
| 2131 | return CLE->isFileScope() && CLE->isLValue(); |
| 2132 | } |
| 2133 | case Expr::MaterializeTemporaryExprClass: |
| 2134 | // A materialized temporary might have been lifetime-extended to static |
| 2135 | // storage duration. |
| 2136 | return cast<MaterializeTemporaryExpr>(Val: E)->getStorageDuration() == SD_Static; |
| 2137 | // A string literal has static storage duration. |
| 2138 | case Expr::StringLiteralClass: |
| 2139 | case Expr::PredefinedExprClass: |
| 2140 | case Expr::ObjCStringLiteralClass: |
| 2141 | case Expr::ObjCEncodeExprClass: |
| 2142 | return true; |
| 2143 | case Expr::ObjCBoxedExprClass: |
| 2144 | return cast<ObjCBoxedExpr>(Val: E)->isExpressibleAsConstantInitializer(); |
| 2145 | case Expr::CallExprClass: |
| 2146 | return IsOpaqueConstantCall(E: cast<CallExpr>(Val: E)); |
| 2147 | // For GCC compatibility, &&label has static storage duration. |
| 2148 | case Expr::AddrLabelExprClass: |
| 2149 | return true; |
| 2150 | // A Block literal expression may be used as the initialization value for |
| 2151 | // Block variables at global or local static scope. |
| 2152 | case Expr::BlockExprClass: |
| 2153 | return !cast<BlockExpr>(Val: E)->getBlockDecl()->hasCaptures(); |
| 2154 | // The APValue generated from a __builtin_source_location will be emitted as a |
| 2155 | // literal. |
| 2156 | case Expr::SourceLocExprClass: |
| 2157 | return true; |
| 2158 | case Expr::ImplicitValueInitExprClass: |
| 2159 | // FIXME: |
| 2160 | // We can never form an lvalue with an implicit value initialization as its |
| 2161 | // base through expression evaluation, so these only appear in one case: the |
| 2162 | // implicit variable declaration we invent when checking whether a constexpr |
| 2163 | // constructor can produce a constant expression. We must assume that such |
| 2164 | // an expression might be a global lvalue. |
| 2165 | return true; |
| 2166 | } |
| 2167 | } |
| 2168 | |
| 2169 | static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { |
| 2170 | return LVal.Base.dyn_cast<const ValueDecl*>(); |
| 2171 | } |
| 2172 | |
| 2173 | // Information about an LValueBase that is some kind of string. |
| 2174 | struct LValueBaseString { |
| 2175 | std::string ObjCEncodeStorage; |
| 2176 | StringRef Bytes; |
| 2177 | int CharWidth; |
| 2178 | }; |
| 2179 | |
| 2180 | // Gets the lvalue base of LVal as a string. |
| 2181 | static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, |
| 2182 | LValueBaseString &AsString) { |
| 2183 | const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>(); |
| 2184 | if (!BaseExpr) |
| 2185 | return false; |
| 2186 | |
| 2187 | // For ObjCEncodeExpr, we need to compute and store the string. |
| 2188 | if (const auto *EE = dyn_cast<ObjCEncodeExpr>(Val: BaseExpr)) { |
| 2189 | Info.Ctx.getObjCEncodingForType(T: EE->getEncodedType(), |
| 2190 | S&: AsString.ObjCEncodeStorage); |
| 2191 | AsString.Bytes = AsString.ObjCEncodeStorage; |
| 2192 | AsString.CharWidth = 1; |
| 2193 | return true; |
| 2194 | } |
| 2195 | |
| 2196 | // Otherwise, we have a StringLiteral. |
| 2197 | const auto *Lit = dyn_cast<StringLiteral>(Val: BaseExpr); |
| 2198 | if (const auto *PE = dyn_cast<PredefinedExpr>(Val: BaseExpr)) |
| 2199 | Lit = PE->getFunctionName(); |
| 2200 | |
| 2201 | if (!Lit) |
| 2202 | return false; |
| 2203 | |
| 2204 | AsString.Bytes = Lit->getBytes(); |
| 2205 | AsString.CharWidth = Lit->getCharByteWidth(); |
| 2206 | return true; |
| 2207 | } |
| 2208 | |
| 2209 | // Determine whether two string literals potentially overlap. This will be the |
| 2210 | // case if they agree on the values of all the bytes on the overlapping region |
| 2211 | // between them. |
| 2212 | // |
| 2213 | // The overlapping region is the portion of the two string literals that must |
| 2214 | // overlap in memory if the pointers actually point to the same address at |
| 2215 | // runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then |
| 2216 | // the overlapping region is "cdef\0", which in this case does agree, so the |
| 2217 | // strings are potentially overlapping. Conversely, for "foobar" + 3 versus |
| 2218 | // "bazbar" + 3, the overlapping region contains all of both strings, so they |
| 2219 | // are not potentially overlapping, even though they agree from the given |
| 2220 | // addresses onwards. |
| 2221 | // |
| 2222 | // See open core issue CWG2765 which is discussing the desired rule here. |
| 2223 | static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, |
| 2224 | const LValue &LHS, |
| 2225 | const LValue &RHS) { |
| 2226 | LValueBaseString LHSString, RHSString; |
| 2227 | if (!GetLValueBaseAsString(Info, LVal: LHS, AsString&: LHSString) || |
| 2228 | !GetLValueBaseAsString(Info, LVal: RHS, AsString&: RHSString)) |
| 2229 | return false; |
| 2230 | |
| 2231 | // This is the byte offset to the location of the first character of LHS |
| 2232 | // within RHS. We don't need to look at the characters of one string that |
| 2233 | // would appear before the start of the other string if they were merged. |
| 2234 | CharUnits Offset = RHS.Offset - LHS.Offset; |
| 2235 | if (Offset.isNegative()) { |
| 2236 | if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity()) |
| 2237 | return false; |
| 2238 | LHSString.Bytes = LHSString.Bytes.drop_front(N: -Offset.getQuantity()); |
| 2239 | } else { |
| 2240 | if (RHSString.Bytes.size() < (size_t)Offset.getQuantity()) |
| 2241 | return false; |
| 2242 | RHSString.Bytes = RHSString.Bytes.drop_front(N: Offset.getQuantity()); |
| 2243 | } |
| 2244 | |
| 2245 | bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size(); |
| 2246 | StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes; |
| 2247 | StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes; |
| 2248 | int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth; |
| 2249 | |
| 2250 | // The null terminator isn't included in the string data, so check for it |
| 2251 | // manually. If the longer string doesn't have a null terminator where the |
| 2252 | // shorter string ends, they aren't potentially overlapping. |
| 2253 | for (int NullByte : llvm::seq(Size: ShorterCharWidth)) { |
| 2254 | if (Shorter.size() + NullByte >= Longer.size()) |
| 2255 | break; |
| 2256 | if (Longer[Shorter.size() + NullByte]) |
| 2257 | return false; |
| 2258 | } |
| 2259 | |
| 2260 | // Otherwise, they're potentially overlapping if and only if the overlapping |
| 2261 | // region is the same. |
| 2262 | return Shorter == Longer.take_front(N: Shorter.size()); |
| 2263 | } |
| 2264 | |
| 2265 | static bool IsWeakLValue(const LValue &Value) { |
| 2266 | const ValueDecl *Decl = GetLValueBaseDecl(LVal: Value); |
| 2267 | return Decl && Decl->isWeak(); |
| 2268 | } |
| 2269 | |
| 2270 | static bool isZeroSized(const LValue &Value) { |
| 2271 | const ValueDecl *Decl = GetLValueBaseDecl(LVal: Value); |
| 2272 | if (isa_and_nonnull<VarDecl>(Val: Decl)) { |
| 2273 | QualType Ty = Decl->getType(); |
| 2274 | if (Ty->isArrayType()) |
| 2275 | return Ty->isIncompleteType() || |
| 2276 | Decl->getASTContext().getTypeSize(T: Ty) == 0; |
| 2277 | } |
| 2278 | return false; |
| 2279 | } |
| 2280 | |
| 2281 | static bool HasSameBase(const LValue &A, const LValue &B) { |
| 2282 | if (!A.getLValueBase()) |
| 2283 | return !B.getLValueBase(); |
| 2284 | if (!B.getLValueBase()) |
| 2285 | return false; |
| 2286 | |
| 2287 | if (A.getLValueBase().getOpaqueValue() != |
| 2288 | B.getLValueBase().getOpaqueValue()) |
| 2289 | return false; |
| 2290 | |
| 2291 | return A.getLValueCallIndex() == B.getLValueCallIndex() && |
| 2292 | A.getLValueVersion() == B.getLValueVersion(); |
| 2293 | } |
| 2294 | |
| 2295 | static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { |
| 2296 | assert(Base && "no location for a null lvalue" ); |
| 2297 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); |
| 2298 | |
| 2299 | // For a parameter, find the corresponding call stack frame (if it still |
| 2300 | // exists), and point at the parameter of the function definition we actually |
| 2301 | // invoked. |
| 2302 | if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(Val: VD)) { |
| 2303 | unsigned Idx = PVD->getFunctionScopeIndex(); |
| 2304 | for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { |
| 2305 | if (F->Arguments.CallIndex == Base.getCallIndex() && |
| 2306 | F->Arguments.Version == Base.getVersion() && F->Callee && |
| 2307 | Idx < F->Callee->getNumParams()) { |
| 2308 | VD = F->Callee->getParamDecl(i: Idx); |
| 2309 | break; |
| 2310 | } |
| 2311 | } |
| 2312 | } |
| 2313 | |
| 2314 | if (VD) |
| 2315 | Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at); |
| 2316 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) |
| 2317 | Info.Note(Loc: E->getExprLoc(), DiagId: diag::note_constexpr_temporary_here); |
| 2318 | else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { |
| 2319 | // FIXME: Produce a note for dangling pointers too. |
| 2320 | if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA)) |
| 2321 | Info.Note(Loc: (*Alloc)->AllocExpr->getExprLoc(), |
| 2322 | DiagId: diag::note_constexpr_dynamic_alloc_here); |
| 2323 | } |
| 2324 | |
| 2325 | // We have no information to show for a typeid(T) object. |
| 2326 | } |
| 2327 | |
| 2328 | enum class CheckEvaluationResultKind { |
| 2329 | ConstantExpression, |
| 2330 | FullyInitialized, |
| 2331 | }; |
| 2332 | |
| 2333 | /// Materialized temporaries that we've already checked to determine if they're |
| 2334 | /// initializsed by a constant expression. |
| 2335 | using CheckedTemporaries = |
| 2336 | llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; |
| 2337 | |
| 2338 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, |
| 2339 | EvalInfo &Info, SourceLocation DiagLoc, |
| 2340 | QualType Type, const APValue &Value, |
| 2341 | ConstantExprKind Kind, |
| 2342 | const FieldDecl *SubobjectDecl, |
| 2343 | CheckedTemporaries &CheckedTemps); |
| 2344 | |
| 2345 | /// Check that this reference or pointer core constant expression is a valid |
| 2346 | /// value for an address or reference constant expression. Return true if we |
| 2347 | /// can fold this expression, whether or not it's a constant expression. |
| 2348 | static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, |
| 2349 | QualType Type, const LValue &LVal, |
| 2350 | ConstantExprKind Kind, |
| 2351 | CheckedTemporaries &CheckedTemps) { |
| 2352 | bool IsReferenceType = Type->isReferenceType(); |
| 2353 | |
| 2354 | APValue::LValueBase Base = LVal.getLValueBase(); |
| 2355 | const SubobjectDesignator &Designator = LVal.getLValueDesignator(); |
| 2356 | |
| 2357 | const Expr *BaseE = Base.dyn_cast<const Expr *>(); |
| 2358 | const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); |
| 2359 | |
| 2360 | // Additional restrictions apply in a template argument. We only enforce the |
| 2361 | // C++20 restrictions here; additional syntactic and semantic restrictions |
| 2362 | // are applied elsewhere. |
| 2363 | if (isTemplateArgument(Kind)) { |
| 2364 | int InvalidBaseKind = -1; |
| 2365 | StringRef Ident; |
| 2366 | if (Base.is<TypeInfoLValue>()) |
| 2367 | InvalidBaseKind = 0; |
| 2368 | else if (isa_and_nonnull<StringLiteral>(Val: BaseE)) |
| 2369 | InvalidBaseKind = 1; |
| 2370 | else if (isa_and_nonnull<MaterializeTemporaryExpr>(Val: BaseE) || |
| 2371 | isa_and_nonnull<LifetimeExtendedTemporaryDecl>(Val: BaseVD)) |
| 2372 | InvalidBaseKind = 2; |
| 2373 | else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(Val: BaseE)) { |
| 2374 | InvalidBaseKind = 3; |
| 2375 | Ident = PE->getIdentKindName(); |
| 2376 | } |
| 2377 | |
| 2378 | if (InvalidBaseKind != -1) { |
| 2379 | Info.FFDiag(Loc, DiagId: diag::note_constexpr_invalid_template_arg) |
| 2380 | << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind |
| 2381 | << Ident; |
| 2382 | return false; |
| 2383 | } |
| 2384 | } |
| 2385 | |
| 2386 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: BaseVD); |
| 2387 | FD && FD->isImmediateFunction()) { |
| 2388 | Info.FFDiag(Loc, DiagId: diag::note_consteval_address_accessible) |
| 2389 | << !Type->isAnyPointerType(); |
| 2390 | Info.Note(Loc: FD->getLocation(), DiagId: diag::note_declared_at); |
| 2391 | return false; |
| 2392 | } |
| 2393 | |
| 2394 | // Check that the object is a global. Note that the fake 'this' object we |
| 2395 | // manufacture when checking potential constant expressions is conservatively |
| 2396 | // assumed to be global here. |
| 2397 | if (!IsGlobalLValue(B: Base)) { |
| 2398 | if (Info.getLangOpts().CPlusPlus11) { |
| 2399 | Info.FFDiag(Loc, DiagId: diag::note_constexpr_non_global, ExtraNotes: 1) |
| 2400 | << IsReferenceType << !Designator.Entries.empty() << !!BaseVD |
| 2401 | << BaseVD; |
| 2402 | auto *VarD = dyn_cast_or_null<VarDecl>(Val: BaseVD); |
| 2403 | if (VarD && VarD->isConstexpr()) { |
| 2404 | // Non-static local constexpr variables have unintuitive semantics: |
| 2405 | // constexpr int a = 1; |
| 2406 | // constexpr const int *p = &a; |
| 2407 | // ... is invalid because the address of 'a' is not constant. Suggest |
| 2408 | // adding a 'static' in this case. |
| 2409 | Info.Note(Loc: VarD->getLocation(), DiagId: diag::note_constexpr_not_static) |
| 2410 | << VarD |
| 2411 | << FixItHint::CreateInsertion(InsertionLoc: VarD->getBeginLoc(), Code: "static " ); |
| 2412 | } else { |
| 2413 | NoteLValueLocation(Info, Base); |
| 2414 | } |
| 2415 | } else { |
| 2416 | Info.FFDiag(Loc); |
| 2417 | } |
| 2418 | // Don't allow references to temporaries to escape. |
| 2419 | return false; |
| 2420 | } |
| 2421 | assert((Info.checkingPotentialConstantExpression() || |
| 2422 | LVal.getLValueCallIndex() == 0) && |
| 2423 | "have call index for global lvalue" ); |
| 2424 | |
| 2425 | if (LVal.allowConstexprUnknown()) { |
| 2426 | if (BaseVD) { |
| 2427 | Info.FFDiag(Loc, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << BaseVD; |
| 2428 | NoteLValueLocation(Info, Base); |
| 2429 | } else { |
| 2430 | Info.FFDiag(Loc); |
| 2431 | } |
| 2432 | return false; |
| 2433 | } |
| 2434 | |
| 2435 | if (Base.is<DynamicAllocLValue>()) { |
| 2436 | Info.FFDiag(Loc, DiagId: diag::note_constexpr_dynamic_alloc) |
| 2437 | << IsReferenceType << !Designator.Entries.empty(); |
| 2438 | NoteLValueLocation(Info, Base); |
| 2439 | return false; |
| 2440 | } |
| 2441 | |
| 2442 | if (BaseVD) { |
| 2443 | if (const VarDecl *Var = dyn_cast<const VarDecl>(Val: BaseVD)) { |
| 2444 | // Check if this is a thread-local variable. |
| 2445 | if (Var->getTLSKind()) |
| 2446 | // FIXME: Diagnostic! |
| 2447 | return false; |
| 2448 | |
| 2449 | // A dllimport variable never acts like a constant, unless we're |
| 2450 | // evaluating a value for use only in name mangling. |
| 2451 | if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) |
| 2452 | // FIXME: Diagnostic! |
| 2453 | return false; |
| 2454 | |
| 2455 | // In CUDA/HIP device compilation, only device side variables have |
| 2456 | // constant addresses. |
| 2457 | if (Info.getASTContext().getLangOpts().CUDA && |
| 2458 | Info.getASTContext().getLangOpts().CUDAIsDevice && |
| 2459 | Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) { |
| 2460 | if ((!Var->hasAttr<CUDADeviceAttr>() && |
| 2461 | !Var->hasAttr<CUDAConstantAttr>() && |
| 2462 | !Var->getType()->isCUDADeviceBuiltinSurfaceType() && |
| 2463 | !Var->getType()->isCUDADeviceBuiltinTextureType()) || |
| 2464 | Var->hasAttr<HIPManagedAttr>()) |
| 2465 | return false; |
| 2466 | } |
| 2467 | } |
| 2468 | if (const auto *FD = dyn_cast<const FunctionDecl>(Val: BaseVD)) { |
| 2469 | // __declspec(dllimport) must be handled very carefully: |
| 2470 | // We must never initialize an expression with the thunk in C++. |
| 2471 | // Doing otherwise would allow the same id-expression to yield |
| 2472 | // different addresses for the same function in different translation |
| 2473 | // units. However, this means that we must dynamically initialize the |
| 2474 | // expression with the contents of the import address table at runtime. |
| 2475 | // |
| 2476 | // The C language has no notion of ODR; furthermore, it has no notion of |
| 2477 | // dynamic initialization. This means that we are permitted to |
| 2478 | // perform initialization with the address of the thunk. |
| 2479 | if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && |
| 2480 | FD->hasAttr<DLLImportAttr>()) |
| 2481 | // FIXME: Diagnostic! |
| 2482 | return false; |
| 2483 | } |
| 2484 | } else if (const auto *MTE = |
| 2485 | dyn_cast_or_null<MaterializeTemporaryExpr>(Val: BaseE)) { |
| 2486 | if (CheckedTemps.insert(Ptr: MTE).second) { |
| 2487 | QualType TempType = getType(B: Base); |
| 2488 | if (TempType.isDestructedType()) { |
| 2489 | Info.FFDiag(Loc: MTE->getExprLoc(), |
| 2490 | DiagId: diag::note_constexpr_unsupported_temporary_nontrivial_dtor) |
| 2491 | << TempType; |
| 2492 | return false; |
| 2493 | } |
| 2494 | |
| 2495 | APValue *V = MTE->getOrCreateValue(MayCreate: false); |
| 2496 | assert(V && "evasluation result refers to uninitialised temporary" ); |
| 2497 | if (!CheckEvaluationResult(CERK: CheckEvaluationResultKind::ConstantExpression, |
| 2498 | Info, DiagLoc: MTE->getExprLoc(), Type: TempType, Value: *V, Kind, |
| 2499 | /*SubobjectDecl=*/nullptr, CheckedTemps)) |
| 2500 | return false; |
| 2501 | } |
| 2502 | } |
| 2503 | |
| 2504 | // Allow address constant expressions to be past-the-end pointers. This is |
| 2505 | // an extension: the standard requires them to point to an object. |
| 2506 | if (!IsReferenceType) |
| 2507 | return true; |
| 2508 | |
| 2509 | // A reference constant expression must refer to an object. |
| 2510 | if (!Base) { |
| 2511 | // FIXME: diagnostic |
| 2512 | Info.CCEDiag(Loc); |
| 2513 | return true; |
| 2514 | } |
| 2515 | |
| 2516 | // Does this refer one past the end of some object? |
| 2517 | if (!Designator.Invalid && Designator.isOnePastTheEnd()) { |
| 2518 | Info.FFDiag(Loc, DiagId: diag::note_constexpr_past_end, ExtraNotes: 1) |
| 2519 | << !Designator.Entries.empty() << !!BaseVD << BaseVD; |
| 2520 | NoteLValueLocation(Info, Base); |
| 2521 | } |
| 2522 | |
| 2523 | return true; |
| 2524 | } |
| 2525 | |
| 2526 | /// Member pointers are constant expressions unless they point to a |
| 2527 | /// non-virtual dllimport member function. |
| 2528 | static bool CheckMemberPointerConstantExpression(EvalInfo &Info, |
| 2529 | SourceLocation Loc, |
| 2530 | QualType Type, |
| 2531 | const APValue &Value, |
| 2532 | ConstantExprKind Kind) { |
| 2533 | const ValueDecl *Member = Value.getMemberPointerDecl(); |
| 2534 | const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Val: Member); |
| 2535 | if (!FD) |
| 2536 | return true; |
| 2537 | if (FD->isImmediateFunction()) { |
| 2538 | Info.FFDiag(Loc, DiagId: diag::note_consteval_address_accessible) << /*pointer*/ 0; |
| 2539 | Info.Note(Loc: FD->getLocation(), DiagId: diag::note_declared_at); |
| 2540 | return false; |
| 2541 | } |
| 2542 | return isForManglingOnly(Kind) || FD->isVirtual() || |
| 2543 | !FD->hasAttr<DLLImportAttr>(); |
| 2544 | } |
| 2545 | |
| 2546 | /// Check that this core constant expression is of literal type, and if not, |
| 2547 | /// produce an appropriate diagnostic. |
| 2548 | static bool CheckLiteralType(EvalInfo &Info, const Expr *E, |
| 2549 | const LValue *This = nullptr) { |
| 2550 | // The restriction to literal types does not exist in C++23 anymore. |
| 2551 | if (Info.getLangOpts().CPlusPlus23) |
| 2552 | return true; |
| 2553 | |
| 2554 | if (!E->isPRValue() || E->getType()->isLiteralType(Ctx: Info.Ctx)) |
| 2555 | return true; |
| 2556 | |
| 2557 | // C++1y: A constant initializer for an object o [...] may also invoke |
| 2558 | // constexpr constructors for o and its subobjects even if those objects |
| 2559 | // are of non-literal class types. |
| 2560 | // |
| 2561 | // C++11 missed this detail for aggregates, so classes like this: |
| 2562 | // struct foo_t { union { int i; volatile int j; } u; }; |
| 2563 | // are not (obviously) initializable like so: |
| 2564 | // __attribute__((__require_constant_initialization__)) |
| 2565 | // static const foo_t x = {{0}}; |
| 2566 | // because "i" is a subobject with non-literal initialization (due to the |
| 2567 | // volatile member of the union). See: |
| 2568 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 |
| 2569 | // Therefore, we use the C++1y behavior. |
| 2570 | if (This && Info.EvaluatingDecl == This->getLValueBase()) |
| 2571 | return true; |
| 2572 | |
| 2573 | // Prvalue constant expressions must be of literal types. |
| 2574 | if (Info.getLangOpts().CPlusPlus11) |
| 2575 | Info.FFDiag(E, DiagId: diag::note_constexpr_nonliteral) |
| 2576 | << E->getType(); |
| 2577 | else |
| 2578 | Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 2579 | return false; |
| 2580 | } |
| 2581 | |
| 2582 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, |
| 2583 | EvalInfo &Info, SourceLocation DiagLoc, |
| 2584 | QualType Type, const APValue &Value, |
| 2585 | ConstantExprKind Kind, |
| 2586 | const FieldDecl *SubobjectDecl, |
| 2587 | CheckedTemporaries &CheckedTemps) { |
| 2588 | if (!Value.hasValue()) { |
| 2589 | if (SubobjectDecl) { |
| 2590 | Info.FFDiag(Loc: DiagLoc, DiagId: diag::note_constexpr_uninitialized) |
| 2591 | << /*(name)*/ 1 << SubobjectDecl; |
| 2592 | Info.Note(Loc: SubobjectDecl->getLocation(), |
| 2593 | DiagId: diag::note_constexpr_subobject_declared_here); |
| 2594 | } else { |
| 2595 | Info.FFDiag(Loc: DiagLoc, DiagId: diag::note_constexpr_uninitialized) |
| 2596 | << /*of type*/ 0 << Type; |
| 2597 | } |
| 2598 | return false; |
| 2599 | } |
| 2600 | |
| 2601 | // We allow _Atomic(T) to be initialized from anything that T can be |
| 2602 | // initialized from. |
| 2603 | if (const AtomicType *AT = Type->getAs<AtomicType>()) |
| 2604 | Type = AT->getValueType(); |
| 2605 | |
| 2606 | // Core issue 1454: For a literal constant expression of array or class type, |
| 2607 | // each subobject of its value shall have been initialized by a constant |
| 2608 | // expression. |
| 2609 | if (Value.isArray()) { |
| 2610 | QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); |
| 2611 | for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { |
| 2612 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, Type: EltTy, |
| 2613 | Value: Value.getArrayInitializedElt(I), Kind, |
| 2614 | SubobjectDecl, CheckedTemps)) |
| 2615 | return false; |
| 2616 | } |
| 2617 | if (!Value.hasArrayFiller()) |
| 2618 | return true; |
| 2619 | return CheckEvaluationResult(CERK, Info, DiagLoc, Type: EltTy, |
| 2620 | Value: Value.getArrayFiller(), Kind, SubobjectDecl, |
| 2621 | CheckedTemps); |
| 2622 | } |
| 2623 | if (Value.isUnion() && Value.getUnionField()) { |
| 2624 | return CheckEvaluationResult( |
| 2625 | CERK, Info, DiagLoc, Type: Value.getUnionField()->getType(), |
| 2626 | Value: Value.getUnionValue(), Kind, SubobjectDecl: Value.getUnionField(), CheckedTemps); |
| 2627 | } |
| 2628 | if (Value.isStruct()) { |
| 2629 | RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); |
| 2630 | if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
| 2631 | unsigned BaseIndex = 0; |
| 2632 | for (const CXXBaseSpecifier &BS : CD->bases()) { |
| 2633 | const APValue &BaseValue = Value.getStructBase(i: BaseIndex); |
| 2634 | if (!BaseValue.hasValue()) { |
| 2635 | SourceLocation TypeBeginLoc = BS.getBaseTypeLoc(); |
| 2636 | Info.FFDiag(Loc: TypeBeginLoc, DiagId: diag::note_constexpr_uninitialized_base) |
| 2637 | << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc()); |
| 2638 | return false; |
| 2639 | } |
| 2640 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, Type: BS.getType(), Value: BaseValue, |
| 2641 | Kind, /*SubobjectDecl=*/nullptr, |
| 2642 | CheckedTemps)) |
| 2643 | return false; |
| 2644 | ++BaseIndex; |
| 2645 | } |
| 2646 | } |
| 2647 | for (const auto *I : RD->fields()) { |
| 2648 | if (I->isUnnamedBitField()) |
| 2649 | continue; |
| 2650 | |
| 2651 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, Type: I->getType(), |
| 2652 | Value: Value.getStructField(i: I->getFieldIndex()), Kind, |
| 2653 | SubobjectDecl: I, CheckedTemps)) |
| 2654 | return false; |
| 2655 | } |
| 2656 | } |
| 2657 | |
| 2658 | if (Value.isLValue() && |
| 2659 | CERK == CheckEvaluationResultKind::ConstantExpression) { |
| 2660 | LValue LVal; |
| 2661 | LVal.setFrom(Ctx&: Info.Ctx, V: Value); |
| 2662 | return CheckLValueConstantExpression(Info, Loc: DiagLoc, Type, LVal, Kind, |
| 2663 | CheckedTemps); |
| 2664 | } |
| 2665 | |
| 2666 | if (Value.isMemberPointer() && |
| 2667 | CERK == CheckEvaluationResultKind::ConstantExpression) |
| 2668 | return CheckMemberPointerConstantExpression(Info, Loc: DiagLoc, Type, Value, Kind); |
| 2669 | |
| 2670 | // Everything else is fine. |
| 2671 | return true; |
| 2672 | } |
| 2673 | |
| 2674 | /// Check that this core constant expression value is a valid value for a |
| 2675 | /// constant expression. If not, report an appropriate diagnostic. Does not |
| 2676 | /// check that the expression is of literal type. |
| 2677 | static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, |
| 2678 | QualType Type, const APValue &Value, |
| 2679 | ConstantExprKind Kind) { |
| 2680 | // Nothing to check for a constant expression of type 'cv void'. |
| 2681 | if (Type->isVoidType()) |
| 2682 | return true; |
| 2683 | |
| 2684 | CheckedTemporaries CheckedTemps; |
| 2685 | return CheckEvaluationResult(CERK: CheckEvaluationResultKind::ConstantExpression, |
| 2686 | Info, DiagLoc, Type, Value, Kind, |
| 2687 | /*SubobjectDecl=*/nullptr, CheckedTemps); |
| 2688 | } |
| 2689 | |
| 2690 | /// Check that this evaluated value is fully-initialized and can be loaded by |
| 2691 | /// an lvalue-to-rvalue conversion. |
| 2692 | static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, |
| 2693 | QualType Type, const APValue &Value) { |
| 2694 | CheckedTemporaries CheckedTemps; |
| 2695 | return CheckEvaluationResult( |
| 2696 | CERK: CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, |
| 2697 | Kind: ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps); |
| 2698 | } |
| 2699 | |
| 2700 | /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless |
| 2701 | /// "the allocated storage is deallocated within the evaluation". |
| 2702 | static bool CheckMemoryLeaks(EvalInfo &Info) { |
| 2703 | if (!Info.HeapAllocs.empty()) { |
| 2704 | // We can still fold to a constant despite a compile-time memory leak, |
| 2705 | // so long as the heap allocation isn't referenced in the result (we check |
| 2706 | // that in CheckConstantExpression). |
| 2707 | Info.CCEDiag(E: Info.HeapAllocs.begin()->second.AllocExpr, |
| 2708 | DiagId: diag::note_constexpr_memory_leak) |
| 2709 | << unsigned(Info.HeapAllocs.size() - 1); |
| 2710 | } |
| 2711 | return true; |
| 2712 | } |
| 2713 | |
| 2714 | static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { |
| 2715 | // A null base expression indicates a null pointer. These are always |
| 2716 | // evaluatable, and they are false unless the offset is zero. |
| 2717 | if (!Value.getLValueBase()) { |
| 2718 | // TODO: Should a non-null pointer with an offset of zero evaluate to true? |
| 2719 | Result = !Value.getLValueOffset().isZero(); |
| 2720 | return true; |
| 2721 | } |
| 2722 | |
| 2723 | // We have a non-null base. These are generally known to be true, but if it's |
| 2724 | // a weak declaration it can be null at runtime. |
| 2725 | Result = true; |
| 2726 | const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); |
| 2727 | return !Decl || !Decl->isWeak(); |
| 2728 | } |
| 2729 | |
| 2730 | static bool HandleConversionToBool(const APValue &Val, bool &Result) { |
| 2731 | // TODO: This function should produce notes if it fails. |
| 2732 | switch (Val.getKind()) { |
| 2733 | case APValue::None: |
| 2734 | case APValue::Indeterminate: |
| 2735 | return false; |
| 2736 | case APValue::Int: |
| 2737 | Result = Val.getInt().getBoolValue(); |
| 2738 | return true; |
| 2739 | case APValue::FixedPoint: |
| 2740 | Result = Val.getFixedPoint().getBoolValue(); |
| 2741 | return true; |
| 2742 | case APValue::Float: |
| 2743 | Result = !Val.getFloat().isZero(); |
| 2744 | return true; |
| 2745 | case APValue::ComplexInt: |
| 2746 | Result = Val.getComplexIntReal().getBoolValue() || |
| 2747 | Val.getComplexIntImag().getBoolValue(); |
| 2748 | return true; |
| 2749 | case APValue::ComplexFloat: |
| 2750 | Result = !Val.getComplexFloatReal().isZero() || |
| 2751 | !Val.getComplexFloatImag().isZero(); |
| 2752 | return true; |
| 2753 | case APValue::LValue: |
| 2754 | return EvalPointerValueAsBool(Value: Val, Result); |
| 2755 | case APValue::MemberPointer: |
| 2756 | if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) { |
| 2757 | return false; |
| 2758 | } |
| 2759 | Result = Val.getMemberPointerDecl(); |
| 2760 | return true; |
| 2761 | case APValue::Vector: |
| 2762 | case APValue::Array: |
| 2763 | case APValue::Struct: |
| 2764 | case APValue::Union: |
| 2765 | case APValue::AddrLabelDiff: |
| 2766 | return false; |
| 2767 | } |
| 2768 | |
| 2769 | llvm_unreachable("unknown APValue kind" ); |
| 2770 | } |
| 2771 | |
| 2772 | static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, |
| 2773 | EvalInfo &Info) { |
| 2774 | assert(!E->isValueDependent()); |
| 2775 | assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition" ); |
| 2776 | APValue Val; |
| 2777 | if (!Evaluate(Result&: Val, Info, E)) |
| 2778 | return false; |
| 2779 | return HandleConversionToBool(Val, Result); |
| 2780 | } |
| 2781 | |
| 2782 | template<typename T> |
| 2783 | static bool HandleOverflow(EvalInfo &Info, const Expr *E, |
| 2784 | const T &SrcValue, QualType DestType) { |
| 2785 | Info.CCEDiag(E, DiagId: diag::note_constexpr_overflow) |
| 2786 | << SrcValue << DestType; |
| 2787 | return Info.noteUndefinedBehavior(); |
| 2788 | } |
| 2789 | |
| 2790 | static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, |
| 2791 | QualType SrcType, const APFloat &Value, |
| 2792 | QualType DestType, APSInt &Result) { |
| 2793 | unsigned DestWidth = Info.Ctx.getIntWidth(T: DestType); |
| 2794 | // Determine whether we are converting to unsigned or signed. |
| 2795 | bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); |
| 2796 | |
| 2797 | Result = APSInt(DestWidth, !DestSigned); |
| 2798 | bool ignored; |
| 2799 | if (Value.convertToInteger(Result, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored) |
| 2800 | & APFloat::opInvalidOp) |
| 2801 | return HandleOverflow(Info, E, SrcValue: Value, DestType); |
| 2802 | return true; |
| 2803 | } |
| 2804 | |
| 2805 | /// Get rounding mode to use in evaluation of the specified expression. |
| 2806 | /// |
| 2807 | /// If rounding mode is unknown at compile time, still try to evaluate the |
| 2808 | /// expression. If the result is exact, it does not depend on rounding mode. |
| 2809 | /// So return "tonearest" mode instead of "dynamic". |
| 2810 | static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) { |
| 2811 | llvm::RoundingMode RM = |
| 2812 | E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts()).getRoundingMode(); |
| 2813 | if (RM == llvm::RoundingMode::Dynamic) |
| 2814 | RM = llvm::RoundingMode::NearestTiesToEven; |
| 2815 | return RM; |
| 2816 | } |
| 2817 | |
| 2818 | /// Check if the given evaluation result is allowed for constant evaluation. |
| 2819 | static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, |
| 2820 | APFloat::opStatus St) { |
| 2821 | // In a constant context, assume that any dynamic rounding mode or FP |
| 2822 | // exception state matches the default floating-point environment. |
| 2823 | if (Info.InConstantContext) |
| 2824 | return true; |
| 2825 | |
| 2826 | FPOptions FPO = E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts()); |
| 2827 | if ((St & APFloat::opInexact) && |
| 2828 | FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { |
| 2829 | // Inexact result means that it depends on rounding mode. If the requested |
| 2830 | // mode is dynamic, the evaluation cannot be made in compile time. |
| 2831 | Info.FFDiag(E, DiagId: diag::note_constexpr_dynamic_rounding); |
| 2832 | return false; |
| 2833 | } |
| 2834 | |
| 2835 | if ((St != APFloat::opOK) && |
| 2836 | (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || |
| 2837 | FPO.getExceptionMode() != LangOptions::FPE_Ignore || |
| 2838 | FPO.getAllowFEnvAccess())) { |
| 2839 | Info.FFDiag(E, DiagId: diag::note_constexpr_float_arithmetic_strict); |
| 2840 | return false; |
| 2841 | } |
| 2842 | |
| 2843 | if ((St & APFloat::opStatus::opInvalidOp) && |
| 2844 | FPO.getExceptionMode() != LangOptions::FPE_Ignore) { |
| 2845 | // There is no usefully definable result. |
| 2846 | Info.FFDiag(E); |
| 2847 | return false; |
| 2848 | } |
| 2849 | |
| 2850 | // FIXME: if: |
| 2851 | // - evaluation triggered other FP exception, and |
| 2852 | // - exception mode is not "ignore", and |
| 2853 | // - the expression being evaluated is not a part of global variable |
| 2854 | // initializer, |
| 2855 | // the evaluation probably need to be rejected. |
| 2856 | return true; |
| 2857 | } |
| 2858 | |
| 2859 | static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, |
| 2860 | QualType SrcType, QualType DestType, |
| 2861 | APFloat &Result) { |
| 2862 | assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) || |
| 2863 | isa<ConvertVectorExpr>(E)) && |
| 2864 | "HandleFloatToFloatCast has been checked with only CastExpr, " |
| 2865 | "CompoundAssignOperator and ConvertVectorExpr. Please either validate " |
| 2866 | "the new expression or address the root cause of this usage." ); |
| 2867 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E); |
| 2868 | APFloat::opStatus St; |
| 2869 | APFloat Value = Result; |
| 2870 | bool ignored; |
| 2871 | St = Result.convert(ToSemantics: Info.Ctx.getFloatTypeSemantics(T: DestType), RM, losesInfo: &ignored); |
| 2872 | return checkFloatingPointResult(Info, E, St); |
| 2873 | } |
| 2874 | |
| 2875 | static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, |
| 2876 | QualType DestType, QualType SrcType, |
| 2877 | const APSInt &Value) { |
| 2878 | unsigned DestWidth = Info.Ctx.getIntWidth(T: DestType); |
| 2879 | // Figure out if this is a truncate, extend or noop cast. |
| 2880 | // If the input is signed, do a sign extend, noop, or truncate. |
| 2881 | APSInt Result = Value.extOrTrunc(width: DestWidth); |
| 2882 | Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); |
| 2883 | if (DestType->isBooleanType()) |
| 2884 | Result = Value.getBoolValue(); |
| 2885 | return Result; |
| 2886 | } |
| 2887 | |
| 2888 | static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, |
| 2889 | const FPOptions FPO, |
| 2890 | QualType SrcType, const APSInt &Value, |
| 2891 | QualType DestType, APFloat &Result) { |
| 2892 | Result = APFloat(Info.Ctx.getFloatTypeSemantics(T: DestType), 1); |
| 2893 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E); |
| 2894 | APFloat::opStatus St = Result.convertFromAPInt(Input: Value, IsSigned: Value.isSigned(), RM); |
| 2895 | return checkFloatingPointResult(Info, E, St); |
| 2896 | } |
| 2897 | |
| 2898 | static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, |
| 2899 | APValue &Value, const FieldDecl *FD) { |
| 2900 | assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield" ); |
| 2901 | |
| 2902 | if (!Value.isInt()) { |
| 2903 | // Trying to store a pointer-cast-to-integer into a bitfield. |
| 2904 | // FIXME: In this case, we should provide the diagnostic for casting |
| 2905 | // a pointer to an integer. |
| 2906 | assert(Value.isLValue() && "integral value neither int nor lvalue?" ); |
| 2907 | Info.FFDiag(E); |
| 2908 | return false; |
| 2909 | } |
| 2910 | |
| 2911 | APSInt &Int = Value.getInt(); |
| 2912 | unsigned OldBitWidth = Int.getBitWidth(); |
| 2913 | unsigned NewBitWidth = FD->getBitWidthValue(); |
| 2914 | if (NewBitWidth < OldBitWidth) |
| 2915 | Int = Int.trunc(width: NewBitWidth).extend(width: OldBitWidth); |
| 2916 | return true; |
| 2917 | } |
| 2918 | |
| 2919 | /// Perform the given integer operation, which is known to need at most BitWidth |
| 2920 | /// bits, and check for overflow in the original type (if that type was not an |
| 2921 | /// unsigned type). |
| 2922 | template<typename Operation> |
| 2923 | static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, |
| 2924 | const APSInt &LHS, const APSInt &RHS, |
| 2925 | unsigned BitWidth, Operation Op, |
| 2926 | APSInt &Result) { |
| 2927 | if (LHS.isUnsigned()) { |
| 2928 | Result = Op(LHS, RHS); |
| 2929 | return true; |
| 2930 | } |
| 2931 | |
| 2932 | APSInt Value(Op(LHS.extend(width: BitWidth), RHS.extend(width: BitWidth)), false); |
| 2933 | Result = Value.trunc(width: LHS.getBitWidth()); |
| 2934 | if (Result.extend(width: BitWidth) != Value) { |
| 2935 | if (Info.checkingForUndefinedBehavior()) |
| 2936 | Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(), |
| 2937 | DiagID: diag::warn_integer_constant_overflow) |
| 2938 | << toString(I: Result, Radix: 10, Signed: Result.isSigned(), /*formatAsCLiteral=*/false, |
| 2939 | /*UpperCase=*/true, /*InsertSeparators=*/true) |
| 2940 | << E->getType() << E->getSourceRange(); |
| 2941 | return HandleOverflow(Info, E, SrcValue: Value, DestType: E->getType()); |
| 2942 | } |
| 2943 | return true; |
| 2944 | } |
| 2945 | |
| 2946 | /// Perform the given binary integer operation. |
| 2947 | static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, |
| 2948 | const APSInt &LHS, BinaryOperatorKind Opcode, |
| 2949 | APSInt RHS, APSInt &Result) { |
| 2950 | bool HandleOverflowResult = true; |
| 2951 | switch (Opcode) { |
| 2952 | default: |
| 2953 | Info.FFDiag(E); |
| 2954 | return false; |
| 2955 | case BO_Mul: |
| 2956 | return CheckedIntArithmetic(Info, E, LHS, RHS, BitWidth: LHS.getBitWidth() * 2, |
| 2957 | Op: std::multiplies<APSInt>(), Result); |
| 2958 | case BO_Add: |
| 2959 | return CheckedIntArithmetic(Info, E, LHS, RHS, BitWidth: LHS.getBitWidth() + 1, |
| 2960 | Op: std::plus<APSInt>(), Result); |
| 2961 | case BO_Sub: |
| 2962 | return CheckedIntArithmetic(Info, E, LHS, RHS, BitWidth: LHS.getBitWidth() + 1, |
| 2963 | Op: std::minus<APSInt>(), Result); |
| 2964 | case BO_And: Result = LHS & RHS; return true; |
| 2965 | case BO_Xor: Result = LHS ^ RHS; return true; |
| 2966 | case BO_Or: Result = LHS | RHS; return true; |
| 2967 | case BO_Div: |
| 2968 | case BO_Rem: |
| 2969 | if (RHS == 0) { |
| 2970 | Info.FFDiag(E, DiagId: diag::note_expr_divide_by_zero) |
| 2971 | << E->getRHS()->getSourceRange(); |
| 2972 | return false; |
| 2973 | } |
| 2974 | // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports |
| 2975 | // this operation and gives the two's complement result. |
| 2976 | if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && |
| 2977 | LHS.isMinSignedValue()) |
| 2978 | HandleOverflowResult = HandleOverflow( |
| 2979 | Info, E, SrcValue: -LHS.extend(width: LHS.getBitWidth() + 1), DestType: E->getType()); |
| 2980 | Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); |
| 2981 | return HandleOverflowResult; |
| 2982 | case BO_Shl: { |
| 2983 | if (Info.getLangOpts().OpenCL) |
| 2984 | // OpenCL 6.3j: shift values are effectively % word size of LHS. |
| 2985 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), |
| 2986 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), |
| 2987 | RHS.isUnsigned()); |
| 2988 | else if (RHS.isSigned() && RHS.isNegative()) { |
| 2989 | // During constant-folding, a negative shift is an opposite shift. Such |
| 2990 | // a shift is not a constant expression. |
| 2991 | Info.CCEDiag(E, DiagId: diag::note_constexpr_negative_shift) << RHS; |
| 2992 | if (!Info.noteUndefinedBehavior()) |
| 2993 | return false; |
| 2994 | RHS = -RHS; |
| 2995 | goto shift_right; |
| 2996 | } |
| 2997 | shift_left: |
| 2998 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of |
| 2999 | // the shifted type. |
| 3000 | unsigned SA = (unsigned) RHS.getLimitedValue(Limit: LHS.getBitWidth()-1); |
| 3001 | if (SA != RHS) { |
| 3002 | Info.CCEDiag(E, DiagId: diag::note_constexpr_large_shift) |
| 3003 | << RHS << E->getType() << LHS.getBitWidth(); |
| 3004 | if (!Info.noteUndefinedBehavior()) |
| 3005 | return false; |
| 3006 | } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { |
| 3007 | // C++11 [expr.shift]p2: A signed left shift must have a non-negative |
| 3008 | // operand, and must not overflow the corresponding unsigned type. |
| 3009 | // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to |
| 3010 | // E1 x 2^E2 module 2^N. |
| 3011 | if (LHS.isNegative()) { |
| 3012 | Info.CCEDiag(E, DiagId: diag::note_constexpr_lshift_of_negative) << LHS; |
| 3013 | if (!Info.noteUndefinedBehavior()) |
| 3014 | return false; |
| 3015 | } else if (LHS.countl_zero() < SA) { |
| 3016 | Info.CCEDiag(E, DiagId: diag::note_constexpr_lshift_discards); |
| 3017 | if (!Info.noteUndefinedBehavior()) |
| 3018 | return false; |
| 3019 | } |
| 3020 | } |
| 3021 | Result = LHS << SA; |
| 3022 | return true; |
| 3023 | } |
| 3024 | case BO_Shr: { |
| 3025 | if (Info.getLangOpts().OpenCL) |
| 3026 | // OpenCL 6.3j: shift values are effectively % word size of LHS. |
| 3027 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), |
| 3028 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), |
| 3029 | RHS.isUnsigned()); |
| 3030 | else if (RHS.isSigned() && RHS.isNegative()) { |
| 3031 | // During constant-folding, a negative shift is an opposite shift. Such a |
| 3032 | // shift is not a constant expression. |
| 3033 | Info.CCEDiag(E, DiagId: diag::note_constexpr_negative_shift) << RHS; |
| 3034 | if (!Info.noteUndefinedBehavior()) |
| 3035 | return false; |
| 3036 | RHS = -RHS; |
| 3037 | goto shift_left; |
| 3038 | } |
| 3039 | shift_right: |
| 3040 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of the |
| 3041 | // shifted type. |
| 3042 | unsigned SA = (unsigned) RHS.getLimitedValue(Limit: LHS.getBitWidth()-1); |
| 3043 | if (SA != RHS) { |
| 3044 | Info.CCEDiag(E, DiagId: diag::note_constexpr_large_shift) |
| 3045 | << RHS << E->getType() << LHS.getBitWidth(); |
| 3046 | if (!Info.noteUndefinedBehavior()) |
| 3047 | return false; |
| 3048 | } |
| 3049 | |
| 3050 | Result = LHS >> SA; |
| 3051 | return true; |
| 3052 | } |
| 3053 | |
| 3054 | case BO_LT: Result = LHS < RHS; return true; |
| 3055 | case BO_GT: Result = LHS > RHS; return true; |
| 3056 | case BO_LE: Result = LHS <= RHS; return true; |
| 3057 | case BO_GE: Result = LHS >= RHS; return true; |
| 3058 | case BO_EQ: Result = LHS == RHS; return true; |
| 3059 | case BO_NE: Result = LHS != RHS; return true; |
| 3060 | case BO_Cmp: |
| 3061 | llvm_unreachable("BO_Cmp should be handled elsewhere" ); |
| 3062 | } |
| 3063 | } |
| 3064 | |
| 3065 | /// Perform the given binary floating-point operation, in-place, on LHS. |
| 3066 | static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, |
| 3067 | APFloat &LHS, BinaryOperatorKind Opcode, |
| 3068 | const APFloat &RHS) { |
| 3069 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E); |
| 3070 | APFloat::opStatus St; |
| 3071 | switch (Opcode) { |
| 3072 | default: |
| 3073 | Info.FFDiag(E); |
| 3074 | return false; |
| 3075 | case BO_Mul: |
| 3076 | St = LHS.multiply(RHS, RM); |
| 3077 | break; |
| 3078 | case BO_Add: |
| 3079 | St = LHS.add(RHS, RM); |
| 3080 | break; |
| 3081 | case BO_Sub: |
| 3082 | St = LHS.subtract(RHS, RM); |
| 3083 | break; |
| 3084 | case BO_Div: |
| 3085 | // [expr.mul]p4: |
| 3086 | // If the second operand of / or % is zero the behavior is undefined. |
| 3087 | if (RHS.isZero()) |
| 3088 | Info.CCEDiag(E, DiagId: diag::note_expr_divide_by_zero); |
| 3089 | St = LHS.divide(RHS, RM); |
| 3090 | break; |
| 3091 | } |
| 3092 | |
| 3093 | // [expr.pre]p4: |
| 3094 | // If during the evaluation of an expression, the result is not |
| 3095 | // mathematically defined [...], the behavior is undefined. |
| 3096 | // FIXME: C++ rules require us to not conform to IEEE 754 here. |
| 3097 | if (LHS.isNaN()) { |
| 3098 | Info.CCEDiag(E, DiagId: diag::note_constexpr_float_arithmetic) << LHS.isNaN(); |
| 3099 | return Info.noteUndefinedBehavior(); |
| 3100 | } |
| 3101 | |
| 3102 | return checkFloatingPointResult(Info, E, St); |
| 3103 | } |
| 3104 | |
| 3105 | static bool handleLogicalOpForVector(const APInt &LHSValue, |
| 3106 | BinaryOperatorKind Opcode, |
| 3107 | const APInt &RHSValue, APInt &Result) { |
| 3108 | bool LHS = (LHSValue != 0); |
| 3109 | bool RHS = (RHSValue != 0); |
| 3110 | |
| 3111 | if (Opcode == BO_LAnd) |
| 3112 | Result = LHS && RHS; |
| 3113 | else |
| 3114 | Result = LHS || RHS; |
| 3115 | return true; |
| 3116 | } |
| 3117 | static bool handleLogicalOpForVector(const APFloat &LHSValue, |
| 3118 | BinaryOperatorKind Opcode, |
| 3119 | const APFloat &RHSValue, APInt &Result) { |
| 3120 | bool LHS = !LHSValue.isZero(); |
| 3121 | bool RHS = !RHSValue.isZero(); |
| 3122 | |
| 3123 | if (Opcode == BO_LAnd) |
| 3124 | Result = LHS && RHS; |
| 3125 | else |
| 3126 | Result = LHS || RHS; |
| 3127 | return true; |
| 3128 | } |
| 3129 | |
| 3130 | static bool handleLogicalOpForVector(const APValue &LHSValue, |
| 3131 | BinaryOperatorKind Opcode, |
| 3132 | const APValue &RHSValue, APInt &Result) { |
| 3133 | // The result is always an int type, however operands match the first. |
| 3134 | if (LHSValue.getKind() == APValue::Int) |
| 3135 | return handleLogicalOpForVector(LHSValue: LHSValue.getInt(), Opcode, |
| 3136 | RHSValue: RHSValue.getInt(), Result); |
| 3137 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options" ); |
| 3138 | return handleLogicalOpForVector(LHSValue: LHSValue.getFloat(), Opcode, |
| 3139 | RHSValue: RHSValue.getFloat(), Result); |
| 3140 | } |
| 3141 | |
| 3142 | template <typename APTy> |
| 3143 | static bool |
| 3144 | handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, |
| 3145 | const APTy &RHSValue, APInt &Result) { |
| 3146 | switch (Opcode) { |
| 3147 | default: |
| 3148 | llvm_unreachable("unsupported binary operator" ); |
| 3149 | case BO_EQ: |
| 3150 | Result = (LHSValue == RHSValue); |
| 3151 | break; |
| 3152 | case BO_NE: |
| 3153 | Result = (LHSValue != RHSValue); |
| 3154 | break; |
| 3155 | case BO_LT: |
| 3156 | Result = (LHSValue < RHSValue); |
| 3157 | break; |
| 3158 | case BO_GT: |
| 3159 | Result = (LHSValue > RHSValue); |
| 3160 | break; |
| 3161 | case BO_LE: |
| 3162 | Result = (LHSValue <= RHSValue); |
| 3163 | break; |
| 3164 | case BO_GE: |
| 3165 | Result = (LHSValue >= RHSValue); |
| 3166 | break; |
| 3167 | } |
| 3168 | |
| 3169 | // The boolean operations on these vector types use an instruction that |
| 3170 | // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 |
| 3171 | // to -1 to make sure that we produce the correct value. |
| 3172 | Result.negate(); |
| 3173 | |
| 3174 | return true; |
| 3175 | } |
| 3176 | |
| 3177 | static bool handleCompareOpForVector(const APValue &LHSValue, |
| 3178 | BinaryOperatorKind Opcode, |
| 3179 | const APValue &RHSValue, APInt &Result) { |
| 3180 | // The result is always an int type, however operands match the first. |
| 3181 | if (LHSValue.getKind() == APValue::Int) |
| 3182 | return handleCompareOpForVectorHelper(LHSValue: LHSValue.getInt(), Opcode, |
| 3183 | RHSValue: RHSValue.getInt(), Result); |
| 3184 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options" ); |
| 3185 | return handleCompareOpForVectorHelper(LHSValue: LHSValue.getFloat(), Opcode, |
| 3186 | RHSValue: RHSValue.getFloat(), Result); |
| 3187 | } |
| 3188 | |
| 3189 | // Perform binary operations for vector types, in place on the LHS. |
| 3190 | static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, |
| 3191 | BinaryOperatorKind Opcode, |
| 3192 | APValue &LHSValue, |
| 3193 | const APValue &RHSValue) { |
| 3194 | assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && |
| 3195 | "Operation not supported on vector types" ); |
| 3196 | |
| 3197 | const auto *VT = E->getType()->castAs<VectorType>(); |
| 3198 | unsigned NumElements = VT->getNumElements(); |
| 3199 | QualType EltTy = VT->getElementType(); |
| 3200 | |
| 3201 | // In the cases (typically C as I've observed) where we aren't evaluating |
| 3202 | // constexpr but are checking for cases where the LHS isn't yet evaluatable, |
| 3203 | // just give up. |
| 3204 | if (!LHSValue.isVector()) { |
| 3205 | assert(LHSValue.isLValue() && |
| 3206 | "A vector result that isn't a vector OR uncalculated LValue" ); |
| 3207 | Info.FFDiag(E); |
| 3208 | return false; |
| 3209 | } |
| 3210 | |
| 3211 | assert(LHSValue.getVectorLength() == NumElements && |
| 3212 | RHSValue.getVectorLength() == NumElements && "Different vector sizes" ); |
| 3213 | |
| 3214 | SmallVector<APValue, 4> ResultElements; |
| 3215 | |
| 3216 | for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { |
| 3217 | APValue LHSElt = LHSValue.getVectorElt(I: EltNum); |
| 3218 | APValue RHSElt = RHSValue.getVectorElt(I: EltNum); |
| 3219 | |
| 3220 | if (EltTy->isIntegerType()) { |
| 3221 | APSInt EltResult{Info.Ctx.getIntWidth(T: EltTy), |
| 3222 | EltTy->isUnsignedIntegerType()}; |
| 3223 | bool Success = true; |
| 3224 | |
| 3225 | if (BinaryOperator::isLogicalOp(Opc: Opcode)) |
| 3226 | Success = handleLogicalOpForVector(LHSValue: LHSElt, Opcode, RHSValue: RHSElt, Result&: EltResult); |
| 3227 | else if (BinaryOperator::isComparisonOp(Opc: Opcode)) |
| 3228 | Success = handleCompareOpForVector(LHSValue: LHSElt, Opcode, RHSValue: RHSElt, Result&: EltResult); |
| 3229 | else |
| 3230 | Success = handleIntIntBinOp(Info, E, LHS: LHSElt.getInt(), Opcode, |
| 3231 | RHS: RHSElt.getInt(), Result&: EltResult); |
| 3232 | |
| 3233 | if (!Success) { |
| 3234 | Info.FFDiag(E); |
| 3235 | return false; |
| 3236 | } |
| 3237 | ResultElements.emplace_back(Args&: EltResult); |
| 3238 | |
| 3239 | } else if (EltTy->isFloatingType()) { |
| 3240 | assert(LHSElt.getKind() == APValue::Float && |
| 3241 | RHSElt.getKind() == APValue::Float && |
| 3242 | "Mismatched LHS/RHS/Result Type" ); |
| 3243 | APFloat LHSFloat = LHSElt.getFloat(); |
| 3244 | |
| 3245 | if (!handleFloatFloatBinOp(Info, E, LHS&: LHSFloat, Opcode, |
| 3246 | RHS: RHSElt.getFloat())) { |
| 3247 | Info.FFDiag(E); |
| 3248 | return false; |
| 3249 | } |
| 3250 | |
| 3251 | ResultElements.emplace_back(Args&: LHSFloat); |
| 3252 | } |
| 3253 | } |
| 3254 | |
| 3255 | LHSValue = APValue(ResultElements.data(), ResultElements.size()); |
| 3256 | return true; |
| 3257 | } |
| 3258 | |
| 3259 | /// Cast an lvalue referring to a base subobject to a derived class, by |
| 3260 | /// truncating the lvalue's path to the given length. |
| 3261 | static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, |
| 3262 | const RecordDecl *TruncatedType, |
| 3263 | unsigned TruncatedElements) { |
| 3264 | SubobjectDesignator &D = Result.Designator; |
| 3265 | |
| 3266 | // Check we actually point to a derived class object. |
| 3267 | if (TruncatedElements == D.Entries.size()) |
| 3268 | return true; |
| 3269 | assert(TruncatedElements >= D.MostDerivedPathLength && |
| 3270 | "not casting to a derived class" ); |
| 3271 | if (!Result.checkSubobject(Info, E, CSK: CSK_Derived)) |
| 3272 | return false; |
| 3273 | |
| 3274 | // Truncate the path to the subobject, and remove any derived-to-base offsets. |
| 3275 | const RecordDecl *RD = TruncatedType; |
| 3276 | for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { |
| 3277 | if (RD->isInvalidDecl()) return false; |
| 3278 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD); |
| 3279 | const CXXRecordDecl *Base = getAsBaseClass(E: D.Entries[I]); |
| 3280 | if (isVirtualBaseClass(E: D.Entries[I])) |
| 3281 | Result.Offset -= Layout.getVBaseClassOffset(VBase: Base); |
| 3282 | else |
| 3283 | Result.Offset -= Layout.getBaseClassOffset(Base); |
| 3284 | RD = Base; |
| 3285 | } |
| 3286 | D.Entries.resize(N: TruncatedElements); |
| 3287 | return true; |
| 3288 | } |
| 3289 | |
| 3290 | static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, |
| 3291 | const CXXRecordDecl *Derived, |
| 3292 | const CXXRecordDecl *Base, |
| 3293 | const ASTRecordLayout *RL = nullptr) { |
| 3294 | if (!RL) { |
| 3295 | if (Derived->isInvalidDecl()) return false; |
| 3296 | RL = &Info.Ctx.getASTRecordLayout(D: Derived); |
| 3297 | } |
| 3298 | |
| 3299 | Obj.addDecl(Info, E, D: Base, /*Virtual*/ false); |
| 3300 | Obj.getLValueOffset() += RL->getBaseClassOffset(Base); |
| 3301 | return true; |
| 3302 | } |
| 3303 | |
| 3304 | static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, |
| 3305 | const CXXRecordDecl *DerivedDecl, |
| 3306 | const CXXBaseSpecifier *Base) { |
| 3307 | const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); |
| 3308 | |
| 3309 | if (!Base->isVirtual()) |
| 3310 | return HandleLValueDirectBase(Info, E, Obj, Derived: DerivedDecl, Base: BaseDecl); |
| 3311 | |
| 3312 | SubobjectDesignator &D = Obj.Designator; |
| 3313 | if (D.Invalid) |
| 3314 | return false; |
| 3315 | |
| 3316 | // Extract most-derived object and corresponding type. |
| 3317 | // FIXME: After implementing P2280R4 it became possible to get references |
| 3318 | // here. We do MostDerivedType->getAsCXXRecordDecl() in several other |
| 3319 | // locations and if we see crashes in those locations in the future |
| 3320 | // it may make more sense to move this fix into Lvalue::set. |
| 3321 | DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl(); |
| 3322 | if (!CastToDerivedClass(Info, E, Result&: Obj, TruncatedType: DerivedDecl, TruncatedElements: D.MostDerivedPathLength)) |
| 3323 | return false; |
| 3324 | |
| 3325 | // Find the virtual base class. |
| 3326 | if (DerivedDecl->isInvalidDecl()) return false; |
| 3327 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: DerivedDecl); |
| 3328 | Obj.addDecl(Info, E, D: BaseDecl, /*Virtual*/ true); |
| 3329 | Obj.getLValueOffset() += Layout.getVBaseClassOffset(VBase: BaseDecl); |
| 3330 | return true; |
| 3331 | } |
| 3332 | |
| 3333 | static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, |
| 3334 | QualType Type, LValue &Result) { |
| 3335 | for (CastExpr::path_const_iterator PathI = E->path_begin(), |
| 3336 | PathE = E->path_end(); |
| 3337 | PathI != PathE; ++PathI) { |
| 3338 | if (!HandleLValueBase(Info, E, Obj&: Result, DerivedDecl: Type->getAsCXXRecordDecl(), |
| 3339 | Base: *PathI)) |
| 3340 | return false; |
| 3341 | Type = (*PathI)->getType(); |
| 3342 | } |
| 3343 | return true; |
| 3344 | } |
| 3345 | |
| 3346 | /// Cast an lvalue referring to a derived class to a known base subobject. |
| 3347 | static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, |
| 3348 | const CXXRecordDecl *DerivedRD, |
| 3349 | const CXXRecordDecl *BaseRD) { |
| 3350 | CXXBasePaths Paths(/*FindAmbiguities=*/false, |
| 3351 | /*RecordPaths=*/true, /*DetectVirtual=*/false); |
| 3352 | if (!DerivedRD->isDerivedFrom(Base: BaseRD, Paths)) |
| 3353 | llvm_unreachable("Class must be derived from the passed in base class!" ); |
| 3354 | |
| 3355 | for (CXXBasePathElement &Elem : Paths.front()) |
| 3356 | if (!HandleLValueBase(Info, E, Obj&: Result, DerivedDecl: Elem.Class, Base: Elem.Base)) |
| 3357 | return false; |
| 3358 | return true; |
| 3359 | } |
| 3360 | |
| 3361 | /// Update LVal to refer to the given field, which must be a member of the type |
| 3362 | /// currently described by LVal. |
| 3363 | static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, |
| 3364 | const FieldDecl *FD, |
| 3365 | const ASTRecordLayout *RL = nullptr) { |
| 3366 | if (!RL) { |
| 3367 | if (FD->getParent()->isInvalidDecl()) return false; |
| 3368 | RL = &Info.Ctx.getASTRecordLayout(D: FD->getParent()); |
| 3369 | } |
| 3370 | |
| 3371 | unsigned I = FD->getFieldIndex(); |
| 3372 | LVal.addDecl(Info, E, D: FD); |
| 3373 | LVal.adjustOffset(N: Info.Ctx.toCharUnitsFromBits(BitSize: RL->getFieldOffset(FieldNo: I))); |
| 3374 | return true; |
| 3375 | } |
| 3376 | |
| 3377 | /// Update LVal to refer to the given indirect field. |
| 3378 | static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, |
| 3379 | LValue &LVal, |
| 3380 | const IndirectFieldDecl *IFD) { |
| 3381 | for (const auto *C : IFD->chain()) |
| 3382 | if (!HandleLValueMember(Info, E, LVal, FD: cast<FieldDecl>(Val: C))) |
| 3383 | return false; |
| 3384 | return true; |
| 3385 | } |
| 3386 | |
| 3387 | enum class SizeOfType { |
| 3388 | SizeOf, |
| 3389 | DataSizeOf, |
| 3390 | }; |
| 3391 | |
| 3392 | /// Get the size of the given type in char units. |
| 3393 | static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, |
| 3394 | CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) { |
| 3395 | // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc |
| 3396 | // extension. |
| 3397 | if (Type->isVoidType() || Type->isFunctionType()) { |
| 3398 | Size = CharUnits::One(); |
| 3399 | return true; |
| 3400 | } |
| 3401 | |
| 3402 | if (Type->isDependentType()) { |
| 3403 | Info.FFDiag(Loc); |
| 3404 | return false; |
| 3405 | } |
| 3406 | |
| 3407 | if (!Type->isConstantSizeType()) { |
| 3408 | // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. |
| 3409 | // FIXME: Better diagnostic. |
| 3410 | Info.FFDiag(Loc); |
| 3411 | return false; |
| 3412 | } |
| 3413 | |
| 3414 | if (SOT == SizeOfType::SizeOf) |
| 3415 | Size = Info.Ctx.getTypeSizeInChars(T: Type); |
| 3416 | else |
| 3417 | Size = Info.Ctx.getTypeInfoDataSizeInChars(T: Type).Width; |
| 3418 | return true; |
| 3419 | } |
| 3420 | |
| 3421 | /// Update a pointer value to model pointer arithmetic. |
| 3422 | /// \param Info - Information about the ongoing evaluation. |
| 3423 | /// \param E - The expression being evaluated, for diagnostic purposes. |
| 3424 | /// \param LVal - The pointer value to be updated. |
| 3425 | /// \param EltTy - The pointee type represented by LVal. |
| 3426 | /// \param Adjustment - The adjustment, in objects of type EltTy, to add. |
| 3427 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, |
| 3428 | LValue &LVal, QualType EltTy, |
| 3429 | APSInt Adjustment) { |
| 3430 | CharUnits SizeOfPointee; |
| 3431 | if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: EltTy, Size&: SizeOfPointee)) |
| 3432 | return false; |
| 3433 | |
| 3434 | LVal.adjustOffsetAndIndex(Info, E, Index: Adjustment, ElementSize: SizeOfPointee); |
| 3435 | return true; |
| 3436 | } |
| 3437 | |
| 3438 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, |
| 3439 | LValue &LVal, QualType EltTy, |
| 3440 | int64_t Adjustment) { |
| 3441 | return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, |
| 3442 | Adjustment: APSInt::get(X: Adjustment)); |
| 3443 | } |
| 3444 | |
| 3445 | /// Update an lvalue to refer to a component of a complex number. |
| 3446 | /// \param Info - Information about the ongoing evaluation. |
| 3447 | /// \param LVal - The lvalue to be updated. |
| 3448 | /// \param EltTy - The complex number's component type. |
| 3449 | /// \param Imag - False for the real component, true for the imaginary. |
| 3450 | static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, |
| 3451 | LValue &LVal, QualType EltTy, |
| 3452 | bool Imag) { |
| 3453 | if (Imag) { |
| 3454 | CharUnits SizeOfComponent; |
| 3455 | if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: EltTy, Size&: SizeOfComponent)) |
| 3456 | return false; |
| 3457 | LVal.Offset += SizeOfComponent; |
| 3458 | } |
| 3459 | LVal.addComplex(Info, E, EltTy, Imag); |
| 3460 | return true; |
| 3461 | } |
| 3462 | |
| 3463 | static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, |
| 3464 | LValue &LVal, QualType EltTy, |
| 3465 | uint64_t Size, uint64_t Idx) { |
| 3466 | if (Idx) { |
| 3467 | CharUnits SizeOfElement; |
| 3468 | if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: EltTy, Size&: SizeOfElement)) |
| 3469 | return false; |
| 3470 | LVal.Offset += SizeOfElement * Idx; |
| 3471 | } |
| 3472 | LVal.addVectorElement(Info, E, EltTy, Size, Idx); |
| 3473 | return true; |
| 3474 | } |
| 3475 | |
| 3476 | /// Try to evaluate the initializer for a variable declaration. |
| 3477 | /// |
| 3478 | /// \param Info Information about the ongoing evaluation. |
| 3479 | /// \param E An expression to be used when printing diagnostics. |
| 3480 | /// \param VD The variable whose initializer should be obtained. |
| 3481 | /// \param Version The version of the variable within the frame. |
| 3482 | /// \param Frame The frame in which the variable was created. Must be null |
| 3483 | /// if this variable is not local to the evaluation. |
| 3484 | /// \param Result Filled in with a pointer to the value of the variable. |
| 3485 | static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, |
| 3486 | const VarDecl *VD, CallStackFrame *Frame, |
| 3487 | unsigned Version, APValue *&Result) { |
| 3488 | // C++23 [expr.const]p8 If we have a reference type allow unknown references |
| 3489 | // and pointers. |
| 3490 | bool AllowConstexprUnknown = |
| 3491 | Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType(); |
| 3492 | |
| 3493 | APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); |
| 3494 | |
| 3495 | auto CheckUninitReference = [&](bool IsLocalVariable) { |
| 3496 | if (!Result->hasValue() && VD->getType()->isReferenceType()) { |
| 3497 | // C++23 [expr.const]p8 |
| 3498 | // ... For such an object that is not usable in constant expressions, the |
| 3499 | // dynamic type of the object is constexpr-unknown. For such a reference |
| 3500 | // that is not usable in constant expressions, the reference is treated |
| 3501 | // as binding to an unspecified object of the referenced type whose |
| 3502 | // lifetime and that of all subobjects includes the entire constant |
| 3503 | // evaluation and whose dynamic type is constexpr-unknown. |
| 3504 | // |
| 3505 | // Variables that are part of the current evaluation are not |
| 3506 | // constexpr-unknown. |
| 3507 | if (!AllowConstexprUnknown || IsLocalVariable) { |
| 3508 | if (!Info.checkingPotentialConstantExpression()) |
| 3509 | Info.FFDiag(E, DiagId: diag::note_constexpr_use_uninit_reference); |
| 3510 | return false; |
| 3511 | } |
| 3512 | Result = &Info.CurrentCall->createConstexprUnknownAPValues(Key: VD, Base); |
| 3513 | } |
| 3514 | return true; |
| 3515 | }; |
| 3516 | |
| 3517 | // If this is a local variable, dig out its value. |
| 3518 | if (Frame) { |
| 3519 | Result = Frame->getTemporary(Key: VD, Version); |
| 3520 | if (Result) |
| 3521 | return CheckUninitReference(/*IsLocalVariable=*/true); |
| 3522 | |
| 3523 | if (!isa<ParmVarDecl>(Val: VD)) { |
| 3524 | // Assume variables referenced within a lambda's call operator that were |
| 3525 | // not declared within the call operator are captures and during checking |
| 3526 | // of a potential constant expression, assume they are unknown constant |
| 3527 | // expressions. |
| 3528 | assert(isLambdaCallOperator(Frame->Callee) && |
| 3529 | (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && |
| 3530 | "missing value for local variable" ); |
| 3531 | if (Info.checkingPotentialConstantExpression()) |
| 3532 | return false; |
| 3533 | // FIXME: This diagnostic is bogus; we do support captures. Is this code |
| 3534 | // still reachable at all? |
| 3535 | Info.FFDiag(Loc: E->getBeginLoc(), |
| 3536 | DiagId: diag::note_unimplemented_constexpr_lambda_feature_ast) |
| 3537 | << "captures not currently allowed" ; |
| 3538 | return false; |
| 3539 | } |
| 3540 | } |
| 3541 | |
| 3542 | // If we're currently evaluating the initializer of this declaration, use that |
| 3543 | // in-flight value. |
| 3544 | if (Info.EvaluatingDecl == Base) { |
| 3545 | Result = Info.EvaluatingDeclValue; |
| 3546 | return CheckUninitReference(/*IsLocalVariable=*/false); |
| 3547 | } |
| 3548 | |
| 3549 | // P2280R4 struck the restriction that variable of reference type lifetime |
| 3550 | // should begin within the evaluation of E |
| 3551 | // Used to be C++20 [expr.const]p5.12.2: |
| 3552 | // ... its lifetime began within the evaluation of E; |
| 3553 | if (isa<ParmVarDecl>(Val: VD)) { |
| 3554 | if (AllowConstexprUnknown) { |
| 3555 | Result = &Info.CurrentCall->createConstexprUnknownAPValues(Key: VD, Base); |
| 3556 | return true; |
| 3557 | } |
| 3558 | |
| 3559 | // Assume parameters of a potential constant expression are usable in |
| 3560 | // constant expressions. |
| 3561 | if (!Info.checkingPotentialConstantExpression() || |
| 3562 | !Info.CurrentCall->Callee || |
| 3563 | !Info.CurrentCall->Callee->Equals(DC: VD->getDeclContext())) { |
| 3564 | if (Info.getLangOpts().CPlusPlus11) { |
| 3565 | Info.FFDiag(E, DiagId: diag::note_constexpr_function_param_value_unknown) |
| 3566 | << VD; |
| 3567 | NoteLValueLocation(Info, Base); |
| 3568 | } else { |
| 3569 | Info.FFDiag(E); |
| 3570 | } |
| 3571 | } |
| 3572 | return false; |
| 3573 | } |
| 3574 | |
| 3575 | if (E->isValueDependent()) |
| 3576 | return false; |
| 3577 | |
| 3578 | // Dig out the initializer, and use the declaration which it's attached to. |
| 3579 | // FIXME: We should eventually check whether the variable has a reachable |
| 3580 | // initializing declaration. |
| 3581 | const Expr *Init = VD->getAnyInitializer(D&: VD); |
| 3582 | // P2280R4 struck the restriction that variable of reference type should have |
| 3583 | // a preceding initialization. |
| 3584 | // Used to be C++20 [expr.const]p5.12: |
| 3585 | // ... reference has a preceding initialization and either ... |
| 3586 | if (!Init && !AllowConstexprUnknown) { |
| 3587 | // Don't diagnose during potential constant expression checking; an |
| 3588 | // initializer might be added later. |
| 3589 | if (!Info.checkingPotentialConstantExpression()) { |
| 3590 | Info.FFDiag(E, DiagId: diag::note_constexpr_var_init_unknown, ExtraNotes: 1) |
| 3591 | << VD; |
| 3592 | NoteLValueLocation(Info, Base); |
| 3593 | } |
| 3594 | return false; |
| 3595 | } |
| 3596 | |
| 3597 | // P2280R4 struck the initialization requirement for variables of reference |
| 3598 | // type so we can no longer assume we have an Init. |
| 3599 | // Used to be C++20 [expr.const]p5.12: |
| 3600 | // ... reference has a preceding initialization and either ... |
| 3601 | if (Init && Init->isValueDependent()) { |
| 3602 | // The DeclRefExpr is not value-dependent, but the variable it refers to |
| 3603 | // has a value-dependent initializer. This should only happen in |
| 3604 | // constant-folding cases, where the variable is not actually of a suitable |
| 3605 | // type for use in a constant expression (otherwise the DeclRefExpr would |
| 3606 | // have been value-dependent too), so diagnose that. |
| 3607 | assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); |
| 3608 | if (!Info.checkingPotentialConstantExpression()) { |
| 3609 | Info.FFDiag(E, DiagId: Info.getLangOpts().CPlusPlus11 |
| 3610 | ? diag::note_constexpr_ltor_non_constexpr |
| 3611 | : diag::note_constexpr_ltor_non_integral, ExtraNotes: 1) |
| 3612 | << VD << VD->getType(); |
| 3613 | NoteLValueLocation(Info, Base); |
| 3614 | } |
| 3615 | return false; |
| 3616 | } |
| 3617 | |
| 3618 | // Check that we can fold the initializer. In C++, we will have already done |
| 3619 | // this in the cases where it matters for conformance. |
| 3620 | // P2280R4 struck the initialization requirement for variables of reference |
| 3621 | // type so we can no longer assume we have an Init. |
| 3622 | // Used to be C++20 [expr.const]p5.12: |
| 3623 | // ... reference has a preceding initialization and either ... |
| 3624 | if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) { |
| 3625 | Info.FFDiag(E, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << VD; |
| 3626 | NoteLValueLocation(Info, Base); |
| 3627 | return false; |
| 3628 | } |
| 3629 | |
| 3630 | // Check that the variable is actually usable in constant expressions. For a |
| 3631 | // const integral variable or a reference, we might have a non-constant |
| 3632 | // initializer that we can nonetheless evaluate the initializer for. Such |
| 3633 | // variables are not usable in constant expressions. In C++98, the |
| 3634 | // initializer also syntactically needs to be an ICE. |
| 3635 | // |
| 3636 | // FIXME: We don't diagnose cases that aren't potentially usable in constant |
| 3637 | // expressions here; doing so would regress diagnostics for things like |
| 3638 | // reading from a volatile constexpr variable. |
| 3639 | if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && |
| 3640 | VD->mightBeUsableInConstantExpressions(C: Info.Ctx) && |
| 3641 | !AllowConstexprUnknown) || |
| 3642 | ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && |
| 3643 | !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Context: Info.Ctx))) { |
| 3644 | if (Init) { |
| 3645 | Info.CCEDiag(E, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << VD; |
| 3646 | NoteLValueLocation(Info, Base); |
| 3647 | } else { |
| 3648 | Info.CCEDiag(E); |
| 3649 | } |
| 3650 | } |
| 3651 | |
| 3652 | // Never use the initializer of a weak variable, not even for constant |
| 3653 | // folding. We can't be sure that this is the definition that will be used. |
| 3654 | if (VD->isWeak()) { |
| 3655 | Info.FFDiag(E, DiagId: diag::note_constexpr_var_init_weak) << VD; |
| 3656 | NoteLValueLocation(Info, Base); |
| 3657 | return false; |
| 3658 | } |
| 3659 | |
| 3660 | Result = VD->getEvaluatedValue(); |
| 3661 | |
| 3662 | if (!Result) { |
| 3663 | if (AllowConstexprUnknown) |
| 3664 | Result = &Info.CurrentCall->createConstexprUnknownAPValues(Key: VD, Base); |
| 3665 | else |
| 3666 | return false; |
| 3667 | } |
| 3668 | |
| 3669 | return CheckUninitReference(/*IsLocalVariable=*/false); |
| 3670 | } |
| 3671 | |
| 3672 | /// Get the base index of the given base class within an APValue representing |
| 3673 | /// the given derived class. |
| 3674 | static unsigned getBaseIndex(const CXXRecordDecl *Derived, |
| 3675 | const CXXRecordDecl *Base) { |
| 3676 | Base = Base->getCanonicalDecl(); |
| 3677 | unsigned Index = 0; |
| 3678 | for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), |
| 3679 | E = Derived->bases_end(); I != E; ++I, ++Index) { |
| 3680 | if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) |
| 3681 | return Index; |
| 3682 | } |
| 3683 | |
| 3684 | llvm_unreachable("base class missing from derived class's bases list" ); |
| 3685 | } |
| 3686 | |
| 3687 | /// Extract the value of a character from a string literal. |
| 3688 | static APSInt (EvalInfo &Info, const Expr *Lit, |
| 3689 | uint64_t Index) { |
| 3690 | assert(!isa<SourceLocExpr>(Lit) && |
| 3691 | "SourceLocExpr should have already been converted to a StringLiteral" ); |
| 3692 | |
| 3693 | // FIXME: Support MakeStringConstant |
| 3694 | if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Val: Lit)) { |
| 3695 | std::string Str; |
| 3696 | Info.Ctx.getObjCEncodingForType(T: ObjCEnc->getEncodedType(), S&: Str); |
| 3697 | assert(Index <= Str.size() && "Index too large" ); |
| 3698 | return APSInt::getUnsigned(X: Str.c_str()[Index]); |
| 3699 | } |
| 3700 | |
| 3701 | if (auto PE = dyn_cast<PredefinedExpr>(Val: Lit)) |
| 3702 | Lit = PE->getFunctionName(); |
| 3703 | const StringLiteral *S = cast<StringLiteral>(Val: Lit); |
| 3704 | const ConstantArrayType *CAT = |
| 3705 | Info.Ctx.getAsConstantArrayType(T: S->getType()); |
| 3706 | assert(CAT && "string literal isn't an array" ); |
| 3707 | QualType CharType = CAT->getElementType(); |
| 3708 | assert(CharType->isIntegerType() && "unexpected character type" ); |
| 3709 | APSInt Value(Info.Ctx.getTypeSize(T: CharType), |
| 3710 | CharType->isUnsignedIntegerType()); |
| 3711 | if (Index < S->getLength()) |
| 3712 | Value = S->getCodeUnit(i: Index); |
| 3713 | return Value; |
| 3714 | } |
| 3715 | |
| 3716 | // Expand a string literal into an array of characters. |
| 3717 | // |
| 3718 | // FIXME: This is inefficient; we should probably introduce something similar |
| 3719 | // to the LLVM ConstantDataArray to make this cheaper. |
| 3720 | static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, |
| 3721 | APValue &Result, |
| 3722 | QualType AllocType = QualType()) { |
| 3723 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( |
| 3724 | T: AllocType.isNull() ? S->getType() : AllocType); |
| 3725 | assert(CAT && "string literal isn't an array" ); |
| 3726 | QualType CharType = CAT->getElementType(); |
| 3727 | assert(CharType->isIntegerType() && "unexpected character type" ); |
| 3728 | |
| 3729 | unsigned Elts = CAT->getZExtSize(); |
| 3730 | Result = APValue(APValue::UninitArray(), |
| 3731 | std::min(a: S->getLength(), b: Elts), Elts); |
| 3732 | APSInt Value(Info.Ctx.getTypeSize(T: CharType), |
| 3733 | CharType->isUnsignedIntegerType()); |
| 3734 | if (Result.hasArrayFiller()) |
| 3735 | Result.getArrayFiller() = APValue(Value); |
| 3736 | for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { |
| 3737 | Value = S->getCodeUnit(i: I); |
| 3738 | Result.getArrayInitializedElt(I) = APValue(Value); |
| 3739 | } |
| 3740 | } |
| 3741 | |
| 3742 | // Expand an array so that it has more than Index filled elements. |
| 3743 | static void expandArray(APValue &Array, unsigned Index) { |
| 3744 | unsigned Size = Array.getArraySize(); |
| 3745 | assert(Index < Size); |
| 3746 | |
| 3747 | // Always at least double the number of elements for which we store a value. |
| 3748 | unsigned OldElts = Array.getArrayInitializedElts(); |
| 3749 | unsigned NewElts = std::max(a: Index+1, b: OldElts * 2); |
| 3750 | NewElts = std::min(a: Size, b: std::max(a: NewElts, b: 8u)); |
| 3751 | |
| 3752 | // Copy the data across. |
| 3753 | APValue NewValue(APValue::UninitArray(), NewElts, Size); |
| 3754 | for (unsigned I = 0; I != OldElts; ++I) |
| 3755 | NewValue.getArrayInitializedElt(I).swap(RHS&: Array.getArrayInitializedElt(I)); |
| 3756 | for (unsigned I = OldElts; I != NewElts; ++I) |
| 3757 | NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); |
| 3758 | if (NewValue.hasArrayFiller()) |
| 3759 | NewValue.getArrayFiller() = Array.getArrayFiller(); |
| 3760 | Array.swap(RHS&: NewValue); |
| 3761 | } |
| 3762 | |
| 3763 | /// Determine whether a type would actually be read by an lvalue-to-rvalue |
| 3764 | /// conversion. If it's of class type, we may assume that the copy operation |
| 3765 | /// is trivial. Note that this is never true for a union type with fields |
| 3766 | /// (because the copy always "reads" the active member) and always true for |
| 3767 | /// a non-class type. |
| 3768 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); |
| 3769 | static bool isReadByLvalueToRvalueConversion(QualType T) { |
| 3770 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
| 3771 | return !RD || isReadByLvalueToRvalueConversion(RD); |
| 3772 | } |
| 3773 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { |
| 3774 | // FIXME: A trivial copy of a union copies the object representation, even if |
| 3775 | // the union is empty. |
| 3776 | if (RD->isUnion()) |
| 3777 | return !RD->field_empty(); |
| 3778 | if (RD->isEmpty()) |
| 3779 | return false; |
| 3780 | |
| 3781 | for (auto *Field : RD->fields()) |
| 3782 | if (!Field->isUnnamedBitField() && |
| 3783 | isReadByLvalueToRvalueConversion(T: Field->getType())) |
| 3784 | return true; |
| 3785 | |
| 3786 | for (auto &BaseSpec : RD->bases()) |
| 3787 | if (isReadByLvalueToRvalueConversion(T: BaseSpec.getType())) |
| 3788 | return true; |
| 3789 | |
| 3790 | return false; |
| 3791 | } |
| 3792 | |
| 3793 | /// Diagnose an attempt to read from any unreadable field within the specified |
| 3794 | /// type, which might be a class type. |
| 3795 | static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, |
| 3796 | QualType T) { |
| 3797 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
| 3798 | if (!RD) |
| 3799 | return false; |
| 3800 | |
| 3801 | if (!RD->hasMutableFields()) |
| 3802 | return false; |
| 3803 | |
| 3804 | for (auto *Field : RD->fields()) { |
| 3805 | // If we're actually going to read this field in some way, then it can't |
| 3806 | // be mutable. If we're in a union, then assigning to a mutable field |
| 3807 | // (even an empty one) can change the active member, so that's not OK. |
| 3808 | // FIXME: Add core issue number for the union case. |
| 3809 | if (Field->isMutable() && |
| 3810 | (RD->isUnion() || isReadByLvalueToRvalueConversion(T: Field->getType()))) { |
| 3811 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_mutable, ExtraNotes: 1) << AK << Field; |
| 3812 | Info.Note(Loc: Field->getLocation(), DiagId: diag::note_declared_at); |
| 3813 | return true; |
| 3814 | } |
| 3815 | |
| 3816 | if (diagnoseMutableFields(Info, E, AK, T: Field->getType())) |
| 3817 | return true; |
| 3818 | } |
| 3819 | |
| 3820 | for (auto &BaseSpec : RD->bases()) |
| 3821 | if (diagnoseMutableFields(Info, E, AK, T: BaseSpec.getType())) |
| 3822 | return true; |
| 3823 | |
| 3824 | // All mutable fields were empty, and thus not actually read. |
| 3825 | return false; |
| 3826 | } |
| 3827 | |
| 3828 | static bool lifetimeStartedInEvaluation(EvalInfo &Info, |
| 3829 | APValue::LValueBase Base, |
| 3830 | bool MutableSubobject = false) { |
| 3831 | // A temporary or transient heap allocation we created. |
| 3832 | if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) |
| 3833 | return true; |
| 3834 | |
| 3835 | switch (Info.IsEvaluatingDecl) { |
| 3836 | case EvalInfo::EvaluatingDeclKind::None: |
| 3837 | return false; |
| 3838 | |
| 3839 | case EvalInfo::EvaluatingDeclKind::Ctor: |
| 3840 | // The variable whose initializer we're evaluating. |
| 3841 | if (Info.EvaluatingDecl == Base) |
| 3842 | return true; |
| 3843 | |
| 3844 | // A temporary lifetime-extended by the variable whose initializer we're |
| 3845 | // evaluating. |
| 3846 | if (auto *BaseE = Base.dyn_cast<const Expr *>()) |
| 3847 | if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(Val: BaseE)) |
| 3848 | return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); |
| 3849 | return false; |
| 3850 | |
| 3851 | case EvalInfo::EvaluatingDeclKind::Dtor: |
| 3852 | // C++2a [expr.const]p6: |
| 3853 | // [during constant destruction] the lifetime of a and its non-mutable |
| 3854 | // subobjects (but not its mutable subobjects) [are] considered to start |
| 3855 | // within e. |
| 3856 | if (MutableSubobject || Base != Info.EvaluatingDecl) |
| 3857 | return false; |
| 3858 | // FIXME: We can meaningfully extend this to cover non-const objects, but |
| 3859 | // we will need special handling: we should be able to access only |
| 3860 | // subobjects of such objects that are themselves declared const. |
| 3861 | QualType T = getType(B: Base); |
| 3862 | return T.isConstQualified() || T->isReferenceType(); |
| 3863 | } |
| 3864 | |
| 3865 | llvm_unreachable("unknown evaluating decl kind" ); |
| 3866 | } |
| 3867 | |
| 3868 | static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, |
| 3869 | SourceLocation CallLoc = {}) { |
| 3870 | return Info.CheckArraySize( |
| 3871 | Loc: CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc, |
| 3872 | BitWidth: CAT->getNumAddressingBits(Context: Info.Ctx), ElemCount: CAT->getZExtSize(), |
| 3873 | /*Diag=*/true); |
| 3874 | } |
| 3875 | |
| 3876 | namespace { |
| 3877 | /// A handle to a complete object (an object that is not a subobject of |
| 3878 | /// another object). |
| 3879 | struct CompleteObject { |
| 3880 | /// The identity of the object. |
| 3881 | APValue::LValueBase Base; |
| 3882 | /// The value of the complete object. |
| 3883 | APValue *Value; |
| 3884 | /// The type of the complete object. |
| 3885 | QualType Type; |
| 3886 | |
| 3887 | CompleteObject() : Value(nullptr) {} |
| 3888 | CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) |
| 3889 | : Base(Base), Value(Value), Type(Type) {} |
| 3890 | |
| 3891 | bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { |
| 3892 | // If this isn't a "real" access (eg, if it's just accessing the type |
| 3893 | // info), allow it. We assume the type doesn't change dynamically for |
| 3894 | // subobjects of constexpr objects (even though we'd hit UB here if it |
| 3895 | // did). FIXME: Is this right? |
| 3896 | if (!isAnyAccess(AK)) |
| 3897 | return true; |
| 3898 | |
| 3899 | // In C++14 onwards, it is permitted to read a mutable member whose |
| 3900 | // lifetime began within the evaluation. |
| 3901 | // FIXME: Should we also allow this in C++11? |
| 3902 | if (!Info.getLangOpts().CPlusPlus14 && |
| 3903 | AK != AccessKinds::AK_IsWithinLifetime) |
| 3904 | return false; |
| 3905 | return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); |
| 3906 | } |
| 3907 | |
| 3908 | explicit operator bool() const { return !Type.isNull(); } |
| 3909 | }; |
| 3910 | } // end anonymous namespace |
| 3911 | |
| 3912 | static QualType getSubobjectType(QualType ObjType, QualType SubobjType, |
| 3913 | bool IsMutable = false) { |
| 3914 | // C++ [basic.type.qualifier]p1: |
| 3915 | // - A const object is an object of type const T or a non-mutable subobject |
| 3916 | // of a const object. |
| 3917 | if (ObjType.isConstQualified() && !IsMutable) |
| 3918 | SubobjType.addConst(); |
| 3919 | // - A volatile object is an object of type const T or a subobject of a |
| 3920 | // volatile object. |
| 3921 | if (ObjType.isVolatileQualified()) |
| 3922 | SubobjType.addVolatile(); |
| 3923 | return SubobjType; |
| 3924 | } |
| 3925 | |
| 3926 | /// Find the designated sub-object of an rvalue. |
| 3927 | template <typename SubobjectHandler> |
| 3928 | static typename SubobjectHandler::result_type |
| 3929 | findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, |
| 3930 | const SubobjectDesignator &Sub, SubobjectHandler &handler) { |
| 3931 | if (Sub.Invalid) |
| 3932 | // A diagnostic will have already been produced. |
| 3933 | return handler.failed(); |
| 3934 | if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { |
| 3935 | if (Info.getLangOpts().CPlusPlus11) |
| 3936 | Info.FFDiag(E, DiagId: Sub.isOnePastTheEnd() |
| 3937 | ? diag::note_constexpr_access_past_end |
| 3938 | : diag::note_constexpr_access_unsized_array) |
| 3939 | << handler.AccessKind; |
| 3940 | else |
| 3941 | Info.FFDiag(E); |
| 3942 | return handler.failed(); |
| 3943 | } |
| 3944 | |
| 3945 | APValue *O = Obj.Value; |
| 3946 | QualType ObjType = Obj.Type; |
| 3947 | const FieldDecl *LastField = nullptr; |
| 3948 | const FieldDecl *VolatileField = nullptr; |
| 3949 | |
| 3950 | // C++23 [expr.const]p8 If we have an unknown reference or pointers and it |
| 3951 | // does not have a value then bail out. |
| 3952 | if (O->allowConstexprUnknown() && !O->hasValue()) |
| 3953 | return false; |
| 3954 | |
| 3955 | // Walk the designator's path to find the subobject. |
| 3956 | for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { |
| 3957 | // Reading an indeterminate value is undefined, but assigning over one is OK. |
| 3958 | if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || |
| 3959 | (O->isIndeterminate() && |
| 3960 | !isValidIndeterminateAccess(handler.AccessKind))) { |
| 3961 | // Object has ended lifetime. |
| 3962 | // If I is non-zero, some subobject (member or array element) of a |
| 3963 | // complete object has ended its lifetime, so this is valid for |
| 3964 | // IsWithinLifetime, resulting in false. |
| 3965 | if (I != 0 && handler.AccessKind == AK_IsWithinLifetime) |
| 3966 | return false; |
| 3967 | if (!Info.checkingPotentialConstantExpression()) |
| 3968 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_uninit) |
| 3969 | << handler.AccessKind << O->isIndeterminate() |
| 3970 | << E->getSourceRange(); |
| 3971 | return handler.failed(); |
| 3972 | } |
| 3973 | |
| 3974 | // C++ [class.ctor]p5, C++ [class.dtor]p5: |
| 3975 | // const and volatile semantics are not applied on an object under |
| 3976 | // {con,de}struction. |
| 3977 | if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && |
| 3978 | ObjType->isRecordType() && |
| 3979 | Info.isEvaluatingCtorDtor( |
| 3980 | Base: Obj.Base, Path: ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) != |
| 3981 | ConstructionPhase::None) { |
| 3982 | ObjType = Info.Ctx.getCanonicalType(T: ObjType); |
| 3983 | ObjType.removeLocalConst(); |
| 3984 | ObjType.removeLocalVolatile(); |
| 3985 | } |
| 3986 | |
| 3987 | // If this is our last pass, check that the final object type is OK. |
| 3988 | if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { |
| 3989 | // Accesses to volatile objects are prohibited. |
| 3990 | if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { |
| 3991 | if (Info.getLangOpts().CPlusPlus) { |
| 3992 | int DiagKind; |
| 3993 | SourceLocation Loc; |
| 3994 | const NamedDecl *Decl = nullptr; |
| 3995 | if (VolatileField) { |
| 3996 | DiagKind = 2; |
| 3997 | Loc = VolatileField->getLocation(); |
| 3998 | Decl = VolatileField; |
| 3999 | } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { |
| 4000 | DiagKind = 1; |
| 4001 | Loc = VD->getLocation(); |
| 4002 | Decl = VD; |
| 4003 | } else { |
| 4004 | DiagKind = 0; |
| 4005 | if (auto *E = Obj.Base.dyn_cast<const Expr *>()) |
| 4006 | Loc = E->getExprLoc(); |
| 4007 | } |
| 4008 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_volatile_obj, ExtraNotes: 1) |
| 4009 | << handler.AccessKind << DiagKind << Decl; |
| 4010 | Info.Note(Loc, DiagId: diag::note_constexpr_volatile_here) << DiagKind; |
| 4011 | } else { |
| 4012 | Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 4013 | } |
| 4014 | return handler.failed(); |
| 4015 | } |
| 4016 | |
| 4017 | // If we are reading an object of class type, there may still be more |
| 4018 | // things we need to check: if there are any mutable subobjects, we |
| 4019 | // cannot perform this read. (This only happens when performing a trivial |
| 4020 | // copy or assignment.) |
| 4021 | if (ObjType->isRecordType() && |
| 4022 | !Obj.mayAccessMutableMembers(Info, AK: handler.AccessKind) && |
| 4023 | diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) |
| 4024 | return handler.failed(); |
| 4025 | } |
| 4026 | |
| 4027 | if (I == N) { |
| 4028 | if (!handler.found(*O, ObjType)) |
| 4029 | return false; |
| 4030 | |
| 4031 | // If we modified a bit-field, truncate it to the right width. |
| 4032 | if (isModification(handler.AccessKind) && |
| 4033 | LastField && LastField->isBitField() && |
| 4034 | !truncateBitfieldValue(Info, E, Value&: *O, FD: LastField)) |
| 4035 | return false; |
| 4036 | |
| 4037 | return true; |
| 4038 | } |
| 4039 | |
| 4040 | LastField = nullptr; |
| 4041 | if (ObjType->isArrayType()) { |
| 4042 | // Next subobject is an array element. |
| 4043 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T: ObjType); |
| 4044 | assert(CAT && "vla in literal type?" ); |
| 4045 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); |
| 4046 | if (CAT->getSize().ule(RHS: Index)) { |
| 4047 | // Note, it should not be possible to form a pointer with a valid |
| 4048 | // designator which points more than one past the end of the array. |
| 4049 | if (Info.getLangOpts().CPlusPlus11) |
| 4050 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_past_end) |
| 4051 | << handler.AccessKind; |
| 4052 | else |
| 4053 | Info.FFDiag(E); |
| 4054 | return handler.failed(); |
| 4055 | } |
| 4056 | |
| 4057 | ObjType = CAT->getElementType(); |
| 4058 | |
| 4059 | if (O->getArrayInitializedElts() > Index) |
| 4060 | O = &O->getArrayInitializedElt(I: Index); |
| 4061 | else if (!isRead(handler.AccessKind)) { |
| 4062 | if (!CheckArraySize(Info, CAT, CallLoc: E->getExprLoc())) |
| 4063 | return handler.failed(); |
| 4064 | |
| 4065 | expandArray(Array&: *O, Index); |
| 4066 | O = &O->getArrayInitializedElt(I: Index); |
| 4067 | } else |
| 4068 | O = &O->getArrayFiller(); |
| 4069 | } else if (ObjType->isAnyComplexType()) { |
| 4070 | // Next subobject is a complex number. |
| 4071 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); |
| 4072 | if (Index > 1) { |
| 4073 | if (Info.getLangOpts().CPlusPlus11) |
| 4074 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_past_end) |
| 4075 | << handler.AccessKind; |
| 4076 | else |
| 4077 | Info.FFDiag(E); |
| 4078 | return handler.failed(); |
| 4079 | } |
| 4080 | |
| 4081 | ObjType = getSubobjectType( |
| 4082 | ObjType, SubobjType: ObjType->castAs<ComplexType>()->getElementType()); |
| 4083 | |
| 4084 | assert(I == N - 1 && "extracting subobject of scalar?" ); |
| 4085 | if (O->isComplexInt()) { |
| 4086 | return handler.found(Index ? O->getComplexIntImag() |
| 4087 | : O->getComplexIntReal(), ObjType); |
| 4088 | } else { |
| 4089 | assert(O->isComplexFloat()); |
| 4090 | return handler.found(Index ? O->getComplexFloatImag() |
| 4091 | : O->getComplexFloatReal(), ObjType); |
| 4092 | } |
| 4093 | } else if (const auto *VT = ObjType->getAs<VectorType>()) { |
| 4094 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); |
| 4095 | unsigned NumElements = VT->getNumElements(); |
| 4096 | if (Index == NumElements) { |
| 4097 | if (Info.getLangOpts().CPlusPlus11) |
| 4098 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_past_end) |
| 4099 | << handler.AccessKind; |
| 4100 | else |
| 4101 | Info.FFDiag(E); |
| 4102 | return handler.failed(); |
| 4103 | } |
| 4104 | |
| 4105 | if (Index > NumElements) { |
| 4106 | Info.CCEDiag(E, DiagId: diag::note_constexpr_array_index) |
| 4107 | << Index << /*array*/ 0 << NumElements; |
| 4108 | return handler.failed(); |
| 4109 | } |
| 4110 | |
| 4111 | ObjType = VT->getElementType(); |
| 4112 | assert(I == N - 1 && "extracting subobject of scalar?" ); |
| 4113 | return handler.found(O->getVectorElt(I: Index), ObjType); |
| 4114 | } else if (const FieldDecl *Field = getAsField(E: Sub.Entries[I])) { |
| 4115 | if (Field->isMutable() && |
| 4116 | !Obj.mayAccessMutableMembers(Info, AK: handler.AccessKind)) { |
| 4117 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_mutable, ExtraNotes: 1) |
| 4118 | << handler.AccessKind << Field; |
| 4119 | Info.Note(Loc: Field->getLocation(), DiagId: diag::note_declared_at); |
| 4120 | return handler.failed(); |
| 4121 | } |
| 4122 | |
| 4123 | // Next subobject is a class, struct or union field. |
| 4124 | RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); |
| 4125 | if (RD->isUnion()) { |
| 4126 | const FieldDecl *UnionField = O->getUnionField(); |
| 4127 | if (!UnionField || |
| 4128 | UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { |
| 4129 | if (I == N - 1 && handler.AccessKind == AK_Construct) { |
| 4130 | // Placement new onto an inactive union member makes it active. |
| 4131 | O->setUnion(Field, Value: APValue()); |
| 4132 | } else { |
| 4133 | // Pointer to/into inactive union member: Not within lifetime |
| 4134 | if (handler.AccessKind == AK_IsWithinLifetime) |
| 4135 | return false; |
| 4136 | // FIXME: If O->getUnionValue() is absent, report that there's no |
| 4137 | // active union member rather than reporting the prior active union |
| 4138 | // member. We'll need to fix nullptr_t to not use APValue() as its |
| 4139 | // representation first. |
| 4140 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_inactive_union_member) |
| 4141 | << handler.AccessKind << Field << !UnionField << UnionField; |
| 4142 | return handler.failed(); |
| 4143 | } |
| 4144 | } |
| 4145 | O = &O->getUnionValue(); |
| 4146 | } else |
| 4147 | O = &O->getStructField(i: Field->getFieldIndex()); |
| 4148 | |
| 4149 | ObjType = getSubobjectType(ObjType, SubobjType: Field->getType(), IsMutable: Field->isMutable()); |
| 4150 | LastField = Field; |
| 4151 | if (Field->getType().isVolatileQualified()) |
| 4152 | VolatileField = Field; |
| 4153 | } else { |
| 4154 | // Next subobject is a base class. |
| 4155 | const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); |
| 4156 | const CXXRecordDecl *Base = getAsBaseClass(E: Sub.Entries[I]); |
| 4157 | O = &O->getStructBase(i: getBaseIndex(Derived, Base)); |
| 4158 | |
| 4159 | ObjType = getSubobjectType(ObjType, SubobjType: Info.Ctx.getRecordType(Decl: Base)); |
| 4160 | } |
| 4161 | } |
| 4162 | } |
| 4163 | |
| 4164 | namespace { |
| 4165 | struct ExtractSubobjectHandler { |
| 4166 | EvalInfo &Info; |
| 4167 | const Expr *E; |
| 4168 | APValue &Result; |
| 4169 | const AccessKinds AccessKind; |
| 4170 | |
| 4171 | typedef bool result_type; |
| 4172 | bool failed() { return false; } |
| 4173 | bool found(APValue &Subobj, QualType SubobjType) { |
| 4174 | Result = Subobj; |
| 4175 | if (AccessKind == AK_ReadObjectRepresentation) |
| 4176 | return true; |
| 4177 | return CheckFullyInitialized(Info, DiagLoc: E->getExprLoc(), Type: SubobjType, Value: Result); |
| 4178 | } |
| 4179 | bool found(APSInt &Value, QualType SubobjType) { |
| 4180 | Result = APValue(Value); |
| 4181 | return true; |
| 4182 | } |
| 4183 | bool found(APFloat &Value, QualType SubobjType) { |
| 4184 | Result = APValue(Value); |
| 4185 | return true; |
| 4186 | } |
| 4187 | }; |
| 4188 | } // end anonymous namespace |
| 4189 | |
| 4190 | /// Extract the designated sub-object of an rvalue. |
| 4191 | static bool (EvalInfo &Info, const Expr *E, |
| 4192 | const CompleteObject &Obj, |
| 4193 | const SubobjectDesignator &Sub, APValue &Result, |
| 4194 | AccessKinds AK = AK_Read) { |
| 4195 | assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); |
| 4196 | ExtractSubobjectHandler Handler = {.Info: Info, .E: E, .Result: Result, .AccessKind: AK}; |
| 4197 | return findSubobject(Info, E, Obj, Sub, handler&: Handler); |
| 4198 | } |
| 4199 | |
| 4200 | namespace { |
| 4201 | struct ModifySubobjectHandler { |
| 4202 | EvalInfo &Info; |
| 4203 | APValue &NewVal; |
| 4204 | const Expr *E; |
| 4205 | |
| 4206 | typedef bool result_type; |
| 4207 | static const AccessKinds AccessKind = AK_Assign; |
| 4208 | |
| 4209 | bool checkConst(QualType QT) { |
| 4210 | // Assigning to a const object has undefined behavior. |
| 4211 | if (QT.isConstQualified()) { |
| 4212 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_const_type) << QT; |
| 4213 | return false; |
| 4214 | } |
| 4215 | return true; |
| 4216 | } |
| 4217 | |
| 4218 | bool failed() { return false; } |
| 4219 | bool found(APValue &Subobj, QualType SubobjType) { |
| 4220 | if (!checkConst(QT: SubobjType)) |
| 4221 | return false; |
| 4222 | // We've been given ownership of NewVal, so just swap it in. |
| 4223 | Subobj.swap(RHS&: NewVal); |
| 4224 | return true; |
| 4225 | } |
| 4226 | bool found(APSInt &Value, QualType SubobjType) { |
| 4227 | if (!checkConst(QT: SubobjType)) |
| 4228 | return false; |
| 4229 | if (!NewVal.isInt()) { |
| 4230 | // Maybe trying to write a cast pointer value into a complex? |
| 4231 | Info.FFDiag(E); |
| 4232 | return false; |
| 4233 | } |
| 4234 | Value = NewVal.getInt(); |
| 4235 | return true; |
| 4236 | } |
| 4237 | bool found(APFloat &Value, QualType SubobjType) { |
| 4238 | if (!checkConst(QT: SubobjType)) |
| 4239 | return false; |
| 4240 | Value = NewVal.getFloat(); |
| 4241 | return true; |
| 4242 | } |
| 4243 | }; |
| 4244 | } // end anonymous namespace |
| 4245 | |
| 4246 | const AccessKinds ModifySubobjectHandler::AccessKind; |
| 4247 | |
| 4248 | /// Update the designated sub-object of an rvalue to the given value. |
| 4249 | static bool modifySubobject(EvalInfo &Info, const Expr *E, |
| 4250 | const CompleteObject &Obj, |
| 4251 | const SubobjectDesignator &Sub, |
| 4252 | APValue &NewVal) { |
| 4253 | ModifySubobjectHandler Handler = { .Info: Info, .NewVal: NewVal, .E: E }; |
| 4254 | return findSubobject(Info, E, Obj, Sub, handler&: Handler); |
| 4255 | } |
| 4256 | |
| 4257 | /// Find the position where two subobject designators diverge, or equivalently |
| 4258 | /// the length of the common initial subsequence. |
| 4259 | static unsigned FindDesignatorMismatch(QualType ObjType, |
| 4260 | const SubobjectDesignator &A, |
| 4261 | const SubobjectDesignator &B, |
| 4262 | bool &WasArrayIndex) { |
| 4263 | unsigned I = 0, N = std::min(a: A.Entries.size(), b: B.Entries.size()); |
| 4264 | for (/**/; I != N; ++I) { |
| 4265 | if (!ObjType.isNull() && |
| 4266 | (ObjType->isArrayType() || ObjType->isAnyComplexType())) { |
| 4267 | // Next subobject is an array element. |
| 4268 | if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { |
| 4269 | WasArrayIndex = true; |
| 4270 | return I; |
| 4271 | } |
| 4272 | if (ObjType->isAnyComplexType()) |
| 4273 | ObjType = ObjType->castAs<ComplexType>()->getElementType(); |
| 4274 | else |
| 4275 | ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); |
| 4276 | } else { |
| 4277 | if (A.Entries[I].getAsBaseOrMember() != |
| 4278 | B.Entries[I].getAsBaseOrMember()) { |
| 4279 | WasArrayIndex = false; |
| 4280 | return I; |
| 4281 | } |
| 4282 | if (const FieldDecl *FD = getAsField(E: A.Entries[I])) |
| 4283 | // Next subobject is a field. |
| 4284 | ObjType = FD->getType(); |
| 4285 | else |
| 4286 | // Next subobject is a base class. |
| 4287 | ObjType = QualType(); |
| 4288 | } |
| 4289 | } |
| 4290 | WasArrayIndex = false; |
| 4291 | return I; |
| 4292 | } |
| 4293 | |
| 4294 | /// Determine whether the given subobject designators refer to elements of the |
| 4295 | /// same array object. |
| 4296 | static bool AreElementsOfSameArray(QualType ObjType, |
| 4297 | const SubobjectDesignator &A, |
| 4298 | const SubobjectDesignator &B) { |
| 4299 | if (A.Entries.size() != B.Entries.size()) |
| 4300 | return false; |
| 4301 | |
| 4302 | bool IsArray = A.MostDerivedIsArrayElement; |
| 4303 | if (IsArray && A.MostDerivedPathLength != A.Entries.size()) |
| 4304 | // A is a subobject of the array element. |
| 4305 | return false; |
| 4306 | |
| 4307 | // If A (and B) designates an array element, the last entry will be the array |
| 4308 | // index. That doesn't have to match. Otherwise, we're in the 'implicit array |
| 4309 | // of length 1' case, and the entire path must match. |
| 4310 | bool WasArrayIndex; |
| 4311 | unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); |
| 4312 | return CommonLength >= A.Entries.size() - IsArray; |
| 4313 | } |
| 4314 | |
| 4315 | /// Find the complete object to which an LValue refers. |
| 4316 | static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, |
| 4317 | AccessKinds AK, const LValue &LVal, |
| 4318 | QualType LValType) { |
| 4319 | if (LVal.InvalidBase) { |
| 4320 | Info.FFDiag(E); |
| 4321 | return CompleteObject(); |
| 4322 | } |
| 4323 | |
| 4324 | if (!LVal.Base) { |
| 4325 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_null) << AK; |
| 4326 | return CompleteObject(); |
| 4327 | } |
| 4328 | |
| 4329 | CallStackFrame *Frame = nullptr; |
| 4330 | unsigned Depth = 0; |
| 4331 | if (LVal.getLValueCallIndex()) { |
| 4332 | std::tie(args&: Frame, args&: Depth) = |
| 4333 | Info.getCallFrameAndDepth(CallIndex: LVal.getLValueCallIndex()); |
| 4334 | if (!Frame) { |
| 4335 | Info.FFDiag(E, DiagId: diag::note_constexpr_lifetime_ended, ExtraNotes: 1) |
| 4336 | << AK << LVal.Base.is<const ValueDecl*>(); |
| 4337 | NoteLValueLocation(Info, Base: LVal.Base); |
| 4338 | return CompleteObject(); |
| 4339 | } |
| 4340 | } |
| 4341 | |
| 4342 | bool IsAccess = isAnyAccess(AK); |
| 4343 | |
| 4344 | // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type |
| 4345 | // is not a constant expression (even if the object is non-volatile). We also |
| 4346 | // apply this rule to C++98, in order to conform to the expected 'volatile' |
| 4347 | // semantics. |
| 4348 | if (isFormalAccess(AK) && LValType.isVolatileQualified()) { |
| 4349 | if (Info.getLangOpts().CPlusPlus) |
| 4350 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_volatile_type) |
| 4351 | << AK << LValType; |
| 4352 | else |
| 4353 | Info.FFDiag(E); |
| 4354 | return CompleteObject(); |
| 4355 | } |
| 4356 | |
| 4357 | // Compute value storage location and type of base object. |
| 4358 | APValue *BaseVal = nullptr; |
| 4359 | QualType BaseType = getType(B: LVal.Base); |
| 4360 | |
| 4361 | if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && |
| 4362 | lifetimeStartedInEvaluation(Info, Base: LVal.Base)) { |
| 4363 | // This is the object whose initializer we're evaluating, so its lifetime |
| 4364 | // started in the current evaluation. |
| 4365 | BaseVal = Info.EvaluatingDeclValue; |
| 4366 | } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { |
| 4367 | // Allow reading from a GUID declaration. |
| 4368 | if (auto *GD = dyn_cast<MSGuidDecl>(Val: D)) { |
| 4369 | if (isModification(AK)) { |
| 4370 | // All the remaining cases do not permit modification of the object. |
| 4371 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global); |
| 4372 | return CompleteObject(); |
| 4373 | } |
| 4374 | APValue &V = GD->getAsAPValue(); |
| 4375 | if (V.isAbsent()) { |
| 4376 | Info.FFDiag(E, DiagId: diag::note_constexpr_unsupported_layout) |
| 4377 | << GD->getType(); |
| 4378 | return CompleteObject(); |
| 4379 | } |
| 4380 | return CompleteObject(LVal.Base, &V, GD->getType()); |
| 4381 | } |
| 4382 | |
| 4383 | // Allow reading the APValue from an UnnamedGlobalConstantDecl. |
| 4384 | if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(Val: D)) { |
| 4385 | if (isModification(AK)) { |
| 4386 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global); |
| 4387 | return CompleteObject(); |
| 4388 | } |
| 4389 | return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), |
| 4390 | GCD->getType()); |
| 4391 | } |
| 4392 | |
| 4393 | // Allow reading from template parameter objects. |
| 4394 | if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: D)) { |
| 4395 | if (isModification(AK)) { |
| 4396 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global); |
| 4397 | return CompleteObject(); |
| 4398 | } |
| 4399 | return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), |
| 4400 | TPO->getType()); |
| 4401 | } |
| 4402 | |
| 4403 | // In C++98, const, non-volatile integers initialized with ICEs are ICEs. |
| 4404 | // In C++11, constexpr, non-volatile variables initialized with constant |
| 4405 | // expressions are constant expressions too. Inside constexpr functions, |
| 4406 | // parameters are constant expressions even if they're non-const. |
| 4407 | // In C++1y, objects local to a constant expression (those with a Frame) are |
| 4408 | // both readable and writable inside constant expressions. |
| 4409 | // In C, such things can also be folded, although they are not ICEs. |
| 4410 | const VarDecl *VD = dyn_cast<VarDecl>(Val: D); |
| 4411 | if (VD) { |
| 4412 | if (const VarDecl *VDef = VD->getDefinition(C&: Info.Ctx)) |
| 4413 | VD = VDef; |
| 4414 | } |
| 4415 | if (!VD || VD->isInvalidDecl()) { |
| 4416 | Info.FFDiag(E); |
| 4417 | return CompleteObject(); |
| 4418 | } |
| 4419 | |
| 4420 | bool IsConstant = BaseType.isConstant(Ctx: Info.Ctx); |
| 4421 | bool ConstexprVar = false; |
| 4422 | if (const auto *VD = dyn_cast_if_present<VarDecl>( |
| 4423 | Val: Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) |
| 4424 | ConstexprVar = VD->isConstexpr(); |
| 4425 | |
| 4426 | // Unless we're looking at a local variable or argument in a constexpr call, |
| 4427 | // the variable we're reading must be const. |
| 4428 | if (!Frame) { |
| 4429 | if (IsAccess && isa<ParmVarDecl>(Val: VD)) { |
| 4430 | // Access of a parameter that's not associated with a frame isn't going |
| 4431 | // to work out, but we can leave it to evaluateVarDeclInit to provide a |
| 4432 | // suitable diagnostic. |
| 4433 | } else if (Info.getLangOpts().CPlusPlus14 && |
| 4434 | lifetimeStartedInEvaluation(Info, Base: LVal.Base)) { |
| 4435 | // OK, we can read and modify an object if we're in the process of |
| 4436 | // evaluating its initializer, because its lifetime began in this |
| 4437 | // evaluation. |
| 4438 | } else if (isModification(AK)) { |
| 4439 | // All the remaining cases do not permit modification of the object. |
| 4440 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global); |
| 4441 | return CompleteObject(); |
| 4442 | } else if (VD->isConstexpr()) { |
| 4443 | // OK, we can read this variable. |
| 4444 | } else if (Info.getLangOpts().C23 && ConstexprVar) { |
| 4445 | Info.FFDiag(E); |
| 4446 | return CompleteObject(); |
| 4447 | } else if (BaseType->isIntegralOrEnumerationType()) { |
| 4448 | if (!IsConstant) { |
| 4449 | if (!IsAccess) |
| 4450 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
| 4451 | if (Info.getLangOpts().CPlusPlus) { |
| 4452 | Info.FFDiag(E, DiagId: diag::note_constexpr_ltor_non_const_int, ExtraNotes: 1) << VD; |
| 4453 | Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at); |
| 4454 | } else { |
| 4455 | Info.FFDiag(E); |
| 4456 | } |
| 4457 | return CompleteObject(); |
| 4458 | } |
| 4459 | } else if (!IsAccess) { |
| 4460 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
| 4461 | } else if (IsConstant && Info.checkingPotentialConstantExpression() && |
| 4462 | BaseType->isLiteralType(Ctx: Info.Ctx) && !VD->hasDefinition()) { |
| 4463 | // This variable might end up being constexpr. Don't diagnose it yet. |
| 4464 | } else if (IsConstant) { |
| 4465 | // Keep evaluating to see what we can do. In particular, we support |
| 4466 | // folding of const floating-point types, in order to make static const |
| 4467 | // data members of such types (supported as an extension) more useful. |
| 4468 | if (Info.getLangOpts().CPlusPlus) { |
| 4469 | Info.CCEDiag(E, DiagId: Info.getLangOpts().CPlusPlus11 |
| 4470 | ? diag::note_constexpr_ltor_non_constexpr |
| 4471 | : diag::note_constexpr_ltor_non_integral, ExtraNotes: 1) |
| 4472 | << VD << BaseType; |
| 4473 | Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at); |
| 4474 | } else { |
| 4475 | Info.CCEDiag(E); |
| 4476 | } |
| 4477 | } else { |
| 4478 | // Never allow reading a non-const value. |
| 4479 | if (Info.getLangOpts().CPlusPlus) { |
| 4480 | Info.FFDiag(E, DiagId: Info.getLangOpts().CPlusPlus11 |
| 4481 | ? diag::note_constexpr_ltor_non_constexpr |
| 4482 | : diag::note_constexpr_ltor_non_integral, ExtraNotes: 1) |
| 4483 | << VD << BaseType; |
| 4484 | Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at); |
| 4485 | } else { |
| 4486 | Info.FFDiag(E); |
| 4487 | } |
| 4488 | return CompleteObject(); |
| 4489 | } |
| 4490 | } |
| 4491 | |
| 4492 | if (!evaluateVarDeclInit(Info, E, VD, Frame, Version: LVal.getLValueVersion(), Result&: BaseVal)) |
| 4493 | return CompleteObject(); |
| 4494 | } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { |
| 4495 | std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); |
| 4496 | if (!Alloc) { |
| 4497 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_deleted_object) << AK; |
| 4498 | return CompleteObject(); |
| 4499 | } |
| 4500 | return CompleteObject(LVal.Base, &(*Alloc)->Value, |
| 4501 | LVal.Base.getDynamicAllocType()); |
| 4502 | } else { |
| 4503 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); |
| 4504 | |
| 4505 | if (!Frame) { |
| 4506 | if (const MaterializeTemporaryExpr *MTE = |
| 4507 | dyn_cast_or_null<MaterializeTemporaryExpr>(Val: Base)) { |
| 4508 | assert(MTE->getStorageDuration() == SD_Static && |
| 4509 | "should have a frame for a non-global materialized temporary" ); |
| 4510 | |
| 4511 | // C++20 [expr.const]p4: [DR2126] |
| 4512 | // An object or reference is usable in constant expressions if it is |
| 4513 | // - a temporary object of non-volatile const-qualified literal type |
| 4514 | // whose lifetime is extended to that of a variable that is usable |
| 4515 | // in constant expressions |
| 4516 | // |
| 4517 | // C++20 [expr.const]p5: |
| 4518 | // an lvalue-to-rvalue conversion [is not allowed unless it applies to] |
| 4519 | // - a non-volatile glvalue that refers to an object that is usable |
| 4520 | // in constant expressions, or |
| 4521 | // - a non-volatile glvalue of literal type that refers to a |
| 4522 | // non-volatile object whose lifetime began within the evaluation |
| 4523 | // of E; |
| 4524 | // |
| 4525 | // C++11 misses the 'began within the evaluation of e' check and |
| 4526 | // instead allows all temporaries, including things like: |
| 4527 | // int &&r = 1; |
| 4528 | // int x = ++r; |
| 4529 | // constexpr int k = r; |
| 4530 | // Therefore we use the C++14-onwards rules in C++11 too. |
| 4531 | // |
| 4532 | // Note that temporaries whose lifetimes began while evaluating a |
| 4533 | // variable's constructor are not usable while evaluating the |
| 4534 | // corresponding destructor, not even if they're of const-qualified |
| 4535 | // types. |
| 4536 | if (!MTE->isUsableInConstantExpressions(Context: Info.Ctx) && |
| 4537 | !lifetimeStartedInEvaluation(Info, Base: LVal.Base)) { |
| 4538 | if (!IsAccess) |
| 4539 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
| 4540 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_static_temporary, ExtraNotes: 1) << AK; |
| 4541 | Info.Note(Loc: MTE->getExprLoc(), DiagId: diag::note_constexpr_temporary_here); |
| 4542 | return CompleteObject(); |
| 4543 | } |
| 4544 | |
| 4545 | BaseVal = MTE->getOrCreateValue(MayCreate: false); |
| 4546 | assert(BaseVal && "got reference to unevaluated temporary" ); |
| 4547 | } else { |
| 4548 | if (!IsAccess) |
| 4549 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
| 4550 | APValue Val; |
| 4551 | LVal.moveInto(V&: Val); |
| 4552 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_unreadable_object) |
| 4553 | << AK |
| 4554 | << Val.getAsString(Ctx: Info.Ctx, |
| 4555 | Ty: Info.Ctx.getLValueReferenceType(T: LValType)); |
| 4556 | NoteLValueLocation(Info, Base: LVal.Base); |
| 4557 | return CompleteObject(); |
| 4558 | } |
| 4559 | } else { |
| 4560 | BaseVal = Frame->getTemporary(Key: Base, Version: LVal.Base.getVersion()); |
| 4561 | assert(BaseVal && "missing value for temporary" ); |
| 4562 | } |
| 4563 | } |
| 4564 | |
| 4565 | // In C++14, we can't safely access any mutable state when we might be |
| 4566 | // evaluating after an unmodeled side effect. Parameters are modeled as state |
| 4567 | // in the caller, but aren't visible once the call returns, so they can be |
| 4568 | // modified in a speculatively-evaluated call. |
| 4569 | // |
| 4570 | // FIXME: Not all local state is mutable. Allow local constant subobjects |
| 4571 | // to be read here (but take care with 'mutable' fields). |
| 4572 | unsigned VisibleDepth = Depth; |
| 4573 | if (llvm::isa_and_nonnull<ParmVarDecl>( |
| 4574 | Val: LVal.Base.dyn_cast<const ValueDecl *>())) |
| 4575 | ++VisibleDepth; |
| 4576 | if ((Frame && Info.getLangOpts().CPlusPlus14 && |
| 4577 | Info.EvalStatus.HasSideEffects) || |
| 4578 | (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) |
| 4579 | return CompleteObject(); |
| 4580 | |
| 4581 | return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); |
| 4582 | } |
| 4583 | |
| 4584 | /// Perform an lvalue-to-rvalue conversion on the given glvalue. This |
| 4585 | /// can also be used for 'lvalue-to-lvalue' conversions for looking up the |
| 4586 | /// glvalue referred to by an entity of reference type. |
| 4587 | /// |
| 4588 | /// \param Info - Information about the ongoing evaluation. |
| 4589 | /// \param Conv - The expression for which we are performing the conversion. |
| 4590 | /// Used for diagnostics. |
| 4591 | /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the |
| 4592 | /// case of a non-class type). |
| 4593 | /// \param LVal - The glvalue on which we are attempting to perform this action. |
| 4594 | /// \param RVal - The produced value will be placed here. |
| 4595 | /// \param WantObjectRepresentation - If true, we're looking for the object |
| 4596 | /// representation rather than the value, and in particular, |
| 4597 | /// there is no requirement that the result be fully initialized. |
| 4598 | static bool |
| 4599 | handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, |
| 4600 | const LValue &LVal, APValue &RVal, |
| 4601 | bool WantObjectRepresentation = false) { |
| 4602 | if (LVal.Designator.Invalid) |
| 4603 | return false; |
| 4604 | |
| 4605 | // Check for special cases where there is no existing APValue to look at. |
| 4606 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); |
| 4607 | |
| 4608 | AccessKinds AK = |
| 4609 | WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; |
| 4610 | |
| 4611 | if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { |
| 4612 | if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Val: Base)) { |
| 4613 | // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the |
| 4614 | // initializer until now for such expressions. Such an expression can't be |
| 4615 | // an ICE in C, so this only matters for fold. |
| 4616 | if (Type.isVolatileQualified()) { |
| 4617 | Info.FFDiag(E: Conv); |
| 4618 | return false; |
| 4619 | } |
| 4620 | |
| 4621 | APValue Lit; |
| 4622 | if (!Evaluate(Result&: Lit, Info, E: CLE->getInitializer())) |
| 4623 | return false; |
| 4624 | |
| 4625 | // According to GCC info page: |
| 4626 | // |
| 4627 | // 6.28 Compound Literals |
| 4628 | // |
| 4629 | // As an optimization, G++ sometimes gives array compound literals longer |
| 4630 | // lifetimes: when the array either appears outside a function or has a |
| 4631 | // const-qualified type. If foo and its initializer had elements of type |
| 4632 | // char *const rather than char *, or if foo were a global variable, the |
| 4633 | // array would have static storage duration. But it is probably safest |
| 4634 | // just to avoid the use of array compound literals in C++ code. |
| 4635 | // |
| 4636 | // Obey that rule by checking constness for converted array types. |
| 4637 | |
| 4638 | QualType CLETy = CLE->getType(); |
| 4639 | if (CLETy->isArrayType() && !Type->isArrayType()) { |
| 4640 | if (!CLETy.isConstant(Ctx: Info.Ctx)) { |
| 4641 | Info.FFDiag(E: Conv); |
| 4642 | Info.Note(Loc: CLE->getExprLoc(), DiagId: diag::note_declared_at); |
| 4643 | return false; |
| 4644 | } |
| 4645 | } |
| 4646 | |
| 4647 | CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); |
| 4648 | return extractSubobject(Info, E: Conv, Obj: LitObj, Sub: LVal.Designator, Result&: RVal, AK); |
| 4649 | } else if (isa<StringLiteral>(Val: Base) || isa<PredefinedExpr>(Val: Base)) { |
| 4650 | // Special-case character extraction so we don't have to construct an |
| 4651 | // APValue for the whole string. |
| 4652 | assert(LVal.Designator.Entries.size() <= 1 && |
| 4653 | "Can only read characters from string literals" ); |
| 4654 | if (LVal.Designator.Entries.empty()) { |
| 4655 | // Fail for now for LValue to RValue conversion of an array. |
| 4656 | // (This shouldn't show up in C/C++, but it could be triggered by a |
| 4657 | // weird EvaluateAsRValue call from a tool.) |
| 4658 | Info.FFDiag(E: Conv); |
| 4659 | return false; |
| 4660 | } |
| 4661 | if (LVal.Designator.isOnePastTheEnd()) { |
| 4662 | if (Info.getLangOpts().CPlusPlus11) |
| 4663 | Info.FFDiag(E: Conv, DiagId: diag::note_constexpr_access_past_end) << AK; |
| 4664 | else |
| 4665 | Info.FFDiag(E: Conv); |
| 4666 | return false; |
| 4667 | } |
| 4668 | uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); |
| 4669 | RVal = APValue(extractStringLiteralCharacter(Info, Lit: Base, Index: CharIndex)); |
| 4670 | return true; |
| 4671 | } |
| 4672 | } |
| 4673 | |
| 4674 | CompleteObject Obj = findCompleteObject(Info, E: Conv, AK, LVal, LValType: Type); |
| 4675 | return Obj && extractSubobject(Info, E: Conv, Obj, Sub: LVal.Designator, Result&: RVal, AK); |
| 4676 | } |
| 4677 | |
| 4678 | /// Perform an assignment of Val to LVal. Takes ownership of Val. |
| 4679 | static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, |
| 4680 | QualType LValType, APValue &Val) { |
| 4681 | if (LVal.Designator.Invalid) |
| 4682 | return false; |
| 4683 | |
| 4684 | if (!Info.getLangOpts().CPlusPlus14) { |
| 4685 | Info.FFDiag(E); |
| 4686 | return false; |
| 4687 | } |
| 4688 | |
| 4689 | CompleteObject Obj = findCompleteObject(Info, E, AK: AK_Assign, LVal, LValType); |
| 4690 | return Obj && modifySubobject(Info, E, Obj, Sub: LVal.Designator, NewVal&: Val); |
| 4691 | } |
| 4692 | |
| 4693 | namespace { |
| 4694 | struct CompoundAssignSubobjectHandler { |
| 4695 | EvalInfo &Info; |
| 4696 | const CompoundAssignOperator *E; |
| 4697 | QualType PromotedLHSType; |
| 4698 | BinaryOperatorKind Opcode; |
| 4699 | const APValue &RHS; |
| 4700 | |
| 4701 | static const AccessKinds AccessKind = AK_Assign; |
| 4702 | |
| 4703 | typedef bool result_type; |
| 4704 | |
| 4705 | bool checkConst(QualType QT) { |
| 4706 | // Assigning to a const object has undefined behavior. |
| 4707 | if (QT.isConstQualified()) { |
| 4708 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_const_type) << QT; |
| 4709 | return false; |
| 4710 | } |
| 4711 | return true; |
| 4712 | } |
| 4713 | |
| 4714 | bool failed() { return false; } |
| 4715 | bool found(APValue &Subobj, QualType SubobjType) { |
| 4716 | switch (Subobj.getKind()) { |
| 4717 | case APValue::Int: |
| 4718 | return found(Value&: Subobj.getInt(), SubobjType); |
| 4719 | case APValue::Float: |
| 4720 | return found(Value&: Subobj.getFloat(), SubobjType); |
| 4721 | case APValue::ComplexInt: |
| 4722 | case APValue::ComplexFloat: |
| 4723 | // FIXME: Implement complex compound assignment. |
| 4724 | Info.FFDiag(E); |
| 4725 | return false; |
| 4726 | case APValue::LValue: |
| 4727 | return foundPointer(Subobj, SubobjType); |
| 4728 | case APValue::Vector: |
| 4729 | return foundVector(Value&: Subobj, SubobjType); |
| 4730 | case APValue::Indeterminate: |
| 4731 | Info.FFDiag(E, DiagId: diag::note_constexpr_access_uninit) |
| 4732 | << /*read of=*/0 << /*uninitialized object=*/1 |
| 4733 | << E->getLHS()->getSourceRange(); |
| 4734 | return false; |
| 4735 | default: |
| 4736 | // FIXME: can this happen? |
| 4737 | Info.FFDiag(E); |
| 4738 | return false; |
| 4739 | } |
| 4740 | } |
| 4741 | |
| 4742 | bool foundVector(APValue &Value, QualType SubobjType) { |
| 4743 | if (!checkConst(QT: SubobjType)) |
| 4744 | return false; |
| 4745 | |
| 4746 | if (!SubobjType->isVectorType()) { |
| 4747 | Info.FFDiag(E); |
| 4748 | return false; |
| 4749 | } |
| 4750 | return handleVectorVectorBinOp(Info, E, Opcode, LHSValue&: Value, RHSValue: RHS); |
| 4751 | } |
| 4752 | |
| 4753 | bool found(APSInt &Value, QualType SubobjType) { |
| 4754 | if (!checkConst(QT: SubobjType)) |
| 4755 | return false; |
| 4756 | |
| 4757 | if (!SubobjType->isIntegerType()) { |
| 4758 | // We don't support compound assignment on integer-cast-to-pointer |
| 4759 | // values. |
| 4760 | Info.FFDiag(E); |
| 4761 | return false; |
| 4762 | } |
| 4763 | |
| 4764 | if (RHS.isInt()) { |
| 4765 | APSInt LHS = |
| 4766 | HandleIntToIntCast(Info, E, DestType: PromotedLHSType, SrcType: SubobjType, Value); |
| 4767 | if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS: RHS.getInt(), Result&: LHS)) |
| 4768 | return false; |
| 4769 | Value = HandleIntToIntCast(Info, E, DestType: SubobjType, SrcType: PromotedLHSType, Value: LHS); |
| 4770 | return true; |
| 4771 | } else if (RHS.isFloat()) { |
| 4772 | const FPOptions FPO = E->getFPFeaturesInEffect( |
| 4773 | LO: Info.Ctx.getLangOpts()); |
| 4774 | APFloat FValue(0.0); |
| 4775 | return HandleIntToFloatCast(Info, E, FPO, SrcType: SubobjType, Value, |
| 4776 | DestType: PromotedLHSType, Result&: FValue) && |
| 4777 | handleFloatFloatBinOp(Info, E, LHS&: FValue, Opcode, RHS: RHS.getFloat()) && |
| 4778 | HandleFloatToIntCast(Info, E, SrcType: PromotedLHSType, Value: FValue, DestType: SubobjType, |
| 4779 | Result&: Value); |
| 4780 | } |
| 4781 | |
| 4782 | Info.FFDiag(E); |
| 4783 | return false; |
| 4784 | } |
| 4785 | bool found(APFloat &Value, QualType SubobjType) { |
| 4786 | return checkConst(QT: SubobjType) && |
| 4787 | HandleFloatToFloatCast(Info, E, SrcType: SubobjType, DestType: PromotedLHSType, |
| 4788 | Result&: Value) && |
| 4789 | handleFloatFloatBinOp(Info, E, LHS&: Value, Opcode, RHS: RHS.getFloat()) && |
| 4790 | HandleFloatToFloatCast(Info, E, SrcType: PromotedLHSType, DestType: SubobjType, Result&: Value); |
| 4791 | } |
| 4792 | bool foundPointer(APValue &Subobj, QualType SubobjType) { |
| 4793 | if (!checkConst(QT: SubobjType)) |
| 4794 | return false; |
| 4795 | |
| 4796 | QualType PointeeType; |
| 4797 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) |
| 4798 | PointeeType = PT->getPointeeType(); |
| 4799 | |
| 4800 | if (PointeeType.isNull() || !RHS.isInt() || |
| 4801 | (Opcode != BO_Add && Opcode != BO_Sub)) { |
| 4802 | Info.FFDiag(E); |
| 4803 | return false; |
| 4804 | } |
| 4805 | |
| 4806 | APSInt Offset = RHS.getInt(); |
| 4807 | if (Opcode == BO_Sub) |
| 4808 | negateAsSigned(Int&: Offset); |
| 4809 | |
| 4810 | LValue LVal; |
| 4811 | LVal.setFrom(Ctx&: Info.Ctx, V: Subobj); |
| 4812 | if (!HandleLValueArrayAdjustment(Info, E, LVal, EltTy: PointeeType, Adjustment: Offset)) |
| 4813 | return false; |
| 4814 | LVal.moveInto(V&: Subobj); |
| 4815 | return true; |
| 4816 | } |
| 4817 | }; |
| 4818 | } // end anonymous namespace |
| 4819 | |
| 4820 | const AccessKinds CompoundAssignSubobjectHandler::AccessKind; |
| 4821 | |
| 4822 | /// Perform a compound assignment of LVal <op>= RVal. |
| 4823 | static bool handleCompoundAssignment(EvalInfo &Info, |
| 4824 | const CompoundAssignOperator *E, |
| 4825 | const LValue &LVal, QualType LValType, |
| 4826 | QualType PromotedLValType, |
| 4827 | BinaryOperatorKind Opcode, |
| 4828 | const APValue &RVal) { |
| 4829 | if (LVal.Designator.Invalid) |
| 4830 | return false; |
| 4831 | |
| 4832 | if (!Info.getLangOpts().CPlusPlus14) { |
| 4833 | Info.FFDiag(E); |
| 4834 | return false; |
| 4835 | } |
| 4836 | |
| 4837 | CompleteObject Obj = findCompleteObject(Info, E, AK: AK_Assign, LVal, LValType); |
| 4838 | CompoundAssignSubobjectHandler Handler = { .Info: Info, .E: E, .PromotedLHSType: PromotedLValType, .Opcode: Opcode, |
| 4839 | .RHS: RVal }; |
| 4840 | return Obj && findSubobject(Info, E, Obj, Sub: LVal.Designator, handler&: Handler); |
| 4841 | } |
| 4842 | |
| 4843 | namespace { |
| 4844 | struct IncDecSubobjectHandler { |
| 4845 | EvalInfo &Info; |
| 4846 | const UnaryOperator *E; |
| 4847 | AccessKinds AccessKind; |
| 4848 | APValue *Old; |
| 4849 | |
| 4850 | typedef bool result_type; |
| 4851 | |
| 4852 | bool checkConst(QualType QT) { |
| 4853 | // Assigning to a const object has undefined behavior. |
| 4854 | if (QT.isConstQualified()) { |
| 4855 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_const_type) << QT; |
| 4856 | return false; |
| 4857 | } |
| 4858 | return true; |
| 4859 | } |
| 4860 | |
| 4861 | bool failed() { return false; } |
| 4862 | bool found(APValue &Subobj, QualType SubobjType) { |
| 4863 | // Stash the old value. Also clear Old, so we don't clobber it later |
| 4864 | // if we're post-incrementing a complex. |
| 4865 | if (Old) { |
| 4866 | *Old = Subobj; |
| 4867 | Old = nullptr; |
| 4868 | } |
| 4869 | |
| 4870 | switch (Subobj.getKind()) { |
| 4871 | case APValue::Int: |
| 4872 | return found(Value&: Subobj.getInt(), SubobjType); |
| 4873 | case APValue::Float: |
| 4874 | return found(Value&: Subobj.getFloat(), SubobjType); |
| 4875 | case APValue::ComplexInt: |
| 4876 | return found(Value&: Subobj.getComplexIntReal(), |
| 4877 | SubobjType: SubobjType->castAs<ComplexType>()->getElementType() |
| 4878 | .withCVRQualifiers(CVR: SubobjType.getCVRQualifiers())); |
| 4879 | case APValue::ComplexFloat: |
| 4880 | return found(Value&: Subobj.getComplexFloatReal(), |
| 4881 | SubobjType: SubobjType->castAs<ComplexType>()->getElementType() |
| 4882 | .withCVRQualifiers(CVR: SubobjType.getCVRQualifiers())); |
| 4883 | case APValue::LValue: |
| 4884 | return foundPointer(Subobj, SubobjType); |
| 4885 | default: |
| 4886 | // FIXME: can this happen? |
| 4887 | Info.FFDiag(E); |
| 4888 | return false; |
| 4889 | } |
| 4890 | } |
| 4891 | bool found(APSInt &Value, QualType SubobjType) { |
| 4892 | if (!checkConst(QT: SubobjType)) |
| 4893 | return false; |
| 4894 | |
| 4895 | if (!SubobjType->isIntegerType()) { |
| 4896 | // We don't support increment / decrement on integer-cast-to-pointer |
| 4897 | // values. |
| 4898 | Info.FFDiag(E); |
| 4899 | return false; |
| 4900 | } |
| 4901 | |
| 4902 | if (Old) *Old = APValue(Value); |
| 4903 | |
| 4904 | // bool arithmetic promotes to int, and the conversion back to bool |
| 4905 | // doesn't reduce mod 2^n, so special-case it. |
| 4906 | if (SubobjType->isBooleanType()) { |
| 4907 | if (AccessKind == AK_Increment) |
| 4908 | Value = 1; |
| 4909 | else |
| 4910 | Value = !Value; |
| 4911 | return true; |
| 4912 | } |
| 4913 | |
| 4914 | bool WasNegative = Value.isNegative(); |
| 4915 | if (AccessKind == AK_Increment) { |
| 4916 | ++Value; |
| 4917 | |
| 4918 | if (!WasNegative && Value.isNegative() && E->canOverflow()) { |
| 4919 | APSInt ActualValue(Value, /*IsUnsigned*/true); |
| 4920 | return HandleOverflow(Info, E, SrcValue: ActualValue, DestType: SubobjType); |
| 4921 | } |
| 4922 | } else { |
| 4923 | --Value; |
| 4924 | |
| 4925 | if (WasNegative && !Value.isNegative() && E->canOverflow()) { |
| 4926 | unsigned BitWidth = Value.getBitWidth(); |
| 4927 | APSInt ActualValue(Value.sext(width: BitWidth + 1), /*IsUnsigned*/false); |
| 4928 | ActualValue.setBit(BitWidth); |
| 4929 | return HandleOverflow(Info, E, SrcValue: ActualValue, DestType: SubobjType); |
| 4930 | } |
| 4931 | } |
| 4932 | return true; |
| 4933 | } |
| 4934 | bool found(APFloat &Value, QualType SubobjType) { |
| 4935 | if (!checkConst(QT: SubobjType)) |
| 4936 | return false; |
| 4937 | |
| 4938 | if (Old) *Old = APValue(Value); |
| 4939 | |
| 4940 | APFloat One(Value.getSemantics(), 1); |
| 4941 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E); |
| 4942 | APFloat::opStatus St; |
| 4943 | if (AccessKind == AK_Increment) |
| 4944 | St = Value.add(RHS: One, RM); |
| 4945 | else |
| 4946 | St = Value.subtract(RHS: One, RM); |
| 4947 | return checkFloatingPointResult(Info, E, St); |
| 4948 | } |
| 4949 | bool foundPointer(APValue &Subobj, QualType SubobjType) { |
| 4950 | if (!checkConst(QT: SubobjType)) |
| 4951 | return false; |
| 4952 | |
| 4953 | QualType PointeeType; |
| 4954 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) |
| 4955 | PointeeType = PT->getPointeeType(); |
| 4956 | else { |
| 4957 | Info.FFDiag(E); |
| 4958 | return false; |
| 4959 | } |
| 4960 | |
| 4961 | LValue LVal; |
| 4962 | LVal.setFrom(Ctx&: Info.Ctx, V: Subobj); |
| 4963 | if (!HandleLValueArrayAdjustment(Info, E, LVal, EltTy: PointeeType, |
| 4964 | Adjustment: AccessKind == AK_Increment ? 1 : -1)) |
| 4965 | return false; |
| 4966 | LVal.moveInto(V&: Subobj); |
| 4967 | return true; |
| 4968 | } |
| 4969 | }; |
| 4970 | } // end anonymous namespace |
| 4971 | |
| 4972 | /// Perform an increment or decrement on LVal. |
| 4973 | static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, |
| 4974 | QualType LValType, bool IsIncrement, APValue *Old) { |
| 4975 | if (LVal.Designator.Invalid) |
| 4976 | return false; |
| 4977 | |
| 4978 | if (!Info.getLangOpts().CPlusPlus14) { |
| 4979 | Info.FFDiag(E); |
| 4980 | return false; |
| 4981 | } |
| 4982 | |
| 4983 | AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; |
| 4984 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); |
| 4985 | IncDecSubobjectHandler Handler = {.Info: Info, .E: cast<UnaryOperator>(Val: E), .AccessKind: AK, .Old: Old}; |
| 4986 | return Obj && findSubobject(Info, E, Obj, Sub: LVal.Designator, handler&: Handler); |
| 4987 | } |
| 4988 | |
| 4989 | /// Build an lvalue for the object argument of a member function call. |
| 4990 | static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, |
| 4991 | LValue &This) { |
| 4992 | if (Object->getType()->isPointerType() && Object->isPRValue()) |
| 4993 | return EvaluatePointer(E: Object, Result&: This, Info); |
| 4994 | |
| 4995 | if (Object->isGLValue()) |
| 4996 | return EvaluateLValue(E: Object, Result&: This, Info); |
| 4997 | |
| 4998 | if (Object->getType()->isLiteralType(Ctx: Info.Ctx)) |
| 4999 | return EvaluateTemporary(E: Object, Result&: This, Info); |
| 5000 | |
| 5001 | if (Object->getType()->isRecordType() && Object->isPRValue()) |
| 5002 | return EvaluateTemporary(E: Object, Result&: This, Info); |
| 5003 | |
| 5004 | Info.FFDiag(E: Object, DiagId: diag::note_constexpr_nonliteral) << Object->getType(); |
| 5005 | return false; |
| 5006 | } |
| 5007 | |
| 5008 | /// HandleMemberPointerAccess - Evaluate a member access operation and build an |
| 5009 | /// lvalue referring to the result. |
| 5010 | /// |
| 5011 | /// \param Info - Information about the ongoing evaluation. |
| 5012 | /// \param LV - An lvalue referring to the base of the member pointer. |
| 5013 | /// \param RHS - The member pointer expression. |
| 5014 | /// \param IncludeMember - Specifies whether the member itself is included in |
| 5015 | /// the resulting LValue subobject designator. This is not possible when |
| 5016 | /// creating a bound member function. |
| 5017 | /// \return The field or method declaration to which the member pointer refers, |
| 5018 | /// or 0 if evaluation fails. |
| 5019 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, |
| 5020 | QualType LVType, |
| 5021 | LValue &LV, |
| 5022 | const Expr *RHS, |
| 5023 | bool IncludeMember = true) { |
| 5024 | MemberPtr MemPtr; |
| 5025 | if (!EvaluateMemberPointer(E: RHS, Result&: MemPtr, Info)) |
| 5026 | return nullptr; |
| 5027 | |
| 5028 | // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to |
| 5029 | // member value, the behavior is undefined. |
| 5030 | if (!MemPtr.getDecl()) { |
| 5031 | // FIXME: Specific diagnostic. |
| 5032 | Info.FFDiag(E: RHS); |
| 5033 | return nullptr; |
| 5034 | } |
| 5035 | |
| 5036 | if (MemPtr.isDerivedMember()) { |
| 5037 | // This is a member of some derived class. Truncate LV appropriately. |
| 5038 | // The end of the derived-to-base path for the base object must match the |
| 5039 | // derived-to-base path for the member pointer. |
| 5040 | if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > |
| 5041 | LV.Designator.Entries.size()) { |
| 5042 | Info.FFDiag(E: RHS); |
| 5043 | return nullptr; |
| 5044 | } |
| 5045 | unsigned PathLengthToMember = |
| 5046 | LV.Designator.Entries.size() - MemPtr.Path.size(); |
| 5047 | for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { |
| 5048 | const CXXRecordDecl *LVDecl = getAsBaseClass( |
| 5049 | E: LV.Designator.Entries[PathLengthToMember + I]); |
| 5050 | const CXXRecordDecl *MPDecl = MemPtr.Path[I]; |
| 5051 | if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { |
| 5052 | Info.FFDiag(E: RHS); |
| 5053 | return nullptr; |
| 5054 | } |
| 5055 | } |
| 5056 | |
| 5057 | // Truncate the lvalue to the appropriate derived class. |
| 5058 | if (!CastToDerivedClass(Info, E: RHS, Result&: LV, TruncatedType: MemPtr.getContainingRecord(), |
| 5059 | TruncatedElements: PathLengthToMember)) |
| 5060 | return nullptr; |
| 5061 | } else if (!MemPtr.Path.empty()) { |
| 5062 | // Extend the LValue path with the member pointer's path. |
| 5063 | LV.Designator.Entries.reserve(N: LV.Designator.Entries.size() + |
| 5064 | MemPtr.Path.size() + IncludeMember); |
| 5065 | |
| 5066 | // Walk down to the appropriate base class. |
| 5067 | if (const PointerType *PT = LVType->getAs<PointerType>()) |
| 5068 | LVType = PT->getPointeeType(); |
| 5069 | const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); |
| 5070 | assert(RD && "member pointer access on non-class-type expression" ); |
| 5071 | // The first class in the path is that of the lvalue. |
| 5072 | for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { |
| 5073 | const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; |
| 5074 | if (!HandleLValueDirectBase(Info, E: RHS, Obj&: LV, Derived: RD, Base)) |
| 5075 | return nullptr; |
| 5076 | RD = Base; |
| 5077 | } |
| 5078 | // Finally cast to the class containing the member. |
| 5079 | if (!HandleLValueDirectBase(Info, E: RHS, Obj&: LV, Derived: RD, |
| 5080 | Base: MemPtr.getContainingRecord())) |
| 5081 | return nullptr; |
| 5082 | } |
| 5083 | |
| 5084 | // Add the member. Note that we cannot build bound member functions here. |
| 5085 | if (IncludeMember) { |
| 5086 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: MemPtr.getDecl())) { |
| 5087 | if (!HandleLValueMember(Info, E: RHS, LVal&: LV, FD)) |
| 5088 | return nullptr; |
| 5089 | } else if (const IndirectFieldDecl *IFD = |
| 5090 | dyn_cast<IndirectFieldDecl>(Val: MemPtr.getDecl())) { |
| 5091 | if (!HandleLValueIndirectMember(Info, E: RHS, LVal&: LV, IFD)) |
| 5092 | return nullptr; |
| 5093 | } else { |
| 5094 | llvm_unreachable("can't construct reference to bound member function" ); |
| 5095 | } |
| 5096 | } |
| 5097 | |
| 5098 | return MemPtr.getDecl(); |
| 5099 | } |
| 5100 | |
| 5101 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, |
| 5102 | const BinaryOperator *BO, |
| 5103 | LValue &LV, |
| 5104 | bool IncludeMember = true) { |
| 5105 | assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); |
| 5106 | |
| 5107 | if (!EvaluateObjectArgument(Info, Object: BO->getLHS(), This&: LV)) { |
| 5108 | if (Info.noteFailure()) { |
| 5109 | MemberPtr MemPtr; |
| 5110 | EvaluateMemberPointer(E: BO->getRHS(), Result&: MemPtr, Info); |
| 5111 | } |
| 5112 | return nullptr; |
| 5113 | } |
| 5114 | |
| 5115 | return HandleMemberPointerAccess(Info, LVType: BO->getLHS()->getType(), LV, |
| 5116 | RHS: BO->getRHS(), IncludeMember); |
| 5117 | } |
| 5118 | |
| 5119 | /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on |
| 5120 | /// the provided lvalue, which currently refers to the base object. |
| 5121 | static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, |
| 5122 | LValue &Result) { |
| 5123 | SubobjectDesignator &D = Result.Designator; |
| 5124 | if (D.Invalid || !Result.checkNullPointer(Info, E, CSK: CSK_Derived)) |
| 5125 | return false; |
| 5126 | |
| 5127 | QualType TargetQT = E->getType(); |
| 5128 | if (const PointerType *PT = TargetQT->getAs<PointerType>()) |
| 5129 | TargetQT = PT->getPointeeType(); |
| 5130 | |
| 5131 | // Check this cast lands within the final derived-to-base subobject path. |
| 5132 | if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { |
| 5133 | Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_downcast) |
| 5134 | << D.MostDerivedType << TargetQT; |
| 5135 | return false; |
| 5136 | } |
| 5137 | |
| 5138 | // Check the type of the final cast. We don't need to check the path, |
| 5139 | // since a cast can only be formed if the path is unique. |
| 5140 | unsigned NewEntriesSize = D.Entries.size() - E->path_size(); |
| 5141 | const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); |
| 5142 | const CXXRecordDecl *FinalType; |
| 5143 | if (NewEntriesSize == D.MostDerivedPathLength) |
| 5144 | FinalType = D.MostDerivedType->getAsCXXRecordDecl(); |
| 5145 | else |
| 5146 | FinalType = getAsBaseClass(E: D.Entries[NewEntriesSize - 1]); |
| 5147 | if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { |
| 5148 | Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_downcast) |
| 5149 | << D.MostDerivedType << TargetQT; |
| 5150 | return false; |
| 5151 | } |
| 5152 | |
| 5153 | // Truncate the lvalue to the appropriate derived class. |
| 5154 | return CastToDerivedClass(Info, E, Result, TruncatedType: TargetType, TruncatedElements: NewEntriesSize); |
| 5155 | } |
| 5156 | |
| 5157 | /// Get the value to use for a default-initialized object of type T. |
| 5158 | /// Return false if it encounters something invalid. |
| 5159 | static bool handleDefaultInitValue(QualType T, APValue &Result) { |
| 5160 | bool Success = true; |
| 5161 | |
| 5162 | // If there is already a value present don't overwrite it. |
| 5163 | if (!Result.isAbsent()) |
| 5164 | return true; |
| 5165 | |
| 5166 | if (auto *RD = T->getAsCXXRecordDecl()) { |
| 5167 | if (RD->isInvalidDecl()) { |
| 5168 | Result = APValue(); |
| 5169 | return false; |
| 5170 | } |
| 5171 | if (RD->isUnion()) { |
| 5172 | Result = APValue((const FieldDecl *)nullptr); |
| 5173 | return true; |
| 5174 | } |
| 5175 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), |
| 5176 | std::distance(first: RD->field_begin(), last: RD->field_end())); |
| 5177 | |
| 5178 | unsigned Index = 0; |
| 5179 | for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), |
| 5180 | End = RD->bases_end(); |
| 5181 | I != End; ++I, ++Index) |
| 5182 | Success &= |
| 5183 | handleDefaultInitValue(T: I->getType(), Result&: Result.getStructBase(i: Index)); |
| 5184 | |
| 5185 | for (const auto *I : RD->fields()) { |
| 5186 | if (I->isUnnamedBitField()) |
| 5187 | continue; |
| 5188 | Success &= handleDefaultInitValue( |
| 5189 | T: I->getType(), Result&: Result.getStructField(i: I->getFieldIndex())); |
| 5190 | } |
| 5191 | return Success; |
| 5192 | } |
| 5193 | |
| 5194 | if (auto *AT = |
| 5195 | dyn_cast_or_null<ConstantArrayType>(Val: T->getAsArrayTypeUnsafe())) { |
| 5196 | Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize()); |
| 5197 | if (Result.hasArrayFiller()) |
| 5198 | Success &= |
| 5199 | handleDefaultInitValue(T: AT->getElementType(), Result&: Result.getArrayFiller()); |
| 5200 | |
| 5201 | return Success; |
| 5202 | } |
| 5203 | |
| 5204 | Result = APValue::IndeterminateValue(); |
| 5205 | return true; |
| 5206 | } |
| 5207 | |
| 5208 | namespace { |
| 5209 | enum EvalStmtResult { |
| 5210 | /// Evaluation failed. |
| 5211 | ESR_Failed, |
| 5212 | /// Hit a 'return' statement. |
| 5213 | ESR_Returned, |
| 5214 | /// Evaluation succeeded. |
| 5215 | ESR_Succeeded, |
| 5216 | /// Hit a 'continue' statement. |
| 5217 | ESR_Continue, |
| 5218 | /// Hit a 'break' statement. |
| 5219 | ESR_Break, |
| 5220 | /// Still scanning for 'case' or 'default' statement. |
| 5221 | ESR_CaseNotFound |
| 5222 | }; |
| 5223 | } |
| 5224 | |
| 5225 | static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { |
| 5226 | if (VD->isInvalidDecl()) |
| 5227 | return false; |
| 5228 | // We don't need to evaluate the initializer for a static local. |
| 5229 | if (!VD->hasLocalStorage()) |
| 5230 | return true; |
| 5231 | |
| 5232 | LValue Result; |
| 5233 | APValue &Val = Info.CurrentCall->createTemporary(Key: VD, T: VD->getType(), |
| 5234 | Scope: ScopeKind::Block, LV&: Result); |
| 5235 | |
| 5236 | const Expr *InitE = VD->getInit(); |
| 5237 | if (!InitE) { |
| 5238 | if (VD->getType()->isDependentType()) |
| 5239 | return Info.noteSideEffect(); |
| 5240 | return handleDefaultInitValue(T: VD->getType(), Result&: Val); |
| 5241 | } |
| 5242 | if (InitE->isValueDependent()) |
| 5243 | return false; |
| 5244 | |
| 5245 | if (!EvaluateInPlace(Result&: Val, Info, This: Result, E: InitE)) { |
| 5246 | // Wipe out any partially-computed value, to allow tracking that this |
| 5247 | // evaluation failed. |
| 5248 | Val = APValue(); |
| 5249 | return false; |
| 5250 | } |
| 5251 | |
| 5252 | return true; |
| 5253 | } |
| 5254 | |
| 5255 | static bool EvaluateDecompositionDeclInit(EvalInfo &Info, |
| 5256 | const DecompositionDecl *DD); |
| 5257 | |
| 5258 | static bool EvaluateDecl(EvalInfo &Info, const Decl *D, |
| 5259 | bool EvaluateConditionDecl = false) { |
| 5260 | bool OK = true; |
| 5261 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) |
| 5262 | OK &= EvaluateVarDecl(Info, VD); |
| 5263 | |
| 5264 | if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(Val: D); |
| 5265 | EvaluateConditionDecl && DD) |
| 5266 | OK &= EvaluateDecompositionDeclInit(Info, DD); |
| 5267 | |
| 5268 | return OK; |
| 5269 | } |
| 5270 | |
| 5271 | static bool EvaluateDecompositionDeclInit(EvalInfo &Info, |
| 5272 | const DecompositionDecl *DD) { |
| 5273 | bool OK = true; |
| 5274 | for (auto *BD : DD->flat_bindings()) |
| 5275 | if (auto *VD = BD->getHoldingVar()) |
| 5276 | OK &= EvaluateDecl(Info, D: VD, /*EvaluateConditionDecl=*/true); |
| 5277 | |
| 5278 | return OK; |
| 5279 | } |
| 5280 | |
| 5281 | static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, |
| 5282 | const VarDecl *VD) { |
| 5283 | if (auto *DD = dyn_cast_if_present<DecompositionDecl>(Val: VD)) { |
| 5284 | if (!EvaluateDecompositionDeclInit(Info, DD)) |
| 5285 | return false; |
| 5286 | } |
| 5287 | return true; |
| 5288 | } |
| 5289 | |
| 5290 | static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { |
| 5291 | assert(E->isValueDependent()); |
| 5292 | if (Info.noteSideEffect()) |
| 5293 | return true; |
| 5294 | assert(E->containsErrors() && "valid value-dependent expression should never " |
| 5295 | "reach invalid code path." ); |
| 5296 | return false; |
| 5297 | } |
| 5298 | |
| 5299 | /// Evaluate a condition (either a variable declaration or an expression). |
| 5300 | static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, |
| 5301 | const Expr *Cond, bool &Result) { |
| 5302 | if (Cond->isValueDependent()) |
| 5303 | return false; |
| 5304 | FullExpressionRAII Scope(Info); |
| 5305 | if (CondDecl && !EvaluateDecl(Info, D: CondDecl)) |
| 5306 | return false; |
| 5307 | if (!EvaluateAsBooleanCondition(E: Cond, Result, Info)) |
| 5308 | return false; |
| 5309 | if (!MaybeEvaluateDeferredVarDeclInit(Info, VD: CondDecl)) |
| 5310 | return false; |
| 5311 | return Scope.destroy(); |
| 5312 | } |
| 5313 | |
| 5314 | namespace { |
| 5315 | /// A location where the result (returned value) of evaluating a |
| 5316 | /// statement should be stored. |
| 5317 | struct StmtResult { |
| 5318 | /// The APValue that should be filled in with the returned value. |
| 5319 | APValue &Value; |
| 5320 | /// The location containing the result, if any (used to support RVO). |
| 5321 | const LValue *Slot; |
| 5322 | }; |
| 5323 | |
| 5324 | struct TempVersionRAII { |
| 5325 | CallStackFrame &Frame; |
| 5326 | |
| 5327 | TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { |
| 5328 | Frame.pushTempVersion(); |
| 5329 | } |
| 5330 | |
| 5331 | ~TempVersionRAII() { |
| 5332 | Frame.popTempVersion(); |
| 5333 | } |
| 5334 | }; |
| 5335 | |
| 5336 | } |
| 5337 | |
| 5338 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, |
| 5339 | const Stmt *S, |
| 5340 | const SwitchCase *SC = nullptr); |
| 5341 | |
| 5342 | /// Evaluate the body of a loop, and translate the result as appropriate. |
| 5343 | static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, |
| 5344 | const Stmt *Body, |
| 5345 | const SwitchCase *Case = nullptr) { |
| 5346 | BlockScopeRAII Scope(Info); |
| 5347 | |
| 5348 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Body, SC: Case); |
| 5349 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) |
| 5350 | ESR = ESR_Failed; |
| 5351 | |
| 5352 | switch (ESR) { |
| 5353 | case ESR_Break: |
| 5354 | return ESR_Succeeded; |
| 5355 | case ESR_Succeeded: |
| 5356 | case ESR_Continue: |
| 5357 | return ESR_Continue; |
| 5358 | case ESR_Failed: |
| 5359 | case ESR_Returned: |
| 5360 | case ESR_CaseNotFound: |
| 5361 | return ESR; |
| 5362 | } |
| 5363 | llvm_unreachable("Invalid EvalStmtResult!" ); |
| 5364 | } |
| 5365 | |
| 5366 | /// Evaluate a switch statement. |
| 5367 | static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, |
| 5368 | const SwitchStmt *SS) { |
| 5369 | BlockScopeRAII Scope(Info); |
| 5370 | |
| 5371 | // Evaluate the switch condition. |
| 5372 | APSInt Value; |
| 5373 | { |
| 5374 | if (const Stmt *Init = SS->getInit()) { |
| 5375 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init); |
| 5376 | if (ESR != ESR_Succeeded) { |
| 5377 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5378 | ESR = ESR_Failed; |
| 5379 | return ESR; |
| 5380 | } |
| 5381 | } |
| 5382 | |
| 5383 | FullExpressionRAII CondScope(Info); |
| 5384 | if (SS->getConditionVariable() && |
| 5385 | !EvaluateDecl(Info, D: SS->getConditionVariable())) |
| 5386 | return ESR_Failed; |
| 5387 | if (SS->getCond()->isValueDependent()) { |
| 5388 | // We don't know what the value is, and which branch should jump to. |
| 5389 | EvaluateDependentExpr(E: SS->getCond(), Info); |
| 5390 | return ESR_Failed; |
| 5391 | } |
| 5392 | if (!EvaluateInteger(E: SS->getCond(), Result&: Value, Info)) |
| 5393 | return ESR_Failed; |
| 5394 | |
| 5395 | if (!MaybeEvaluateDeferredVarDeclInit(Info, VD: SS->getConditionVariable())) |
| 5396 | return ESR_Failed; |
| 5397 | |
| 5398 | if (!CondScope.destroy()) |
| 5399 | return ESR_Failed; |
| 5400 | } |
| 5401 | |
| 5402 | // Find the switch case corresponding to the value of the condition. |
| 5403 | // FIXME: Cache this lookup. |
| 5404 | const SwitchCase *Found = nullptr; |
| 5405 | for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; |
| 5406 | SC = SC->getNextSwitchCase()) { |
| 5407 | if (isa<DefaultStmt>(Val: SC)) { |
| 5408 | Found = SC; |
| 5409 | continue; |
| 5410 | } |
| 5411 | |
| 5412 | const CaseStmt *CS = cast<CaseStmt>(Val: SC); |
| 5413 | APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Ctx: Info.Ctx); |
| 5414 | APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Ctx: Info.Ctx) |
| 5415 | : LHS; |
| 5416 | if (LHS <= Value && Value <= RHS) { |
| 5417 | Found = SC; |
| 5418 | break; |
| 5419 | } |
| 5420 | } |
| 5421 | |
| 5422 | if (!Found) |
| 5423 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
| 5424 | |
| 5425 | // Search the switch body for the switch case and evaluate it from there. |
| 5426 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: SS->getBody(), SC: Found); |
| 5427 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) |
| 5428 | return ESR_Failed; |
| 5429 | |
| 5430 | switch (ESR) { |
| 5431 | case ESR_Break: |
| 5432 | return ESR_Succeeded; |
| 5433 | case ESR_Succeeded: |
| 5434 | case ESR_Continue: |
| 5435 | case ESR_Failed: |
| 5436 | case ESR_Returned: |
| 5437 | return ESR; |
| 5438 | case ESR_CaseNotFound: |
| 5439 | // This can only happen if the switch case is nested within a statement |
| 5440 | // expression. We have no intention of supporting that. |
| 5441 | Info.FFDiag(Loc: Found->getBeginLoc(), |
| 5442 | DiagId: diag::note_constexpr_stmt_expr_unsupported); |
| 5443 | return ESR_Failed; |
| 5444 | } |
| 5445 | llvm_unreachable("Invalid EvalStmtResult!" ); |
| 5446 | } |
| 5447 | |
| 5448 | static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { |
| 5449 | // An expression E is a core constant expression unless the evaluation of E |
| 5450 | // would evaluate one of the following: [C++23] - a control flow that passes |
| 5451 | // through a declaration of a variable with static or thread storage duration |
| 5452 | // unless that variable is usable in constant expressions. |
| 5453 | if (VD->isLocalVarDecl() && VD->isStaticLocal() && |
| 5454 | !VD->isUsableInConstantExpressions(C: Info.Ctx)) { |
| 5455 | Info.CCEDiag(Loc: VD->getLocation(), DiagId: diag::note_constexpr_static_local) |
| 5456 | << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; |
| 5457 | return false; |
| 5458 | } |
| 5459 | return true; |
| 5460 | } |
| 5461 | |
| 5462 | // Evaluate a statement. |
| 5463 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, |
| 5464 | const Stmt *S, const SwitchCase *Case) { |
| 5465 | if (!Info.nextStep(S)) |
| 5466 | return ESR_Failed; |
| 5467 | |
| 5468 | // If we're hunting down a 'case' or 'default' label, recurse through |
| 5469 | // substatements until we hit the label. |
| 5470 | if (Case) { |
| 5471 | switch (S->getStmtClass()) { |
| 5472 | case Stmt::CompoundStmtClass: |
| 5473 | // FIXME: Precompute which substatement of a compound statement we |
| 5474 | // would jump to, and go straight there rather than performing a |
| 5475 | // linear scan each time. |
| 5476 | case Stmt::LabelStmtClass: |
| 5477 | case Stmt::AttributedStmtClass: |
| 5478 | case Stmt::DoStmtClass: |
| 5479 | break; |
| 5480 | |
| 5481 | case Stmt::CaseStmtClass: |
| 5482 | case Stmt::DefaultStmtClass: |
| 5483 | if (Case == S) |
| 5484 | Case = nullptr; |
| 5485 | break; |
| 5486 | |
| 5487 | case Stmt::IfStmtClass: { |
| 5488 | // FIXME: Precompute which side of an 'if' we would jump to, and go |
| 5489 | // straight there rather than scanning both sides. |
| 5490 | const IfStmt *IS = cast<IfStmt>(Val: S); |
| 5491 | |
| 5492 | // Wrap the evaluation in a block scope, in case it's a DeclStmt |
| 5493 | // preceded by our switch label. |
| 5494 | BlockScopeRAII Scope(Info); |
| 5495 | |
| 5496 | // Step into the init statement in case it brings an (uninitialized) |
| 5497 | // variable into scope. |
| 5498 | if (const Stmt *Init = IS->getInit()) { |
| 5499 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init, Case); |
| 5500 | if (ESR != ESR_CaseNotFound) { |
| 5501 | assert(ESR != ESR_Succeeded); |
| 5502 | return ESR; |
| 5503 | } |
| 5504 | } |
| 5505 | |
| 5506 | // Condition variable must be initialized if it exists. |
| 5507 | // FIXME: We can skip evaluating the body if there's a condition |
| 5508 | // variable, as there can't be any case labels within it. |
| 5509 | // (The same is true for 'for' statements.) |
| 5510 | |
| 5511 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: IS->getThen(), Case); |
| 5512 | if (ESR == ESR_Failed) |
| 5513 | return ESR; |
| 5514 | if (ESR != ESR_CaseNotFound) |
| 5515 | return Scope.destroy() ? ESR : ESR_Failed; |
| 5516 | if (!IS->getElse()) |
| 5517 | return ESR_CaseNotFound; |
| 5518 | |
| 5519 | ESR = EvaluateStmt(Result, Info, S: IS->getElse(), Case); |
| 5520 | if (ESR == ESR_Failed) |
| 5521 | return ESR; |
| 5522 | if (ESR != ESR_CaseNotFound) |
| 5523 | return Scope.destroy() ? ESR : ESR_Failed; |
| 5524 | return ESR_CaseNotFound; |
| 5525 | } |
| 5526 | |
| 5527 | case Stmt::WhileStmtClass: { |
| 5528 | EvalStmtResult ESR = |
| 5529 | EvaluateLoopBody(Result, Info, Body: cast<WhileStmt>(Val: S)->getBody(), Case); |
| 5530 | if (ESR != ESR_Continue) |
| 5531 | return ESR; |
| 5532 | break; |
| 5533 | } |
| 5534 | |
| 5535 | case Stmt::ForStmtClass: { |
| 5536 | const ForStmt *FS = cast<ForStmt>(Val: S); |
| 5537 | BlockScopeRAII Scope(Info); |
| 5538 | |
| 5539 | // Step into the init statement in case it brings an (uninitialized) |
| 5540 | // variable into scope. |
| 5541 | if (const Stmt *Init = FS->getInit()) { |
| 5542 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init, Case); |
| 5543 | if (ESR != ESR_CaseNotFound) { |
| 5544 | assert(ESR != ESR_Succeeded); |
| 5545 | return ESR; |
| 5546 | } |
| 5547 | } |
| 5548 | |
| 5549 | EvalStmtResult ESR = |
| 5550 | EvaluateLoopBody(Result, Info, Body: FS->getBody(), Case); |
| 5551 | if (ESR != ESR_Continue) |
| 5552 | return ESR; |
| 5553 | if (const auto *Inc = FS->getInc()) { |
| 5554 | if (Inc->isValueDependent()) { |
| 5555 | if (!EvaluateDependentExpr(E: Inc, Info)) |
| 5556 | return ESR_Failed; |
| 5557 | } else { |
| 5558 | FullExpressionRAII IncScope(Info); |
| 5559 | if (!EvaluateIgnoredValue(Info, E: Inc) || !IncScope.destroy()) |
| 5560 | return ESR_Failed; |
| 5561 | } |
| 5562 | } |
| 5563 | break; |
| 5564 | } |
| 5565 | |
| 5566 | case Stmt::DeclStmtClass: { |
| 5567 | // Start the lifetime of any uninitialized variables we encounter. They |
| 5568 | // might be used by the selected branch of the switch. |
| 5569 | const DeclStmt *DS = cast<DeclStmt>(Val: S); |
| 5570 | for (const auto *D : DS->decls()) { |
| 5571 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) { |
| 5572 | if (!CheckLocalVariableDeclaration(Info, VD)) |
| 5573 | return ESR_Failed; |
| 5574 | if (VD->hasLocalStorage() && !VD->getInit()) |
| 5575 | if (!EvaluateVarDecl(Info, VD)) |
| 5576 | return ESR_Failed; |
| 5577 | // FIXME: If the variable has initialization that can't be jumped |
| 5578 | // over, bail out of any immediately-surrounding compound-statement |
| 5579 | // too. There can't be any case labels here. |
| 5580 | } |
| 5581 | } |
| 5582 | return ESR_CaseNotFound; |
| 5583 | } |
| 5584 | |
| 5585 | default: |
| 5586 | return ESR_CaseNotFound; |
| 5587 | } |
| 5588 | } |
| 5589 | |
| 5590 | switch (S->getStmtClass()) { |
| 5591 | default: |
| 5592 | if (const Expr *E = dyn_cast<Expr>(Val: S)) { |
| 5593 | if (E->isValueDependent()) { |
| 5594 | if (!EvaluateDependentExpr(E, Info)) |
| 5595 | return ESR_Failed; |
| 5596 | } else { |
| 5597 | // Don't bother evaluating beyond an expression-statement which couldn't |
| 5598 | // be evaluated. |
| 5599 | // FIXME: Do we need the FullExpressionRAII object here? |
| 5600 | // VisitExprWithCleanups should create one when necessary. |
| 5601 | FullExpressionRAII Scope(Info); |
| 5602 | if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) |
| 5603 | return ESR_Failed; |
| 5604 | } |
| 5605 | return ESR_Succeeded; |
| 5606 | } |
| 5607 | |
| 5608 | Info.FFDiag(Loc: S->getBeginLoc()) << S->getSourceRange(); |
| 5609 | return ESR_Failed; |
| 5610 | |
| 5611 | case Stmt::NullStmtClass: |
| 5612 | return ESR_Succeeded; |
| 5613 | |
| 5614 | case Stmt::DeclStmtClass: { |
| 5615 | const DeclStmt *DS = cast<DeclStmt>(Val: S); |
| 5616 | for (const auto *D : DS->decls()) { |
| 5617 | const VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: D); |
| 5618 | if (VD && !CheckLocalVariableDeclaration(Info, VD)) |
| 5619 | return ESR_Failed; |
| 5620 | // Each declaration initialization is its own full-expression. |
| 5621 | FullExpressionRAII Scope(Info); |
| 5622 | if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) && |
| 5623 | !Info.noteFailure()) |
| 5624 | return ESR_Failed; |
| 5625 | if (!Scope.destroy()) |
| 5626 | return ESR_Failed; |
| 5627 | } |
| 5628 | return ESR_Succeeded; |
| 5629 | } |
| 5630 | |
| 5631 | case Stmt::ReturnStmtClass: { |
| 5632 | const Expr *RetExpr = cast<ReturnStmt>(Val: S)->getRetValue(); |
| 5633 | FullExpressionRAII Scope(Info); |
| 5634 | if (RetExpr && RetExpr->isValueDependent()) { |
| 5635 | EvaluateDependentExpr(E: RetExpr, Info); |
| 5636 | // We know we returned, but we don't know what the value is. |
| 5637 | return ESR_Failed; |
| 5638 | } |
| 5639 | if (RetExpr && |
| 5640 | !(Result.Slot |
| 5641 | ? EvaluateInPlace(Result&: Result.Value, Info, This: *Result.Slot, E: RetExpr) |
| 5642 | : Evaluate(Result&: Result.Value, Info, E: RetExpr))) |
| 5643 | return ESR_Failed; |
| 5644 | return Scope.destroy() ? ESR_Returned : ESR_Failed; |
| 5645 | } |
| 5646 | |
| 5647 | case Stmt::CompoundStmtClass: { |
| 5648 | BlockScopeRAII Scope(Info); |
| 5649 | |
| 5650 | const CompoundStmt *CS = cast<CompoundStmt>(Val: S); |
| 5651 | for (const auto *BI : CS->body()) { |
| 5652 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: BI, Case); |
| 5653 | if (ESR == ESR_Succeeded) |
| 5654 | Case = nullptr; |
| 5655 | else if (ESR != ESR_CaseNotFound) { |
| 5656 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5657 | return ESR_Failed; |
| 5658 | return ESR; |
| 5659 | } |
| 5660 | } |
| 5661 | if (Case) |
| 5662 | return ESR_CaseNotFound; |
| 5663 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
| 5664 | } |
| 5665 | |
| 5666 | case Stmt::IfStmtClass: { |
| 5667 | const IfStmt *IS = cast<IfStmt>(Val: S); |
| 5668 | |
| 5669 | // Evaluate the condition, as either a var decl or as an expression. |
| 5670 | BlockScopeRAII Scope(Info); |
| 5671 | if (const Stmt *Init = IS->getInit()) { |
| 5672 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init); |
| 5673 | if (ESR != ESR_Succeeded) { |
| 5674 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5675 | return ESR_Failed; |
| 5676 | return ESR; |
| 5677 | } |
| 5678 | } |
| 5679 | bool Cond; |
| 5680 | if (IS->isConsteval()) { |
| 5681 | Cond = IS->isNonNegatedConsteval(); |
| 5682 | // If we are not in a constant context, if consteval should not evaluate |
| 5683 | // to true. |
| 5684 | if (!Info.InConstantContext) |
| 5685 | Cond = !Cond; |
| 5686 | } else if (!EvaluateCond(Info, CondDecl: IS->getConditionVariable(), Cond: IS->getCond(), |
| 5687 | Result&: Cond)) |
| 5688 | return ESR_Failed; |
| 5689 | |
| 5690 | if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { |
| 5691 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: SubStmt); |
| 5692 | if (ESR != ESR_Succeeded) { |
| 5693 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5694 | return ESR_Failed; |
| 5695 | return ESR; |
| 5696 | } |
| 5697 | } |
| 5698 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
| 5699 | } |
| 5700 | |
| 5701 | case Stmt::WhileStmtClass: { |
| 5702 | const WhileStmt *WS = cast<WhileStmt>(Val: S); |
| 5703 | while (true) { |
| 5704 | BlockScopeRAII Scope(Info); |
| 5705 | bool Continue; |
| 5706 | if (!EvaluateCond(Info, CondDecl: WS->getConditionVariable(), Cond: WS->getCond(), |
| 5707 | Result&: Continue)) |
| 5708 | return ESR_Failed; |
| 5709 | if (!Continue) |
| 5710 | break; |
| 5711 | |
| 5712 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, Body: WS->getBody()); |
| 5713 | if (ESR != ESR_Continue) { |
| 5714 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5715 | return ESR_Failed; |
| 5716 | return ESR; |
| 5717 | } |
| 5718 | if (!Scope.destroy()) |
| 5719 | return ESR_Failed; |
| 5720 | } |
| 5721 | return ESR_Succeeded; |
| 5722 | } |
| 5723 | |
| 5724 | case Stmt::DoStmtClass: { |
| 5725 | const DoStmt *DS = cast<DoStmt>(Val: S); |
| 5726 | bool Continue; |
| 5727 | do { |
| 5728 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, Body: DS->getBody(), Case); |
| 5729 | if (ESR != ESR_Continue) |
| 5730 | return ESR; |
| 5731 | Case = nullptr; |
| 5732 | |
| 5733 | if (DS->getCond()->isValueDependent()) { |
| 5734 | EvaluateDependentExpr(E: DS->getCond(), Info); |
| 5735 | // Bailout as we don't know whether to keep going or terminate the loop. |
| 5736 | return ESR_Failed; |
| 5737 | } |
| 5738 | FullExpressionRAII CondScope(Info); |
| 5739 | if (!EvaluateAsBooleanCondition(E: DS->getCond(), Result&: Continue, Info) || |
| 5740 | !CondScope.destroy()) |
| 5741 | return ESR_Failed; |
| 5742 | } while (Continue); |
| 5743 | return ESR_Succeeded; |
| 5744 | } |
| 5745 | |
| 5746 | case Stmt::ForStmtClass: { |
| 5747 | const ForStmt *FS = cast<ForStmt>(Val: S); |
| 5748 | BlockScopeRAII ForScope(Info); |
| 5749 | if (FS->getInit()) { |
| 5750 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: FS->getInit()); |
| 5751 | if (ESR != ESR_Succeeded) { |
| 5752 | if (ESR != ESR_Failed && !ForScope.destroy()) |
| 5753 | return ESR_Failed; |
| 5754 | return ESR; |
| 5755 | } |
| 5756 | } |
| 5757 | while (true) { |
| 5758 | BlockScopeRAII IterScope(Info); |
| 5759 | bool Continue = true; |
| 5760 | if (FS->getCond() && !EvaluateCond(Info, CondDecl: FS->getConditionVariable(), |
| 5761 | Cond: FS->getCond(), Result&: Continue)) |
| 5762 | return ESR_Failed; |
| 5763 | |
| 5764 | if (!Continue) { |
| 5765 | if (!IterScope.destroy()) |
| 5766 | return ESR_Failed; |
| 5767 | break; |
| 5768 | } |
| 5769 | |
| 5770 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, Body: FS->getBody()); |
| 5771 | if (ESR != ESR_Continue) { |
| 5772 | if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) |
| 5773 | return ESR_Failed; |
| 5774 | return ESR; |
| 5775 | } |
| 5776 | |
| 5777 | if (const auto *Inc = FS->getInc()) { |
| 5778 | if (Inc->isValueDependent()) { |
| 5779 | if (!EvaluateDependentExpr(E: Inc, Info)) |
| 5780 | return ESR_Failed; |
| 5781 | } else { |
| 5782 | FullExpressionRAII IncScope(Info); |
| 5783 | if (!EvaluateIgnoredValue(Info, E: Inc) || !IncScope.destroy()) |
| 5784 | return ESR_Failed; |
| 5785 | } |
| 5786 | } |
| 5787 | |
| 5788 | if (!IterScope.destroy()) |
| 5789 | return ESR_Failed; |
| 5790 | } |
| 5791 | return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; |
| 5792 | } |
| 5793 | |
| 5794 | case Stmt::CXXForRangeStmtClass: { |
| 5795 | const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(Val: S); |
| 5796 | BlockScopeRAII Scope(Info); |
| 5797 | |
| 5798 | // Evaluate the init-statement if present. |
| 5799 | if (FS->getInit()) { |
| 5800 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: FS->getInit()); |
| 5801 | if (ESR != ESR_Succeeded) { |
| 5802 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5803 | return ESR_Failed; |
| 5804 | return ESR; |
| 5805 | } |
| 5806 | } |
| 5807 | |
| 5808 | // Initialize the __range variable. |
| 5809 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: FS->getRangeStmt()); |
| 5810 | if (ESR != ESR_Succeeded) { |
| 5811 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5812 | return ESR_Failed; |
| 5813 | return ESR; |
| 5814 | } |
| 5815 | |
| 5816 | // In error-recovery cases it's possible to get here even if we failed to |
| 5817 | // synthesize the __begin and __end variables. |
| 5818 | if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) |
| 5819 | return ESR_Failed; |
| 5820 | |
| 5821 | // Create the __begin and __end iterators. |
| 5822 | ESR = EvaluateStmt(Result, Info, S: FS->getBeginStmt()); |
| 5823 | if (ESR != ESR_Succeeded) { |
| 5824 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5825 | return ESR_Failed; |
| 5826 | return ESR; |
| 5827 | } |
| 5828 | ESR = EvaluateStmt(Result, Info, S: FS->getEndStmt()); |
| 5829 | if (ESR != ESR_Succeeded) { |
| 5830 | if (ESR != ESR_Failed && !Scope.destroy()) |
| 5831 | return ESR_Failed; |
| 5832 | return ESR; |
| 5833 | } |
| 5834 | |
| 5835 | while (true) { |
| 5836 | // Condition: __begin != __end. |
| 5837 | { |
| 5838 | if (FS->getCond()->isValueDependent()) { |
| 5839 | EvaluateDependentExpr(E: FS->getCond(), Info); |
| 5840 | // We don't know whether to keep going or terminate the loop. |
| 5841 | return ESR_Failed; |
| 5842 | } |
| 5843 | bool Continue = true; |
| 5844 | FullExpressionRAII CondExpr(Info); |
| 5845 | if (!EvaluateAsBooleanCondition(E: FS->getCond(), Result&: Continue, Info)) |
| 5846 | return ESR_Failed; |
| 5847 | if (!Continue) |
| 5848 | break; |
| 5849 | } |
| 5850 | |
| 5851 | // User's variable declaration, initialized by *__begin. |
| 5852 | BlockScopeRAII InnerScope(Info); |
| 5853 | ESR = EvaluateStmt(Result, Info, S: FS->getLoopVarStmt()); |
| 5854 | if (ESR != ESR_Succeeded) { |
| 5855 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) |
| 5856 | return ESR_Failed; |
| 5857 | return ESR; |
| 5858 | } |
| 5859 | |
| 5860 | // Loop body. |
| 5861 | ESR = EvaluateLoopBody(Result, Info, Body: FS->getBody()); |
| 5862 | if (ESR != ESR_Continue) { |
| 5863 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) |
| 5864 | return ESR_Failed; |
| 5865 | return ESR; |
| 5866 | } |
| 5867 | if (FS->getInc()->isValueDependent()) { |
| 5868 | if (!EvaluateDependentExpr(E: FS->getInc(), Info)) |
| 5869 | return ESR_Failed; |
| 5870 | } else { |
| 5871 | // Increment: ++__begin |
| 5872 | if (!EvaluateIgnoredValue(Info, E: FS->getInc())) |
| 5873 | return ESR_Failed; |
| 5874 | } |
| 5875 | |
| 5876 | if (!InnerScope.destroy()) |
| 5877 | return ESR_Failed; |
| 5878 | } |
| 5879 | |
| 5880 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
| 5881 | } |
| 5882 | |
| 5883 | case Stmt::SwitchStmtClass: |
| 5884 | return EvaluateSwitch(Result, Info, SS: cast<SwitchStmt>(Val: S)); |
| 5885 | |
| 5886 | case Stmt::ContinueStmtClass: |
| 5887 | return ESR_Continue; |
| 5888 | |
| 5889 | case Stmt::BreakStmtClass: |
| 5890 | return ESR_Break; |
| 5891 | |
| 5892 | case Stmt::LabelStmtClass: |
| 5893 | return EvaluateStmt(Result, Info, S: cast<LabelStmt>(Val: S)->getSubStmt(), Case); |
| 5894 | |
| 5895 | case Stmt::AttributedStmtClass: { |
| 5896 | const auto *AS = cast<AttributedStmt>(Val: S); |
| 5897 | const auto *SS = AS->getSubStmt(); |
| 5898 | MSConstexprContextRAII ConstexprContext( |
| 5899 | *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(container: AS->getAttrs()) && |
| 5900 | isa<ReturnStmt>(Val: SS)); |
| 5901 | |
| 5902 | auto LO = Info.getASTContext().getLangOpts(); |
| 5903 | if (LO.CXXAssumptions && !LO.MSVCCompat) { |
| 5904 | for (auto *Attr : AS->getAttrs()) { |
| 5905 | auto *AA = dyn_cast<CXXAssumeAttr>(Val: Attr); |
| 5906 | if (!AA) |
| 5907 | continue; |
| 5908 | |
| 5909 | auto *Assumption = AA->getAssumption(); |
| 5910 | if (Assumption->isValueDependent()) |
| 5911 | return ESR_Failed; |
| 5912 | |
| 5913 | if (Assumption->HasSideEffects(Ctx: Info.getASTContext())) |
| 5914 | continue; |
| 5915 | |
| 5916 | bool Value; |
| 5917 | if (!EvaluateAsBooleanCondition(E: Assumption, Result&: Value, Info)) |
| 5918 | return ESR_Failed; |
| 5919 | if (!Value) { |
| 5920 | Info.CCEDiag(Loc: Assumption->getExprLoc(), |
| 5921 | DiagId: diag::note_constexpr_assumption_failed); |
| 5922 | return ESR_Failed; |
| 5923 | } |
| 5924 | } |
| 5925 | } |
| 5926 | |
| 5927 | return EvaluateStmt(Result, Info, S: SS, Case); |
| 5928 | } |
| 5929 | |
| 5930 | case Stmt::CaseStmtClass: |
| 5931 | case Stmt::DefaultStmtClass: |
| 5932 | return EvaluateStmt(Result, Info, S: cast<SwitchCase>(Val: S)->getSubStmt(), Case); |
| 5933 | case Stmt::CXXTryStmtClass: |
| 5934 | // Evaluate try blocks by evaluating all sub statements. |
| 5935 | return EvaluateStmt(Result, Info, S: cast<CXXTryStmt>(Val: S)->getTryBlock(), Case); |
| 5936 | } |
| 5937 | } |
| 5938 | |
| 5939 | /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial |
| 5940 | /// default constructor. If so, we'll fold it whether or not it's marked as |
| 5941 | /// constexpr. If it is marked as constexpr, we will never implicitly define it, |
| 5942 | /// so we need special handling. |
| 5943 | static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, |
| 5944 | const CXXConstructorDecl *CD, |
| 5945 | bool IsValueInitialization) { |
| 5946 | if (!CD->isTrivial() || !CD->isDefaultConstructor()) |
| 5947 | return false; |
| 5948 | |
| 5949 | // Value-initialization does not call a trivial default constructor, so such a |
| 5950 | // call is a core constant expression whether or not the constructor is |
| 5951 | // constexpr. |
| 5952 | if (!CD->isConstexpr() && !IsValueInitialization) { |
| 5953 | if (Info.getLangOpts().CPlusPlus11) { |
| 5954 | // FIXME: If DiagDecl is an implicitly-declared special member function, |
| 5955 | // we should be much more explicit about why it's not constexpr. |
| 5956 | Info.CCEDiag(Loc, DiagId: diag::note_constexpr_invalid_function, ExtraNotes: 1) |
| 5957 | << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; |
| 5958 | Info.Note(Loc: CD->getLocation(), DiagId: diag::note_declared_at); |
| 5959 | } else { |
| 5960 | Info.CCEDiag(Loc, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 5961 | } |
| 5962 | } |
| 5963 | return true; |
| 5964 | } |
| 5965 | |
| 5966 | /// CheckConstexprFunction - Check that a function can be called in a constant |
| 5967 | /// expression. |
| 5968 | static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, |
| 5969 | const FunctionDecl *Declaration, |
| 5970 | const FunctionDecl *Definition, |
| 5971 | const Stmt *Body) { |
| 5972 | // Potential constant expressions can contain calls to declared, but not yet |
| 5973 | // defined, constexpr functions. |
| 5974 | if (Info.checkingPotentialConstantExpression() && !Definition && |
| 5975 | Declaration->isConstexpr()) |
| 5976 | return false; |
| 5977 | |
| 5978 | // Bail out if the function declaration itself is invalid. We will |
| 5979 | // have produced a relevant diagnostic while parsing it, so just |
| 5980 | // note the problematic sub-expression. |
| 5981 | if (Declaration->isInvalidDecl()) { |
| 5982 | Info.FFDiag(Loc: CallLoc, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 5983 | return false; |
| 5984 | } |
| 5985 | |
| 5986 | // DR1872: An instantiated virtual constexpr function can't be called in a |
| 5987 | // constant expression (prior to C++20). We can still constant-fold such a |
| 5988 | // call. |
| 5989 | if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Val: Declaration) && |
| 5990 | cast<CXXMethodDecl>(Val: Declaration)->isVirtual()) |
| 5991 | Info.CCEDiag(Loc: CallLoc, DiagId: diag::note_constexpr_virtual_call); |
| 5992 | |
| 5993 | if (Definition && Definition->isInvalidDecl()) { |
| 5994 | Info.FFDiag(Loc: CallLoc, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 5995 | return false; |
| 5996 | } |
| 5997 | |
| 5998 | // Can we evaluate this function call? |
| 5999 | if (Definition && Body && |
| 6000 | (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr && |
| 6001 | Definition->hasAttr<MSConstexprAttr>()))) |
| 6002 | return true; |
| 6003 | |
| 6004 | const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; |
| 6005 | // Special note for the assert() macro, as the normal error message falsely |
| 6006 | // implies we cannot use an assertion during constant evaluation. |
| 6007 | if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) { |
| 6008 | // FIXME: Instead of checking for an implementation-defined function, |
| 6009 | // check and evaluate the assert() macro. |
| 6010 | StringRef Name = DiagDecl->getName(); |
| 6011 | bool AssertFailed = |
| 6012 | Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert" ; |
| 6013 | if (AssertFailed) { |
| 6014 | Info.FFDiag(Loc: CallLoc, DiagId: diag::note_constexpr_assert_failed); |
| 6015 | return false; |
| 6016 | } |
| 6017 | } |
| 6018 | |
| 6019 | if (Info.getLangOpts().CPlusPlus11) { |
| 6020 | // If this function is not constexpr because it is an inherited |
| 6021 | // non-constexpr constructor, diagnose that directly. |
| 6022 | auto *CD = dyn_cast<CXXConstructorDecl>(Val: DiagDecl); |
| 6023 | if (CD && CD->isInheritingConstructor()) { |
| 6024 | auto *Inherited = CD->getInheritedConstructor().getConstructor(); |
| 6025 | if (!Inherited->isConstexpr()) |
| 6026 | DiagDecl = CD = Inherited; |
| 6027 | } |
| 6028 | |
| 6029 | // FIXME: If DiagDecl is an implicitly-declared special member function |
| 6030 | // or an inheriting constructor, we should be much more explicit about why |
| 6031 | // it's not constexpr. |
| 6032 | if (CD && CD->isInheritingConstructor()) |
| 6033 | Info.FFDiag(Loc: CallLoc, DiagId: diag::note_constexpr_invalid_inhctor, ExtraNotes: 1) |
| 6034 | << CD->getInheritedConstructor().getConstructor()->getParent(); |
| 6035 | else |
| 6036 | Info.FFDiag(Loc: CallLoc, DiagId: diag::note_constexpr_invalid_function, ExtraNotes: 1) |
| 6037 | << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; |
| 6038 | Info.Note(Loc: DiagDecl->getLocation(), DiagId: diag::note_declared_at); |
| 6039 | } else { |
| 6040 | Info.FFDiag(Loc: CallLoc, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 6041 | } |
| 6042 | return false; |
| 6043 | } |
| 6044 | |
| 6045 | namespace { |
| 6046 | struct CheckDynamicTypeHandler { |
| 6047 | AccessKinds AccessKind; |
| 6048 | typedef bool result_type; |
| 6049 | bool failed() { return false; } |
| 6050 | bool found(APValue &Subobj, QualType SubobjType) { return true; } |
| 6051 | bool found(APSInt &Value, QualType SubobjType) { return true; } |
| 6052 | bool found(APFloat &Value, QualType SubobjType) { return true; } |
| 6053 | }; |
| 6054 | } // end anonymous namespace |
| 6055 | |
| 6056 | /// Check that we can access the notional vptr of an object / determine its |
| 6057 | /// dynamic type. |
| 6058 | static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, |
| 6059 | AccessKinds AK, bool Polymorphic) { |
| 6060 | // We are not allowed to invoke a virtual function whose dynamic type |
| 6061 | // is constexpr-unknown, so stop early and let this fail later on if we |
| 6062 | // attempt to do so. |
| 6063 | // C++23 [expr.const]p5.6 |
| 6064 | // an invocation of a virtual function ([class.virtual]) for an object whose |
| 6065 | // dynamic type is constexpr-unknown; |
| 6066 | if (This.allowConstexprUnknown()) |
| 6067 | return true; |
| 6068 | |
| 6069 | if (This.Designator.Invalid) |
| 6070 | return false; |
| 6071 | |
| 6072 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal: This, LValType: QualType()); |
| 6073 | |
| 6074 | if (!Obj) |
| 6075 | return false; |
| 6076 | |
| 6077 | if (!Obj.Value) { |
| 6078 | // The object is not usable in constant expressions, so we can't inspect |
| 6079 | // its value to see if it's in-lifetime or what the active union members |
| 6080 | // are. We can still check for a one-past-the-end lvalue. |
| 6081 | if (This.Designator.isOnePastTheEnd() || |
| 6082 | This.Designator.isMostDerivedAnUnsizedArray()) { |
| 6083 | Info.FFDiag(E, DiagId: This.Designator.isOnePastTheEnd() |
| 6084 | ? diag::note_constexpr_access_past_end |
| 6085 | : diag::note_constexpr_access_unsized_array) |
| 6086 | << AK; |
| 6087 | return false; |
| 6088 | } else if (Polymorphic) { |
| 6089 | // Conservatively refuse to perform a polymorphic operation if we would |
| 6090 | // not be able to read a notional 'vptr' value. |
| 6091 | APValue Val; |
| 6092 | This.moveInto(V&: Val); |
| 6093 | QualType StarThisType = |
| 6094 | Info.Ctx.getLValueReferenceType(T: This.Designator.getType(Ctx&: Info.Ctx)); |
| 6095 | Info.FFDiag(E, DiagId: diag::note_constexpr_polymorphic_unknown_dynamic_type) |
| 6096 | << AK << Val.getAsString(Ctx: Info.Ctx, Ty: StarThisType); |
| 6097 | return false; |
| 6098 | } |
| 6099 | return true; |
| 6100 | } |
| 6101 | |
| 6102 | CheckDynamicTypeHandler Handler{.AccessKind: AK}; |
| 6103 | return Obj && findSubobject(Info, E, Obj, Sub: This.Designator, handler&: Handler); |
| 6104 | } |
| 6105 | |
| 6106 | /// Check that the pointee of the 'this' pointer in a member function call is |
| 6107 | /// either within its lifetime or in its period of construction or destruction. |
| 6108 | static bool |
| 6109 | checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, |
| 6110 | const LValue &This, |
| 6111 | const CXXMethodDecl *NamedMember) { |
| 6112 | return checkDynamicType( |
| 6113 | Info, E, This, |
| 6114 | AK: isa<CXXDestructorDecl>(Val: NamedMember) ? AK_Destroy : AK_MemberCall, Polymorphic: false); |
| 6115 | } |
| 6116 | |
| 6117 | struct DynamicType { |
| 6118 | /// The dynamic class type of the object. |
| 6119 | const CXXRecordDecl *Type; |
| 6120 | /// The corresponding path length in the lvalue. |
| 6121 | unsigned PathLength; |
| 6122 | }; |
| 6123 | |
| 6124 | static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, |
| 6125 | unsigned PathLength) { |
| 6126 | assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= |
| 6127 | Designator.Entries.size() && "invalid path length" ); |
| 6128 | return (PathLength == Designator.MostDerivedPathLength) |
| 6129 | ? Designator.MostDerivedType->getAsCXXRecordDecl() |
| 6130 | : getAsBaseClass(E: Designator.Entries[PathLength - 1]); |
| 6131 | } |
| 6132 | |
| 6133 | /// Determine the dynamic type of an object. |
| 6134 | static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info, |
| 6135 | const Expr *E, |
| 6136 | LValue &This, |
| 6137 | AccessKinds AK) { |
| 6138 | // If we don't have an lvalue denoting an object of class type, there is no |
| 6139 | // meaningful dynamic type. (We consider objects of non-class type to have no |
| 6140 | // dynamic type.) |
| 6141 | if (!checkDynamicType(Info, E, This, AK, |
| 6142 | Polymorphic: (AK == AK_TypeId |
| 6143 | ? (E->getType()->isReferenceType() ? true : false) |
| 6144 | : true))) |
| 6145 | return std::nullopt; |
| 6146 | |
| 6147 | if (This.Designator.Invalid) |
| 6148 | return std::nullopt; |
| 6149 | |
| 6150 | // Refuse to compute a dynamic type in the presence of virtual bases. This |
| 6151 | // shouldn't happen other than in constant-folding situations, since literal |
| 6152 | // types can't have virtual bases. |
| 6153 | // |
| 6154 | // Note that consumers of DynamicType assume that the type has no virtual |
| 6155 | // bases, and will need modifications if this restriction is relaxed. |
| 6156 | const CXXRecordDecl *Class = |
| 6157 | This.Designator.MostDerivedType->getAsCXXRecordDecl(); |
| 6158 | if (!Class || Class->getNumVBases()) { |
| 6159 | Info.FFDiag(E); |
| 6160 | return std::nullopt; |
| 6161 | } |
| 6162 | |
| 6163 | // FIXME: For very deep class hierarchies, it might be beneficial to use a |
| 6164 | // binary search here instead. But the overwhelmingly common case is that |
| 6165 | // we're not in the middle of a constructor, so it probably doesn't matter |
| 6166 | // in practice. |
| 6167 | ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; |
| 6168 | for (unsigned PathLength = This.Designator.MostDerivedPathLength; |
| 6169 | PathLength <= Path.size(); ++PathLength) { |
| 6170 | switch (Info.isEvaluatingCtorDtor(Base: This.getLValueBase(), |
| 6171 | Path: Path.slice(N: 0, M: PathLength))) { |
| 6172 | case ConstructionPhase::Bases: |
| 6173 | case ConstructionPhase::DestroyingBases: |
| 6174 | // We're constructing or destroying a base class. This is not the dynamic |
| 6175 | // type. |
| 6176 | break; |
| 6177 | |
| 6178 | case ConstructionPhase::None: |
| 6179 | case ConstructionPhase::AfterBases: |
| 6180 | case ConstructionPhase::AfterFields: |
| 6181 | case ConstructionPhase::Destroying: |
| 6182 | // We've finished constructing the base classes and not yet started |
| 6183 | // destroying them again, so this is the dynamic type. |
| 6184 | return DynamicType{.Type: getBaseClassType(Designator&: This.Designator, PathLength), |
| 6185 | .PathLength: PathLength}; |
| 6186 | } |
| 6187 | } |
| 6188 | |
| 6189 | // CWG issue 1517: we're constructing a base class of the object described by |
| 6190 | // 'This', so that object has not yet begun its period of construction and |
| 6191 | // any polymorphic operation on it results in undefined behavior. |
| 6192 | Info.FFDiag(E); |
| 6193 | return std::nullopt; |
| 6194 | } |
| 6195 | |
| 6196 | /// Perform virtual dispatch. |
| 6197 | static const CXXMethodDecl *HandleVirtualDispatch( |
| 6198 | EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, |
| 6199 | llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { |
| 6200 | std::optional<DynamicType> DynType = ComputeDynamicType( |
| 6201 | Info, E, This, |
| 6202 | AK: isa<CXXDestructorDecl>(Val: Found) ? AK_Destroy : AK_MemberCall); |
| 6203 | if (!DynType) |
| 6204 | return nullptr; |
| 6205 | |
| 6206 | // Find the final overrider. It must be declared in one of the classes on the |
| 6207 | // path from the dynamic type to the static type. |
| 6208 | // FIXME: If we ever allow literal types to have virtual base classes, that |
| 6209 | // won't be true. |
| 6210 | const CXXMethodDecl *Callee = Found; |
| 6211 | unsigned PathLength = DynType->PathLength; |
| 6212 | for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { |
| 6213 | const CXXRecordDecl *Class = getBaseClassType(Designator&: This.Designator, PathLength); |
| 6214 | const CXXMethodDecl *Overrider = |
| 6215 | Found->getCorrespondingMethodDeclaredInClass(RD: Class, MayBeBase: false); |
| 6216 | if (Overrider) { |
| 6217 | Callee = Overrider; |
| 6218 | break; |
| 6219 | } |
| 6220 | } |
| 6221 | |
| 6222 | // C++2a [class.abstract]p6: |
| 6223 | // the effect of making a virtual call to a pure virtual function [...] is |
| 6224 | // undefined |
| 6225 | if (Callee->isPureVirtual()) { |
| 6226 | Info.FFDiag(E, DiagId: diag::note_constexpr_pure_virtual_call, ExtraNotes: 1) << Callee; |
| 6227 | Info.Note(Loc: Callee->getLocation(), DiagId: diag::note_declared_at); |
| 6228 | return nullptr; |
| 6229 | } |
| 6230 | |
| 6231 | // If necessary, walk the rest of the path to determine the sequence of |
| 6232 | // covariant adjustment steps to apply. |
| 6233 | if (!Info.Ctx.hasSameUnqualifiedType(T1: Callee->getReturnType(), |
| 6234 | T2: Found->getReturnType())) { |
| 6235 | CovariantAdjustmentPath.push_back(Elt: Callee->getReturnType()); |
| 6236 | for (unsigned CovariantPathLength = PathLength + 1; |
| 6237 | CovariantPathLength != This.Designator.Entries.size(); |
| 6238 | ++CovariantPathLength) { |
| 6239 | const CXXRecordDecl *NextClass = |
| 6240 | getBaseClassType(Designator&: This.Designator, PathLength: CovariantPathLength); |
| 6241 | const CXXMethodDecl *Next = |
| 6242 | Found->getCorrespondingMethodDeclaredInClass(RD: NextClass, MayBeBase: false); |
| 6243 | if (Next && !Info.Ctx.hasSameUnqualifiedType( |
| 6244 | T1: Next->getReturnType(), T2: CovariantAdjustmentPath.back())) |
| 6245 | CovariantAdjustmentPath.push_back(Elt: Next->getReturnType()); |
| 6246 | } |
| 6247 | if (!Info.Ctx.hasSameUnqualifiedType(T1: Found->getReturnType(), |
| 6248 | T2: CovariantAdjustmentPath.back())) |
| 6249 | CovariantAdjustmentPath.push_back(Elt: Found->getReturnType()); |
| 6250 | } |
| 6251 | |
| 6252 | // Perform 'this' adjustment. |
| 6253 | if (!CastToDerivedClass(Info, E, Result&: This, TruncatedType: Callee->getParent(), TruncatedElements: PathLength)) |
| 6254 | return nullptr; |
| 6255 | |
| 6256 | return Callee; |
| 6257 | } |
| 6258 | |
| 6259 | /// Perform the adjustment from a value returned by a virtual function to |
| 6260 | /// a value of the statically expected type, which may be a pointer or |
| 6261 | /// reference to a base class of the returned type. |
| 6262 | static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, |
| 6263 | APValue &Result, |
| 6264 | ArrayRef<QualType> Path) { |
| 6265 | assert(Result.isLValue() && |
| 6266 | "unexpected kind of APValue for covariant return" ); |
| 6267 | if (Result.isNullPointer()) |
| 6268 | return true; |
| 6269 | |
| 6270 | LValue LVal; |
| 6271 | LVal.setFrom(Ctx&: Info.Ctx, V: Result); |
| 6272 | |
| 6273 | const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); |
| 6274 | for (unsigned I = 1; I != Path.size(); ++I) { |
| 6275 | const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); |
| 6276 | assert(OldClass && NewClass && "unexpected kind of covariant return" ); |
| 6277 | if (OldClass != NewClass && |
| 6278 | !CastToBaseClass(Info, E, Result&: LVal, DerivedRD: OldClass, BaseRD: NewClass)) |
| 6279 | return false; |
| 6280 | OldClass = NewClass; |
| 6281 | } |
| 6282 | |
| 6283 | LVal.moveInto(V&: Result); |
| 6284 | return true; |
| 6285 | } |
| 6286 | |
| 6287 | /// Determine whether \p Base, which is known to be a direct base class of |
| 6288 | /// \p Derived, is a public base class. |
| 6289 | static bool isBaseClassPublic(const CXXRecordDecl *Derived, |
| 6290 | const CXXRecordDecl *Base) { |
| 6291 | for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { |
| 6292 | auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); |
| 6293 | if (BaseClass && declaresSameEntity(D1: BaseClass, D2: Base)) |
| 6294 | return BaseSpec.getAccessSpecifier() == AS_public; |
| 6295 | } |
| 6296 | llvm_unreachable("Base is not a direct base of Derived" ); |
| 6297 | } |
| 6298 | |
| 6299 | /// Apply the given dynamic cast operation on the provided lvalue. |
| 6300 | /// |
| 6301 | /// This implements the hard case of dynamic_cast, requiring a "runtime check" |
| 6302 | /// to find a suitable target subobject. |
| 6303 | static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, |
| 6304 | LValue &Ptr) { |
| 6305 | // We can't do anything with a non-symbolic pointer value. |
| 6306 | SubobjectDesignator &D = Ptr.Designator; |
| 6307 | if (D.Invalid) |
| 6308 | return false; |
| 6309 | |
| 6310 | // C++ [expr.dynamic.cast]p6: |
| 6311 | // If v is a null pointer value, the result is a null pointer value. |
| 6312 | if (Ptr.isNullPointer() && !E->isGLValue()) |
| 6313 | return true; |
| 6314 | |
| 6315 | // For all the other cases, we need the pointer to point to an object within |
| 6316 | // its lifetime / period of construction / destruction, and we need to know |
| 6317 | // its dynamic type. |
| 6318 | std::optional<DynamicType> DynType = |
| 6319 | ComputeDynamicType(Info, E, This&: Ptr, AK: AK_DynamicCast); |
| 6320 | if (!DynType) |
| 6321 | return false; |
| 6322 | |
| 6323 | // C++ [expr.dynamic.cast]p7: |
| 6324 | // If T is "pointer to cv void", then the result is a pointer to the most |
| 6325 | // derived object |
| 6326 | if (E->getType()->isVoidPointerType()) |
| 6327 | return CastToDerivedClass(Info, E, Result&: Ptr, TruncatedType: DynType->Type, TruncatedElements: DynType->PathLength); |
| 6328 | |
| 6329 | const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); |
| 6330 | assert(C && "dynamic_cast target is not void pointer nor class" ); |
| 6331 | CanQualType CQT = Info.Ctx.getCanonicalType(T: Info.Ctx.getRecordType(Decl: C)); |
| 6332 | |
| 6333 | auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { |
| 6334 | // C++ [expr.dynamic.cast]p9: |
| 6335 | if (!E->isGLValue()) { |
| 6336 | // The value of a failed cast to pointer type is the null pointer value |
| 6337 | // of the required result type. |
| 6338 | Ptr.setNull(Ctx&: Info.Ctx, PointerTy: E->getType()); |
| 6339 | return true; |
| 6340 | } |
| 6341 | |
| 6342 | // A failed cast to reference type throws [...] std::bad_cast. |
| 6343 | unsigned DiagKind; |
| 6344 | if (!Paths && (declaresSameEntity(D1: DynType->Type, D2: C) || |
| 6345 | DynType->Type->isDerivedFrom(Base: C))) |
| 6346 | DiagKind = 0; |
| 6347 | else if (!Paths || Paths->begin() == Paths->end()) |
| 6348 | DiagKind = 1; |
| 6349 | else if (Paths->isAmbiguous(BaseType: CQT)) |
| 6350 | DiagKind = 2; |
| 6351 | else { |
| 6352 | assert(Paths->front().Access != AS_public && "why did the cast fail?" ); |
| 6353 | DiagKind = 3; |
| 6354 | } |
| 6355 | Info.FFDiag(E, DiagId: diag::note_constexpr_dynamic_cast_to_reference_failed) |
| 6356 | << DiagKind << Ptr.Designator.getType(Ctx&: Info.Ctx) |
| 6357 | << Info.Ctx.getRecordType(Decl: DynType->Type) |
| 6358 | << E->getType().getUnqualifiedType(); |
| 6359 | return false; |
| 6360 | }; |
| 6361 | |
| 6362 | // Runtime check, phase 1: |
| 6363 | // Walk from the base subobject towards the derived object looking for the |
| 6364 | // target type. |
| 6365 | for (int PathLength = Ptr.Designator.Entries.size(); |
| 6366 | PathLength >= (int)DynType->PathLength; --PathLength) { |
| 6367 | const CXXRecordDecl *Class = getBaseClassType(Designator&: Ptr.Designator, PathLength); |
| 6368 | if (declaresSameEntity(D1: Class, D2: C)) |
| 6369 | return CastToDerivedClass(Info, E, Result&: Ptr, TruncatedType: Class, TruncatedElements: PathLength); |
| 6370 | // We can only walk across public inheritance edges. |
| 6371 | if (PathLength > (int)DynType->PathLength && |
| 6372 | !isBaseClassPublic(Derived: getBaseClassType(Designator&: Ptr.Designator, PathLength: PathLength - 1), |
| 6373 | Base: Class)) |
| 6374 | return RuntimeCheckFailed(nullptr); |
| 6375 | } |
| 6376 | |
| 6377 | // Runtime check, phase 2: |
| 6378 | // Search the dynamic type for an unambiguous public base of type C. |
| 6379 | CXXBasePaths Paths(/*FindAmbiguities=*/true, |
| 6380 | /*RecordPaths=*/true, /*DetectVirtual=*/false); |
| 6381 | if (DynType->Type->isDerivedFrom(Base: C, Paths) && !Paths.isAmbiguous(BaseType: CQT) && |
| 6382 | Paths.front().Access == AS_public) { |
| 6383 | // Downcast to the dynamic type... |
| 6384 | if (!CastToDerivedClass(Info, E, Result&: Ptr, TruncatedType: DynType->Type, TruncatedElements: DynType->PathLength)) |
| 6385 | return false; |
| 6386 | // ... then upcast to the chosen base class subobject. |
| 6387 | for (CXXBasePathElement &Elem : Paths.front()) |
| 6388 | if (!HandleLValueBase(Info, E, Obj&: Ptr, DerivedDecl: Elem.Class, Base: Elem.Base)) |
| 6389 | return false; |
| 6390 | return true; |
| 6391 | } |
| 6392 | |
| 6393 | // Otherwise, the runtime check fails. |
| 6394 | return RuntimeCheckFailed(&Paths); |
| 6395 | } |
| 6396 | |
| 6397 | namespace { |
| 6398 | struct StartLifetimeOfUnionMemberHandler { |
| 6399 | EvalInfo &Info; |
| 6400 | const Expr *LHSExpr; |
| 6401 | const FieldDecl *Field; |
| 6402 | bool DuringInit; |
| 6403 | bool Failed = false; |
| 6404 | static const AccessKinds AccessKind = AK_Assign; |
| 6405 | |
| 6406 | typedef bool result_type; |
| 6407 | bool failed() { return Failed; } |
| 6408 | bool found(APValue &Subobj, QualType SubobjType) { |
| 6409 | // We are supposed to perform no initialization but begin the lifetime of |
| 6410 | // the object. We interpret that as meaning to do what default |
| 6411 | // initialization of the object would do if all constructors involved were |
| 6412 | // trivial: |
| 6413 | // * All base, non-variant member, and array element subobjects' lifetimes |
| 6414 | // begin |
| 6415 | // * No variant members' lifetimes begin |
| 6416 | // * All scalar subobjects whose lifetimes begin have indeterminate values |
| 6417 | assert(SubobjType->isUnionType()); |
| 6418 | if (declaresSameEntity(D1: Subobj.getUnionField(), D2: Field)) { |
| 6419 | // This union member is already active. If it's also in-lifetime, there's |
| 6420 | // nothing to do. |
| 6421 | if (Subobj.getUnionValue().hasValue()) |
| 6422 | return true; |
| 6423 | } else if (DuringInit) { |
| 6424 | // We're currently in the process of initializing a different union |
| 6425 | // member. If we carried on, that initialization would attempt to |
| 6426 | // store to an inactive union member, resulting in undefined behavior. |
| 6427 | Info.FFDiag(E: LHSExpr, |
| 6428 | DiagId: diag::note_constexpr_union_member_change_during_init); |
| 6429 | return false; |
| 6430 | } |
| 6431 | APValue Result; |
| 6432 | Failed = !handleDefaultInitValue(T: Field->getType(), Result); |
| 6433 | Subobj.setUnion(Field, Value: Result); |
| 6434 | return true; |
| 6435 | } |
| 6436 | bool found(APSInt &Value, QualType SubobjType) { |
| 6437 | llvm_unreachable("wrong value kind for union object" ); |
| 6438 | } |
| 6439 | bool found(APFloat &Value, QualType SubobjType) { |
| 6440 | llvm_unreachable("wrong value kind for union object" ); |
| 6441 | } |
| 6442 | }; |
| 6443 | } // end anonymous namespace |
| 6444 | |
| 6445 | const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; |
| 6446 | |
| 6447 | /// Handle a builtin simple-assignment or a call to a trivial assignment |
| 6448 | /// operator whose left-hand side might involve a union member access. If it |
| 6449 | /// does, implicitly start the lifetime of any accessed union elements per |
| 6450 | /// C++20 [class.union]5. |
| 6451 | static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, |
| 6452 | const Expr *LHSExpr, |
| 6453 | const LValue &LHS) { |
| 6454 | if (LHS.InvalidBase || LHS.Designator.Invalid) |
| 6455 | return false; |
| 6456 | |
| 6457 | llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; |
| 6458 | // C++ [class.union]p5: |
| 6459 | // define the set S(E) of subexpressions of E as follows: |
| 6460 | unsigned PathLength = LHS.Designator.Entries.size(); |
| 6461 | for (const Expr *E = LHSExpr; E != nullptr;) { |
| 6462 | // -- If E is of the form A.B, S(E) contains the elements of S(A)... |
| 6463 | if (auto *ME = dyn_cast<MemberExpr>(Val: E)) { |
| 6464 | auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()); |
| 6465 | // Note that we can't implicitly start the lifetime of a reference, |
| 6466 | // so we don't need to proceed any further if we reach one. |
| 6467 | if (!FD || FD->getType()->isReferenceType()) |
| 6468 | break; |
| 6469 | |
| 6470 | // ... and also contains A.B if B names a union member ... |
| 6471 | if (FD->getParent()->isUnion()) { |
| 6472 | // ... of a non-class, non-array type, or of a class type with a |
| 6473 | // trivial default constructor that is not deleted, or an array of |
| 6474 | // such types. |
| 6475 | auto *RD = |
| 6476 | FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
| 6477 | if (!RD || RD->hasTrivialDefaultConstructor()) |
| 6478 | UnionPathLengths.push_back(Elt: {PathLength - 1, FD}); |
| 6479 | } |
| 6480 | |
| 6481 | E = ME->getBase(); |
| 6482 | --PathLength; |
| 6483 | assert(declaresSameEntity(FD, |
| 6484 | LHS.Designator.Entries[PathLength] |
| 6485 | .getAsBaseOrMember().getPointer())); |
| 6486 | |
| 6487 | // -- If E is of the form A[B] and is interpreted as a built-in array |
| 6488 | // subscripting operator, S(E) is [S(the array operand, if any)]. |
| 6489 | } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: E)) { |
| 6490 | // Step over an ArrayToPointerDecay implicit cast. |
| 6491 | auto *Base = ASE->getBase()->IgnoreImplicit(); |
| 6492 | if (!Base->getType()->isArrayType()) |
| 6493 | break; |
| 6494 | |
| 6495 | E = Base; |
| 6496 | --PathLength; |
| 6497 | |
| 6498 | } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) { |
| 6499 | // Step over a derived-to-base conversion. |
| 6500 | E = ICE->getSubExpr(); |
| 6501 | if (ICE->getCastKind() == CK_NoOp) |
| 6502 | continue; |
| 6503 | if (ICE->getCastKind() != CK_DerivedToBase && |
| 6504 | ICE->getCastKind() != CK_UncheckedDerivedToBase) |
| 6505 | break; |
| 6506 | // Walk path backwards as we walk up from the base to the derived class. |
| 6507 | for (const CXXBaseSpecifier *Elt : llvm::reverse(C: ICE->path())) { |
| 6508 | if (Elt->isVirtual()) { |
| 6509 | // A class with virtual base classes never has a trivial default |
| 6510 | // constructor, so S(E) is empty in this case. |
| 6511 | E = nullptr; |
| 6512 | break; |
| 6513 | } |
| 6514 | |
| 6515 | --PathLength; |
| 6516 | assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), |
| 6517 | LHS.Designator.Entries[PathLength] |
| 6518 | .getAsBaseOrMember().getPointer())); |
| 6519 | } |
| 6520 | |
| 6521 | // -- Otherwise, S(E) is empty. |
| 6522 | } else { |
| 6523 | break; |
| 6524 | } |
| 6525 | } |
| 6526 | |
| 6527 | // Common case: no unions' lifetimes are started. |
| 6528 | if (UnionPathLengths.empty()) |
| 6529 | return true; |
| 6530 | |
| 6531 | // if modification of X [would access an inactive union member], an object |
| 6532 | // of the type of X is implicitly created |
| 6533 | CompleteObject Obj = |
| 6534 | findCompleteObject(Info, E: LHSExpr, AK: AK_Assign, LVal: LHS, LValType: LHSExpr->getType()); |
| 6535 | if (!Obj) |
| 6536 | return false; |
| 6537 | for (std::pair<unsigned, const FieldDecl *> LengthAndField : |
| 6538 | llvm::reverse(C&: UnionPathLengths)) { |
| 6539 | // Form a designator for the union object. |
| 6540 | SubobjectDesignator D = LHS.Designator; |
| 6541 | D.truncate(Ctx&: Info.Ctx, Base: LHS.Base, NewLength: LengthAndField.first); |
| 6542 | |
| 6543 | bool DuringInit = Info.isEvaluatingCtorDtor(Base: LHS.Base, Path: D.Entries) == |
| 6544 | ConstructionPhase::AfterBases; |
| 6545 | StartLifetimeOfUnionMemberHandler StartLifetime{ |
| 6546 | .Info: Info, .LHSExpr: LHSExpr, .Field: LengthAndField.second, .DuringInit: DuringInit}; |
| 6547 | if (!findSubobject(Info, E: LHSExpr, Obj, Sub: D, handler&: StartLifetime)) |
| 6548 | return false; |
| 6549 | } |
| 6550 | |
| 6551 | return true; |
| 6552 | } |
| 6553 | |
| 6554 | static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, |
| 6555 | CallRef Call, EvalInfo &Info, bool NonNull = false, |
| 6556 | APValue **EvaluatedArg = nullptr) { |
| 6557 | LValue LV; |
| 6558 | // Create the parameter slot and register its destruction. For a vararg |
| 6559 | // argument, create a temporary. |
| 6560 | // FIXME: For calling conventions that destroy parameters in the callee, |
| 6561 | // should we consider performing destruction when the function returns |
| 6562 | // instead? |
| 6563 | APValue &V = PVD ? Info.CurrentCall->createParam(Args: Call, PVD, LV) |
| 6564 | : Info.CurrentCall->createTemporary(Key: Arg, T: Arg->getType(), |
| 6565 | Scope: ScopeKind::Call, LV); |
| 6566 | if (!EvaluateInPlace(Result&: V, Info, This: LV, E: Arg)) |
| 6567 | return false; |
| 6568 | |
| 6569 | // Passing a null pointer to an __attribute__((nonnull)) parameter results in |
| 6570 | // undefined behavior, so is non-constant. |
| 6571 | if (NonNull && V.isLValue() && V.isNullPointer()) { |
| 6572 | Info.CCEDiag(E: Arg, DiagId: diag::note_non_null_attribute_failed); |
| 6573 | return false; |
| 6574 | } |
| 6575 | |
| 6576 | if (EvaluatedArg) |
| 6577 | *EvaluatedArg = &V; |
| 6578 | |
| 6579 | return true; |
| 6580 | } |
| 6581 | |
| 6582 | /// Evaluate the arguments to a function call. |
| 6583 | static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, |
| 6584 | EvalInfo &Info, const FunctionDecl *Callee, |
| 6585 | bool RightToLeft = false, |
| 6586 | LValue *ObjectArg = nullptr) { |
| 6587 | bool Success = true; |
| 6588 | llvm::SmallBitVector ForbiddenNullArgs; |
| 6589 | if (Callee->hasAttr<NonNullAttr>()) { |
| 6590 | ForbiddenNullArgs.resize(N: Args.size()); |
| 6591 | for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { |
| 6592 | if (!Attr->args_size()) { |
| 6593 | ForbiddenNullArgs.set(); |
| 6594 | break; |
| 6595 | } else |
| 6596 | for (auto Idx : Attr->args()) { |
| 6597 | unsigned ASTIdx = Idx.getASTIndex(); |
| 6598 | if (ASTIdx >= Args.size()) |
| 6599 | continue; |
| 6600 | ForbiddenNullArgs[ASTIdx] = true; |
| 6601 | } |
| 6602 | } |
| 6603 | } |
| 6604 | for (unsigned I = 0; I < Args.size(); I++) { |
| 6605 | unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; |
| 6606 | const ParmVarDecl *PVD = |
| 6607 | Idx < Callee->getNumParams() ? Callee->getParamDecl(i: Idx) : nullptr; |
| 6608 | bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; |
| 6609 | APValue *That = nullptr; |
| 6610 | if (!EvaluateCallArg(PVD, Arg: Args[Idx], Call, Info, NonNull, EvaluatedArg: &That)) { |
| 6611 | // If we're checking for a potential constant expression, evaluate all |
| 6612 | // initializers even if some of them fail. |
| 6613 | if (!Info.noteFailure()) |
| 6614 | return false; |
| 6615 | Success = false; |
| 6616 | } |
| 6617 | if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue()) |
| 6618 | ObjectArg->setFrom(Ctx&: Info.Ctx, V: *That); |
| 6619 | } |
| 6620 | return Success; |
| 6621 | } |
| 6622 | |
| 6623 | /// Perform a trivial copy from Param, which is the parameter of a copy or move |
| 6624 | /// constructor or assignment operator. |
| 6625 | static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, |
| 6626 | const Expr *E, APValue &Result, |
| 6627 | bool CopyObjectRepresentation) { |
| 6628 | // Find the reference argument. |
| 6629 | CallStackFrame *Frame = Info.CurrentCall; |
| 6630 | APValue *RefValue = Info.getParamSlot(Call: Frame->Arguments, PVD: Param); |
| 6631 | if (!RefValue) { |
| 6632 | Info.FFDiag(E); |
| 6633 | return false; |
| 6634 | } |
| 6635 | |
| 6636 | // Copy out the contents of the RHS object. |
| 6637 | LValue RefLValue; |
| 6638 | RefLValue.setFrom(Ctx&: Info.Ctx, V: *RefValue); |
| 6639 | return handleLValueToRValueConversion( |
| 6640 | Info, Conv: E, Type: Param->getType().getNonReferenceType(), LVal: RefLValue, RVal&: Result, |
| 6641 | WantObjectRepresentation: CopyObjectRepresentation); |
| 6642 | } |
| 6643 | |
| 6644 | /// Evaluate a function call. |
| 6645 | static bool HandleFunctionCall(SourceLocation CallLoc, |
| 6646 | const FunctionDecl *Callee, |
| 6647 | const LValue *ObjectArg, const Expr *E, |
| 6648 | ArrayRef<const Expr *> Args, CallRef Call, |
| 6649 | const Stmt *Body, EvalInfo &Info, |
| 6650 | APValue &Result, const LValue *ResultSlot) { |
| 6651 | if (!Info.CheckCallLimit(Loc: CallLoc)) |
| 6652 | return false; |
| 6653 | |
| 6654 | CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call); |
| 6655 | |
| 6656 | // For a trivial copy or move assignment, perform an APValue copy. This is |
| 6657 | // essential for unions, where the operations performed by the assignment |
| 6658 | // operator cannot be represented as statements. |
| 6659 | // |
| 6660 | // Skip this for non-union classes with no fields; in that case, the defaulted |
| 6661 | // copy/move does not actually read the object. |
| 6662 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Callee); |
| 6663 | if (MD && MD->isDefaulted() && |
| 6664 | (MD->getParent()->isUnion() || |
| 6665 | (MD->isTrivial() && |
| 6666 | isReadByLvalueToRvalueConversion(RD: MD->getParent())))) { |
| 6667 | unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0; |
| 6668 | assert(ObjectArg && |
| 6669 | (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); |
| 6670 | APValue RHSValue; |
| 6671 | if (!handleTrivialCopy(Info, Param: MD->getParamDecl(i: 0), E: Args[0], Result&: RHSValue, |
| 6672 | CopyObjectRepresentation: MD->getParent()->isUnion())) |
| 6673 | return false; |
| 6674 | |
| 6675 | LValue Obj; |
| 6676 | if (!handleAssignment(Info, E: Args[ExplicitOffset], LVal: *ObjectArg, |
| 6677 | LValType: MD->getFunctionObjectParameterReferenceType(), |
| 6678 | Val&: RHSValue)) |
| 6679 | return false; |
| 6680 | ObjectArg->moveInto(V&: Result); |
| 6681 | return true; |
| 6682 | } else if (MD && isLambdaCallOperator(MD)) { |
| 6683 | // We're in a lambda; determine the lambda capture field maps unless we're |
| 6684 | // just constexpr checking a lambda's call operator. constexpr checking is |
| 6685 | // done before the captures have been added to the closure object (unless |
| 6686 | // we're inferring constexpr-ness), so we don't have access to them in this |
| 6687 | // case. But since we don't need the captures to constexpr check, we can |
| 6688 | // just ignore them. |
| 6689 | if (!Info.checkingPotentialConstantExpression()) |
| 6690 | MD->getParent()->getCaptureFields(Captures&: Frame.LambdaCaptureFields, |
| 6691 | ThisCapture&: Frame.LambdaThisCaptureField); |
| 6692 | } |
| 6693 | |
| 6694 | StmtResult Ret = {.Value: Result, .Slot: ResultSlot}; |
| 6695 | EvalStmtResult ESR = EvaluateStmt(Result&: Ret, Info, S: Body); |
| 6696 | if (ESR == ESR_Succeeded) { |
| 6697 | if (Callee->getReturnType()->isVoidType()) |
| 6698 | return true; |
| 6699 | Info.FFDiag(Loc: Callee->getEndLoc(), DiagId: diag::note_constexpr_no_return); |
| 6700 | } |
| 6701 | return ESR == ESR_Returned; |
| 6702 | } |
| 6703 | |
| 6704 | /// Evaluate a constructor call. |
| 6705 | static bool HandleConstructorCall(const Expr *E, const LValue &This, |
| 6706 | CallRef Call, |
| 6707 | const CXXConstructorDecl *Definition, |
| 6708 | EvalInfo &Info, APValue &Result) { |
| 6709 | SourceLocation CallLoc = E->getExprLoc(); |
| 6710 | if (!Info.CheckCallLimit(Loc: CallLoc)) |
| 6711 | return false; |
| 6712 | |
| 6713 | const CXXRecordDecl *RD = Definition->getParent(); |
| 6714 | if (RD->getNumVBases()) { |
| 6715 | Info.FFDiag(Loc: CallLoc, DiagId: diag::note_constexpr_virtual_base) << RD; |
| 6716 | return false; |
| 6717 | } |
| 6718 | |
| 6719 | EvalInfo::EvaluatingConstructorRAII EvalObj( |
| 6720 | Info, |
| 6721 | ObjectUnderConstruction{.Base: This.getLValueBase(), .Path: This.Designator.Entries}, |
| 6722 | RD->getNumBases()); |
| 6723 | CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call); |
| 6724 | |
| 6725 | // FIXME: Creating an APValue just to hold a nonexistent return value is |
| 6726 | // wasteful. |
| 6727 | APValue RetVal; |
| 6728 | StmtResult Ret = {.Value: RetVal, .Slot: nullptr}; |
| 6729 | |
| 6730 | // If it's a delegating constructor, delegate. |
| 6731 | if (Definition->isDelegatingConstructor()) { |
| 6732 | CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); |
| 6733 | if ((*I)->getInit()->isValueDependent()) { |
| 6734 | if (!EvaluateDependentExpr(E: (*I)->getInit(), Info)) |
| 6735 | return false; |
| 6736 | } else { |
| 6737 | FullExpressionRAII InitScope(Info); |
| 6738 | if (!EvaluateInPlace(Result, Info, This, E: (*I)->getInit()) || |
| 6739 | !InitScope.destroy()) |
| 6740 | return false; |
| 6741 | } |
| 6742 | return EvaluateStmt(Result&: Ret, Info, S: Definition->getBody()) != ESR_Failed; |
| 6743 | } |
| 6744 | |
| 6745 | // For a trivial copy or move constructor, perform an APValue copy. This is |
| 6746 | // essential for unions (or classes with anonymous union members), where the |
| 6747 | // operations performed by the constructor cannot be represented by |
| 6748 | // ctor-initializers. |
| 6749 | // |
| 6750 | // Skip this for empty non-union classes; we should not perform an |
| 6751 | // lvalue-to-rvalue conversion on them because their copy constructor does not |
| 6752 | // actually read them. |
| 6753 | if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && |
| 6754 | (Definition->getParent()->isUnion() || |
| 6755 | (Definition->isTrivial() && |
| 6756 | isReadByLvalueToRvalueConversion(RD: Definition->getParent())))) { |
| 6757 | return handleTrivialCopy(Info, Param: Definition->getParamDecl(i: 0), E, Result, |
| 6758 | CopyObjectRepresentation: Definition->getParent()->isUnion()); |
| 6759 | } |
| 6760 | |
| 6761 | // Reserve space for the struct members. |
| 6762 | if (!Result.hasValue()) { |
| 6763 | if (!RD->isUnion()) |
| 6764 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), |
| 6765 | std::distance(first: RD->field_begin(), last: RD->field_end())); |
| 6766 | else |
| 6767 | // A union starts with no active member. |
| 6768 | Result = APValue((const FieldDecl*)nullptr); |
| 6769 | } |
| 6770 | |
| 6771 | if (RD->isInvalidDecl()) return false; |
| 6772 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD); |
| 6773 | |
| 6774 | // A scope for temporaries lifetime-extended by reference members. |
| 6775 | BlockScopeRAII LifetimeExtendedScope(Info); |
| 6776 | |
| 6777 | bool Success = true; |
| 6778 | unsigned BasesSeen = 0; |
| 6779 | #ifndef NDEBUG |
| 6780 | CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); |
| 6781 | #endif |
| 6782 | CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); |
| 6783 | auto SkipToField = [&](FieldDecl *FD, bool Indirect) { |
| 6784 | // We might be initializing the same field again if this is an indirect |
| 6785 | // field initialization. |
| 6786 | if (FieldIt == RD->field_end() || |
| 6787 | FieldIt->getFieldIndex() > FD->getFieldIndex()) { |
| 6788 | assert(Indirect && "fields out of order?" ); |
| 6789 | return; |
| 6790 | } |
| 6791 | |
| 6792 | // Default-initialize any fields with no explicit initializer. |
| 6793 | for (; !declaresSameEntity(D1: *FieldIt, D2: FD); ++FieldIt) { |
| 6794 | assert(FieldIt != RD->field_end() && "missing field?" ); |
| 6795 | if (!FieldIt->isUnnamedBitField()) |
| 6796 | Success &= handleDefaultInitValue( |
| 6797 | T: FieldIt->getType(), |
| 6798 | Result&: Result.getStructField(i: FieldIt->getFieldIndex())); |
| 6799 | } |
| 6800 | ++FieldIt; |
| 6801 | }; |
| 6802 | for (const auto *I : Definition->inits()) { |
| 6803 | LValue Subobject = This; |
| 6804 | LValue SubobjectParent = This; |
| 6805 | APValue *Value = &Result; |
| 6806 | |
| 6807 | // Determine the subobject to initialize. |
| 6808 | FieldDecl *FD = nullptr; |
| 6809 | if (I->isBaseInitializer()) { |
| 6810 | QualType BaseType(I->getBaseClass(), 0); |
| 6811 | #ifndef NDEBUG |
| 6812 | // Non-virtual base classes are initialized in the order in the class |
| 6813 | // definition. We have already checked for virtual base classes. |
| 6814 | assert(!BaseIt->isVirtual() && "virtual base for literal type" ); |
| 6815 | assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) && |
| 6816 | "base class initializers not in expected order" ); |
| 6817 | ++BaseIt; |
| 6818 | #endif |
| 6819 | if (!HandleLValueDirectBase(Info, E: I->getInit(), Obj&: Subobject, Derived: RD, |
| 6820 | Base: BaseType->getAsCXXRecordDecl(), RL: &Layout)) |
| 6821 | return false; |
| 6822 | Value = &Result.getStructBase(i: BasesSeen++); |
| 6823 | } else if ((FD = I->getMember())) { |
| 6824 | if (!HandleLValueMember(Info, E: I->getInit(), LVal&: Subobject, FD, RL: &Layout)) |
| 6825 | return false; |
| 6826 | if (RD->isUnion()) { |
| 6827 | Result = APValue(FD); |
| 6828 | Value = &Result.getUnionValue(); |
| 6829 | } else { |
| 6830 | SkipToField(FD, false); |
| 6831 | Value = &Result.getStructField(i: FD->getFieldIndex()); |
| 6832 | } |
| 6833 | } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { |
| 6834 | // Walk the indirect field decl's chain to find the object to initialize, |
| 6835 | // and make sure we've initialized every step along it. |
| 6836 | auto IndirectFieldChain = IFD->chain(); |
| 6837 | for (auto *C : IndirectFieldChain) { |
| 6838 | FD = cast<FieldDecl>(Val: C); |
| 6839 | CXXRecordDecl *CD = cast<CXXRecordDecl>(Val: FD->getParent()); |
| 6840 | // Switch the union field if it differs. This happens if we had |
| 6841 | // preceding zero-initialization, and we're now initializing a union |
| 6842 | // subobject other than the first. |
| 6843 | // FIXME: In this case, the values of the other subobjects are |
| 6844 | // specified, since zero-initialization sets all padding bits to zero. |
| 6845 | if (!Value->hasValue() || |
| 6846 | (Value->isUnion() && |
| 6847 | !declaresSameEntity(D1: Value->getUnionField(), D2: FD))) { |
| 6848 | if (CD->isUnion()) |
| 6849 | *Value = APValue(FD); |
| 6850 | else |
| 6851 | // FIXME: This immediately starts the lifetime of all members of |
| 6852 | // an anonymous struct. It would be preferable to strictly start |
| 6853 | // member lifetime in initialization order. |
| 6854 | Success &= |
| 6855 | handleDefaultInitValue(T: Info.Ctx.getRecordType(Decl: CD), Result&: *Value); |
| 6856 | } |
| 6857 | // Store Subobject as its parent before updating it for the last element |
| 6858 | // in the chain. |
| 6859 | if (C == IndirectFieldChain.back()) |
| 6860 | SubobjectParent = Subobject; |
| 6861 | if (!HandleLValueMember(Info, E: I->getInit(), LVal&: Subobject, FD)) |
| 6862 | return false; |
| 6863 | if (CD->isUnion()) |
| 6864 | Value = &Value->getUnionValue(); |
| 6865 | else { |
| 6866 | if (C == IndirectFieldChain.front() && !RD->isUnion()) |
| 6867 | SkipToField(FD, true); |
| 6868 | Value = &Value->getStructField(i: FD->getFieldIndex()); |
| 6869 | } |
| 6870 | } |
| 6871 | } else { |
| 6872 | llvm_unreachable("unknown base initializer kind" ); |
| 6873 | } |
| 6874 | |
| 6875 | // Need to override This for implicit field initializers as in this case |
| 6876 | // This refers to innermost anonymous struct/union containing initializer, |
| 6877 | // not to currently constructed class. |
| 6878 | const Expr *Init = I->getInit(); |
| 6879 | if (Init->isValueDependent()) { |
| 6880 | if (!EvaluateDependentExpr(E: Init, Info)) |
| 6881 | return false; |
| 6882 | } else { |
| 6883 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, |
| 6884 | isa<CXXDefaultInitExpr>(Val: Init)); |
| 6885 | FullExpressionRAII InitScope(Info); |
| 6886 | if (!EvaluateInPlace(Result&: *Value, Info, This: Subobject, E: Init) || |
| 6887 | (FD && FD->isBitField() && |
| 6888 | !truncateBitfieldValue(Info, E: Init, Value&: *Value, FD))) { |
| 6889 | // If we're checking for a potential constant expression, evaluate all |
| 6890 | // initializers even if some of them fail. |
| 6891 | if (!Info.noteFailure()) |
| 6892 | return false; |
| 6893 | Success = false; |
| 6894 | } |
| 6895 | } |
| 6896 | |
| 6897 | // This is the point at which the dynamic type of the object becomes this |
| 6898 | // class type. |
| 6899 | if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) |
| 6900 | EvalObj.finishedConstructingBases(); |
| 6901 | } |
| 6902 | |
| 6903 | // Default-initialize any remaining fields. |
| 6904 | if (!RD->isUnion()) { |
| 6905 | for (; FieldIt != RD->field_end(); ++FieldIt) { |
| 6906 | if (!FieldIt->isUnnamedBitField()) |
| 6907 | Success &= handleDefaultInitValue( |
| 6908 | T: FieldIt->getType(), |
| 6909 | Result&: Result.getStructField(i: FieldIt->getFieldIndex())); |
| 6910 | } |
| 6911 | } |
| 6912 | |
| 6913 | EvalObj.finishedConstructingFields(); |
| 6914 | |
| 6915 | return Success && |
| 6916 | EvaluateStmt(Result&: Ret, Info, S: Definition->getBody()) != ESR_Failed && |
| 6917 | LifetimeExtendedScope.destroy(); |
| 6918 | } |
| 6919 | |
| 6920 | static bool HandleConstructorCall(const Expr *E, const LValue &This, |
| 6921 | ArrayRef<const Expr*> Args, |
| 6922 | const CXXConstructorDecl *Definition, |
| 6923 | EvalInfo &Info, APValue &Result) { |
| 6924 | CallScopeRAII CallScope(Info); |
| 6925 | CallRef Call = Info.CurrentCall->createCall(Callee: Definition); |
| 6926 | if (!EvaluateArgs(Args, Call, Info, Callee: Definition)) |
| 6927 | return false; |
| 6928 | |
| 6929 | return HandleConstructorCall(E, This, Call, Definition, Info, Result) && |
| 6930 | CallScope.destroy(); |
| 6931 | } |
| 6932 | |
| 6933 | static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, |
| 6934 | const LValue &This, APValue &Value, |
| 6935 | QualType T) { |
| 6936 | // Objects can only be destroyed while they're within their lifetimes. |
| 6937 | // FIXME: We have no representation for whether an object of type nullptr_t |
| 6938 | // is in its lifetime; it usually doesn't matter. Perhaps we should model it |
| 6939 | // as indeterminate instead? |
| 6940 | if (Value.isAbsent() && !T->isNullPtrType()) { |
| 6941 | APValue Printable; |
| 6942 | This.moveInto(V&: Printable); |
| 6943 | Info.FFDiag(Loc: CallRange.getBegin(), |
| 6944 | DiagId: diag::note_constexpr_destroy_out_of_lifetime) |
| 6945 | << Printable.getAsString(Ctx: Info.Ctx, Ty: Info.Ctx.getLValueReferenceType(T)); |
| 6946 | return false; |
| 6947 | } |
| 6948 | |
| 6949 | // Invent an expression for location purposes. |
| 6950 | // FIXME: We shouldn't need to do this. |
| 6951 | OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue); |
| 6952 | |
| 6953 | // For arrays, destroy elements right-to-left. |
| 6954 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { |
| 6955 | uint64_t Size = CAT->getZExtSize(); |
| 6956 | QualType ElemT = CAT->getElementType(); |
| 6957 | |
| 6958 | if (!CheckArraySize(Info, CAT, CallLoc: CallRange.getBegin())) |
| 6959 | return false; |
| 6960 | |
| 6961 | LValue ElemLV = This; |
| 6962 | ElemLV.addArray(Info, E: &LocE, CAT); |
| 6963 | if (!HandleLValueArrayAdjustment(Info, E: &LocE, LVal&: ElemLV, EltTy: ElemT, Adjustment: Size)) |
| 6964 | return false; |
| 6965 | |
| 6966 | // Ensure that we have actual array elements available to destroy; the |
| 6967 | // destructors might mutate the value, so we can't run them on the array |
| 6968 | // filler. |
| 6969 | if (Size && Size > Value.getArrayInitializedElts()) |
| 6970 | expandArray(Array&: Value, Index: Value.getArraySize() - 1); |
| 6971 | |
| 6972 | // The size of the array might have been reduced by |
| 6973 | // a placement new. |
| 6974 | for (Size = Value.getArraySize(); Size != 0; --Size) { |
| 6975 | APValue &Elem = Value.getArrayInitializedElt(I: Size - 1); |
| 6976 | if (!HandleLValueArrayAdjustment(Info, E: &LocE, LVal&: ElemLV, EltTy: ElemT, Adjustment: -1) || |
| 6977 | !HandleDestructionImpl(Info, CallRange, This: ElemLV, Value&: Elem, T: ElemT)) |
| 6978 | return false; |
| 6979 | } |
| 6980 | |
| 6981 | // End the lifetime of this array now. |
| 6982 | Value = APValue(); |
| 6983 | return true; |
| 6984 | } |
| 6985 | |
| 6986 | const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); |
| 6987 | if (!RD) { |
| 6988 | if (T.isDestructedType()) { |
| 6989 | Info.FFDiag(Loc: CallRange.getBegin(), |
| 6990 | DiagId: diag::note_constexpr_unsupported_destruction) |
| 6991 | << T; |
| 6992 | return false; |
| 6993 | } |
| 6994 | |
| 6995 | Value = APValue(); |
| 6996 | return true; |
| 6997 | } |
| 6998 | |
| 6999 | if (RD->getNumVBases()) { |
| 7000 | Info.FFDiag(Loc: CallRange.getBegin(), DiagId: diag::note_constexpr_virtual_base) << RD; |
| 7001 | return false; |
| 7002 | } |
| 7003 | |
| 7004 | const CXXDestructorDecl *DD = RD->getDestructor(); |
| 7005 | if (!DD && !RD->hasTrivialDestructor()) { |
| 7006 | Info.FFDiag(Loc: CallRange.getBegin()); |
| 7007 | return false; |
| 7008 | } |
| 7009 | |
| 7010 | if (!DD || DD->isTrivial() || |
| 7011 | (RD->isAnonymousStructOrUnion() && RD->isUnion())) { |
| 7012 | // A trivial destructor just ends the lifetime of the object. Check for |
| 7013 | // this case before checking for a body, because we might not bother |
| 7014 | // building a body for a trivial destructor. Note that it doesn't matter |
| 7015 | // whether the destructor is constexpr in this case; all trivial |
| 7016 | // destructors are constexpr. |
| 7017 | // |
| 7018 | // If an anonymous union would be destroyed, some enclosing destructor must |
| 7019 | // have been explicitly defined, and the anonymous union destruction should |
| 7020 | // have no effect. |
| 7021 | Value = APValue(); |
| 7022 | return true; |
| 7023 | } |
| 7024 | |
| 7025 | if (!Info.CheckCallLimit(Loc: CallRange.getBegin())) |
| 7026 | return false; |
| 7027 | |
| 7028 | const FunctionDecl *Definition = nullptr; |
| 7029 | const Stmt *Body = DD->getBody(Definition); |
| 7030 | |
| 7031 | if (!CheckConstexprFunction(Info, CallLoc: CallRange.getBegin(), Declaration: DD, Definition, Body)) |
| 7032 | return false; |
| 7033 | |
| 7034 | CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr, |
| 7035 | CallRef()); |
| 7036 | |
| 7037 | // We're now in the period of destruction of this object. |
| 7038 | unsigned BasesLeft = RD->getNumBases(); |
| 7039 | EvalInfo::EvaluatingDestructorRAII EvalObj( |
| 7040 | Info, |
| 7041 | ObjectUnderConstruction{.Base: This.getLValueBase(), .Path: This.Designator.Entries}); |
| 7042 | if (!EvalObj.DidInsert) { |
| 7043 | // C++2a [class.dtor]p19: |
| 7044 | // the behavior is undefined if the destructor is invoked for an object |
| 7045 | // whose lifetime has ended |
| 7046 | // (Note that formally the lifetime ends when the period of destruction |
| 7047 | // begins, even though certain uses of the object remain valid until the |
| 7048 | // period of destruction ends.) |
| 7049 | Info.FFDiag(Loc: CallRange.getBegin(), DiagId: diag::note_constexpr_double_destroy); |
| 7050 | return false; |
| 7051 | } |
| 7052 | |
| 7053 | // FIXME: Creating an APValue just to hold a nonexistent return value is |
| 7054 | // wasteful. |
| 7055 | APValue RetVal; |
| 7056 | StmtResult Ret = {.Value: RetVal, .Slot: nullptr}; |
| 7057 | if (EvaluateStmt(Result&: Ret, Info, S: Definition->getBody()) == ESR_Failed) |
| 7058 | return false; |
| 7059 | |
| 7060 | // A union destructor does not implicitly destroy its members. |
| 7061 | if (RD->isUnion()) |
| 7062 | return true; |
| 7063 | |
| 7064 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD); |
| 7065 | |
| 7066 | // We don't have a good way to iterate fields in reverse, so collect all the |
| 7067 | // fields first and then walk them backwards. |
| 7068 | SmallVector<FieldDecl*, 16> Fields(RD->fields()); |
| 7069 | for (const FieldDecl *FD : llvm::reverse(C&: Fields)) { |
| 7070 | if (FD->isUnnamedBitField()) |
| 7071 | continue; |
| 7072 | |
| 7073 | LValue Subobject = This; |
| 7074 | if (!HandleLValueMember(Info, E: &LocE, LVal&: Subobject, FD, RL: &Layout)) |
| 7075 | return false; |
| 7076 | |
| 7077 | APValue *SubobjectValue = &Value.getStructField(i: FD->getFieldIndex()); |
| 7078 | if (!HandleDestructionImpl(Info, CallRange, This: Subobject, Value&: *SubobjectValue, |
| 7079 | T: FD->getType())) |
| 7080 | return false; |
| 7081 | } |
| 7082 | |
| 7083 | if (BasesLeft != 0) |
| 7084 | EvalObj.startedDestroyingBases(); |
| 7085 | |
| 7086 | // Destroy base classes in reverse order. |
| 7087 | for (const CXXBaseSpecifier &Base : llvm::reverse(C: RD->bases())) { |
| 7088 | --BasesLeft; |
| 7089 | |
| 7090 | QualType BaseType = Base.getType(); |
| 7091 | LValue Subobject = This; |
| 7092 | if (!HandleLValueDirectBase(Info, E: &LocE, Obj&: Subobject, Derived: RD, |
| 7093 | Base: BaseType->getAsCXXRecordDecl(), RL: &Layout)) |
| 7094 | return false; |
| 7095 | |
| 7096 | APValue *SubobjectValue = &Value.getStructBase(i: BasesLeft); |
| 7097 | if (!HandleDestructionImpl(Info, CallRange, This: Subobject, Value&: *SubobjectValue, |
| 7098 | T: BaseType)) |
| 7099 | return false; |
| 7100 | } |
| 7101 | assert(BasesLeft == 0 && "NumBases was wrong?" ); |
| 7102 | |
| 7103 | // The period of destruction ends now. The object is gone. |
| 7104 | Value = APValue(); |
| 7105 | return true; |
| 7106 | } |
| 7107 | |
| 7108 | namespace { |
| 7109 | struct DestroyObjectHandler { |
| 7110 | EvalInfo &Info; |
| 7111 | const Expr *E; |
| 7112 | const LValue &This; |
| 7113 | const AccessKinds AccessKind; |
| 7114 | |
| 7115 | typedef bool result_type; |
| 7116 | bool failed() { return false; } |
| 7117 | bool found(APValue &Subobj, QualType SubobjType) { |
| 7118 | return HandleDestructionImpl(Info, CallRange: E->getSourceRange(), This, Value&: Subobj, |
| 7119 | T: SubobjType); |
| 7120 | } |
| 7121 | bool found(APSInt &Value, QualType SubobjType) { |
| 7122 | Info.FFDiag(E, DiagId: diag::note_constexpr_destroy_complex_elem); |
| 7123 | return false; |
| 7124 | } |
| 7125 | bool found(APFloat &Value, QualType SubobjType) { |
| 7126 | Info.FFDiag(E, DiagId: diag::note_constexpr_destroy_complex_elem); |
| 7127 | return false; |
| 7128 | } |
| 7129 | }; |
| 7130 | } |
| 7131 | |
| 7132 | /// Perform a destructor or pseudo-destructor call on the given object, which |
| 7133 | /// might in general not be a complete object. |
| 7134 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, |
| 7135 | const LValue &This, QualType ThisType) { |
| 7136 | CompleteObject Obj = findCompleteObject(Info, E, AK: AK_Destroy, LVal: This, LValType: ThisType); |
| 7137 | DestroyObjectHandler Handler = {.Info: Info, .E: E, .This: This, .AccessKind: AK_Destroy}; |
| 7138 | return Obj && findSubobject(Info, E, Obj, Sub: This.Designator, handler&: Handler); |
| 7139 | } |
| 7140 | |
| 7141 | /// Destroy and end the lifetime of the given complete object. |
| 7142 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, |
| 7143 | APValue::LValueBase LVBase, APValue &Value, |
| 7144 | QualType T) { |
| 7145 | // If we've had an unmodeled side-effect, we can't rely on mutable state |
| 7146 | // (such as the object we're about to destroy) being correct. |
| 7147 | if (Info.EvalStatus.HasSideEffects) |
| 7148 | return false; |
| 7149 | |
| 7150 | LValue LV; |
| 7151 | LV.set(B: {LVBase}); |
| 7152 | return HandleDestructionImpl(Info, CallRange: Loc, This: LV, Value, T); |
| 7153 | } |
| 7154 | |
| 7155 | /// Perform a call to 'operator new' or to `__builtin_operator_new'. |
| 7156 | static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, |
| 7157 | LValue &Result) { |
| 7158 | if (Info.checkingPotentialConstantExpression() || |
| 7159 | Info.SpeculativeEvaluationDepth) |
| 7160 | return false; |
| 7161 | |
| 7162 | // This is permitted only within a call to std::allocator<T>::allocate. |
| 7163 | auto Caller = Info.getStdAllocatorCaller(FnName: "allocate" ); |
| 7164 | if (!Caller) { |
| 7165 | Info.FFDiag(Loc: E->getExprLoc(), DiagId: Info.getLangOpts().CPlusPlus20 |
| 7166 | ? diag::note_constexpr_new_untyped |
| 7167 | : diag::note_constexpr_new); |
| 7168 | return false; |
| 7169 | } |
| 7170 | |
| 7171 | QualType ElemType = Caller.ElemType; |
| 7172 | if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { |
| 7173 | Info.FFDiag(Loc: E->getExprLoc(), |
| 7174 | DiagId: diag::note_constexpr_new_not_complete_object_type) |
| 7175 | << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; |
| 7176 | return false; |
| 7177 | } |
| 7178 | |
| 7179 | APSInt ByteSize; |
| 7180 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: ByteSize, Info)) |
| 7181 | return false; |
| 7182 | bool IsNothrow = false; |
| 7183 | for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { |
| 7184 | EvaluateIgnoredValue(Info, E: E->getArg(Arg: I)); |
| 7185 | IsNothrow |= E->getType()->isNothrowT(); |
| 7186 | } |
| 7187 | |
| 7188 | CharUnits ElemSize; |
| 7189 | if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: ElemType, Size&: ElemSize)) |
| 7190 | return false; |
| 7191 | APInt Size, Remainder; |
| 7192 | APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); |
| 7193 | APInt::udivrem(LHS: ByteSize, RHS: ElemSizeAP, Quotient&: Size, Remainder); |
| 7194 | if (Remainder != 0) { |
| 7195 | // This likely indicates a bug in the implementation of 'std::allocator'. |
| 7196 | Info.FFDiag(Loc: E->getExprLoc(), DiagId: diag::note_constexpr_operator_new_bad_size) |
| 7197 | << ByteSize << APSInt(ElemSizeAP, true) << ElemType; |
| 7198 | return false; |
| 7199 | } |
| 7200 | |
| 7201 | if (!Info.CheckArraySize(Loc: E->getBeginLoc(), BitWidth: ByteSize.getActiveBits(), |
| 7202 | ElemCount: Size.getZExtValue(), /*Diag=*/!IsNothrow)) { |
| 7203 | if (IsNothrow) { |
| 7204 | Result.setNull(Ctx&: Info.Ctx, PointerTy: E->getType()); |
| 7205 | return true; |
| 7206 | } |
| 7207 | return false; |
| 7208 | } |
| 7209 | |
| 7210 | QualType AllocType = Info.Ctx.getConstantArrayType( |
| 7211 | EltTy: ElemType, ArySize: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 7212 | APValue *Val = Info.createHeapAlloc(E: Caller.Call, T: AllocType, LV&: Result); |
| 7213 | *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); |
| 7214 | Result.addArray(Info, E, CAT: cast<ConstantArrayType>(Val&: AllocType)); |
| 7215 | return true; |
| 7216 | } |
| 7217 | |
| 7218 | static bool hasVirtualDestructor(QualType T) { |
| 7219 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
| 7220 | if (CXXDestructorDecl *DD = RD->getDestructor()) |
| 7221 | return DD->isVirtual(); |
| 7222 | return false; |
| 7223 | } |
| 7224 | |
| 7225 | static const FunctionDecl *getVirtualOperatorDelete(QualType T) { |
| 7226 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
| 7227 | if (CXXDestructorDecl *DD = RD->getDestructor()) |
| 7228 | return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; |
| 7229 | return nullptr; |
| 7230 | } |
| 7231 | |
| 7232 | /// Check that the given object is a suitable pointer to a heap allocation that |
| 7233 | /// still exists and is of the right kind for the purpose of a deletion. |
| 7234 | /// |
| 7235 | /// On success, returns the heap allocation to deallocate. On failure, produces |
| 7236 | /// a diagnostic and returns std::nullopt. |
| 7237 | static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, |
| 7238 | const LValue &Pointer, |
| 7239 | DynAlloc::Kind DeallocKind) { |
| 7240 | auto PointerAsString = [&] { |
| 7241 | return Pointer.toString(Ctx&: Info.Ctx, T: Info.Ctx.VoidPtrTy); |
| 7242 | }; |
| 7243 | |
| 7244 | DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); |
| 7245 | if (!DA) { |
| 7246 | Info.FFDiag(E, DiagId: diag::note_constexpr_delete_not_heap_alloc) |
| 7247 | << PointerAsString(); |
| 7248 | if (Pointer.Base) |
| 7249 | NoteLValueLocation(Info, Base: Pointer.Base); |
| 7250 | return std::nullopt; |
| 7251 | } |
| 7252 | |
| 7253 | std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); |
| 7254 | if (!Alloc) { |
| 7255 | Info.FFDiag(E, DiagId: diag::note_constexpr_double_delete); |
| 7256 | return std::nullopt; |
| 7257 | } |
| 7258 | |
| 7259 | if (DeallocKind != (*Alloc)->getKind()) { |
| 7260 | QualType AllocType = Pointer.Base.getDynamicAllocType(); |
| 7261 | Info.FFDiag(E, DiagId: diag::note_constexpr_new_delete_mismatch) |
| 7262 | << DeallocKind << (*Alloc)->getKind() << AllocType; |
| 7263 | NoteLValueLocation(Info, Base: Pointer.Base); |
| 7264 | return std::nullopt; |
| 7265 | } |
| 7266 | |
| 7267 | bool Subobject = false; |
| 7268 | if (DeallocKind == DynAlloc::New) { |
| 7269 | Subobject = Pointer.Designator.MostDerivedPathLength != 0 || |
| 7270 | Pointer.Designator.isOnePastTheEnd(); |
| 7271 | } else { |
| 7272 | Subobject = Pointer.Designator.Entries.size() != 1 || |
| 7273 | Pointer.Designator.Entries[0].getAsArrayIndex() != 0; |
| 7274 | } |
| 7275 | if (Subobject) { |
| 7276 | Info.FFDiag(E, DiagId: diag::note_constexpr_delete_subobject) |
| 7277 | << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); |
| 7278 | return std::nullopt; |
| 7279 | } |
| 7280 | |
| 7281 | return Alloc; |
| 7282 | } |
| 7283 | |
| 7284 | // Perform a call to 'operator delete' or '__builtin_operator_delete'. |
| 7285 | static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { |
| 7286 | if (Info.checkingPotentialConstantExpression() || |
| 7287 | Info.SpeculativeEvaluationDepth) |
| 7288 | return false; |
| 7289 | |
| 7290 | // This is permitted only within a call to std::allocator<T>::deallocate. |
| 7291 | if (!Info.getStdAllocatorCaller(FnName: "deallocate" )) { |
| 7292 | Info.FFDiag(Loc: E->getExprLoc()); |
| 7293 | return true; |
| 7294 | } |
| 7295 | |
| 7296 | LValue Pointer; |
| 7297 | if (!EvaluatePointer(E: E->getArg(Arg: 0), Result&: Pointer, Info)) |
| 7298 | return false; |
| 7299 | for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) |
| 7300 | EvaluateIgnoredValue(Info, E: E->getArg(Arg: I)); |
| 7301 | |
| 7302 | if (Pointer.Designator.Invalid) |
| 7303 | return false; |
| 7304 | |
| 7305 | // Deleting a null pointer would have no effect, but it's not permitted by |
| 7306 | // std::allocator<T>::deallocate's contract. |
| 7307 | if (Pointer.isNullPointer()) { |
| 7308 | Info.CCEDiag(Loc: E->getExprLoc(), DiagId: diag::note_constexpr_deallocate_null); |
| 7309 | return true; |
| 7310 | } |
| 7311 | |
| 7312 | if (!CheckDeleteKind(Info, E, Pointer, DeallocKind: DynAlloc::StdAllocator)) |
| 7313 | return false; |
| 7314 | |
| 7315 | Info.HeapAllocs.erase(x: Pointer.Base.get<DynamicAllocLValue>()); |
| 7316 | return true; |
| 7317 | } |
| 7318 | |
| 7319 | //===----------------------------------------------------------------------===// |
| 7320 | // Generic Evaluation |
| 7321 | //===----------------------------------------------------------------------===// |
| 7322 | namespace { |
| 7323 | |
| 7324 | class BitCastBuffer { |
| 7325 | // FIXME: We're going to need bit-level granularity when we support |
| 7326 | // bit-fields. |
| 7327 | // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but |
| 7328 | // we don't support a host or target where that is the case. Still, we should |
| 7329 | // use a more generic type in case we ever do. |
| 7330 | SmallVector<std::optional<unsigned char>, 32> Bytes; |
| 7331 | |
| 7332 | static_assert(std::numeric_limits<unsigned char>::digits >= 8, |
| 7333 | "Need at least 8 bit unsigned char" ); |
| 7334 | |
| 7335 | bool TargetIsLittleEndian; |
| 7336 | |
| 7337 | public: |
| 7338 | BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) |
| 7339 | : Bytes(Width.getQuantity()), |
| 7340 | TargetIsLittleEndian(TargetIsLittleEndian) {} |
| 7341 | |
| 7342 | [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width, |
| 7343 | SmallVectorImpl<unsigned char> &Output) const { |
| 7344 | for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { |
| 7345 | // If a byte of an integer is uninitialized, then the whole integer is |
| 7346 | // uninitialized. |
| 7347 | if (!Bytes[I.getQuantity()]) |
| 7348 | return false; |
| 7349 | Output.push_back(Elt: *Bytes[I.getQuantity()]); |
| 7350 | } |
| 7351 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) |
| 7352 | std::reverse(first: Output.begin(), last: Output.end()); |
| 7353 | return true; |
| 7354 | } |
| 7355 | |
| 7356 | void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { |
| 7357 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) |
| 7358 | std::reverse(first: Input.begin(), last: Input.end()); |
| 7359 | |
| 7360 | size_t Index = 0; |
| 7361 | for (unsigned char Byte : Input) { |
| 7362 | assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?" ); |
| 7363 | Bytes[Offset.getQuantity() + Index] = Byte; |
| 7364 | ++Index; |
| 7365 | } |
| 7366 | } |
| 7367 | |
| 7368 | size_t size() { return Bytes.size(); } |
| 7369 | }; |
| 7370 | |
| 7371 | /// Traverse an APValue to produce an BitCastBuffer, emulating how the current |
| 7372 | /// target would represent the value at runtime. |
| 7373 | class APValueToBufferConverter { |
| 7374 | EvalInfo &Info; |
| 7375 | BitCastBuffer Buffer; |
| 7376 | const CastExpr *BCE; |
| 7377 | |
| 7378 | APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, |
| 7379 | const CastExpr *BCE) |
| 7380 | : Info(Info), |
| 7381 | Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), |
| 7382 | BCE(BCE) {} |
| 7383 | |
| 7384 | bool visit(const APValue &Val, QualType Ty) { |
| 7385 | return visit(Val, Ty, Offset: CharUnits::fromQuantity(Quantity: 0)); |
| 7386 | } |
| 7387 | |
| 7388 | // Write out Val with type Ty into Buffer starting at Offset. |
| 7389 | bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { |
| 7390 | assert((size_t)Offset.getQuantity() <= Buffer.size()); |
| 7391 | |
| 7392 | // As a special case, nullptr_t has an indeterminate value. |
| 7393 | if (Ty->isNullPtrType()) |
| 7394 | return true; |
| 7395 | |
| 7396 | // Dig through Src to find the byte at SrcOffset. |
| 7397 | switch (Val.getKind()) { |
| 7398 | case APValue::Indeterminate: |
| 7399 | case APValue::None: |
| 7400 | return true; |
| 7401 | |
| 7402 | case APValue::Int: |
| 7403 | return visitInt(Val: Val.getInt(), Ty, Offset); |
| 7404 | case APValue::Float: |
| 7405 | return visitFloat(Val: Val.getFloat(), Ty, Offset); |
| 7406 | case APValue::Array: |
| 7407 | return visitArray(Val, Ty, Offset); |
| 7408 | case APValue::Struct: |
| 7409 | return visitRecord(Val, Ty, Offset); |
| 7410 | case APValue::Vector: |
| 7411 | return visitVector(Val, Ty, Offset); |
| 7412 | |
| 7413 | case APValue::ComplexInt: |
| 7414 | case APValue::ComplexFloat: |
| 7415 | return visitComplex(Val, Ty, Offset); |
| 7416 | case APValue::FixedPoint: |
| 7417 | // FIXME: We should support these. |
| 7418 | |
| 7419 | case APValue::Union: |
| 7420 | case APValue::MemberPointer: |
| 7421 | case APValue::AddrLabelDiff: { |
| 7422 | Info.FFDiag(Loc: BCE->getBeginLoc(), |
| 7423 | DiagId: diag::note_constexpr_bit_cast_unsupported_type) |
| 7424 | << Ty; |
| 7425 | return false; |
| 7426 | } |
| 7427 | |
| 7428 | case APValue::LValue: |
| 7429 | llvm_unreachable("LValue subobject in bit_cast?" ); |
| 7430 | } |
| 7431 | llvm_unreachable("Unhandled APValue::ValueKind" ); |
| 7432 | } |
| 7433 | |
| 7434 | bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { |
| 7435 | const RecordDecl *RD = Ty->getAsRecordDecl(); |
| 7436 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD); |
| 7437 | |
| 7438 | // Visit the base classes. |
| 7439 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
| 7440 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { |
| 7441 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; |
| 7442 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); |
| 7443 | const APValue &Base = Val.getStructBase(i: I); |
| 7444 | |
| 7445 | // Can happen in error cases. |
| 7446 | if (!Base.isStruct()) |
| 7447 | return false; |
| 7448 | |
| 7449 | if (!visitRecord(Val: Base, Ty: BS.getType(), |
| 7450 | Offset: Layout.getBaseClassOffset(Base: BaseDecl) + Offset)) |
| 7451 | return false; |
| 7452 | } |
| 7453 | } |
| 7454 | |
| 7455 | // Visit the fields. |
| 7456 | unsigned FieldIdx = 0; |
| 7457 | for (FieldDecl *FD : RD->fields()) { |
| 7458 | if (FD->isBitField()) { |
| 7459 | Info.FFDiag(Loc: BCE->getBeginLoc(), |
| 7460 | DiagId: diag::note_constexpr_bit_cast_unsupported_bitfield); |
| 7461 | return false; |
| 7462 | } |
| 7463 | |
| 7464 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldNo: FieldIdx); |
| 7465 | |
| 7466 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && |
| 7467 | "only bit-fields can have sub-char alignment" ); |
| 7468 | CharUnits FieldOffset = |
| 7469 | Info.Ctx.toCharUnitsFromBits(BitSize: FieldOffsetBits) + Offset; |
| 7470 | QualType FieldTy = FD->getType(); |
| 7471 | if (!visit(Val: Val.getStructField(i: FieldIdx), Ty: FieldTy, Offset: FieldOffset)) |
| 7472 | return false; |
| 7473 | ++FieldIdx; |
| 7474 | } |
| 7475 | |
| 7476 | return true; |
| 7477 | } |
| 7478 | |
| 7479 | bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { |
| 7480 | const auto *CAT = |
| 7481 | dyn_cast_or_null<ConstantArrayType>(Val: Ty->getAsArrayTypeUnsafe()); |
| 7482 | if (!CAT) |
| 7483 | return false; |
| 7484 | |
| 7485 | CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(T: CAT->getElementType()); |
| 7486 | unsigned NumInitializedElts = Val.getArrayInitializedElts(); |
| 7487 | unsigned ArraySize = Val.getArraySize(); |
| 7488 | // First, initialize the initialized elements. |
| 7489 | for (unsigned I = 0; I != NumInitializedElts; ++I) { |
| 7490 | const APValue &SubObj = Val.getArrayInitializedElt(I); |
| 7491 | if (!visit(Val: SubObj, Ty: CAT->getElementType(), Offset: Offset + I * ElemWidth)) |
| 7492 | return false; |
| 7493 | } |
| 7494 | |
| 7495 | // Next, initialize the rest of the array using the filler. |
| 7496 | if (Val.hasArrayFiller()) { |
| 7497 | const APValue &Filler = Val.getArrayFiller(); |
| 7498 | for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { |
| 7499 | if (!visit(Val: Filler, Ty: CAT->getElementType(), Offset: Offset + I * ElemWidth)) |
| 7500 | return false; |
| 7501 | } |
| 7502 | } |
| 7503 | |
| 7504 | return true; |
| 7505 | } |
| 7506 | |
| 7507 | bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) { |
| 7508 | const ComplexType *ComplexTy = Ty->castAs<ComplexType>(); |
| 7509 | QualType EltTy = ComplexTy->getElementType(); |
| 7510 | CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(T: EltTy); |
| 7511 | bool IsInt = Val.isComplexInt(); |
| 7512 | |
| 7513 | if (IsInt) { |
| 7514 | if (!visitInt(Val: Val.getComplexIntReal(), Ty: EltTy, |
| 7515 | Offset: Offset + (0 * EltSizeChars))) |
| 7516 | return false; |
| 7517 | if (!visitInt(Val: Val.getComplexIntImag(), Ty: EltTy, |
| 7518 | Offset: Offset + (1 * EltSizeChars))) |
| 7519 | return false; |
| 7520 | } else { |
| 7521 | if (!visitFloat(Val: Val.getComplexFloatReal(), Ty: EltTy, |
| 7522 | Offset: Offset + (0 * EltSizeChars))) |
| 7523 | return false; |
| 7524 | if (!visitFloat(Val: Val.getComplexFloatImag(), Ty: EltTy, |
| 7525 | Offset: Offset + (1 * EltSizeChars))) |
| 7526 | return false; |
| 7527 | } |
| 7528 | |
| 7529 | return true; |
| 7530 | } |
| 7531 | |
| 7532 | bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) { |
| 7533 | const VectorType *VTy = Ty->castAs<VectorType>(); |
| 7534 | QualType EltTy = VTy->getElementType(); |
| 7535 | unsigned NElts = VTy->getNumElements(); |
| 7536 | |
| 7537 | if (VTy->isPackedVectorBoolType(ctx: Info.Ctx)) { |
| 7538 | // Special handling for OpenCL bool vectors: |
| 7539 | // Since these vectors are stored as packed bits, but we can't write |
| 7540 | // individual bits to the BitCastBuffer, we'll buffer all of the elements |
| 7541 | // together into an appropriately sized APInt and write them all out at |
| 7542 | // once. Because we don't accept vectors where NElts * EltSize isn't a |
| 7543 | // multiple of the char size, there will be no padding space, so we don't |
| 7544 | // have to worry about writing data which should have been left |
| 7545 | // uninitialized. |
| 7546 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); |
| 7547 | |
| 7548 | llvm::APInt Res = llvm::APInt::getZero(numBits: NElts); |
| 7549 | for (unsigned I = 0; I < NElts; ++I) { |
| 7550 | const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt(); |
| 7551 | assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 && |
| 7552 | "bool vector element must be 1-bit unsigned integer!" ); |
| 7553 | |
| 7554 | Res.insertBits(SubBits: EltAsInt, bitPosition: BigEndian ? (NElts - I - 1) : I); |
| 7555 | } |
| 7556 | |
| 7557 | SmallVector<uint8_t, 8> Bytes(NElts / 8); |
| 7558 | llvm::StoreIntToMemory(IntVal: Res, Dst: &*Bytes.begin(), StoreBytes: NElts / 8); |
| 7559 | Buffer.writeObject(Offset, Input&: Bytes); |
| 7560 | } else { |
| 7561 | // Iterate over each of the elements and write them out to the buffer at |
| 7562 | // the appropriate offset. |
| 7563 | CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(T: EltTy); |
| 7564 | for (unsigned I = 0; I < NElts; ++I) { |
| 7565 | if (!visit(Val: Val.getVectorElt(I), Ty: EltTy, Offset: Offset + I * EltSizeChars)) |
| 7566 | return false; |
| 7567 | } |
| 7568 | } |
| 7569 | |
| 7570 | return true; |
| 7571 | } |
| 7572 | |
| 7573 | bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { |
| 7574 | APSInt AdjustedVal = Val; |
| 7575 | unsigned Width = AdjustedVal.getBitWidth(); |
| 7576 | if (Ty->isBooleanType()) { |
| 7577 | Width = Info.Ctx.getTypeSize(T: Ty); |
| 7578 | AdjustedVal = AdjustedVal.extend(width: Width); |
| 7579 | } |
| 7580 | |
| 7581 | SmallVector<uint8_t, 8> Bytes(Width / 8); |
| 7582 | llvm::StoreIntToMemory(IntVal: AdjustedVal, Dst: &*Bytes.begin(), StoreBytes: Width / 8); |
| 7583 | Buffer.writeObject(Offset, Input&: Bytes); |
| 7584 | return true; |
| 7585 | } |
| 7586 | |
| 7587 | bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { |
| 7588 | APSInt AsInt(Val.bitcastToAPInt()); |
| 7589 | return visitInt(Val: AsInt, Ty, Offset); |
| 7590 | } |
| 7591 | |
| 7592 | public: |
| 7593 | static std::optional<BitCastBuffer> |
| 7594 | convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) { |
| 7595 | CharUnits DstSize = Info.Ctx.getTypeSizeInChars(T: BCE->getType()); |
| 7596 | APValueToBufferConverter Converter(Info, DstSize, BCE); |
| 7597 | if (!Converter.visit(Val: Src, Ty: BCE->getSubExpr()->getType())) |
| 7598 | return std::nullopt; |
| 7599 | return Converter.Buffer; |
| 7600 | } |
| 7601 | }; |
| 7602 | |
| 7603 | /// Write an BitCastBuffer into an APValue. |
| 7604 | class BufferToAPValueConverter { |
| 7605 | EvalInfo &Info; |
| 7606 | const BitCastBuffer &Buffer; |
| 7607 | const CastExpr *BCE; |
| 7608 | |
| 7609 | BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, |
| 7610 | const CastExpr *BCE) |
| 7611 | : Info(Info), Buffer(Buffer), BCE(BCE) {} |
| 7612 | |
| 7613 | // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast |
| 7614 | // with an invalid type, so anything left is a deficiency on our part (FIXME). |
| 7615 | // Ideally this will be unreachable. |
| 7616 | std::nullopt_t unsupportedType(QualType Ty) { |
| 7617 | Info.FFDiag(Loc: BCE->getBeginLoc(), |
| 7618 | DiagId: diag::note_constexpr_bit_cast_unsupported_type) |
| 7619 | << Ty; |
| 7620 | return std::nullopt; |
| 7621 | } |
| 7622 | |
| 7623 | std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) { |
| 7624 | Info.FFDiag(Loc: BCE->getBeginLoc(), |
| 7625 | DiagId: diag::note_constexpr_bit_cast_unrepresentable_value) |
| 7626 | << Ty << toString(I: Val, /*Radix=*/10); |
| 7627 | return std::nullopt; |
| 7628 | } |
| 7629 | |
| 7630 | std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset, |
| 7631 | const EnumType *EnumSugar = nullptr) { |
| 7632 | if (T->isNullPtrType()) { |
| 7633 | uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QT: QualType(T, 0)); |
| 7634 | return APValue((Expr *)nullptr, |
| 7635 | /*Offset=*/CharUnits::fromQuantity(Quantity: NullValue), |
| 7636 | APValue::NoLValuePath{}, /*IsNullPtr=*/true); |
| 7637 | } |
| 7638 | |
| 7639 | CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); |
| 7640 | |
| 7641 | // Work around floating point types that contain unused padding bytes. This |
| 7642 | // is really just `long double` on x86, which is the only fundamental type |
| 7643 | // with padding bytes. |
| 7644 | if (T->isRealFloatingType()) { |
| 7645 | const llvm::fltSemantics &Semantics = |
| 7646 | Info.Ctx.getFloatTypeSemantics(T: QualType(T, 0)); |
| 7647 | unsigned NumBits = llvm::APFloatBase::getSizeInBits(Sem: Semantics); |
| 7648 | assert(NumBits % 8 == 0); |
| 7649 | CharUnits NumBytes = CharUnits::fromQuantity(Quantity: NumBits / 8); |
| 7650 | if (NumBytes != SizeOf) |
| 7651 | SizeOf = NumBytes; |
| 7652 | } |
| 7653 | |
| 7654 | SmallVector<uint8_t, 8> Bytes; |
| 7655 | if (!Buffer.readObject(Offset, Width: SizeOf, Output&: Bytes)) { |
| 7656 | // If this is std::byte or unsigned char, then its okay to store an |
| 7657 | // indeterminate value. |
| 7658 | bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); |
| 7659 | bool IsUChar = |
| 7660 | !EnumSugar && (T->isSpecificBuiltinType(K: BuiltinType::UChar) || |
| 7661 | T->isSpecificBuiltinType(K: BuiltinType::Char_U)); |
| 7662 | if (!IsStdByte && !IsUChar) { |
| 7663 | QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); |
| 7664 | Info.FFDiag(Loc: BCE->getExprLoc(), |
| 7665 | DiagId: diag::note_constexpr_bit_cast_indet_dest) |
| 7666 | << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; |
| 7667 | return std::nullopt; |
| 7668 | } |
| 7669 | |
| 7670 | return APValue::IndeterminateValue(); |
| 7671 | } |
| 7672 | |
| 7673 | APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); |
| 7674 | llvm::LoadIntFromMemory(IntVal&: Val, Src: &*Bytes.begin(), LoadBytes: Bytes.size()); |
| 7675 | |
| 7676 | if (T->isIntegralOrEnumerationType()) { |
| 7677 | Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); |
| 7678 | |
| 7679 | unsigned IntWidth = Info.Ctx.getIntWidth(T: QualType(T, 0)); |
| 7680 | if (IntWidth != Val.getBitWidth()) { |
| 7681 | APSInt Truncated = Val.trunc(width: IntWidth); |
| 7682 | if (Truncated.extend(width: Val.getBitWidth()) != Val) |
| 7683 | return unrepresentableValue(Ty: QualType(T, 0), Val); |
| 7684 | Val = Truncated; |
| 7685 | } |
| 7686 | |
| 7687 | return APValue(Val); |
| 7688 | } |
| 7689 | |
| 7690 | if (T->isRealFloatingType()) { |
| 7691 | const llvm::fltSemantics &Semantics = |
| 7692 | Info.Ctx.getFloatTypeSemantics(T: QualType(T, 0)); |
| 7693 | return APValue(APFloat(Semantics, Val)); |
| 7694 | } |
| 7695 | |
| 7696 | return unsupportedType(Ty: QualType(T, 0)); |
| 7697 | } |
| 7698 | |
| 7699 | std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { |
| 7700 | const RecordDecl *RD = RTy->getAsRecordDecl(); |
| 7701 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD); |
| 7702 | |
| 7703 | unsigned NumBases = 0; |
| 7704 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
| 7705 | NumBases = CXXRD->getNumBases(); |
| 7706 | |
| 7707 | APValue ResultVal(APValue::UninitStruct(), NumBases, |
| 7708 | std::distance(first: RD->field_begin(), last: RD->field_end())); |
| 7709 | |
| 7710 | // Visit the base classes. |
| 7711 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
| 7712 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { |
| 7713 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; |
| 7714 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); |
| 7715 | |
| 7716 | std::optional<APValue> SubObj = visitType( |
| 7717 | Ty: BS.getType(), Offset: Layout.getBaseClassOffset(Base: BaseDecl) + Offset); |
| 7718 | if (!SubObj) |
| 7719 | return std::nullopt; |
| 7720 | ResultVal.getStructBase(i: I) = *SubObj; |
| 7721 | } |
| 7722 | } |
| 7723 | |
| 7724 | // Visit the fields. |
| 7725 | unsigned FieldIdx = 0; |
| 7726 | for (FieldDecl *FD : RD->fields()) { |
| 7727 | // FIXME: We don't currently support bit-fields. A lot of the logic for |
| 7728 | // this is in CodeGen, so we need to factor it around. |
| 7729 | if (FD->isBitField()) { |
| 7730 | Info.FFDiag(Loc: BCE->getBeginLoc(), |
| 7731 | DiagId: diag::note_constexpr_bit_cast_unsupported_bitfield); |
| 7732 | return std::nullopt; |
| 7733 | } |
| 7734 | |
| 7735 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldNo: FieldIdx); |
| 7736 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); |
| 7737 | |
| 7738 | CharUnits FieldOffset = |
| 7739 | CharUnits::fromQuantity(Quantity: FieldOffsetBits / Info.Ctx.getCharWidth()) + |
| 7740 | Offset; |
| 7741 | QualType FieldTy = FD->getType(); |
| 7742 | std::optional<APValue> SubObj = visitType(Ty: FieldTy, Offset: FieldOffset); |
| 7743 | if (!SubObj) |
| 7744 | return std::nullopt; |
| 7745 | ResultVal.getStructField(i: FieldIdx) = *SubObj; |
| 7746 | ++FieldIdx; |
| 7747 | } |
| 7748 | |
| 7749 | return ResultVal; |
| 7750 | } |
| 7751 | |
| 7752 | std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { |
| 7753 | QualType RepresentationType = Ty->getDecl()->getIntegerType(); |
| 7754 | assert(!RepresentationType.isNull() && |
| 7755 | "enum forward decl should be caught by Sema" ); |
| 7756 | const auto *AsBuiltin = |
| 7757 | RepresentationType.getCanonicalType()->castAs<BuiltinType>(); |
| 7758 | // Recurse into the underlying type. Treat std::byte transparently as |
| 7759 | // unsigned char. |
| 7760 | return visit(T: AsBuiltin, Offset, /*EnumTy=*/EnumSugar: Ty); |
| 7761 | } |
| 7762 | |
| 7763 | std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { |
| 7764 | size_t Size = Ty->getLimitedSize(); |
| 7765 | CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(T: Ty->getElementType()); |
| 7766 | |
| 7767 | APValue ArrayValue(APValue::UninitArray(), Size, Size); |
| 7768 | for (size_t I = 0; I != Size; ++I) { |
| 7769 | std::optional<APValue> ElementValue = |
| 7770 | visitType(Ty: Ty->getElementType(), Offset: Offset + I * ElementWidth); |
| 7771 | if (!ElementValue) |
| 7772 | return std::nullopt; |
| 7773 | ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); |
| 7774 | } |
| 7775 | |
| 7776 | return ArrayValue; |
| 7777 | } |
| 7778 | |
| 7779 | std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) { |
| 7780 | QualType ElementType = Ty->getElementType(); |
| 7781 | CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(T: ElementType); |
| 7782 | bool IsInt = ElementType->isIntegerType(); |
| 7783 | |
| 7784 | std::optional<APValue> Values[2]; |
| 7785 | for (unsigned I = 0; I != 2; ++I) { |
| 7786 | Values[I] = visitType(Ty: Ty->getElementType(), Offset: Offset + I * ElementWidth); |
| 7787 | if (!Values[I]) |
| 7788 | return std::nullopt; |
| 7789 | } |
| 7790 | |
| 7791 | if (IsInt) |
| 7792 | return APValue(Values[0]->getInt(), Values[1]->getInt()); |
| 7793 | return APValue(Values[0]->getFloat(), Values[1]->getFloat()); |
| 7794 | } |
| 7795 | |
| 7796 | std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) { |
| 7797 | QualType EltTy = VTy->getElementType(); |
| 7798 | unsigned NElts = VTy->getNumElements(); |
| 7799 | unsigned EltSize = |
| 7800 | VTy->isPackedVectorBoolType(ctx: Info.Ctx) ? 1 : Info.Ctx.getTypeSize(T: EltTy); |
| 7801 | |
| 7802 | SmallVector<APValue, 4> Elts; |
| 7803 | Elts.reserve(N: NElts); |
| 7804 | if (VTy->isPackedVectorBoolType(ctx: Info.Ctx)) { |
| 7805 | // Special handling for OpenCL bool vectors: |
| 7806 | // Since these vectors are stored as packed bits, but we can't read |
| 7807 | // individual bits from the BitCastBuffer, we'll buffer all of the |
| 7808 | // elements together into an appropriately sized APInt and write them all |
| 7809 | // out at once. Because we don't accept vectors where NElts * EltSize |
| 7810 | // isn't a multiple of the char size, there will be no padding space, so |
| 7811 | // we don't have to worry about reading any padding data which didn't |
| 7812 | // actually need to be accessed. |
| 7813 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); |
| 7814 | |
| 7815 | SmallVector<uint8_t, 8> Bytes; |
| 7816 | Bytes.reserve(N: NElts / 8); |
| 7817 | if (!Buffer.readObject(Offset, Width: CharUnits::fromQuantity(Quantity: NElts / 8), Output&: Bytes)) |
| 7818 | return std::nullopt; |
| 7819 | |
| 7820 | APSInt SValInt(NElts, true); |
| 7821 | llvm::LoadIntFromMemory(IntVal&: SValInt, Src: &*Bytes.begin(), LoadBytes: Bytes.size()); |
| 7822 | |
| 7823 | for (unsigned I = 0; I < NElts; ++I) { |
| 7824 | llvm::APInt Elt = |
| 7825 | SValInt.extractBits(numBits: 1, bitPosition: (BigEndian ? NElts - I - 1 : I) * EltSize); |
| 7826 | Elts.emplace_back( |
| 7827 | Args: APSInt(std::move(Elt), !EltTy->isSignedIntegerType())); |
| 7828 | } |
| 7829 | } else { |
| 7830 | // Iterate over each of the elements and read them from the buffer at |
| 7831 | // the appropriate offset. |
| 7832 | CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(T: EltTy); |
| 7833 | for (unsigned I = 0; I < NElts; ++I) { |
| 7834 | std::optional<APValue> EltValue = |
| 7835 | visitType(Ty: EltTy, Offset: Offset + I * EltSizeChars); |
| 7836 | if (!EltValue) |
| 7837 | return std::nullopt; |
| 7838 | Elts.push_back(Elt: std::move(*EltValue)); |
| 7839 | } |
| 7840 | } |
| 7841 | |
| 7842 | return APValue(Elts.data(), Elts.size()); |
| 7843 | } |
| 7844 | |
| 7845 | std::optional<APValue> visit(const Type *Ty, CharUnits Offset) { |
| 7846 | return unsupportedType(Ty: QualType(Ty, 0)); |
| 7847 | } |
| 7848 | |
| 7849 | std::optional<APValue> visitType(QualType Ty, CharUnits Offset) { |
| 7850 | QualType Can = Ty.getCanonicalType(); |
| 7851 | |
| 7852 | switch (Can->getTypeClass()) { |
| 7853 | #define TYPE(Class, Base) \ |
| 7854 | case Type::Class: \ |
| 7855 | return visit(cast<Class##Type>(Can.getTypePtr()), Offset); |
| 7856 | #define ABSTRACT_TYPE(Class, Base) |
| 7857 | #define NON_CANONICAL_TYPE(Class, Base) \ |
| 7858 | case Type::Class: \ |
| 7859 | llvm_unreachable("non-canonical type should be impossible!"); |
| 7860 | #define DEPENDENT_TYPE(Class, Base) \ |
| 7861 | case Type::Class: \ |
| 7862 | llvm_unreachable( \ |
| 7863 | "dependent types aren't supported in the constant evaluator!"); |
| 7864 | #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ |
| 7865 | case Type::Class: \ |
| 7866 | llvm_unreachable("either dependent or not canonical!"); |
| 7867 | #include "clang/AST/TypeNodes.inc" |
| 7868 | } |
| 7869 | llvm_unreachable("Unhandled Type::TypeClass" ); |
| 7870 | } |
| 7871 | |
| 7872 | public: |
| 7873 | // Pull out a full value of type DstType. |
| 7874 | static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, |
| 7875 | const CastExpr *BCE) { |
| 7876 | BufferToAPValueConverter Converter(Info, Buffer, BCE); |
| 7877 | return Converter.visitType(Ty: BCE->getType(), Offset: CharUnits::fromQuantity(Quantity: 0)); |
| 7878 | } |
| 7879 | }; |
| 7880 | |
| 7881 | static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, |
| 7882 | QualType Ty, EvalInfo *Info, |
| 7883 | const ASTContext &Ctx, |
| 7884 | bool CheckingDest) { |
| 7885 | Ty = Ty.getCanonicalType(); |
| 7886 | |
| 7887 | auto diag = [&](int Reason) { |
| 7888 | if (Info) |
| 7889 | Info->FFDiag(Loc, DiagId: diag::note_constexpr_bit_cast_invalid_type) |
| 7890 | << CheckingDest << (Reason == 4) << Reason; |
| 7891 | return false; |
| 7892 | }; |
| 7893 | auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { |
| 7894 | if (Info) |
| 7895 | Info->Note(Loc: NoteLoc, DiagId: diag::note_constexpr_bit_cast_invalid_subtype) |
| 7896 | << NoteTy << Construct << Ty; |
| 7897 | return false; |
| 7898 | }; |
| 7899 | |
| 7900 | if (Ty->isUnionType()) |
| 7901 | return diag(0); |
| 7902 | if (Ty->isPointerType()) |
| 7903 | return diag(1); |
| 7904 | if (Ty->isMemberPointerType()) |
| 7905 | return diag(2); |
| 7906 | if (Ty.isVolatileQualified()) |
| 7907 | return diag(3); |
| 7908 | |
| 7909 | if (RecordDecl *Record = Ty->getAsRecordDecl()) { |
| 7910 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: Record)) { |
| 7911 | for (CXXBaseSpecifier &BS : CXXRD->bases()) |
| 7912 | if (!checkBitCastConstexprEligibilityType(Loc, Ty: BS.getType(), Info, Ctx, |
| 7913 | CheckingDest)) |
| 7914 | return note(1, BS.getType(), BS.getBeginLoc()); |
| 7915 | } |
| 7916 | for (FieldDecl *FD : Record->fields()) { |
| 7917 | if (FD->getType()->isReferenceType()) |
| 7918 | return diag(4); |
| 7919 | if (!checkBitCastConstexprEligibilityType(Loc, Ty: FD->getType(), Info, Ctx, |
| 7920 | CheckingDest)) |
| 7921 | return note(0, FD->getType(), FD->getBeginLoc()); |
| 7922 | } |
| 7923 | } |
| 7924 | |
| 7925 | if (Ty->isArrayType() && |
| 7926 | !checkBitCastConstexprEligibilityType(Loc, Ty: Ctx.getBaseElementType(QT: Ty), |
| 7927 | Info, Ctx, CheckingDest)) |
| 7928 | return false; |
| 7929 | |
| 7930 | if (const auto *VTy = Ty->getAs<VectorType>()) { |
| 7931 | QualType EltTy = VTy->getElementType(); |
| 7932 | unsigned NElts = VTy->getNumElements(); |
| 7933 | unsigned EltSize = |
| 7934 | VTy->isPackedVectorBoolType(ctx: Ctx) ? 1 : Ctx.getTypeSize(T: EltTy); |
| 7935 | |
| 7936 | if ((NElts * EltSize) % Ctx.getCharWidth() != 0) { |
| 7937 | // The vector's size in bits is not a multiple of the target's byte size, |
| 7938 | // so its layout is unspecified. For now, we'll simply treat these cases |
| 7939 | // as unsupported (this should only be possible with OpenCL bool vectors |
| 7940 | // whose element count isn't a multiple of the byte size). |
| 7941 | Info->FFDiag(Loc, DiagId: diag::note_constexpr_bit_cast_invalid_vector) |
| 7942 | << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth(); |
| 7943 | return false; |
| 7944 | } |
| 7945 | |
| 7946 | if (EltTy->isRealFloatingType() && |
| 7947 | &Ctx.getFloatTypeSemantics(T: EltTy) == &APFloat::x87DoubleExtended()) { |
| 7948 | // The layout for x86_fp80 vectors seems to be handled very inconsistently |
| 7949 | // by both clang and LLVM, so for now we won't allow bit_casts involving |
| 7950 | // it in a constexpr context. |
| 7951 | Info->FFDiag(Loc, DiagId: diag::note_constexpr_bit_cast_unsupported_type) |
| 7952 | << EltTy; |
| 7953 | return false; |
| 7954 | } |
| 7955 | } |
| 7956 | |
| 7957 | return true; |
| 7958 | } |
| 7959 | |
| 7960 | static bool checkBitCastConstexprEligibility(EvalInfo *Info, |
| 7961 | const ASTContext &Ctx, |
| 7962 | const CastExpr *BCE) { |
| 7963 | bool DestOK = checkBitCastConstexprEligibilityType( |
| 7964 | Loc: BCE->getBeginLoc(), Ty: BCE->getType(), Info, Ctx, CheckingDest: true); |
| 7965 | bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( |
| 7966 | Loc: BCE->getBeginLoc(), |
| 7967 | Ty: BCE->getSubExpr()->getType(), Info, Ctx, CheckingDest: false); |
| 7968 | return SourceOK; |
| 7969 | } |
| 7970 | |
| 7971 | static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, |
| 7972 | const APValue &SourceRValue, |
| 7973 | const CastExpr *BCE) { |
| 7974 | assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && |
| 7975 | "no host or target supports non 8-bit chars" ); |
| 7976 | |
| 7977 | if (!checkBitCastConstexprEligibility(Info: &Info, Ctx: Info.Ctx, BCE)) |
| 7978 | return false; |
| 7979 | |
| 7980 | // Read out SourceValue into a char buffer. |
| 7981 | std::optional<BitCastBuffer> Buffer = |
| 7982 | APValueToBufferConverter::convert(Info, Src: SourceRValue, BCE); |
| 7983 | if (!Buffer) |
| 7984 | return false; |
| 7985 | |
| 7986 | // Write out the buffer into a new APValue. |
| 7987 | std::optional<APValue> MaybeDestValue = |
| 7988 | BufferToAPValueConverter::convert(Info, Buffer&: *Buffer, BCE); |
| 7989 | if (!MaybeDestValue) |
| 7990 | return false; |
| 7991 | |
| 7992 | DestValue = std::move(*MaybeDestValue); |
| 7993 | return true; |
| 7994 | } |
| 7995 | |
| 7996 | static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, |
| 7997 | APValue &SourceValue, |
| 7998 | const CastExpr *BCE) { |
| 7999 | assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && |
| 8000 | "no host or target supports non 8-bit chars" ); |
| 8001 | assert(SourceValue.isLValue() && |
| 8002 | "LValueToRValueBitcast requires an lvalue operand!" ); |
| 8003 | |
| 8004 | LValue SourceLValue; |
| 8005 | APValue SourceRValue; |
| 8006 | SourceLValue.setFrom(Ctx&: Info.Ctx, V: SourceValue); |
| 8007 | if (!handleLValueToRValueConversion( |
| 8008 | Info, Conv: BCE, Type: BCE->getSubExpr()->getType().withConst(), LVal: SourceLValue, |
| 8009 | RVal&: SourceRValue, /*WantObjectRepresentation=*/true)) |
| 8010 | return false; |
| 8011 | |
| 8012 | return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE); |
| 8013 | } |
| 8014 | |
| 8015 | template <class Derived> |
| 8016 | class ExprEvaluatorBase |
| 8017 | : public ConstStmtVisitor<Derived, bool> { |
| 8018 | private: |
| 8019 | Derived &getDerived() { return static_cast<Derived&>(*this); } |
| 8020 | bool DerivedSuccess(const APValue &V, const Expr *E) { |
| 8021 | return getDerived().Success(V, E); |
| 8022 | } |
| 8023 | bool DerivedZeroInitialization(const Expr *E) { |
| 8024 | return getDerived().ZeroInitialization(E); |
| 8025 | } |
| 8026 | |
| 8027 | // Check whether a conditional operator with a non-constant condition is a |
| 8028 | // potential constant expression. If neither arm is a potential constant |
| 8029 | // expression, then the conditional operator is not either. |
| 8030 | template<typename ConditionalOperator> |
| 8031 | void CheckPotentialConstantConditional(const ConditionalOperator *E) { |
| 8032 | assert(Info.checkingPotentialConstantExpression()); |
| 8033 | |
| 8034 | // Speculatively evaluate both arms. |
| 8035 | SmallVector<PartialDiagnosticAt, 8> Diag; |
| 8036 | { |
| 8037 | SpeculativeEvaluationRAII Speculate(Info, &Diag); |
| 8038 | StmtVisitorTy::Visit(E->getFalseExpr()); |
| 8039 | if (Diag.empty()) |
| 8040 | return; |
| 8041 | } |
| 8042 | |
| 8043 | { |
| 8044 | SpeculativeEvaluationRAII Speculate(Info, &Diag); |
| 8045 | Diag.clear(); |
| 8046 | StmtVisitorTy::Visit(E->getTrueExpr()); |
| 8047 | if (Diag.empty()) |
| 8048 | return; |
| 8049 | } |
| 8050 | |
| 8051 | Error(E, diag::note_constexpr_conditional_never_const); |
| 8052 | } |
| 8053 | |
| 8054 | |
| 8055 | template<typename ConditionalOperator> |
| 8056 | bool HandleConditionalOperator(const ConditionalOperator *E) { |
| 8057 | bool BoolResult; |
| 8058 | if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { |
| 8059 | if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { |
| 8060 | CheckPotentialConstantConditional(E); |
| 8061 | return false; |
| 8062 | } |
| 8063 | if (Info.noteFailure()) { |
| 8064 | StmtVisitorTy::Visit(E->getTrueExpr()); |
| 8065 | StmtVisitorTy::Visit(E->getFalseExpr()); |
| 8066 | } |
| 8067 | return false; |
| 8068 | } |
| 8069 | |
| 8070 | Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); |
| 8071 | return StmtVisitorTy::Visit(EvalExpr); |
| 8072 | } |
| 8073 | |
| 8074 | protected: |
| 8075 | EvalInfo &Info; |
| 8076 | typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; |
| 8077 | typedef ExprEvaluatorBase ExprEvaluatorBaseTy; |
| 8078 | |
| 8079 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { |
| 8080 | return Info.CCEDiag(E, DiagId: D); |
| 8081 | } |
| 8082 | |
| 8083 | bool ZeroInitialization(const Expr *E) { return Error(E); } |
| 8084 | |
| 8085 | bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) { |
| 8086 | unsigned BuiltinOp = E->getBuiltinCallee(); |
| 8087 | return BuiltinOp != 0 && |
| 8088 | Info.Ctx.BuiltinInfo.isConstantEvaluated(ID: BuiltinOp); |
| 8089 | } |
| 8090 | |
| 8091 | public: |
| 8092 | ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} |
| 8093 | |
| 8094 | EvalInfo &getEvalInfo() { return Info; } |
| 8095 | |
| 8096 | /// Report an evaluation error. This should only be called when an error is |
| 8097 | /// first discovered. When propagating an error, just return false. |
| 8098 | bool Error(const Expr *E, diag::kind D) { |
| 8099 | Info.FFDiag(E, DiagId: D) << E->getSourceRange(); |
| 8100 | return false; |
| 8101 | } |
| 8102 | bool Error(const Expr *E) { |
| 8103 | return Error(E, diag::note_invalid_subexpr_in_const_expr); |
| 8104 | } |
| 8105 | |
| 8106 | bool VisitStmt(const Stmt *) { |
| 8107 | llvm_unreachable("Expression evaluator should not be called on stmts" ); |
| 8108 | } |
| 8109 | bool VisitExpr(const Expr *E) { |
| 8110 | return Error(E); |
| 8111 | } |
| 8112 | |
| 8113 | bool VisitEmbedExpr(const EmbedExpr *E) { |
| 8114 | const auto It = E->begin(); |
| 8115 | return StmtVisitorTy::Visit(*It); |
| 8116 | } |
| 8117 | |
| 8118 | bool VisitPredefinedExpr(const PredefinedExpr *E) { |
| 8119 | return StmtVisitorTy::Visit(E->getFunctionName()); |
| 8120 | } |
| 8121 | bool VisitConstantExpr(const ConstantExpr *E) { |
| 8122 | if (E->hasAPValueResult()) |
| 8123 | return DerivedSuccess(V: E->getAPValueResult(), E); |
| 8124 | |
| 8125 | return StmtVisitorTy::Visit(E->getSubExpr()); |
| 8126 | } |
| 8127 | |
| 8128 | bool VisitParenExpr(const ParenExpr *E) |
| 8129 | { return StmtVisitorTy::Visit(E->getSubExpr()); } |
| 8130 | bool VisitUnaryExtension(const UnaryOperator *E) |
| 8131 | { return StmtVisitorTy::Visit(E->getSubExpr()); } |
| 8132 | bool VisitUnaryPlus(const UnaryOperator *E) |
| 8133 | { return StmtVisitorTy::Visit(E->getSubExpr()); } |
| 8134 | bool VisitChooseExpr(const ChooseExpr *E) |
| 8135 | { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } |
| 8136 | bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) |
| 8137 | { return StmtVisitorTy::Visit(E->getResultExpr()); } |
| 8138 | bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) |
| 8139 | { return StmtVisitorTy::Visit(E->getReplacement()); } |
| 8140 | bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { |
| 8141 | TempVersionRAII RAII(*Info.CurrentCall); |
| 8142 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); |
| 8143 | return StmtVisitorTy::Visit(E->getExpr()); |
| 8144 | } |
| 8145 | bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { |
| 8146 | TempVersionRAII RAII(*Info.CurrentCall); |
| 8147 | // The initializer may not have been parsed yet, or might be erroneous. |
| 8148 | if (!E->getExpr()) |
| 8149 | return Error(E); |
| 8150 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); |
| 8151 | return StmtVisitorTy::Visit(E->getExpr()); |
| 8152 | } |
| 8153 | |
| 8154 | bool VisitExprWithCleanups(const ExprWithCleanups *E) { |
| 8155 | FullExpressionRAII Scope(Info); |
| 8156 | return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); |
| 8157 | } |
| 8158 | |
| 8159 | // Temporaries are registered when created, so we don't care about |
| 8160 | // CXXBindTemporaryExpr. |
| 8161 | bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { |
| 8162 | return StmtVisitorTy::Visit(E->getSubExpr()); |
| 8163 | } |
| 8164 | |
| 8165 | bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { |
| 8166 | CCEDiag(E, D: diag::note_constexpr_invalid_cast) |
| 8167 | << diag::ConstexprInvalidCastKind::Reinterpret; |
| 8168 | return static_cast<Derived*>(this)->VisitCastExpr(E); |
| 8169 | } |
| 8170 | bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { |
| 8171 | if (!Info.Ctx.getLangOpts().CPlusPlus20) |
| 8172 | CCEDiag(E, D: diag::note_constexpr_invalid_cast) |
| 8173 | << diag::ConstexprInvalidCastKind::Dynamic; |
| 8174 | return static_cast<Derived*>(this)->VisitCastExpr(E); |
| 8175 | } |
| 8176 | bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { |
| 8177 | return static_cast<Derived*>(this)->VisitCastExpr(E); |
| 8178 | } |
| 8179 | |
| 8180 | bool VisitBinaryOperator(const BinaryOperator *E) { |
| 8181 | switch (E->getOpcode()) { |
| 8182 | default: |
| 8183 | return Error(E); |
| 8184 | |
| 8185 | case BO_Comma: |
| 8186 | VisitIgnoredValue(E: E->getLHS()); |
| 8187 | return StmtVisitorTy::Visit(E->getRHS()); |
| 8188 | |
| 8189 | case BO_PtrMemD: |
| 8190 | case BO_PtrMemI: { |
| 8191 | LValue Obj; |
| 8192 | if (!HandleMemberPointerAccess(Info, BO: E, LV&: Obj)) |
| 8193 | return false; |
| 8194 | APValue Result; |
| 8195 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getType(), LVal: Obj, RVal&: Result)) |
| 8196 | return false; |
| 8197 | return DerivedSuccess(V: Result, E); |
| 8198 | } |
| 8199 | } |
| 8200 | } |
| 8201 | |
| 8202 | bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { |
| 8203 | return StmtVisitorTy::Visit(E->getSemanticForm()); |
| 8204 | } |
| 8205 | |
| 8206 | bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { |
| 8207 | // Evaluate and cache the common expression. We treat it as a temporary, |
| 8208 | // even though it's not quite the same thing. |
| 8209 | LValue CommonLV; |
| 8210 | if (!Evaluate(Result&: Info.CurrentCall->createTemporary( |
| 8211 | Key: E->getOpaqueValue(), |
| 8212 | T: getStorageType(Ctx: Info.Ctx, E: E->getOpaqueValue()), |
| 8213 | Scope: ScopeKind::FullExpression, LV&: CommonLV), |
| 8214 | Info, E: E->getCommon())) |
| 8215 | return false; |
| 8216 | |
| 8217 | return HandleConditionalOperator(E); |
| 8218 | } |
| 8219 | |
| 8220 | bool VisitConditionalOperator(const ConditionalOperator *E) { |
| 8221 | bool IsBcpCall = false; |
| 8222 | // If the condition (ignoring parens) is a __builtin_constant_p call, |
| 8223 | // the result is a constant expression if it can be folded without |
| 8224 | // side-effects. This is an important GNU extension. See GCC PR38377 |
| 8225 | // for discussion. |
| 8226 | if (const CallExpr *CallCE = |
| 8227 | dyn_cast<CallExpr>(Val: E->getCond()->IgnoreParenCasts())) |
| 8228 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) |
| 8229 | IsBcpCall = true; |
| 8230 | |
| 8231 | // Always assume __builtin_constant_p(...) ? ... : ... is a potential |
| 8232 | // constant expression; we can't check whether it's potentially foldable. |
| 8233 | // FIXME: We should instead treat __builtin_constant_p as non-constant if |
| 8234 | // it would return 'false' in this mode. |
| 8235 | if (Info.checkingPotentialConstantExpression() && IsBcpCall) |
| 8236 | return false; |
| 8237 | |
| 8238 | FoldConstant Fold(Info, IsBcpCall); |
| 8239 | if (!HandleConditionalOperator(E)) { |
| 8240 | Fold.keepDiagnostics(); |
| 8241 | return false; |
| 8242 | } |
| 8243 | |
| 8244 | return true; |
| 8245 | } |
| 8246 | |
| 8247 | bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { |
| 8248 | if (APValue *Value = Info.CurrentCall->getCurrentTemporary(Key: E); |
| 8249 | Value && !Value->isAbsent()) |
| 8250 | return DerivedSuccess(V: *Value, E); |
| 8251 | |
| 8252 | const Expr *Source = E->getSourceExpr(); |
| 8253 | if (!Source) |
| 8254 | return Error(E); |
| 8255 | if (Source == E) { |
| 8256 | assert(0 && "OpaqueValueExpr recursively refers to itself" ); |
| 8257 | return Error(E); |
| 8258 | } |
| 8259 | return StmtVisitorTy::Visit(Source); |
| 8260 | } |
| 8261 | |
| 8262 | bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { |
| 8263 | for (const Expr *SemE : E->semantics()) { |
| 8264 | if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SemE)) { |
| 8265 | // FIXME: We can't handle the case where an OpaqueValueExpr is also the |
| 8266 | // result expression: there could be two different LValues that would |
| 8267 | // refer to the same object in that case, and we can't model that. |
| 8268 | if (SemE == E->getResultExpr()) |
| 8269 | return Error(E); |
| 8270 | |
| 8271 | // Unique OVEs get evaluated if and when we encounter them when |
| 8272 | // emitting the rest of the semantic form, rather than eagerly. |
| 8273 | if (OVE->isUnique()) |
| 8274 | continue; |
| 8275 | |
| 8276 | LValue LV; |
| 8277 | if (!Evaluate(Result&: Info.CurrentCall->createTemporary( |
| 8278 | Key: OVE, T: getStorageType(Ctx: Info.Ctx, E: OVE), |
| 8279 | Scope: ScopeKind::FullExpression, LV), |
| 8280 | Info, E: OVE->getSourceExpr())) |
| 8281 | return false; |
| 8282 | } else if (SemE == E->getResultExpr()) { |
| 8283 | if (!StmtVisitorTy::Visit(SemE)) |
| 8284 | return false; |
| 8285 | } else { |
| 8286 | if (!EvaluateIgnoredValue(Info, E: SemE)) |
| 8287 | return false; |
| 8288 | } |
| 8289 | } |
| 8290 | return true; |
| 8291 | } |
| 8292 | |
| 8293 | bool VisitCallExpr(const CallExpr *E) { |
| 8294 | APValue Result; |
| 8295 | if (!handleCallExpr(E, Result, ResultSlot: nullptr)) |
| 8296 | return false; |
| 8297 | return DerivedSuccess(V: Result, E); |
| 8298 | } |
| 8299 | |
| 8300 | bool handleCallExpr(const CallExpr *E, APValue &Result, |
| 8301 | const LValue *ResultSlot) { |
| 8302 | CallScopeRAII CallScope(Info); |
| 8303 | |
| 8304 | const Expr *Callee = E->getCallee()->IgnoreParens(); |
| 8305 | QualType CalleeType = Callee->getType(); |
| 8306 | |
| 8307 | const FunctionDecl *FD = nullptr; |
| 8308 | LValue *This = nullptr, ObjectArg; |
| 8309 | auto Args = ArrayRef(E->getArgs(), E->getNumArgs()); |
| 8310 | bool HasQualifier = false; |
| 8311 | |
| 8312 | CallRef Call; |
| 8313 | |
| 8314 | // Extract function decl and 'this' pointer from the callee. |
| 8315 | if (CalleeType->isSpecificBuiltinType(K: BuiltinType::BoundMember)) { |
| 8316 | const CXXMethodDecl *Member = nullptr; |
| 8317 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: Callee)) { |
| 8318 | // Explicit bound member calls, such as x.f() or p->g(); |
| 8319 | if (!EvaluateObjectArgument(Info, Object: ME->getBase(), This&: ObjectArg)) |
| 8320 | return false; |
| 8321 | Member = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl()); |
| 8322 | if (!Member) |
| 8323 | return Error(Callee); |
| 8324 | This = &ObjectArg; |
| 8325 | HasQualifier = ME->hasQualifier(); |
| 8326 | } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: Callee)) { |
| 8327 | // Indirect bound member calls ('.*' or '->*'). |
| 8328 | const ValueDecl *D = |
| 8329 | HandleMemberPointerAccess(Info, BO: BE, LV&: ObjectArg, IncludeMember: false); |
| 8330 | if (!D) |
| 8331 | return false; |
| 8332 | Member = dyn_cast<CXXMethodDecl>(Val: D); |
| 8333 | if (!Member) |
| 8334 | return Error(Callee); |
| 8335 | This = &ObjectArg; |
| 8336 | } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Val: Callee)) { |
| 8337 | if (!Info.getLangOpts().CPlusPlus20) |
| 8338 | Info.CCEDiag(E: PDE, DiagId: diag::note_constexpr_pseudo_destructor); |
| 8339 | return EvaluateObjectArgument(Info, Object: PDE->getBase(), This&: ObjectArg) && |
| 8340 | HandleDestruction(Info, E: PDE, This: ObjectArg, ThisType: PDE->getDestroyedType()); |
| 8341 | } else |
| 8342 | return Error(Callee); |
| 8343 | FD = Member; |
| 8344 | } else if (CalleeType->isFunctionPointerType()) { |
| 8345 | LValue CalleeLV; |
| 8346 | if (!EvaluatePointer(E: Callee, Result&: CalleeLV, Info)) |
| 8347 | return false; |
| 8348 | |
| 8349 | if (!CalleeLV.getLValueOffset().isZero()) |
| 8350 | return Error(Callee); |
| 8351 | if (CalleeLV.isNullPointer()) { |
| 8352 | Info.FFDiag(E: Callee, DiagId: diag::note_constexpr_null_callee) |
| 8353 | << const_cast<Expr *>(Callee); |
| 8354 | return false; |
| 8355 | } |
| 8356 | FD = dyn_cast_or_null<FunctionDecl>( |
| 8357 | Val: CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); |
| 8358 | if (!FD) |
| 8359 | return Error(Callee); |
| 8360 | // Don't call function pointers which have been cast to some other type. |
| 8361 | // Per DR (no number yet), the caller and callee can differ in noexcept. |
| 8362 | if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( |
| 8363 | T: CalleeType->getPointeeType(), U: FD->getType())) { |
| 8364 | return Error(E); |
| 8365 | } |
| 8366 | |
| 8367 | // For an (overloaded) assignment expression, evaluate the RHS before the |
| 8368 | // LHS. |
| 8369 | auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: E); |
| 8370 | if (OCE && OCE->isAssignmentOp()) { |
| 8371 | assert(Args.size() == 2 && "wrong number of arguments in assignment" ); |
| 8372 | Call = Info.CurrentCall->createCall(Callee: FD); |
| 8373 | bool HasThis = false; |
| 8374 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) |
| 8375 | HasThis = MD->isImplicitObjectMemberFunction(); |
| 8376 | if (!EvaluateArgs(Args: HasThis ? Args.slice(N: 1) : Args, Call, Info, Callee: FD, |
| 8377 | /*RightToLeft=*/true, ObjectArg: &ObjectArg)) |
| 8378 | return false; |
| 8379 | } |
| 8380 | |
| 8381 | // Overloaded operator calls to member functions are represented as normal |
| 8382 | // calls with '*this' as the first argument. |
| 8383 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD); |
| 8384 | if (MD && |
| 8385 | (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) { |
| 8386 | // FIXME: When selecting an implicit conversion for an overloaded |
| 8387 | // operator delete, we sometimes try to evaluate calls to conversion |
| 8388 | // operators without a 'this' parameter! |
| 8389 | if (Args.empty()) |
| 8390 | return Error(E); |
| 8391 | |
| 8392 | if (!EvaluateObjectArgument(Info, Object: Args[0], This&: ObjectArg)) |
| 8393 | return false; |
| 8394 | |
| 8395 | // If we are calling a static operator, the 'this' argument needs to be |
| 8396 | // ignored after being evaluated. |
| 8397 | if (MD->isInstance()) |
| 8398 | This = &ObjectArg; |
| 8399 | |
| 8400 | // If this is syntactically a simple assignment using a trivial |
| 8401 | // assignment operator, start the lifetimes of union members as needed, |
| 8402 | // per C++20 [class.union]5. |
| 8403 | if (Info.getLangOpts().CPlusPlus20 && OCE && |
| 8404 | OCE->getOperator() == OO_Equal && MD->isTrivial() && |
| 8405 | !MaybeHandleUnionActiveMemberChange(Info, LHSExpr: Args[0], LHS: ObjectArg)) |
| 8406 | return false; |
| 8407 | |
| 8408 | Args = Args.slice(N: 1); |
| 8409 | } else if (MD && MD->isLambdaStaticInvoker()) { |
| 8410 | // Map the static invoker for the lambda back to the call operator. |
| 8411 | // Conveniently, we don't have to slice out the 'this' argument (as is |
| 8412 | // being done for the non-static case), since a static member function |
| 8413 | // doesn't have an implicit argument passed in. |
| 8414 | const CXXRecordDecl *ClosureClass = MD->getParent(); |
| 8415 | assert( |
| 8416 | ClosureClass->captures_begin() == ClosureClass->captures_end() && |
| 8417 | "Number of captures must be zero for conversion to function-ptr" ); |
| 8418 | |
| 8419 | const CXXMethodDecl *LambdaCallOp = |
| 8420 | ClosureClass->getLambdaCallOperator(); |
| 8421 | |
| 8422 | // Set 'FD', the function that will be called below, to the call |
| 8423 | // operator. If the closure object represents a generic lambda, find |
| 8424 | // the corresponding specialization of the call operator. |
| 8425 | |
| 8426 | if (ClosureClass->isGenericLambda()) { |
| 8427 | assert(MD->isFunctionTemplateSpecialization() && |
| 8428 | "A generic lambda's static-invoker function must be a " |
| 8429 | "template specialization" ); |
| 8430 | const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); |
| 8431 | FunctionTemplateDecl *CallOpTemplate = |
| 8432 | LambdaCallOp->getDescribedFunctionTemplate(); |
| 8433 | void *InsertPos = nullptr; |
| 8434 | FunctionDecl *CorrespondingCallOpSpecialization = |
| 8435 | CallOpTemplate->findSpecialization(Args: TAL->asArray(), InsertPos); |
| 8436 | assert(CorrespondingCallOpSpecialization && |
| 8437 | "We must always have a function call operator specialization " |
| 8438 | "that corresponds to our static invoker specialization" ); |
| 8439 | assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization)); |
| 8440 | FD = CorrespondingCallOpSpecialization; |
| 8441 | } else |
| 8442 | FD = LambdaCallOp; |
| 8443 | } else if (FD->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) { |
| 8444 | if (FD->getDeclName().isAnyOperatorNew()) { |
| 8445 | LValue Ptr; |
| 8446 | if (!HandleOperatorNewCall(Info, E, Result&: Ptr)) |
| 8447 | return false; |
| 8448 | Ptr.moveInto(V&: Result); |
| 8449 | return CallScope.destroy(); |
| 8450 | } else { |
| 8451 | return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); |
| 8452 | } |
| 8453 | } |
| 8454 | } else |
| 8455 | return Error(E); |
| 8456 | |
| 8457 | // Evaluate the arguments now if we've not already done so. |
| 8458 | if (!Call) { |
| 8459 | Call = Info.CurrentCall->createCall(Callee: FD); |
| 8460 | if (!EvaluateArgs(Args, Call, Info, Callee: FD, /*RightToLeft*/ false, |
| 8461 | ObjectArg: &ObjectArg)) |
| 8462 | return false; |
| 8463 | } |
| 8464 | |
| 8465 | SmallVector<QualType, 4> CovariantAdjustmentPath; |
| 8466 | if (This) { |
| 8467 | auto *NamedMember = dyn_cast<CXXMethodDecl>(Val: FD); |
| 8468 | if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { |
| 8469 | // Perform virtual dispatch, if necessary. |
| 8470 | FD = HandleVirtualDispatch(Info, E, This&: *This, Found: NamedMember, |
| 8471 | CovariantAdjustmentPath); |
| 8472 | if (!FD) |
| 8473 | return false; |
| 8474 | } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) { |
| 8475 | // Check that the 'this' pointer points to an object of the right type. |
| 8476 | // FIXME: If this is an assignment operator call, we may need to change |
| 8477 | // the active union member before we check this. |
| 8478 | if (!checkNonVirtualMemberCallThisPointer(Info, E, This: *This, NamedMember)) |
| 8479 | return false; |
| 8480 | } |
| 8481 | } |
| 8482 | |
| 8483 | // Destructor calls are different enough that they have their own codepath. |
| 8484 | if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: FD)) { |
| 8485 | assert(This && "no 'this' pointer for destructor call" ); |
| 8486 | return HandleDestruction(Info, E, This: *This, |
| 8487 | ThisType: Info.Ctx.getRecordType(Decl: DD->getParent())) && |
| 8488 | CallScope.destroy(); |
| 8489 | } |
| 8490 | |
| 8491 | const FunctionDecl *Definition = nullptr; |
| 8492 | Stmt *Body = FD->getBody(Definition); |
| 8493 | SourceLocation Loc = E->getExprLoc(); |
| 8494 | |
| 8495 | // Treat the object argument as `this` when evaluating defaulted |
| 8496 | // special menmber functions |
| 8497 | if (FD->hasCXXExplicitFunctionObjectParameter()) |
| 8498 | This = &ObjectArg; |
| 8499 | |
| 8500 | if (!CheckConstexprFunction(Info, CallLoc: Loc, Declaration: FD, Definition, Body) || |
| 8501 | !HandleFunctionCall(CallLoc: Loc, Callee: Definition, ObjectArg: This, E, Args, Call, Body, Info, |
| 8502 | Result, ResultSlot)) |
| 8503 | return false; |
| 8504 | |
| 8505 | if (!CovariantAdjustmentPath.empty() && |
| 8506 | !HandleCovariantReturnAdjustment(Info, E, Result, |
| 8507 | Path: CovariantAdjustmentPath)) |
| 8508 | return false; |
| 8509 | |
| 8510 | return CallScope.destroy(); |
| 8511 | } |
| 8512 | |
| 8513 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { |
| 8514 | return StmtVisitorTy::Visit(E->getInitializer()); |
| 8515 | } |
| 8516 | bool VisitInitListExpr(const InitListExpr *E) { |
| 8517 | if (E->getNumInits() == 0) |
| 8518 | return DerivedZeroInitialization(E); |
| 8519 | if (E->getNumInits() == 1) |
| 8520 | return StmtVisitorTy::Visit(E->getInit(Init: 0)); |
| 8521 | return Error(E); |
| 8522 | } |
| 8523 | bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { |
| 8524 | return DerivedZeroInitialization(E); |
| 8525 | } |
| 8526 | bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { |
| 8527 | return DerivedZeroInitialization(E); |
| 8528 | } |
| 8529 | bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { |
| 8530 | return DerivedZeroInitialization(E); |
| 8531 | } |
| 8532 | |
| 8533 | /// A member expression where the object is a prvalue is itself a prvalue. |
| 8534 | bool VisitMemberExpr(const MemberExpr *E) { |
| 8535 | assert(!Info.Ctx.getLangOpts().CPlusPlus11 && |
| 8536 | "missing temporary materialization conversion" ); |
| 8537 | assert(!E->isArrow() && "missing call to bound member function?" ); |
| 8538 | |
| 8539 | APValue Val; |
| 8540 | if (!Evaluate(Result&: Val, Info, E: E->getBase())) |
| 8541 | return false; |
| 8542 | |
| 8543 | QualType BaseTy = E->getBase()->getType(); |
| 8544 | |
| 8545 | const FieldDecl *FD = dyn_cast<FieldDecl>(Val: E->getMemberDecl()); |
| 8546 | if (!FD) return Error(E); |
| 8547 | assert(!FD->getType()->isReferenceType() && "prvalue reference?" ); |
| 8548 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == |
| 8549 | FD->getParent()->getCanonicalDecl() && "record / field mismatch" ); |
| 8550 | |
| 8551 | // Note: there is no lvalue base here. But this case should only ever |
| 8552 | // happen in C or in C++98, where we cannot be evaluating a constexpr |
| 8553 | // constructor, which is the only case the base matters. |
| 8554 | CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); |
| 8555 | SubobjectDesignator Designator(BaseTy); |
| 8556 | Designator.addDeclUnchecked(D: FD); |
| 8557 | |
| 8558 | APValue Result; |
| 8559 | return extractSubobject(Info, E, Obj, Sub: Designator, Result) && |
| 8560 | DerivedSuccess(V: Result, E); |
| 8561 | } |
| 8562 | |
| 8563 | bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { |
| 8564 | APValue Val; |
| 8565 | if (!Evaluate(Result&: Val, Info, E: E->getBase())) |
| 8566 | return false; |
| 8567 | |
| 8568 | if (Val.isVector()) { |
| 8569 | SmallVector<uint32_t, 4> Indices; |
| 8570 | E->getEncodedElementAccess(Elts&: Indices); |
| 8571 | if (Indices.size() == 1) { |
| 8572 | // Return scalar. |
| 8573 | return DerivedSuccess(V: Val.getVectorElt(I: Indices[0]), E); |
| 8574 | } else { |
| 8575 | // Construct new APValue vector. |
| 8576 | SmallVector<APValue, 4> Elts; |
| 8577 | for (unsigned I = 0; I < Indices.size(); ++I) { |
| 8578 | Elts.push_back(Elt: Val.getVectorElt(I: Indices[I])); |
| 8579 | } |
| 8580 | APValue VecResult(Elts.data(), Indices.size()); |
| 8581 | return DerivedSuccess(V: VecResult, E); |
| 8582 | } |
| 8583 | } |
| 8584 | |
| 8585 | return false; |
| 8586 | } |
| 8587 | |
| 8588 | bool VisitCastExpr(const CastExpr *E) { |
| 8589 | switch (E->getCastKind()) { |
| 8590 | default: |
| 8591 | break; |
| 8592 | |
| 8593 | case CK_AtomicToNonAtomic: { |
| 8594 | APValue AtomicVal; |
| 8595 | // This does not need to be done in place even for class/array types: |
| 8596 | // atomic-to-non-atomic conversion implies copying the object |
| 8597 | // representation. |
| 8598 | if (!Evaluate(Result&: AtomicVal, Info, E: E->getSubExpr())) |
| 8599 | return false; |
| 8600 | return DerivedSuccess(V: AtomicVal, E); |
| 8601 | } |
| 8602 | |
| 8603 | case CK_NoOp: |
| 8604 | case CK_UserDefinedConversion: |
| 8605 | return StmtVisitorTy::Visit(E->getSubExpr()); |
| 8606 | |
| 8607 | case CK_LValueToRValue: { |
| 8608 | LValue LVal; |
| 8609 | if (!EvaluateLValue(E: E->getSubExpr(), Result&: LVal, Info)) |
| 8610 | return false; |
| 8611 | APValue RVal; |
| 8612 | // Note, we use the subexpression's type in order to retain cv-qualifiers. |
| 8613 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getSubExpr()->getType(), |
| 8614 | LVal, RVal)) |
| 8615 | return false; |
| 8616 | return DerivedSuccess(V: RVal, E); |
| 8617 | } |
| 8618 | case CK_LValueToRValueBitCast: { |
| 8619 | APValue DestValue, SourceValue; |
| 8620 | if (!Evaluate(Result&: SourceValue, Info, E: E->getSubExpr())) |
| 8621 | return false; |
| 8622 | if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, BCE: E)) |
| 8623 | return false; |
| 8624 | return DerivedSuccess(V: DestValue, E); |
| 8625 | } |
| 8626 | |
| 8627 | case CK_AddressSpaceConversion: { |
| 8628 | APValue Value; |
| 8629 | if (!Evaluate(Result&: Value, Info, E: E->getSubExpr())) |
| 8630 | return false; |
| 8631 | return DerivedSuccess(V: Value, E); |
| 8632 | } |
| 8633 | } |
| 8634 | |
| 8635 | return Error(E); |
| 8636 | } |
| 8637 | |
| 8638 | bool VisitUnaryPostInc(const UnaryOperator *UO) { |
| 8639 | return VisitUnaryPostIncDec(UO); |
| 8640 | } |
| 8641 | bool VisitUnaryPostDec(const UnaryOperator *UO) { |
| 8642 | return VisitUnaryPostIncDec(UO); |
| 8643 | } |
| 8644 | bool VisitUnaryPostIncDec(const UnaryOperator *UO) { |
| 8645 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) |
| 8646 | return Error(UO); |
| 8647 | |
| 8648 | LValue LVal; |
| 8649 | if (!EvaluateLValue(E: UO->getSubExpr(), Result&: LVal, Info)) |
| 8650 | return false; |
| 8651 | APValue RVal; |
| 8652 | if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), |
| 8653 | UO->isIncrementOp(), &RVal)) |
| 8654 | return false; |
| 8655 | return DerivedSuccess(V: RVal, E: UO); |
| 8656 | } |
| 8657 | |
| 8658 | bool VisitStmtExpr(const StmtExpr *E) { |
| 8659 | // We will have checked the full-expressions inside the statement expression |
| 8660 | // when they were completed, and don't need to check them again now. |
| 8661 | llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior, |
| 8662 | false); |
| 8663 | |
| 8664 | const CompoundStmt *CS = E->getSubStmt(); |
| 8665 | if (CS->body_empty()) |
| 8666 | return true; |
| 8667 | |
| 8668 | BlockScopeRAII Scope(Info); |
| 8669 | for (CompoundStmt::const_body_iterator BI = CS->body_begin(), |
| 8670 | BE = CS->body_end(); |
| 8671 | /**/; ++BI) { |
| 8672 | if (BI + 1 == BE) { |
| 8673 | const Expr *FinalExpr = dyn_cast<Expr>(Val: *BI); |
| 8674 | if (!FinalExpr) { |
| 8675 | Info.FFDiag(Loc: (*BI)->getBeginLoc(), |
| 8676 | DiagId: diag::note_constexpr_stmt_expr_unsupported); |
| 8677 | return false; |
| 8678 | } |
| 8679 | return this->Visit(FinalExpr) && Scope.destroy(); |
| 8680 | } |
| 8681 | |
| 8682 | APValue ReturnValue; |
| 8683 | StmtResult Result = { .Value: ReturnValue, .Slot: nullptr }; |
| 8684 | EvalStmtResult ESR = EvaluateStmt(Result, Info, S: *BI); |
| 8685 | if (ESR != ESR_Succeeded) { |
| 8686 | // FIXME: If the statement-expression terminated due to 'return', |
| 8687 | // 'break', or 'continue', it would be nice to propagate that to |
| 8688 | // the outer statement evaluation rather than bailing out. |
| 8689 | if (ESR != ESR_Failed) |
| 8690 | Info.FFDiag(Loc: (*BI)->getBeginLoc(), |
| 8691 | DiagId: diag::note_constexpr_stmt_expr_unsupported); |
| 8692 | return false; |
| 8693 | } |
| 8694 | } |
| 8695 | |
| 8696 | llvm_unreachable("Return from function from the loop above." ); |
| 8697 | } |
| 8698 | |
| 8699 | bool VisitPackIndexingExpr(const PackIndexingExpr *E) { |
| 8700 | return StmtVisitorTy::Visit(E->getSelectedExpr()); |
| 8701 | } |
| 8702 | |
| 8703 | /// Visit a value which is evaluated, but whose value is ignored. |
| 8704 | void VisitIgnoredValue(const Expr *E) { |
| 8705 | EvaluateIgnoredValue(Info, E); |
| 8706 | } |
| 8707 | |
| 8708 | /// Potentially visit a MemberExpr's base expression. |
| 8709 | void VisitIgnoredBaseExpression(const Expr *E) { |
| 8710 | // While MSVC doesn't evaluate the base expression, it does diagnose the |
| 8711 | // presence of side-effecting behavior. |
| 8712 | if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Ctx: Info.Ctx)) |
| 8713 | return; |
| 8714 | VisitIgnoredValue(E); |
| 8715 | } |
| 8716 | }; |
| 8717 | |
| 8718 | } // namespace |
| 8719 | |
| 8720 | //===----------------------------------------------------------------------===// |
| 8721 | // Common base class for lvalue and temporary evaluation. |
| 8722 | //===----------------------------------------------------------------------===// |
| 8723 | namespace { |
| 8724 | template<class Derived> |
| 8725 | class LValueExprEvaluatorBase |
| 8726 | : public ExprEvaluatorBase<Derived> { |
| 8727 | protected: |
| 8728 | LValue &Result; |
| 8729 | bool InvalidBaseOK; |
| 8730 | typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; |
| 8731 | typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; |
| 8732 | |
| 8733 | bool Success(APValue::LValueBase B) { |
| 8734 | Result.set(B); |
| 8735 | return true; |
| 8736 | } |
| 8737 | |
| 8738 | bool evaluatePointer(const Expr *E, LValue &Result) { |
| 8739 | return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); |
| 8740 | } |
| 8741 | |
| 8742 | public: |
| 8743 | LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) |
| 8744 | : ExprEvaluatorBaseTy(Info), Result(Result), |
| 8745 | InvalidBaseOK(InvalidBaseOK) {} |
| 8746 | |
| 8747 | bool Success(const APValue &V, const Expr *E) { |
| 8748 | Result.setFrom(Ctx&: this->Info.Ctx, V); |
| 8749 | return true; |
| 8750 | } |
| 8751 | |
| 8752 | bool VisitMemberExpr(const MemberExpr *E) { |
| 8753 | // Handle non-static data members. |
| 8754 | QualType BaseTy; |
| 8755 | bool EvalOK; |
| 8756 | if (E->isArrow()) { |
| 8757 | EvalOK = evaluatePointer(E: E->getBase(), Result); |
| 8758 | BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); |
| 8759 | } else if (E->getBase()->isPRValue()) { |
| 8760 | assert(E->getBase()->getType()->isRecordType()); |
| 8761 | EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); |
| 8762 | BaseTy = E->getBase()->getType(); |
| 8763 | } else { |
| 8764 | EvalOK = this->Visit(E->getBase()); |
| 8765 | BaseTy = E->getBase()->getType(); |
| 8766 | } |
| 8767 | if (!EvalOK) { |
| 8768 | if (!InvalidBaseOK) |
| 8769 | return false; |
| 8770 | Result.setInvalid(B: E); |
| 8771 | return true; |
| 8772 | } |
| 8773 | |
| 8774 | const ValueDecl *MD = E->getMemberDecl(); |
| 8775 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: E->getMemberDecl())) { |
| 8776 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == |
| 8777 | FD->getParent()->getCanonicalDecl() && "record / field mismatch" ); |
| 8778 | (void)BaseTy; |
| 8779 | if (!HandleLValueMember(this->Info, E, Result, FD)) |
| 8780 | return false; |
| 8781 | } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(Val: MD)) { |
| 8782 | if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) |
| 8783 | return false; |
| 8784 | } else |
| 8785 | return this->Error(E); |
| 8786 | |
| 8787 | if (MD->getType()->isReferenceType()) { |
| 8788 | APValue RefValue; |
| 8789 | if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, |
| 8790 | RefValue)) |
| 8791 | return false; |
| 8792 | return Success(RefValue, E); |
| 8793 | } |
| 8794 | return true; |
| 8795 | } |
| 8796 | |
| 8797 | bool VisitBinaryOperator(const BinaryOperator *E) { |
| 8798 | switch (E->getOpcode()) { |
| 8799 | default: |
| 8800 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 8801 | |
| 8802 | case BO_PtrMemD: |
| 8803 | case BO_PtrMemI: |
| 8804 | return HandleMemberPointerAccess(this->Info, E, Result); |
| 8805 | } |
| 8806 | } |
| 8807 | |
| 8808 | bool VisitCastExpr(const CastExpr *E) { |
| 8809 | switch (E->getCastKind()) { |
| 8810 | default: |
| 8811 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 8812 | |
| 8813 | case CK_DerivedToBase: |
| 8814 | case CK_UncheckedDerivedToBase: |
| 8815 | if (!this->Visit(E->getSubExpr())) |
| 8816 | return false; |
| 8817 | |
| 8818 | // Now figure out the necessary offset to add to the base LV to get from |
| 8819 | // the derived class to the base class. |
| 8820 | return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), |
| 8821 | Result); |
| 8822 | } |
| 8823 | } |
| 8824 | }; |
| 8825 | } |
| 8826 | |
| 8827 | //===----------------------------------------------------------------------===// |
| 8828 | // LValue Evaluation |
| 8829 | // |
| 8830 | // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), |
| 8831 | // function designators (in C), decl references to void objects (in C), and |
| 8832 | // temporaries (if building with -Wno-address-of-temporary). |
| 8833 | // |
| 8834 | // LValue evaluation produces values comprising a base expression of one of the |
| 8835 | // following types: |
| 8836 | // - Declarations |
| 8837 | // * VarDecl |
| 8838 | // * FunctionDecl |
| 8839 | // - Literals |
| 8840 | // * CompoundLiteralExpr in C (and in global scope in C++) |
| 8841 | // * StringLiteral |
| 8842 | // * PredefinedExpr |
| 8843 | // * ObjCStringLiteralExpr |
| 8844 | // * ObjCEncodeExpr |
| 8845 | // * AddrLabelExpr |
| 8846 | // * BlockExpr |
| 8847 | // * CallExpr for a MakeStringConstant builtin |
| 8848 | // - typeid(T) expressions, as TypeInfoLValues |
| 8849 | // - Locals and temporaries |
| 8850 | // * MaterializeTemporaryExpr |
| 8851 | // * Any Expr, with a CallIndex indicating the function in which the temporary |
| 8852 | // was evaluated, for cases where the MaterializeTemporaryExpr is missing |
| 8853 | // from the AST (FIXME). |
| 8854 | // * A MaterializeTemporaryExpr that has static storage duration, with no |
| 8855 | // CallIndex, for a lifetime-extended temporary. |
| 8856 | // * The ConstantExpr that is currently being evaluated during evaluation of an |
| 8857 | // immediate invocation. |
| 8858 | // plus an offset in bytes. |
| 8859 | //===----------------------------------------------------------------------===// |
| 8860 | namespace { |
| 8861 | class LValueExprEvaluator |
| 8862 | : public LValueExprEvaluatorBase<LValueExprEvaluator> { |
| 8863 | public: |
| 8864 | LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : |
| 8865 | LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} |
| 8866 | |
| 8867 | bool VisitVarDecl(const Expr *E, const VarDecl *VD); |
| 8868 | bool VisitUnaryPreIncDec(const UnaryOperator *UO); |
| 8869 | |
| 8870 | bool VisitCallExpr(const CallExpr *E); |
| 8871 | bool VisitDeclRefExpr(const DeclRefExpr *E); |
| 8872 | bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(B: E); } |
| 8873 | bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); |
| 8874 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); |
| 8875 | bool VisitMemberExpr(const MemberExpr *E); |
| 8876 | bool VisitStringLiteral(const StringLiteral *E) { |
| 8877 | return Success(B: APValue::LValueBase( |
| 8878 | E, 0, Info.getASTContext().getNextStringLiteralVersion())); |
| 8879 | } |
| 8880 | bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(B: E); } |
| 8881 | bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); |
| 8882 | bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); |
| 8883 | bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); |
| 8884 | bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E); |
| 8885 | bool VisitUnaryDeref(const UnaryOperator *E); |
| 8886 | bool VisitUnaryReal(const UnaryOperator *E); |
| 8887 | bool VisitUnaryImag(const UnaryOperator *E); |
| 8888 | bool VisitUnaryPreInc(const UnaryOperator *UO) { |
| 8889 | return VisitUnaryPreIncDec(UO); |
| 8890 | } |
| 8891 | bool VisitUnaryPreDec(const UnaryOperator *UO) { |
| 8892 | return VisitUnaryPreIncDec(UO); |
| 8893 | } |
| 8894 | bool VisitBinAssign(const BinaryOperator *BO); |
| 8895 | bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); |
| 8896 | |
| 8897 | bool VisitCastExpr(const CastExpr *E) { |
| 8898 | switch (E->getCastKind()) { |
| 8899 | default: |
| 8900 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); |
| 8901 | |
| 8902 | case CK_LValueBitCast: |
| 8903 | this->CCEDiag(E, D: diag::note_constexpr_invalid_cast) |
| 8904 | << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret |
| 8905 | << Info.Ctx.getLangOpts().CPlusPlus; |
| 8906 | if (!Visit(S: E->getSubExpr())) |
| 8907 | return false; |
| 8908 | Result.Designator.setInvalid(); |
| 8909 | return true; |
| 8910 | |
| 8911 | case CK_BaseToDerived: |
| 8912 | if (!Visit(S: E->getSubExpr())) |
| 8913 | return false; |
| 8914 | return HandleBaseToDerivedCast(Info, E, Result); |
| 8915 | |
| 8916 | case CK_Dynamic: |
| 8917 | if (!Visit(S: E->getSubExpr())) |
| 8918 | return false; |
| 8919 | return HandleDynamicCast(Info, E: cast<ExplicitCastExpr>(Val: E), Ptr&: Result); |
| 8920 | } |
| 8921 | } |
| 8922 | }; |
| 8923 | } // end anonymous namespace |
| 8924 | |
| 8925 | /// Get an lvalue to a field of a lambda's closure type. |
| 8926 | static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, |
| 8927 | const CXXMethodDecl *MD, const FieldDecl *FD, |
| 8928 | bool LValueToRValueConversion) { |
| 8929 | // Static lambda function call operators can't have captures. We already |
| 8930 | // diagnosed this, so bail out here. |
| 8931 | if (MD->isStatic()) { |
| 8932 | assert(Info.CurrentCall->This == nullptr && |
| 8933 | "This should not be set for a static call operator" ); |
| 8934 | return false; |
| 8935 | } |
| 8936 | |
| 8937 | // Start with 'Result' referring to the complete closure object... |
| 8938 | if (MD->isExplicitObjectMemberFunction()) { |
| 8939 | // Self may be passed by reference or by value. |
| 8940 | const ParmVarDecl *Self = MD->getParamDecl(i: 0); |
| 8941 | if (Self->getType()->isReferenceType()) { |
| 8942 | APValue *RefValue = Info.getParamSlot(Call: Info.CurrentCall->Arguments, PVD: Self); |
| 8943 | if (!RefValue->allowConstexprUnknown() || RefValue->hasValue()) |
| 8944 | Result.setFrom(Ctx&: Info.Ctx, V: *RefValue); |
| 8945 | } else { |
| 8946 | const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(PVD: Self); |
| 8947 | CallStackFrame *Frame = |
| 8948 | Info.getCallFrameAndDepth(CallIndex: Info.CurrentCall->Arguments.CallIndex) |
| 8949 | .first; |
| 8950 | unsigned Version = Info.CurrentCall->Arguments.Version; |
| 8951 | Result.set(B: {VD, Frame->Index, Version}); |
| 8952 | } |
| 8953 | } else |
| 8954 | Result = *Info.CurrentCall->This; |
| 8955 | |
| 8956 | // ... then update it to refer to the field of the closure object |
| 8957 | // that represents the capture. |
| 8958 | if (!HandleLValueMember(Info, E, LVal&: Result, FD)) |
| 8959 | return false; |
| 8960 | |
| 8961 | // And if the field is of reference type (or if we captured '*this' by |
| 8962 | // reference), update 'Result' to refer to what |
| 8963 | // the field refers to. |
| 8964 | if (LValueToRValueConversion) { |
| 8965 | APValue RVal; |
| 8966 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: FD->getType(), LVal: Result, RVal)) |
| 8967 | return false; |
| 8968 | Result.setFrom(Ctx&: Info.Ctx, V: RVal); |
| 8969 | } |
| 8970 | return true; |
| 8971 | } |
| 8972 | |
| 8973 | /// Evaluate an expression as an lvalue. This can be legitimately called on |
| 8974 | /// expressions which are not glvalues, in three cases: |
| 8975 | /// * function designators in C, and |
| 8976 | /// * "extern void" objects |
| 8977 | /// * @selector() expressions in Objective-C |
| 8978 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, |
| 8979 | bool InvalidBaseOK) { |
| 8980 | assert(!E->isValueDependent()); |
| 8981 | assert(E->isGLValue() || E->getType()->isFunctionType() || |
| 8982 | E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens())); |
| 8983 | return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(S: E); |
| 8984 | } |
| 8985 | |
| 8986 | bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { |
| 8987 | const NamedDecl *D = E->getDecl(); |
| 8988 | if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl, |
| 8989 | UnnamedGlobalConstantDecl>(Val: D)) |
| 8990 | return Success(B: cast<ValueDecl>(Val: D)); |
| 8991 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) |
| 8992 | return VisitVarDecl(E, VD); |
| 8993 | if (const BindingDecl *BD = dyn_cast<BindingDecl>(Val: D)) |
| 8994 | return Visit(S: BD->getBinding()); |
| 8995 | return Error(E); |
| 8996 | } |
| 8997 | |
| 8998 | bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { |
| 8999 | // If we are within a lambda's call operator, check whether the 'VD' referred |
| 9000 | // to within 'E' actually represents a lambda-capture that maps to a |
| 9001 | // data-member/field within the closure object, and if so, evaluate to the |
| 9002 | // field or what the field refers to. |
| 9003 | if (Info.CurrentCall && isLambdaCallOperator(DC: Info.CurrentCall->Callee) && |
| 9004 | isa<DeclRefExpr>(Val: E) && |
| 9005 | cast<DeclRefExpr>(Val: E)->refersToEnclosingVariableOrCapture()) { |
| 9006 | // We don't always have a complete capture-map when checking or inferring if |
| 9007 | // the function call operator meets the requirements of a constexpr function |
| 9008 | // - but we don't need to evaluate the captures to determine constexprness |
| 9009 | // (dcl.constexpr C++17). |
| 9010 | if (Info.checkingPotentialConstantExpression()) |
| 9011 | return false; |
| 9012 | |
| 9013 | if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(Val: VD)) { |
| 9014 | const auto *MD = cast<CXXMethodDecl>(Val: Info.CurrentCall->Callee); |
| 9015 | return HandleLambdaCapture(Info, E, Result, MD, FD, |
| 9016 | LValueToRValueConversion: FD->getType()->isReferenceType()); |
| 9017 | } |
| 9018 | } |
| 9019 | |
| 9020 | CallStackFrame *Frame = nullptr; |
| 9021 | unsigned Version = 0; |
| 9022 | if (VD->hasLocalStorage()) { |
| 9023 | // Only if a local variable was declared in the function currently being |
| 9024 | // evaluated, do we expect to be able to find its value in the current |
| 9025 | // frame. (Otherwise it was likely declared in an enclosing context and |
| 9026 | // could either have a valid evaluatable value (for e.g. a constexpr |
| 9027 | // variable) or be ill-formed (and trigger an appropriate evaluation |
| 9028 | // diagnostic)). |
| 9029 | CallStackFrame *CurrFrame = Info.CurrentCall; |
| 9030 | if (CurrFrame->Callee && CurrFrame->Callee->Equals(DC: VD->getDeclContext())) { |
| 9031 | // Function parameters are stored in some caller's frame. (Usually the |
| 9032 | // immediate caller, but for an inherited constructor they may be more |
| 9033 | // distant.) |
| 9034 | if (auto *PVD = dyn_cast<ParmVarDecl>(Val: VD)) { |
| 9035 | if (CurrFrame->Arguments) { |
| 9036 | VD = CurrFrame->Arguments.getOrigParam(PVD); |
| 9037 | Frame = |
| 9038 | Info.getCallFrameAndDepth(CallIndex: CurrFrame->Arguments.CallIndex).first; |
| 9039 | Version = CurrFrame->Arguments.Version; |
| 9040 | } |
| 9041 | } else { |
| 9042 | Frame = CurrFrame; |
| 9043 | Version = CurrFrame->getCurrentTemporaryVersion(Key: VD); |
| 9044 | } |
| 9045 | } |
| 9046 | } |
| 9047 | |
| 9048 | if (!VD->getType()->isReferenceType()) { |
| 9049 | if (Frame) { |
| 9050 | Result.set(B: {VD, Frame->Index, Version}); |
| 9051 | return true; |
| 9052 | } |
| 9053 | return Success(B: VD); |
| 9054 | } |
| 9055 | |
| 9056 | if (!Info.getLangOpts().CPlusPlus11) { |
| 9057 | Info.CCEDiag(E, DiagId: diag::note_constexpr_ltor_non_integral, ExtraNotes: 1) |
| 9058 | << VD << VD->getType(); |
| 9059 | Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at); |
| 9060 | } |
| 9061 | |
| 9062 | APValue *V; |
| 9063 | if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, Result&: V)) |
| 9064 | return false; |
| 9065 | |
| 9066 | return Success(V: *V, E); |
| 9067 | } |
| 9068 | |
| 9069 | bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) { |
| 9070 | if (!IsConstantEvaluatedBuiltinCall(E)) |
| 9071 | return ExprEvaluatorBaseTy::VisitCallExpr(E); |
| 9072 | |
| 9073 | switch (E->getBuiltinCallee()) { |
| 9074 | default: |
| 9075 | return false; |
| 9076 | case Builtin::BIas_const: |
| 9077 | case Builtin::BIforward: |
| 9078 | case Builtin::BIforward_like: |
| 9079 | case Builtin::BImove: |
| 9080 | case Builtin::BImove_if_noexcept: |
| 9081 | if (cast<FunctionDecl>(Val: E->getCalleeDecl())->isConstexpr()) |
| 9082 | return Visit(S: E->getArg(Arg: 0)); |
| 9083 | break; |
| 9084 | } |
| 9085 | |
| 9086 | return ExprEvaluatorBaseTy::VisitCallExpr(E); |
| 9087 | } |
| 9088 | |
| 9089 | bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( |
| 9090 | const MaterializeTemporaryExpr *E) { |
| 9091 | // Walk through the expression to find the materialized temporary itself. |
| 9092 | SmallVector<const Expr *, 2> CommaLHSs; |
| 9093 | SmallVector<SubobjectAdjustment, 2> Adjustments; |
| 9094 | const Expr *Inner = |
| 9095 | E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs, Adjustments); |
| 9096 | |
| 9097 | // If we passed any comma operators, evaluate their LHSs. |
| 9098 | for (const Expr *E : CommaLHSs) |
| 9099 | if (!EvaluateIgnoredValue(Info, E)) |
| 9100 | return false; |
| 9101 | |
| 9102 | // A materialized temporary with static storage duration can appear within the |
| 9103 | // result of a constant expression evaluation, so we need to preserve its |
| 9104 | // value for use outside this evaluation. |
| 9105 | APValue *Value; |
| 9106 | if (E->getStorageDuration() == SD_Static) { |
| 9107 | if (Info.EvalMode == EvalInfo::EM_ConstantFold) |
| 9108 | return false; |
| 9109 | // FIXME: What about SD_Thread? |
| 9110 | Value = E->getOrCreateValue(MayCreate: true); |
| 9111 | *Value = APValue(); |
| 9112 | Result.set(B: E); |
| 9113 | } else { |
| 9114 | Value = &Info.CurrentCall->createTemporary( |
| 9115 | Key: E, T: Inner->getType(), |
| 9116 | Scope: E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression |
| 9117 | : ScopeKind::Block, |
| 9118 | LV&: Result); |
| 9119 | } |
| 9120 | |
| 9121 | QualType Type = Inner->getType(); |
| 9122 | |
| 9123 | // Materialize the temporary itself. |
| 9124 | if (!EvaluateInPlace(Result&: *Value, Info, This: Result, E: Inner)) { |
| 9125 | *Value = APValue(); |
| 9126 | return false; |
| 9127 | } |
| 9128 | |
| 9129 | // Adjust our lvalue to refer to the desired subobject. |
| 9130 | for (unsigned I = Adjustments.size(); I != 0; /**/) { |
| 9131 | --I; |
| 9132 | switch (Adjustments[I].Kind) { |
| 9133 | case SubobjectAdjustment::DerivedToBaseAdjustment: |
| 9134 | if (!HandleLValueBasePath(Info, E: Adjustments[I].DerivedToBase.BasePath, |
| 9135 | Type, Result)) |
| 9136 | return false; |
| 9137 | Type = Adjustments[I].DerivedToBase.BasePath->getType(); |
| 9138 | break; |
| 9139 | |
| 9140 | case SubobjectAdjustment::FieldAdjustment: |
| 9141 | if (!HandleLValueMember(Info, E, LVal&: Result, FD: Adjustments[I].Field)) |
| 9142 | return false; |
| 9143 | Type = Adjustments[I].Field->getType(); |
| 9144 | break; |
| 9145 | |
| 9146 | case SubobjectAdjustment::MemberPointerAdjustment: |
| 9147 | if (!HandleMemberPointerAccess(Info&: this->Info, LVType: Type, LV&: Result, |
| 9148 | RHS: Adjustments[I].Ptr.RHS)) |
| 9149 | return false; |
| 9150 | Type = Adjustments[I].Ptr.MPT->getPointeeType(); |
| 9151 | break; |
| 9152 | } |
| 9153 | } |
| 9154 | |
| 9155 | return true; |
| 9156 | } |
| 9157 | |
| 9158 | bool |
| 9159 | LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { |
| 9160 | assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && |
| 9161 | "lvalue compound literal in c++?" ); |
| 9162 | // Defer visiting the literal until the lvalue-to-rvalue conversion. We can |
| 9163 | // only see this when folding in C, so there's no standard to follow here. |
| 9164 | return Success(B: E); |
| 9165 | } |
| 9166 | |
| 9167 | bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { |
| 9168 | TypeInfoLValue TypeInfo; |
| 9169 | |
| 9170 | if (!E->isPotentiallyEvaluated()) { |
| 9171 | if (E->isTypeOperand()) |
| 9172 | TypeInfo = TypeInfoLValue(E->getTypeOperand(Context: Info.Ctx).getTypePtr()); |
| 9173 | else |
| 9174 | TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); |
| 9175 | } else { |
| 9176 | if (!Info.Ctx.getLangOpts().CPlusPlus20) { |
| 9177 | Info.CCEDiag(E, DiagId: diag::note_constexpr_typeid_polymorphic) |
| 9178 | << E->getExprOperand()->getType() |
| 9179 | << E->getExprOperand()->getSourceRange(); |
| 9180 | } |
| 9181 | |
| 9182 | if (!Visit(S: E->getExprOperand())) |
| 9183 | return false; |
| 9184 | |
| 9185 | std::optional<DynamicType> DynType = |
| 9186 | ComputeDynamicType(Info, E, This&: Result, AK: AK_TypeId); |
| 9187 | if (!DynType) |
| 9188 | return false; |
| 9189 | |
| 9190 | TypeInfo = |
| 9191 | TypeInfoLValue(Info.Ctx.getRecordType(Decl: DynType->Type).getTypePtr()); |
| 9192 | } |
| 9193 | |
| 9194 | return Success(B: APValue::LValueBase::getTypeInfo(LV: TypeInfo, TypeInfo: E->getType())); |
| 9195 | } |
| 9196 | |
| 9197 | bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { |
| 9198 | return Success(B: E->getGuidDecl()); |
| 9199 | } |
| 9200 | |
| 9201 | bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { |
| 9202 | // Handle static data members. |
| 9203 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: E->getMemberDecl())) { |
| 9204 | VisitIgnoredBaseExpression(E: E->getBase()); |
| 9205 | return VisitVarDecl(E, VD); |
| 9206 | } |
| 9207 | |
| 9208 | // Handle static member functions. |
| 9209 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl())) { |
| 9210 | if (MD->isStatic()) { |
| 9211 | VisitIgnoredBaseExpression(E: E->getBase()); |
| 9212 | return Success(B: MD); |
| 9213 | } |
| 9214 | } |
| 9215 | |
| 9216 | // Handle non-static data members. |
| 9217 | return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); |
| 9218 | } |
| 9219 | |
| 9220 | bool LValueExprEvaluator::VisitExtVectorElementExpr( |
| 9221 | const ExtVectorElementExpr *E) { |
| 9222 | bool Success = true; |
| 9223 | |
| 9224 | APValue Val; |
| 9225 | if (!Evaluate(Result&: Val, Info, E: E->getBase())) { |
| 9226 | if (!Info.noteFailure()) |
| 9227 | return false; |
| 9228 | Success = false; |
| 9229 | } |
| 9230 | |
| 9231 | SmallVector<uint32_t, 4> Indices; |
| 9232 | E->getEncodedElementAccess(Elts&: Indices); |
| 9233 | // FIXME: support accessing more than one element |
| 9234 | if (Indices.size() > 1) |
| 9235 | return false; |
| 9236 | |
| 9237 | if (Success) { |
| 9238 | Result.setFrom(Ctx&: Info.Ctx, V: Val); |
| 9239 | QualType BaseType = E->getBase()->getType(); |
| 9240 | if (E->isArrow()) |
| 9241 | BaseType = BaseType->getPointeeType(); |
| 9242 | const auto *VT = BaseType->castAs<VectorType>(); |
| 9243 | HandleLValueVectorElement(Info, E, LVal&: Result, EltTy: VT->getElementType(), |
| 9244 | Size: VT->getNumElements(), Idx: Indices[0]); |
| 9245 | } |
| 9246 | |
| 9247 | return Success; |
| 9248 | } |
| 9249 | |
| 9250 | bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { |
| 9251 | if (E->getBase()->getType()->isSveVLSBuiltinType()) |
| 9252 | return Error(E); |
| 9253 | |
| 9254 | APSInt Index; |
| 9255 | bool Success = true; |
| 9256 | |
| 9257 | if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) { |
| 9258 | APValue Val; |
| 9259 | if (!Evaluate(Result&: Val, Info, E: E->getBase())) { |
| 9260 | if (!Info.noteFailure()) |
| 9261 | return false; |
| 9262 | Success = false; |
| 9263 | } |
| 9264 | |
| 9265 | if (!EvaluateInteger(E: E->getIdx(), Result&: Index, Info)) { |
| 9266 | if (!Info.noteFailure()) |
| 9267 | return false; |
| 9268 | Success = false; |
| 9269 | } |
| 9270 | |
| 9271 | if (Success) { |
| 9272 | Result.setFrom(Ctx&: Info.Ctx, V: Val); |
| 9273 | HandleLValueVectorElement(Info, E, LVal&: Result, EltTy: VT->getElementType(), |
| 9274 | Size: VT->getNumElements(), Idx: Index.getExtValue()); |
| 9275 | } |
| 9276 | |
| 9277 | return Success; |
| 9278 | } |
| 9279 | |
| 9280 | // C++17's rules require us to evaluate the LHS first, regardless of which |
| 9281 | // side is the base. |
| 9282 | for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { |
| 9283 | if (SubExpr == E->getBase() ? !evaluatePointer(E: SubExpr, Result) |
| 9284 | : !EvaluateInteger(E: SubExpr, Result&: Index, Info)) { |
| 9285 | if (!Info.noteFailure()) |
| 9286 | return false; |
| 9287 | Success = false; |
| 9288 | } |
| 9289 | } |
| 9290 | |
| 9291 | return Success && |
| 9292 | HandleLValueArrayAdjustment(Info, E, LVal&: Result, EltTy: E->getType(), Adjustment: Index); |
| 9293 | } |
| 9294 | |
| 9295 | bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { |
| 9296 | return evaluatePointer(E: E->getSubExpr(), Result); |
| 9297 | } |
| 9298 | |
| 9299 | bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { |
| 9300 | if (!Visit(S: E->getSubExpr())) |
| 9301 | return false; |
| 9302 | // __real is a no-op on scalar lvalues. |
| 9303 | if (E->getSubExpr()->getType()->isAnyComplexType()) |
| 9304 | HandleLValueComplexElement(Info, E, LVal&: Result, EltTy: E->getType(), Imag: false); |
| 9305 | return true; |
| 9306 | } |
| 9307 | |
| 9308 | bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { |
| 9309 | assert(E->getSubExpr()->getType()->isAnyComplexType() && |
| 9310 | "lvalue __imag__ on scalar?" ); |
| 9311 | if (!Visit(S: E->getSubExpr())) |
| 9312 | return false; |
| 9313 | HandleLValueComplexElement(Info, E, LVal&: Result, EltTy: E->getType(), Imag: true); |
| 9314 | return true; |
| 9315 | } |
| 9316 | |
| 9317 | bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { |
| 9318 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) |
| 9319 | return Error(E: UO); |
| 9320 | |
| 9321 | if (!this->Visit(S: UO->getSubExpr())) |
| 9322 | return false; |
| 9323 | |
| 9324 | return handleIncDec( |
| 9325 | Info&: this->Info, E: UO, LVal: Result, LValType: UO->getSubExpr()->getType(), |
| 9326 | IsIncrement: UO->isIncrementOp(), Old: nullptr); |
| 9327 | } |
| 9328 | |
| 9329 | bool LValueExprEvaluator::VisitCompoundAssignOperator( |
| 9330 | const CompoundAssignOperator *CAO) { |
| 9331 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) |
| 9332 | return Error(E: CAO); |
| 9333 | |
| 9334 | bool Success = true; |
| 9335 | |
| 9336 | // C++17 onwards require that we evaluate the RHS first. |
| 9337 | APValue RHS; |
| 9338 | if (!Evaluate(Result&: RHS, Info&: this->Info, E: CAO->getRHS())) { |
| 9339 | if (!Info.noteFailure()) |
| 9340 | return false; |
| 9341 | Success = false; |
| 9342 | } |
| 9343 | |
| 9344 | // The overall lvalue result is the result of evaluating the LHS. |
| 9345 | if (!this->Visit(S: CAO->getLHS()) || !Success) |
| 9346 | return false; |
| 9347 | |
| 9348 | return handleCompoundAssignment( |
| 9349 | Info&: this->Info, E: CAO, |
| 9350 | LVal: Result, LValType: CAO->getLHS()->getType(), PromotedLValType: CAO->getComputationLHSType(), |
| 9351 | Opcode: CAO->getOpForCompoundAssignment(Opc: CAO->getOpcode()), RVal: RHS); |
| 9352 | } |
| 9353 | |
| 9354 | bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { |
| 9355 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) |
| 9356 | return Error(E); |
| 9357 | |
| 9358 | bool Success = true; |
| 9359 | |
| 9360 | // C++17 onwards require that we evaluate the RHS first. |
| 9361 | APValue NewVal; |
| 9362 | if (!Evaluate(Result&: NewVal, Info&: this->Info, E: E->getRHS())) { |
| 9363 | if (!Info.noteFailure()) |
| 9364 | return false; |
| 9365 | Success = false; |
| 9366 | } |
| 9367 | |
| 9368 | if (!this->Visit(S: E->getLHS()) || !Success) |
| 9369 | return false; |
| 9370 | |
| 9371 | if (Info.getLangOpts().CPlusPlus20 && |
| 9372 | !MaybeHandleUnionActiveMemberChange(Info, LHSExpr: E->getLHS(), LHS: Result)) |
| 9373 | return false; |
| 9374 | |
| 9375 | return handleAssignment(Info&: this->Info, E, LVal: Result, LValType: E->getLHS()->getType(), |
| 9376 | Val&: NewVal); |
| 9377 | } |
| 9378 | |
| 9379 | //===----------------------------------------------------------------------===// |
| 9380 | // Pointer Evaluation |
| 9381 | //===----------------------------------------------------------------------===// |
| 9382 | |
| 9383 | /// Attempts to compute the number of bytes available at the pointer |
| 9384 | /// returned by a function with the alloc_size attribute. Returns true if we |
| 9385 | /// were successful. Places an unsigned number into `Result`. |
| 9386 | /// |
| 9387 | /// This expects the given CallExpr to be a call to a function with an |
| 9388 | /// alloc_size attribute. |
| 9389 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, |
| 9390 | const CallExpr *Call, |
| 9391 | llvm::APInt &Result) { |
| 9392 | const AllocSizeAttr *AllocSize = getAllocSizeAttr(CE: Call); |
| 9393 | |
| 9394 | assert(AllocSize && AllocSize->getElemSizeParam().isValid()); |
| 9395 | unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); |
| 9396 | unsigned BitsInSizeT = Ctx.getTypeSize(T: Ctx.getSizeType()); |
| 9397 | if (Call->getNumArgs() <= SizeArgNo) |
| 9398 | return false; |
| 9399 | |
| 9400 | auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { |
| 9401 | Expr::EvalResult ExprResult; |
| 9402 | if (!E->EvaluateAsInt(Result&: ExprResult, Ctx, AllowSideEffects: Expr::SE_AllowSideEffects)) |
| 9403 | return false; |
| 9404 | Into = ExprResult.Val.getInt(); |
| 9405 | if (Into.isNegative() || !Into.isIntN(N: BitsInSizeT)) |
| 9406 | return false; |
| 9407 | Into = Into.zext(width: BitsInSizeT); |
| 9408 | return true; |
| 9409 | }; |
| 9410 | |
| 9411 | APSInt SizeOfElem; |
| 9412 | if (!EvaluateAsSizeT(Call->getArg(Arg: SizeArgNo), SizeOfElem)) |
| 9413 | return false; |
| 9414 | |
| 9415 | if (!AllocSize->getNumElemsParam().isValid()) { |
| 9416 | Result = std::move(SizeOfElem); |
| 9417 | return true; |
| 9418 | } |
| 9419 | |
| 9420 | APSInt NumberOfElems; |
| 9421 | unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); |
| 9422 | if (!EvaluateAsSizeT(Call->getArg(Arg: NumArgNo), NumberOfElems)) |
| 9423 | return false; |
| 9424 | |
| 9425 | bool Overflow; |
| 9426 | llvm::APInt BytesAvailable = SizeOfElem.umul_ov(RHS: NumberOfElems, Overflow); |
| 9427 | if (Overflow) |
| 9428 | return false; |
| 9429 | |
| 9430 | Result = std::move(BytesAvailable); |
| 9431 | return true; |
| 9432 | } |
| 9433 | |
| 9434 | /// Convenience function. LVal's base must be a call to an alloc_size |
| 9435 | /// function. |
| 9436 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, |
| 9437 | const LValue &LVal, |
| 9438 | llvm::APInt &Result) { |
| 9439 | assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && |
| 9440 | "Can't get the size of a non alloc_size function" ); |
| 9441 | const auto *Base = LVal.getLValueBase().get<const Expr *>(); |
| 9442 | const CallExpr *CE = tryUnwrapAllocSizeCall(E: Base); |
| 9443 | return getBytesReturnedByAllocSizeCall(Ctx, Call: CE, Result); |
| 9444 | } |
| 9445 | |
| 9446 | /// Attempts to evaluate the given LValueBase as the result of a call to |
| 9447 | /// a function with the alloc_size attribute. If it was possible to do so, this |
| 9448 | /// function will return true, make Result's Base point to said function call, |
| 9449 | /// and mark Result's Base as invalid. |
| 9450 | static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, |
| 9451 | LValue &Result) { |
| 9452 | if (Base.isNull()) |
| 9453 | return false; |
| 9454 | |
| 9455 | // Because we do no form of static analysis, we only support const variables. |
| 9456 | // |
| 9457 | // Additionally, we can't support parameters, nor can we support static |
| 9458 | // variables (in the latter case, use-before-assign isn't UB; in the former, |
| 9459 | // we have no clue what they'll be assigned to). |
| 9460 | const auto *VD = |
| 9461 | dyn_cast_or_null<VarDecl>(Val: Base.dyn_cast<const ValueDecl *>()); |
| 9462 | if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) |
| 9463 | return false; |
| 9464 | |
| 9465 | const Expr *Init = VD->getAnyInitializer(); |
| 9466 | if (!Init || Init->getType().isNull()) |
| 9467 | return false; |
| 9468 | |
| 9469 | const Expr *E = Init->IgnoreParens(); |
| 9470 | if (!tryUnwrapAllocSizeCall(E)) |
| 9471 | return false; |
| 9472 | |
| 9473 | // Store E instead of E unwrapped so that the type of the LValue's base is |
| 9474 | // what the user wanted. |
| 9475 | Result.setInvalid(B: E); |
| 9476 | |
| 9477 | QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); |
| 9478 | Result.addUnsizedArray(Info, E, ElemTy: Pointee); |
| 9479 | return true; |
| 9480 | } |
| 9481 | |
| 9482 | namespace { |
| 9483 | class PointerExprEvaluator |
| 9484 | : public ExprEvaluatorBase<PointerExprEvaluator> { |
| 9485 | LValue &Result; |
| 9486 | bool InvalidBaseOK; |
| 9487 | |
| 9488 | bool Success(const Expr *E) { |
| 9489 | Result.set(B: E); |
| 9490 | return true; |
| 9491 | } |
| 9492 | |
| 9493 | bool evaluateLValue(const Expr *E, LValue &Result) { |
| 9494 | return EvaluateLValue(E, Result, Info, InvalidBaseOK); |
| 9495 | } |
| 9496 | |
| 9497 | bool evaluatePointer(const Expr *E, LValue &Result) { |
| 9498 | return EvaluatePointer(E, Result, Info, InvalidBaseOK); |
| 9499 | } |
| 9500 | |
| 9501 | bool visitNonBuiltinCallExpr(const CallExpr *E); |
| 9502 | public: |
| 9503 | |
| 9504 | PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) |
| 9505 | : ExprEvaluatorBaseTy(info), Result(Result), |
| 9506 | InvalidBaseOK(InvalidBaseOK) {} |
| 9507 | |
| 9508 | bool Success(const APValue &V, const Expr *E) { |
| 9509 | Result.setFrom(Ctx&: Info.Ctx, V); |
| 9510 | return true; |
| 9511 | } |
| 9512 | bool ZeroInitialization(const Expr *E) { |
| 9513 | Result.setNull(Ctx&: Info.Ctx, PointerTy: E->getType()); |
| 9514 | return true; |
| 9515 | } |
| 9516 | |
| 9517 | bool VisitBinaryOperator(const BinaryOperator *E); |
| 9518 | bool VisitCastExpr(const CastExpr* E); |
| 9519 | bool VisitUnaryAddrOf(const UnaryOperator *E); |
| 9520 | bool VisitObjCStringLiteral(const ObjCStringLiteral *E) |
| 9521 | { return Success(E); } |
| 9522 | bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { |
| 9523 | if (E->isExpressibleAsConstantInitializer()) |
| 9524 | return Success(E); |
| 9525 | if (Info.noteFailure()) |
| 9526 | EvaluateIgnoredValue(Info, E: E->getSubExpr()); |
| 9527 | return Error(E); |
| 9528 | } |
| 9529 | bool VisitAddrLabelExpr(const AddrLabelExpr *E) |
| 9530 | { return Success(E); } |
| 9531 | bool VisitCallExpr(const CallExpr *E); |
| 9532 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); |
| 9533 | bool VisitBlockExpr(const BlockExpr *E) { |
| 9534 | if (!E->getBlockDecl()->hasCaptures()) |
| 9535 | return Success(E); |
| 9536 | return Error(E); |
| 9537 | } |
| 9538 | bool VisitCXXThisExpr(const CXXThisExpr *E) { |
| 9539 | auto DiagnoseInvalidUseOfThis = [&] { |
| 9540 | if (Info.getLangOpts().CPlusPlus11) |
| 9541 | Info.FFDiag(E, DiagId: diag::note_constexpr_this) << E->isImplicit(); |
| 9542 | else |
| 9543 | Info.FFDiag(E); |
| 9544 | }; |
| 9545 | |
| 9546 | // Can't look at 'this' when checking a potential constant expression. |
| 9547 | if (Info.checkingPotentialConstantExpression()) |
| 9548 | return false; |
| 9549 | |
| 9550 | bool IsExplicitLambda = |
| 9551 | isLambdaCallWithExplicitObjectParameter(DC: Info.CurrentCall->Callee); |
| 9552 | if (!IsExplicitLambda) { |
| 9553 | if (!Info.CurrentCall->This) { |
| 9554 | DiagnoseInvalidUseOfThis(); |
| 9555 | return false; |
| 9556 | } |
| 9557 | |
| 9558 | Result = *Info.CurrentCall->This; |
| 9559 | } |
| 9560 | |
| 9561 | if (isLambdaCallOperator(DC: Info.CurrentCall->Callee)) { |
| 9562 | // Ensure we actually have captured 'this'. If something was wrong with |
| 9563 | // 'this' capture, the error would have been previously reported. |
| 9564 | // Otherwise we can be inside of a default initialization of an object |
| 9565 | // declared by lambda's body, so no need to return false. |
| 9566 | if (!Info.CurrentCall->LambdaThisCaptureField) { |
| 9567 | if (IsExplicitLambda && !Info.CurrentCall->This) { |
| 9568 | DiagnoseInvalidUseOfThis(); |
| 9569 | return false; |
| 9570 | } |
| 9571 | |
| 9572 | return true; |
| 9573 | } |
| 9574 | |
| 9575 | const auto *MD = cast<CXXMethodDecl>(Val: Info.CurrentCall->Callee); |
| 9576 | return HandleLambdaCapture( |
| 9577 | Info, E, Result, MD, FD: Info.CurrentCall->LambdaThisCaptureField, |
| 9578 | LValueToRValueConversion: Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType()); |
| 9579 | } |
| 9580 | return true; |
| 9581 | } |
| 9582 | |
| 9583 | bool VisitCXXNewExpr(const CXXNewExpr *E); |
| 9584 | |
| 9585 | bool VisitSourceLocExpr(const SourceLocExpr *E) { |
| 9586 | assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?" ); |
| 9587 | APValue LValResult = E->EvaluateInContext( |
| 9588 | Ctx: Info.Ctx, DefaultExpr: Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); |
| 9589 | Result.setFrom(Ctx&: Info.Ctx, V: LValResult); |
| 9590 | return true; |
| 9591 | } |
| 9592 | |
| 9593 | bool VisitEmbedExpr(const EmbedExpr *E) { |
| 9594 | llvm::report_fatal_error(reason: "Not yet implemented for ExprConstant.cpp" ); |
| 9595 | return true; |
| 9596 | } |
| 9597 | |
| 9598 | bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { |
| 9599 | std::string ResultStr = E->ComputeName(Context&: Info.Ctx); |
| 9600 | |
| 9601 | QualType CharTy = Info.Ctx.CharTy.withConst(); |
| 9602 | APInt Size(Info.Ctx.getTypeSize(T: Info.Ctx.getSizeType()), |
| 9603 | ResultStr.size() + 1); |
| 9604 | QualType ArrayTy = Info.Ctx.getConstantArrayType( |
| 9605 | EltTy: CharTy, ArySize: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 9606 | |
| 9607 | StringLiteral *SL = |
| 9608 | StringLiteral::Create(Ctx: Info.Ctx, Str: ResultStr, Kind: StringLiteralKind::Ordinary, |
| 9609 | /*Pascal*/ false, Ty: ArrayTy, Locs: E->getLocation()); |
| 9610 | |
| 9611 | evaluateLValue(E: SL, Result); |
| 9612 | Result.addArray(Info, E, CAT: cast<ConstantArrayType>(Val&: ArrayTy)); |
| 9613 | return true; |
| 9614 | } |
| 9615 | |
| 9616 | // FIXME: Missing: @protocol, @selector |
| 9617 | }; |
| 9618 | } // end anonymous namespace |
| 9619 | |
| 9620 | static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, |
| 9621 | bool InvalidBaseOK) { |
| 9622 | assert(!E->isValueDependent()); |
| 9623 | assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); |
| 9624 | return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(S: E); |
| 9625 | } |
| 9626 | |
| 9627 | bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { |
| 9628 | if (E->getOpcode() != BO_Add && |
| 9629 | E->getOpcode() != BO_Sub) |
| 9630 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 9631 | |
| 9632 | const Expr *PExp = E->getLHS(); |
| 9633 | const Expr *IExp = E->getRHS(); |
| 9634 | if (IExp->getType()->isPointerType()) |
| 9635 | std::swap(a&: PExp, b&: IExp); |
| 9636 | |
| 9637 | bool EvalPtrOK = evaluatePointer(E: PExp, Result); |
| 9638 | if (!EvalPtrOK && !Info.noteFailure()) |
| 9639 | return false; |
| 9640 | |
| 9641 | llvm::APSInt Offset; |
| 9642 | if (!EvaluateInteger(E: IExp, Result&: Offset, Info) || !EvalPtrOK) |
| 9643 | return false; |
| 9644 | |
| 9645 | if (E->getOpcode() == BO_Sub) |
| 9646 | negateAsSigned(Int&: Offset); |
| 9647 | |
| 9648 | QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); |
| 9649 | return HandleLValueArrayAdjustment(Info, E, LVal&: Result, EltTy: Pointee, Adjustment: Offset); |
| 9650 | } |
| 9651 | |
| 9652 | bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { |
| 9653 | return evaluateLValue(E: E->getSubExpr(), Result); |
| 9654 | } |
| 9655 | |
| 9656 | // Is the provided decl 'std::source_location::current'? |
| 9657 | static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) { |
| 9658 | if (!FD) |
| 9659 | return false; |
| 9660 | const IdentifierInfo *FnII = FD->getIdentifier(); |
| 9661 | if (!FnII || !FnII->isStr(Str: "current" )) |
| 9662 | return false; |
| 9663 | |
| 9664 | const auto *RD = dyn_cast<RecordDecl>(Val: FD->getParent()); |
| 9665 | if (!RD) |
| 9666 | return false; |
| 9667 | |
| 9668 | const IdentifierInfo *ClassII = RD->getIdentifier(); |
| 9669 | return RD->isInStdNamespace() && ClassII && ClassII->isStr(Str: "source_location" ); |
| 9670 | } |
| 9671 | |
| 9672 | bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 9673 | const Expr *SubExpr = E->getSubExpr(); |
| 9674 | |
| 9675 | switch (E->getCastKind()) { |
| 9676 | default: |
| 9677 | break; |
| 9678 | case CK_BitCast: |
| 9679 | case CK_CPointerToObjCPointerCast: |
| 9680 | case CK_BlockPointerToObjCPointerCast: |
| 9681 | case CK_AnyPointerToBlockPointerCast: |
| 9682 | case CK_AddressSpaceConversion: |
| 9683 | if (!Visit(S: SubExpr)) |
| 9684 | return false; |
| 9685 | // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are |
| 9686 | // permitted in constant expressions in C++11. Bitcasts from cv void* are |
| 9687 | // also static_casts, but we disallow them as a resolution to DR1312. |
| 9688 | if (!E->getType()->isVoidPointerType()) { |
| 9689 | // In some circumstances, we permit casting from void* to cv1 T*, when the |
| 9690 | // actual pointee object is actually a cv2 T. |
| 9691 | bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid && |
| 9692 | !Result.IsNullPtr; |
| 9693 | bool VoidPtrCastMaybeOK = |
| 9694 | Result.IsNullPtr || |
| 9695 | (HasValidResult && |
| 9696 | Info.Ctx.hasSimilarType(T1: Result.Designator.getType(Ctx&: Info.Ctx), |
| 9697 | T2: E->getType()->getPointeeType())); |
| 9698 | // 1. We'll allow it in std::allocator::allocate, and anything which that |
| 9699 | // calls. |
| 9700 | // 2. HACK 2022-03-28: Work around an issue with libstdc++'s |
| 9701 | // <source_location> header. Fixed in GCC 12 and later (2022-04-??). |
| 9702 | // We'll allow it in the body of std::source_location::current. GCC's |
| 9703 | // implementation had a parameter of type `void*`, and casts from |
| 9704 | // that back to `const __impl*` in its body. |
| 9705 | if (VoidPtrCastMaybeOK && |
| 9706 | (Info.getStdAllocatorCaller(FnName: "allocate" ) || |
| 9707 | IsDeclSourceLocationCurrent(FD: Info.CurrentCall->Callee) || |
| 9708 | Info.getLangOpts().CPlusPlus26)) { |
| 9709 | // Permitted. |
| 9710 | } else { |
| 9711 | if (SubExpr->getType()->isVoidPointerType() && |
| 9712 | Info.getLangOpts().CPlusPlus) { |
| 9713 | if (HasValidResult) |
| 9714 | CCEDiag(E, D: diag::note_constexpr_invalid_void_star_cast) |
| 9715 | << SubExpr->getType() << Info.getLangOpts().CPlusPlus26 |
| 9716 | << Result.Designator.getType(Ctx&: Info.Ctx).getCanonicalType() |
| 9717 | << E->getType()->getPointeeType(); |
| 9718 | else |
| 9719 | CCEDiag(E, D: diag::note_constexpr_invalid_cast) |
| 9720 | << diag::ConstexprInvalidCastKind::CastFrom |
| 9721 | << SubExpr->getType(); |
| 9722 | } else |
| 9723 | CCEDiag(E, D: diag::note_constexpr_invalid_cast) |
| 9724 | << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret |
| 9725 | << Info.Ctx.getLangOpts().CPlusPlus; |
| 9726 | Result.Designator.setInvalid(); |
| 9727 | } |
| 9728 | } |
| 9729 | if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) |
| 9730 | ZeroInitialization(E); |
| 9731 | return true; |
| 9732 | |
| 9733 | case CK_DerivedToBase: |
| 9734 | case CK_UncheckedDerivedToBase: |
| 9735 | if (!evaluatePointer(E: E->getSubExpr(), Result)) |
| 9736 | return false; |
| 9737 | if (!Result.Base && Result.Offset.isZero()) |
| 9738 | return true; |
| 9739 | |
| 9740 | // Now figure out the necessary offset to add to the base LV to get from |
| 9741 | // the derived class to the base class. |
| 9742 | return HandleLValueBasePath(Info, E, Type: E->getSubExpr()->getType()-> |
| 9743 | castAs<PointerType>()->getPointeeType(), |
| 9744 | Result); |
| 9745 | |
| 9746 | case CK_BaseToDerived: |
| 9747 | if (!Visit(S: E->getSubExpr())) |
| 9748 | return false; |
| 9749 | if (!Result.Base && Result.Offset.isZero()) |
| 9750 | return true; |
| 9751 | return HandleBaseToDerivedCast(Info, E, Result); |
| 9752 | |
| 9753 | case CK_Dynamic: |
| 9754 | if (!Visit(S: E->getSubExpr())) |
| 9755 | return false; |
| 9756 | return HandleDynamicCast(Info, E: cast<ExplicitCastExpr>(Val: E), Ptr&: Result); |
| 9757 | |
| 9758 | case CK_NullToPointer: |
| 9759 | VisitIgnoredValue(E: E->getSubExpr()); |
| 9760 | return ZeroInitialization(E); |
| 9761 | |
| 9762 | case CK_IntegralToPointer: { |
| 9763 | CCEDiag(E, D: diag::note_constexpr_invalid_cast) |
| 9764 | << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret |
| 9765 | << Info.Ctx.getLangOpts().CPlusPlus; |
| 9766 | |
| 9767 | APValue Value; |
| 9768 | if (!EvaluateIntegerOrLValue(E: SubExpr, Result&: Value, Info)) |
| 9769 | break; |
| 9770 | |
| 9771 | if (Value.isInt()) { |
| 9772 | unsigned Size = Info.Ctx.getTypeSize(T: E->getType()); |
| 9773 | uint64_t N = Value.getInt().extOrTrunc(width: Size).getZExtValue(); |
| 9774 | Result.Base = (Expr*)nullptr; |
| 9775 | Result.InvalidBase = false; |
| 9776 | Result.Offset = CharUnits::fromQuantity(Quantity: N); |
| 9777 | Result.Designator.setInvalid(); |
| 9778 | Result.IsNullPtr = false; |
| 9779 | return true; |
| 9780 | } else { |
| 9781 | // In rare instances, the value isn't an lvalue. |
| 9782 | // For example, when the value is the difference between the addresses of |
| 9783 | // two labels. We reject that as a constant expression because we can't |
| 9784 | // compute a valid offset to convert into a pointer. |
| 9785 | if (!Value.isLValue()) |
| 9786 | return false; |
| 9787 | |
| 9788 | // Cast is of an lvalue, no need to change value. |
| 9789 | Result.setFrom(Ctx&: Info.Ctx, V: Value); |
| 9790 | return true; |
| 9791 | } |
| 9792 | } |
| 9793 | |
| 9794 | case CK_ArrayToPointerDecay: { |
| 9795 | if (SubExpr->isGLValue()) { |
| 9796 | if (!evaluateLValue(E: SubExpr, Result)) |
| 9797 | return false; |
| 9798 | } else { |
| 9799 | APValue &Value = Info.CurrentCall->createTemporary( |
| 9800 | Key: SubExpr, T: SubExpr->getType(), Scope: ScopeKind::FullExpression, LV&: Result); |
| 9801 | if (!EvaluateInPlace(Result&: Value, Info, This: Result, E: SubExpr)) |
| 9802 | return false; |
| 9803 | } |
| 9804 | // The result is a pointer to the first element of the array. |
| 9805 | auto *AT = Info.Ctx.getAsArrayType(T: SubExpr->getType()); |
| 9806 | if (auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) |
| 9807 | Result.addArray(Info, E, CAT); |
| 9808 | else |
| 9809 | Result.addUnsizedArray(Info, E, ElemTy: AT->getElementType()); |
| 9810 | return true; |
| 9811 | } |
| 9812 | |
| 9813 | case CK_FunctionToPointerDecay: |
| 9814 | return evaluateLValue(E: SubExpr, Result); |
| 9815 | |
| 9816 | case CK_LValueToRValue: { |
| 9817 | LValue LVal; |
| 9818 | if (!evaluateLValue(E: E->getSubExpr(), Result&: LVal)) |
| 9819 | return false; |
| 9820 | |
| 9821 | APValue RVal; |
| 9822 | // Note, we use the subexpression's type in order to retain cv-qualifiers. |
| 9823 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getSubExpr()->getType(), |
| 9824 | LVal, RVal)) |
| 9825 | return InvalidBaseOK && |
| 9826 | evaluateLValueAsAllocSize(Info, Base: LVal.Base, Result); |
| 9827 | return Success(V: RVal, E); |
| 9828 | } |
| 9829 | } |
| 9830 | |
| 9831 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 9832 | } |
| 9833 | |
| 9834 | static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, |
| 9835 | UnaryExprOrTypeTrait ExprKind) { |
| 9836 | // C++ [expr.alignof]p3: |
| 9837 | // When alignof is applied to a reference type, the result is the |
| 9838 | // alignment of the referenced type. |
| 9839 | T = T.getNonReferenceType(); |
| 9840 | |
| 9841 | if (T.getQualifiers().hasUnaligned()) |
| 9842 | return CharUnits::One(); |
| 9843 | |
| 9844 | const bool AlignOfReturnsPreferred = |
| 9845 | Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; |
| 9846 | |
| 9847 | // __alignof is defined to return the preferred alignment. |
| 9848 | // Before 8, clang returned the preferred alignment for alignof and _Alignof |
| 9849 | // as well. |
| 9850 | if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) |
| 9851 | return Ctx.toCharUnitsFromBits(BitSize: Ctx.getPreferredTypeAlign(T: T.getTypePtr())); |
| 9852 | // alignof and _Alignof are defined to return the ABI alignment. |
| 9853 | else if (ExprKind == UETT_AlignOf) |
| 9854 | return Ctx.getTypeAlignInChars(T: T.getTypePtr()); |
| 9855 | else |
| 9856 | llvm_unreachable("GetAlignOfType on a non-alignment ExprKind" ); |
| 9857 | } |
| 9858 | |
| 9859 | CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, |
| 9860 | UnaryExprOrTypeTrait ExprKind) { |
| 9861 | E = E->IgnoreParens(); |
| 9862 | |
| 9863 | // The kinds of expressions that we have special-case logic here for |
| 9864 | // should be kept up to date with the special checks for those |
| 9865 | // expressions in Sema. |
| 9866 | |
| 9867 | // alignof decl is always accepted, even if it doesn't make sense: we default |
| 9868 | // to 1 in those cases. |
| 9869 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
| 9870 | return Ctx.getDeclAlign(D: DRE->getDecl(), |
| 9871 | /*RefAsPointee*/ ForAlignof: true); |
| 9872 | |
| 9873 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) |
| 9874 | return Ctx.getDeclAlign(D: ME->getMemberDecl(), |
| 9875 | /*RefAsPointee*/ ForAlignof: true); |
| 9876 | |
| 9877 | return GetAlignOfType(Ctx, T: E->getType(), ExprKind); |
| 9878 | } |
| 9879 | |
| 9880 | static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { |
| 9881 | if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) |
| 9882 | return Info.Ctx.getDeclAlign(D: VD); |
| 9883 | if (const auto *E = Value.Base.dyn_cast<const Expr *>()) |
| 9884 | return GetAlignOfExpr(Ctx: Info.Ctx, E, ExprKind: UETT_AlignOf); |
| 9885 | return GetAlignOfType(Ctx: Info.Ctx, T: Value.Base.getTypeInfoType(), ExprKind: UETT_AlignOf); |
| 9886 | } |
| 9887 | |
| 9888 | /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, |
| 9889 | /// __builtin_is_aligned and __builtin_assume_aligned. |
| 9890 | static bool getAlignmentArgument(const Expr *E, QualType ForType, |
| 9891 | EvalInfo &Info, APSInt &Alignment) { |
| 9892 | if (!EvaluateInteger(E, Result&: Alignment, Info)) |
| 9893 | return false; |
| 9894 | if (Alignment < 0 || !Alignment.isPowerOf2()) { |
| 9895 | Info.FFDiag(E, DiagId: diag::note_constexpr_invalid_alignment) << Alignment; |
| 9896 | return false; |
| 9897 | } |
| 9898 | unsigned SrcWidth = Info.Ctx.getIntWidth(T: ForType); |
| 9899 | APSInt MaxValue(APInt::getOneBitSet(numBits: SrcWidth, BitNo: SrcWidth - 1)); |
| 9900 | if (APSInt::compareValues(I1: Alignment, I2: MaxValue) > 0) { |
| 9901 | Info.FFDiag(E, DiagId: diag::note_constexpr_alignment_too_big) |
| 9902 | << MaxValue << ForType << Alignment; |
| 9903 | return false; |
| 9904 | } |
| 9905 | // Ensure both alignment and source value have the same bit width so that we |
| 9906 | // don't assert when computing the resulting value. |
| 9907 | APSInt ExtAlignment = |
| 9908 | APSInt(Alignment.zextOrTrunc(width: SrcWidth), /*isUnsigned=*/true); |
| 9909 | assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && |
| 9910 | "Alignment should not be changed by ext/trunc" ); |
| 9911 | Alignment = ExtAlignment; |
| 9912 | assert(Alignment.getBitWidth() == SrcWidth); |
| 9913 | return true; |
| 9914 | } |
| 9915 | |
| 9916 | // To be clear: this happily visits unsupported builtins. Better name welcomed. |
| 9917 | bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { |
| 9918 | if (ExprEvaluatorBaseTy::VisitCallExpr(E)) |
| 9919 | return true; |
| 9920 | |
| 9921 | if (!(InvalidBaseOK && getAllocSizeAttr(CE: E))) |
| 9922 | return false; |
| 9923 | |
| 9924 | Result.setInvalid(B: E); |
| 9925 | QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); |
| 9926 | Result.addUnsizedArray(Info, E, ElemTy: PointeeTy); |
| 9927 | return true; |
| 9928 | } |
| 9929 | |
| 9930 | bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { |
| 9931 | if (!IsConstantEvaluatedBuiltinCall(E)) |
| 9932 | return visitNonBuiltinCallExpr(E); |
| 9933 | return VisitBuiltinCallExpr(E, BuiltinOp: E->getBuiltinCallee()); |
| 9934 | } |
| 9935 | |
| 9936 | // Determine if T is a character type for which we guarantee that |
| 9937 | // sizeof(T) == 1. |
| 9938 | static bool isOneByteCharacterType(QualType T) { |
| 9939 | return T->isCharType() || T->isChar8Type(); |
| 9940 | } |
| 9941 | |
| 9942 | bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, |
| 9943 | unsigned BuiltinOp) { |
| 9944 | if (IsOpaqueConstantCall(E)) |
| 9945 | return Success(E); |
| 9946 | |
| 9947 | switch (BuiltinOp) { |
| 9948 | case Builtin::BIaddressof: |
| 9949 | case Builtin::BI__addressof: |
| 9950 | case Builtin::BI__builtin_addressof: |
| 9951 | return evaluateLValue(E: E->getArg(Arg: 0), Result); |
| 9952 | case Builtin::BI__builtin_assume_aligned: { |
| 9953 | // We need to be very careful here because: if the pointer does not have the |
| 9954 | // asserted alignment, then the behavior is undefined, and undefined |
| 9955 | // behavior is non-constant. |
| 9956 | if (!evaluatePointer(E: E->getArg(Arg: 0), Result)) |
| 9957 | return false; |
| 9958 | |
| 9959 | LValue OffsetResult(Result); |
| 9960 | APSInt Alignment; |
| 9961 | if (!getAlignmentArgument(E: E->getArg(Arg: 1), ForType: E->getArg(Arg: 0)->getType(), Info, |
| 9962 | Alignment)) |
| 9963 | return false; |
| 9964 | CharUnits Align = CharUnits::fromQuantity(Quantity: Alignment.getZExtValue()); |
| 9965 | |
| 9966 | if (E->getNumArgs() > 2) { |
| 9967 | APSInt Offset; |
| 9968 | if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: Offset, Info)) |
| 9969 | return false; |
| 9970 | |
| 9971 | int64_t AdditionalOffset = -Offset.getZExtValue(); |
| 9972 | OffsetResult.Offset += CharUnits::fromQuantity(Quantity: AdditionalOffset); |
| 9973 | } |
| 9974 | |
| 9975 | // If there is a base object, then it must have the correct alignment. |
| 9976 | if (OffsetResult.Base) { |
| 9977 | CharUnits BaseAlignment = getBaseAlignment(Info, Value: OffsetResult); |
| 9978 | |
| 9979 | if (BaseAlignment < Align) { |
| 9980 | Result.Designator.setInvalid(); |
| 9981 | CCEDiag(E: E->getArg(Arg: 0), D: diag::note_constexpr_baa_insufficient_alignment) |
| 9982 | << 0 << BaseAlignment.getQuantity() << Align.getQuantity(); |
| 9983 | return false; |
| 9984 | } |
| 9985 | } |
| 9986 | |
| 9987 | // The offset must also have the correct alignment. |
| 9988 | if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { |
| 9989 | Result.Designator.setInvalid(); |
| 9990 | |
| 9991 | (OffsetResult.Base |
| 9992 | ? CCEDiag(E: E->getArg(Arg: 0), |
| 9993 | D: diag::note_constexpr_baa_insufficient_alignment) |
| 9994 | << 1 |
| 9995 | : CCEDiag(E: E->getArg(Arg: 0), |
| 9996 | D: diag::note_constexpr_baa_value_insufficient_alignment)) |
| 9997 | << OffsetResult.Offset.getQuantity() << Align.getQuantity(); |
| 9998 | return false; |
| 9999 | } |
| 10000 | |
| 10001 | return true; |
| 10002 | } |
| 10003 | case Builtin::BI__builtin_align_up: |
| 10004 | case Builtin::BI__builtin_align_down: { |
| 10005 | if (!evaluatePointer(E: E->getArg(Arg: 0), Result)) |
| 10006 | return false; |
| 10007 | APSInt Alignment; |
| 10008 | if (!getAlignmentArgument(E: E->getArg(Arg: 1), ForType: E->getArg(Arg: 0)->getType(), Info, |
| 10009 | Alignment)) |
| 10010 | return false; |
| 10011 | CharUnits BaseAlignment = getBaseAlignment(Info, Value: Result); |
| 10012 | CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(offset: Result.Offset); |
| 10013 | // For align_up/align_down, we can return the same value if the alignment |
| 10014 | // is known to be greater or equal to the requested value. |
| 10015 | if (PtrAlign.getQuantity() >= Alignment) |
| 10016 | return true; |
| 10017 | |
| 10018 | // The alignment could be greater than the minimum at run-time, so we cannot |
| 10019 | // infer much about the resulting pointer value. One case is possible: |
| 10020 | // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we |
| 10021 | // can infer the correct index if the requested alignment is smaller than |
| 10022 | // the base alignment so we can perform the computation on the offset. |
| 10023 | if (BaseAlignment.getQuantity() >= Alignment) { |
| 10024 | assert(Alignment.getBitWidth() <= 64 && |
| 10025 | "Cannot handle > 64-bit address-space" ); |
| 10026 | uint64_t Alignment64 = Alignment.getZExtValue(); |
| 10027 | CharUnits NewOffset = CharUnits::fromQuantity( |
| 10028 | Quantity: BuiltinOp == Builtin::BI__builtin_align_down |
| 10029 | ? llvm::alignDown(Value: Result.Offset.getQuantity(), Align: Alignment64) |
| 10030 | : llvm::alignTo(Value: Result.Offset.getQuantity(), Align: Alignment64)); |
| 10031 | Result.adjustOffset(N: NewOffset - Result.Offset); |
| 10032 | // TODO: diagnose out-of-bounds values/only allow for arrays? |
| 10033 | return true; |
| 10034 | } |
| 10035 | // Otherwise, we cannot constant-evaluate the result. |
| 10036 | Info.FFDiag(E: E->getArg(Arg: 0), DiagId: diag::note_constexpr_alignment_adjust) |
| 10037 | << Alignment; |
| 10038 | return false; |
| 10039 | } |
| 10040 | case Builtin::BI__builtin_operator_new: |
| 10041 | return HandleOperatorNewCall(Info, E, Result); |
| 10042 | case Builtin::BI__builtin_launder: |
| 10043 | return evaluatePointer(E: E->getArg(Arg: 0), Result); |
| 10044 | case Builtin::BIstrchr: |
| 10045 | case Builtin::BIwcschr: |
| 10046 | case Builtin::BImemchr: |
| 10047 | case Builtin::BIwmemchr: |
| 10048 | if (Info.getLangOpts().CPlusPlus11) |
| 10049 | Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function) |
| 10050 | << /*isConstexpr*/ 0 << /*isConstructor*/ 0 |
| 10051 | << Info.Ctx.BuiltinInfo.getQuotedName(ID: BuiltinOp); |
| 10052 | else |
| 10053 | Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 10054 | [[fallthrough]]; |
| 10055 | case Builtin::BI__builtin_strchr: |
| 10056 | case Builtin::BI__builtin_wcschr: |
| 10057 | case Builtin::BI__builtin_memchr: |
| 10058 | case Builtin::BI__builtin_char_memchr: |
| 10059 | case Builtin::BI__builtin_wmemchr: { |
| 10060 | if (!Visit(S: E->getArg(Arg: 0))) |
| 10061 | return false; |
| 10062 | APSInt Desired; |
| 10063 | if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: Desired, Info)) |
| 10064 | return false; |
| 10065 | uint64_t MaxLength = uint64_t(-1); |
| 10066 | if (BuiltinOp != Builtin::BIstrchr && |
| 10067 | BuiltinOp != Builtin::BIwcschr && |
| 10068 | BuiltinOp != Builtin::BI__builtin_strchr && |
| 10069 | BuiltinOp != Builtin::BI__builtin_wcschr) { |
| 10070 | APSInt N; |
| 10071 | if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: N, Info)) |
| 10072 | return false; |
| 10073 | MaxLength = N.getZExtValue(); |
| 10074 | } |
| 10075 | // We cannot find the value if there are no candidates to match against. |
| 10076 | if (MaxLength == 0u) |
| 10077 | return ZeroInitialization(E); |
| 10078 | if (!Result.checkNullPointerForFoldAccess(Info, E, AK: AK_Read) || |
| 10079 | Result.Designator.Invalid) |
| 10080 | return false; |
| 10081 | QualType CharTy = Result.Designator.getType(Ctx&: Info.Ctx); |
| 10082 | bool IsRawByte = BuiltinOp == Builtin::BImemchr || |
| 10083 | BuiltinOp == Builtin::BI__builtin_memchr; |
| 10084 | assert(IsRawByte || |
| 10085 | Info.Ctx.hasSameUnqualifiedType( |
| 10086 | CharTy, E->getArg(0)->getType()->getPointeeType())); |
| 10087 | // Pointers to const void may point to objects of incomplete type. |
| 10088 | if (IsRawByte && CharTy->isIncompleteType()) { |
| 10089 | Info.FFDiag(E, DiagId: diag::note_constexpr_ltor_incomplete_type) << CharTy; |
| 10090 | return false; |
| 10091 | } |
| 10092 | // Give up on byte-oriented matching against multibyte elements. |
| 10093 | // FIXME: We can compare the bytes in the correct order. |
| 10094 | if (IsRawByte && !isOneByteCharacterType(T: CharTy)) { |
| 10095 | Info.FFDiag(E, DiagId: diag::note_constexpr_memchr_unsupported) |
| 10096 | << Info.Ctx.BuiltinInfo.getQuotedName(ID: BuiltinOp) << CharTy; |
| 10097 | return false; |
| 10098 | } |
| 10099 | // Figure out what value we're actually looking for (after converting to |
| 10100 | // the corresponding unsigned type if necessary). |
| 10101 | uint64_t DesiredVal; |
| 10102 | bool StopAtNull = false; |
| 10103 | switch (BuiltinOp) { |
| 10104 | case Builtin::BIstrchr: |
| 10105 | case Builtin::BI__builtin_strchr: |
| 10106 | // strchr compares directly to the passed integer, and therefore |
| 10107 | // always fails if given an int that is not a char. |
| 10108 | if (!APSInt::isSameValue(I1: HandleIntToIntCast(Info, E, DestType: CharTy, |
| 10109 | SrcType: E->getArg(Arg: 1)->getType(), |
| 10110 | Value: Desired), |
| 10111 | I2: Desired)) |
| 10112 | return ZeroInitialization(E); |
| 10113 | StopAtNull = true; |
| 10114 | [[fallthrough]]; |
| 10115 | case Builtin::BImemchr: |
| 10116 | case Builtin::BI__builtin_memchr: |
| 10117 | case Builtin::BI__builtin_char_memchr: |
| 10118 | // memchr compares by converting both sides to unsigned char. That's also |
| 10119 | // correct for strchr if we get this far (to cope with plain char being |
| 10120 | // unsigned in the strchr case). |
| 10121 | DesiredVal = Desired.trunc(width: Info.Ctx.getCharWidth()).getZExtValue(); |
| 10122 | break; |
| 10123 | |
| 10124 | case Builtin::BIwcschr: |
| 10125 | case Builtin::BI__builtin_wcschr: |
| 10126 | StopAtNull = true; |
| 10127 | [[fallthrough]]; |
| 10128 | case Builtin::BIwmemchr: |
| 10129 | case Builtin::BI__builtin_wmemchr: |
| 10130 | // wcschr and wmemchr are given a wchar_t to look for. Just use it. |
| 10131 | DesiredVal = Desired.getZExtValue(); |
| 10132 | break; |
| 10133 | } |
| 10134 | |
| 10135 | for (; MaxLength; --MaxLength) { |
| 10136 | APValue Char; |
| 10137 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: CharTy, LVal: Result, RVal&: Char) || |
| 10138 | !Char.isInt()) |
| 10139 | return false; |
| 10140 | if (Char.getInt().getZExtValue() == DesiredVal) |
| 10141 | return true; |
| 10142 | if (StopAtNull && !Char.getInt()) |
| 10143 | break; |
| 10144 | if (!HandleLValueArrayAdjustment(Info, E, LVal&: Result, EltTy: CharTy, Adjustment: 1)) |
| 10145 | return false; |
| 10146 | } |
| 10147 | // Not found: return nullptr. |
| 10148 | return ZeroInitialization(E); |
| 10149 | } |
| 10150 | |
| 10151 | case Builtin::BImemcpy: |
| 10152 | case Builtin::BImemmove: |
| 10153 | case Builtin::BIwmemcpy: |
| 10154 | case Builtin::BIwmemmove: |
| 10155 | if (Info.getLangOpts().CPlusPlus11) |
| 10156 | Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function) |
| 10157 | << /*isConstexpr*/ 0 << /*isConstructor*/ 0 |
| 10158 | << Info.Ctx.BuiltinInfo.getQuotedName(ID: BuiltinOp); |
| 10159 | else |
| 10160 | Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 10161 | [[fallthrough]]; |
| 10162 | case Builtin::BI__builtin_memcpy: |
| 10163 | case Builtin::BI__builtin_memmove: |
| 10164 | case Builtin::BI__builtin_wmemcpy: |
| 10165 | case Builtin::BI__builtin_wmemmove: { |
| 10166 | bool WChar = BuiltinOp == Builtin::BIwmemcpy || |
| 10167 | BuiltinOp == Builtin::BIwmemmove || |
| 10168 | BuiltinOp == Builtin::BI__builtin_wmemcpy || |
| 10169 | BuiltinOp == Builtin::BI__builtin_wmemmove; |
| 10170 | bool Move = BuiltinOp == Builtin::BImemmove || |
| 10171 | BuiltinOp == Builtin::BIwmemmove || |
| 10172 | BuiltinOp == Builtin::BI__builtin_memmove || |
| 10173 | BuiltinOp == Builtin::BI__builtin_wmemmove; |
| 10174 | |
| 10175 | // The result of mem* is the first argument. |
| 10176 | if (!Visit(S: E->getArg(Arg: 0))) |
| 10177 | return false; |
| 10178 | LValue Dest = Result; |
| 10179 | |
| 10180 | LValue Src; |
| 10181 | if (!EvaluatePointer(E: E->getArg(Arg: 1), Result&: Src, Info)) |
| 10182 | return false; |
| 10183 | |
| 10184 | APSInt N; |
| 10185 | if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: N, Info)) |
| 10186 | return false; |
| 10187 | assert(!N.isSigned() && "memcpy and friends take an unsigned size" ); |
| 10188 | |
| 10189 | // If the size is zero, we treat this as always being a valid no-op. |
| 10190 | // (Even if one of the src and dest pointers is null.) |
| 10191 | if (!N) |
| 10192 | return true; |
| 10193 | |
| 10194 | // Otherwise, if either of the operands is null, we can't proceed. Don't |
| 10195 | // try to determine the type of the copied objects, because there aren't |
| 10196 | // any. |
| 10197 | if (!Src.Base || !Dest.Base) { |
| 10198 | APValue Val; |
| 10199 | (!Src.Base ? Src : Dest).moveInto(V&: Val); |
| 10200 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_null) |
| 10201 | << Move << WChar << !!Src.Base |
| 10202 | << Val.getAsString(Ctx: Info.Ctx, Ty: E->getArg(Arg: 0)->getType()); |
| 10203 | return false; |
| 10204 | } |
| 10205 | if (Src.Designator.Invalid || Dest.Designator.Invalid) |
| 10206 | return false; |
| 10207 | |
| 10208 | // We require that Src and Dest are both pointers to arrays of |
| 10209 | // trivially-copyable type. (For the wide version, the designator will be |
| 10210 | // invalid if the designated object is not a wchar_t.) |
| 10211 | QualType T = Dest.Designator.getType(Ctx&: Info.Ctx); |
| 10212 | QualType SrcT = Src.Designator.getType(Ctx&: Info.Ctx); |
| 10213 | if (!Info.Ctx.hasSameUnqualifiedType(T1: T, T2: SrcT)) { |
| 10214 | // FIXME: Consider using our bit_cast implementation to support this. |
| 10215 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; |
| 10216 | return false; |
| 10217 | } |
| 10218 | if (T->isIncompleteType()) { |
| 10219 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_incomplete_type) << Move << T; |
| 10220 | return false; |
| 10221 | } |
| 10222 | if (!T.isTriviallyCopyableType(Context: Info.Ctx)) { |
| 10223 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_nontrivial) << Move << T; |
| 10224 | return false; |
| 10225 | } |
| 10226 | |
| 10227 | // Figure out how many T's we're copying. |
| 10228 | uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); |
| 10229 | if (TSize == 0) |
| 10230 | return false; |
| 10231 | if (!WChar) { |
| 10232 | uint64_t Remainder; |
| 10233 | llvm::APInt OrigN = N; |
| 10234 | llvm::APInt::udivrem(LHS: OrigN, RHS: TSize, Quotient&: N, Remainder); |
| 10235 | if (Remainder) { |
| 10236 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_unsupported) |
| 10237 | << Move << WChar << 0 << T << toString(I: OrigN, Radix: 10, /*Signed*/false) |
| 10238 | << (unsigned)TSize; |
| 10239 | return false; |
| 10240 | } |
| 10241 | } |
| 10242 | |
| 10243 | // Check that the copying will remain within the arrays, just so that we |
| 10244 | // can give a more meaningful diagnostic. This implicitly also checks that |
| 10245 | // N fits into 64 bits. |
| 10246 | uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; |
| 10247 | uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; |
| 10248 | if (N.ugt(RHS: RemainingSrcSize) || N.ugt(RHS: RemainingDestSize)) { |
| 10249 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_unsupported) |
| 10250 | << Move << WChar << (N.ugt(RHS: RemainingSrcSize) ? 1 : 2) << T |
| 10251 | << toString(I: N, Radix: 10, /*Signed*/false); |
| 10252 | return false; |
| 10253 | } |
| 10254 | uint64_t NElems = N.getZExtValue(); |
| 10255 | uint64_t NBytes = NElems * TSize; |
| 10256 | |
| 10257 | // Check for overlap. |
| 10258 | int Direction = 1; |
| 10259 | if (HasSameBase(A: Src, B: Dest)) { |
| 10260 | uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); |
| 10261 | uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); |
| 10262 | if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { |
| 10263 | // Dest is inside the source region. |
| 10264 | if (!Move) { |
| 10265 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_overlap) << WChar; |
| 10266 | return false; |
| 10267 | } |
| 10268 | // For memmove and friends, copy backwards. |
| 10269 | if (!HandleLValueArrayAdjustment(Info, E, LVal&: Src, EltTy: T, Adjustment: NElems - 1) || |
| 10270 | !HandleLValueArrayAdjustment(Info, E, LVal&: Dest, EltTy: T, Adjustment: NElems - 1)) |
| 10271 | return false; |
| 10272 | Direction = -1; |
| 10273 | } else if (!Move && SrcOffset >= DestOffset && |
| 10274 | SrcOffset - DestOffset < NBytes) { |
| 10275 | // Src is inside the destination region for memcpy: invalid. |
| 10276 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_overlap) << WChar; |
| 10277 | return false; |
| 10278 | } |
| 10279 | } |
| 10280 | |
| 10281 | while (true) { |
| 10282 | APValue Val; |
| 10283 | // FIXME: Set WantObjectRepresentation to true if we're copying a |
| 10284 | // char-like type? |
| 10285 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: T, LVal: Src, RVal&: Val) || |
| 10286 | !handleAssignment(Info, E, LVal: Dest, LValType: T, Val)) |
| 10287 | return false; |
| 10288 | // Do not iterate past the last element; if we're copying backwards, that |
| 10289 | // might take us off the start of the array. |
| 10290 | if (--NElems == 0) |
| 10291 | return true; |
| 10292 | if (!HandleLValueArrayAdjustment(Info, E, LVal&: Src, EltTy: T, Adjustment: Direction) || |
| 10293 | !HandleLValueArrayAdjustment(Info, E, LVal&: Dest, EltTy: T, Adjustment: Direction)) |
| 10294 | return false; |
| 10295 | } |
| 10296 | } |
| 10297 | |
| 10298 | default: |
| 10299 | return false; |
| 10300 | } |
| 10301 | } |
| 10302 | |
| 10303 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, |
| 10304 | APValue &Result, const InitListExpr *ILE, |
| 10305 | QualType AllocType); |
| 10306 | static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, |
| 10307 | APValue &Result, |
| 10308 | const CXXConstructExpr *CCE, |
| 10309 | QualType AllocType); |
| 10310 | |
| 10311 | bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { |
| 10312 | if (!Info.getLangOpts().CPlusPlus20) |
| 10313 | Info.CCEDiag(E, DiagId: diag::note_constexpr_new); |
| 10314 | |
| 10315 | // We cannot speculatively evaluate a delete expression. |
| 10316 | if (Info.SpeculativeEvaluationDepth) |
| 10317 | return false; |
| 10318 | |
| 10319 | FunctionDecl *OperatorNew = E->getOperatorNew(); |
| 10320 | QualType AllocType = E->getAllocatedType(); |
| 10321 | QualType TargetType = AllocType; |
| 10322 | |
| 10323 | bool IsNothrow = false; |
| 10324 | bool IsPlacement = false; |
| 10325 | |
| 10326 | if (E->getNumPlacementArgs() == 1 && |
| 10327 | E->getPlacementArg(I: 0)->getType()->isNothrowT()) { |
| 10328 | // The only new-placement list we support is of the form (std::nothrow). |
| 10329 | // |
| 10330 | // FIXME: There is no restriction on this, but it's not clear that any |
| 10331 | // other form makes any sense. We get here for cases such as: |
| 10332 | // |
| 10333 | // new (std::align_val_t{N}) X(int) |
| 10334 | // |
| 10335 | // (which should presumably be valid only if N is a multiple of |
| 10336 | // alignof(int), and in any case can't be deallocated unless N is |
| 10337 | // alignof(X) and X has new-extended alignment). |
| 10338 | LValue Nothrow; |
| 10339 | if (!EvaluateLValue(E: E->getPlacementArg(I: 0), Result&: Nothrow, Info)) |
| 10340 | return false; |
| 10341 | IsNothrow = true; |
| 10342 | } else if (OperatorNew->isReservedGlobalPlacementOperator()) { |
| 10343 | if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 || |
| 10344 | (Info.CurrentCall->CanEvalMSConstexpr && |
| 10345 | OperatorNew->hasAttr<MSConstexprAttr>())) { |
| 10346 | if (!EvaluatePointer(E: E->getPlacementArg(I: 0), Result, Info)) |
| 10347 | return false; |
| 10348 | if (Result.Designator.Invalid) |
| 10349 | return false; |
| 10350 | TargetType = E->getPlacementArg(I: 0)->getType(); |
| 10351 | IsPlacement = true; |
| 10352 | } else { |
| 10353 | Info.FFDiag(E, DiagId: diag::note_constexpr_new_placement) |
| 10354 | << /*C++26 feature*/ 1 << E->getSourceRange(); |
| 10355 | return false; |
| 10356 | } |
| 10357 | } else if (E->getNumPlacementArgs()) { |
| 10358 | Info.FFDiag(E, DiagId: diag::note_constexpr_new_placement) |
| 10359 | << /*Unsupported*/ 0 << E->getSourceRange(); |
| 10360 | return false; |
| 10361 | } else if (!OperatorNew |
| 10362 | ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) { |
| 10363 | Info.FFDiag(E, DiagId: diag::note_constexpr_new_non_replaceable) |
| 10364 | << isa<CXXMethodDecl>(Val: OperatorNew) << OperatorNew; |
| 10365 | return false; |
| 10366 | } |
| 10367 | |
| 10368 | const Expr *Init = E->getInitializer(); |
| 10369 | const InitListExpr *ResizedArrayILE = nullptr; |
| 10370 | const CXXConstructExpr *ResizedArrayCCE = nullptr; |
| 10371 | bool ValueInit = false; |
| 10372 | |
| 10373 | if (std::optional<const Expr *> ArraySize = E->getArraySize()) { |
| 10374 | const Expr *Stripped = *ArraySize; |
| 10375 | for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Stripped); |
| 10376 | Stripped = ICE->getSubExpr()) |
| 10377 | if (ICE->getCastKind() != CK_NoOp && |
| 10378 | ICE->getCastKind() != CK_IntegralCast) |
| 10379 | break; |
| 10380 | |
| 10381 | llvm::APSInt ArrayBound; |
| 10382 | if (!EvaluateInteger(E: Stripped, Result&: ArrayBound, Info)) |
| 10383 | return false; |
| 10384 | |
| 10385 | // C++ [expr.new]p9: |
| 10386 | // The expression is erroneous if: |
| 10387 | // -- [...] its value before converting to size_t [or] applying the |
| 10388 | // second standard conversion sequence is less than zero |
| 10389 | if (ArrayBound.isSigned() && ArrayBound.isNegative()) { |
| 10390 | if (IsNothrow) |
| 10391 | return ZeroInitialization(E); |
| 10392 | |
| 10393 | Info.FFDiag(E: *ArraySize, DiagId: diag::note_constexpr_new_negative) |
| 10394 | << ArrayBound << (*ArraySize)->getSourceRange(); |
| 10395 | return false; |
| 10396 | } |
| 10397 | |
| 10398 | // -- its value is such that the size of the allocated object would |
| 10399 | // exceed the implementation-defined limit |
| 10400 | if (!Info.CheckArraySize(Loc: ArraySize.value()->getExprLoc(), |
| 10401 | BitWidth: ConstantArrayType::getNumAddressingBits( |
| 10402 | Context: Info.Ctx, ElementType: AllocType, NumElements: ArrayBound), |
| 10403 | ElemCount: ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) { |
| 10404 | if (IsNothrow) |
| 10405 | return ZeroInitialization(E); |
| 10406 | return false; |
| 10407 | } |
| 10408 | |
| 10409 | // -- the new-initializer is a braced-init-list and the number of |
| 10410 | // array elements for which initializers are provided [...] |
| 10411 | // exceeds the number of elements to initialize |
| 10412 | if (!Init) { |
| 10413 | // No initialization is performed. |
| 10414 | } else if (isa<CXXScalarValueInitExpr>(Val: Init) || |
| 10415 | isa<ImplicitValueInitExpr>(Val: Init)) { |
| 10416 | ValueInit = true; |
| 10417 | } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) { |
| 10418 | ResizedArrayCCE = CCE; |
| 10419 | } else { |
| 10420 | auto *CAT = Info.Ctx.getAsConstantArrayType(T: Init->getType()); |
| 10421 | assert(CAT && "unexpected type for array initializer" ); |
| 10422 | |
| 10423 | unsigned Bits = |
| 10424 | std::max(a: CAT->getSizeBitWidth(), b: ArrayBound.getBitWidth()); |
| 10425 | llvm::APInt InitBound = CAT->getSize().zext(width: Bits); |
| 10426 | llvm::APInt AllocBound = ArrayBound.zext(width: Bits); |
| 10427 | if (InitBound.ugt(RHS: AllocBound)) { |
| 10428 | if (IsNothrow) |
| 10429 | return ZeroInitialization(E); |
| 10430 | |
| 10431 | Info.FFDiag(E: *ArraySize, DiagId: diag::note_constexpr_new_too_small) |
| 10432 | << toString(I: AllocBound, Radix: 10, /*Signed=*/false) |
| 10433 | << toString(I: InitBound, Radix: 10, /*Signed=*/false) |
| 10434 | << (*ArraySize)->getSourceRange(); |
| 10435 | return false; |
| 10436 | } |
| 10437 | |
| 10438 | // If the sizes differ, we must have an initializer list, and we need |
| 10439 | // special handling for this case when we initialize. |
| 10440 | if (InitBound != AllocBound) |
| 10441 | ResizedArrayILE = cast<InitListExpr>(Val: Init); |
| 10442 | } |
| 10443 | |
| 10444 | AllocType = Info.Ctx.getConstantArrayType(EltTy: AllocType, ArySize: ArrayBound, SizeExpr: nullptr, |
| 10445 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 10446 | } else { |
| 10447 | assert(!AllocType->isArrayType() && |
| 10448 | "array allocation with non-array new" ); |
| 10449 | } |
| 10450 | |
| 10451 | APValue *Val; |
| 10452 | if (IsPlacement) { |
| 10453 | AccessKinds AK = AK_Construct; |
| 10454 | struct FindObjectHandler { |
| 10455 | EvalInfo &Info; |
| 10456 | const Expr *E; |
| 10457 | QualType AllocType; |
| 10458 | const AccessKinds AccessKind; |
| 10459 | APValue *Value; |
| 10460 | |
| 10461 | typedef bool result_type; |
| 10462 | bool failed() { return false; } |
| 10463 | bool checkConst(QualType QT) { |
| 10464 | if (QT.isConstQualified()) { |
| 10465 | Info.FFDiag(E, DiagId: diag::note_constexpr_modify_const_type) << QT; |
| 10466 | return false; |
| 10467 | } |
| 10468 | return true; |
| 10469 | } |
| 10470 | bool found(APValue &Subobj, QualType SubobjType) { |
| 10471 | if (!checkConst(QT: SubobjType)) |
| 10472 | return false; |
| 10473 | // FIXME: Reject the cases where [basic.life]p8 would not permit the |
| 10474 | // old name of the object to be used to name the new object. |
| 10475 | unsigned SubobjectSize = 1; |
| 10476 | unsigned AllocSize = 1; |
| 10477 | if (auto *CAT = dyn_cast<ConstantArrayType>(Val&: AllocType)) |
| 10478 | AllocSize = CAT->getZExtSize(); |
| 10479 | if (auto *CAT = dyn_cast<ConstantArrayType>(Val&: SubobjType)) |
| 10480 | SubobjectSize = CAT->getZExtSize(); |
| 10481 | if (SubobjectSize < AllocSize || |
| 10482 | !Info.Ctx.hasSimilarType(T1: Info.Ctx.getBaseElementType(QT: SubobjType), |
| 10483 | T2: Info.Ctx.getBaseElementType(QT: AllocType))) { |
| 10484 | Info.FFDiag(E, DiagId: diag::note_constexpr_placement_new_wrong_type) |
| 10485 | << SubobjType << AllocType; |
| 10486 | return false; |
| 10487 | } |
| 10488 | Value = &Subobj; |
| 10489 | return true; |
| 10490 | } |
| 10491 | bool found(APSInt &Value, QualType SubobjType) { |
| 10492 | Info.FFDiag(E, DiagId: diag::note_constexpr_construct_complex_elem); |
| 10493 | return false; |
| 10494 | } |
| 10495 | bool found(APFloat &Value, QualType SubobjType) { |
| 10496 | Info.FFDiag(E, DiagId: diag::note_constexpr_construct_complex_elem); |
| 10497 | return false; |
| 10498 | } |
| 10499 | } Handler = {.Info: Info, .E: E, .AllocType: AllocType, .AccessKind: AK, .Value: nullptr}; |
| 10500 | |
| 10501 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal: Result, LValType: AllocType); |
| 10502 | if (!Obj || !findSubobject(Info, E, Obj, Sub: Result.Designator, handler&: Handler)) |
| 10503 | return false; |
| 10504 | |
| 10505 | Val = Handler.Value; |
| 10506 | |
| 10507 | // [basic.life]p1: |
| 10508 | // The lifetime of an object o of type T ends when [...] the storage |
| 10509 | // which the object occupies is [...] reused by an object that is not |
| 10510 | // nested within o (6.6.2). |
| 10511 | *Val = APValue(); |
| 10512 | } else { |
| 10513 | // Perform the allocation and obtain a pointer to the resulting object. |
| 10514 | Val = Info.createHeapAlloc(E, T: AllocType, LV&: Result); |
| 10515 | if (!Val) |
| 10516 | return false; |
| 10517 | } |
| 10518 | |
| 10519 | if (ValueInit) { |
| 10520 | ImplicitValueInitExpr VIE(AllocType); |
| 10521 | if (!EvaluateInPlace(Result&: *Val, Info, This: Result, E: &VIE)) |
| 10522 | return false; |
| 10523 | } else if (ResizedArrayILE) { |
| 10524 | if (!EvaluateArrayNewInitList(Info, This&: Result, Result&: *Val, ILE: ResizedArrayILE, |
| 10525 | AllocType)) |
| 10526 | return false; |
| 10527 | } else if (ResizedArrayCCE) { |
| 10528 | if (!EvaluateArrayNewConstructExpr(Info, This&: Result, Result&: *Val, CCE: ResizedArrayCCE, |
| 10529 | AllocType)) |
| 10530 | return false; |
| 10531 | } else if (Init) { |
| 10532 | if (!EvaluateInPlace(Result&: *Val, Info, This: Result, E: Init)) |
| 10533 | return false; |
| 10534 | } else if (!handleDefaultInitValue(T: AllocType, Result&: *Val)) { |
| 10535 | return false; |
| 10536 | } |
| 10537 | |
| 10538 | // Array new returns a pointer to the first element, not a pointer to the |
| 10539 | // array. |
| 10540 | if (auto *AT = AllocType->getAsArrayTypeUnsafe()) |
| 10541 | Result.addArray(Info, E, CAT: cast<ConstantArrayType>(Val: AT)); |
| 10542 | |
| 10543 | return true; |
| 10544 | } |
| 10545 | //===----------------------------------------------------------------------===// |
| 10546 | // Member Pointer Evaluation |
| 10547 | //===----------------------------------------------------------------------===// |
| 10548 | |
| 10549 | namespace { |
| 10550 | class MemberPointerExprEvaluator |
| 10551 | : public ExprEvaluatorBase<MemberPointerExprEvaluator> { |
| 10552 | MemberPtr &Result; |
| 10553 | |
| 10554 | bool Success(const ValueDecl *D) { |
| 10555 | Result = MemberPtr(D); |
| 10556 | return true; |
| 10557 | } |
| 10558 | public: |
| 10559 | |
| 10560 | MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) |
| 10561 | : ExprEvaluatorBaseTy(Info), Result(Result) {} |
| 10562 | |
| 10563 | bool Success(const APValue &V, const Expr *E) { |
| 10564 | Result.setFrom(V); |
| 10565 | return true; |
| 10566 | } |
| 10567 | bool ZeroInitialization(const Expr *E) { |
| 10568 | return Success(D: (const ValueDecl*)nullptr); |
| 10569 | } |
| 10570 | |
| 10571 | bool VisitCastExpr(const CastExpr *E); |
| 10572 | bool VisitUnaryAddrOf(const UnaryOperator *E); |
| 10573 | }; |
| 10574 | } // end anonymous namespace |
| 10575 | |
| 10576 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, |
| 10577 | EvalInfo &Info) { |
| 10578 | assert(!E->isValueDependent()); |
| 10579 | assert(E->isPRValue() && E->getType()->isMemberPointerType()); |
| 10580 | return MemberPointerExprEvaluator(Info, Result).Visit(S: E); |
| 10581 | } |
| 10582 | |
| 10583 | bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 10584 | switch (E->getCastKind()) { |
| 10585 | default: |
| 10586 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 10587 | |
| 10588 | case CK_NullToMemberPointer: |
| 10589 | VisitIgnoredValue(E: E->getSubExpr()); |
| 10590 | return ZeroInitialization(E); |
| 10591 | |
| 10592 | case CK_BaseToDerivedMemberPointer: { |
| 10593 | if (!Visit(S: E->getSubExpr())) |
| 10594 | return false; |
| 10595 | if (E->path_empty()) |
| 10596 | return true; |
| 10597 | // Base-to-derived member pointer casts store the path in derived-to-base |
| 10598 | // order, so iterate backwards. The CXXBaseSpecifier also provides us with |
| 10599 | // the wrong end of the derived->base arc, so stagger the path by one class. |
| 10600 | typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; |
| 10601 | for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); |
| 10602 | PathI != PathE; ++PathI) { |
| 10603 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase" ); |
| 10604 | const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); |
| 10605 | if (!Result.castToDerived(Derived)) |
| 10606 | return Error(E); |
| 10607 | } |
| 10608 | if (!Result.castToDerived(Derived: E->getType() |
| 10609 | ->castAs<MemberPointerType>() |
| 10610 | ->getMostRecentCXXRecordDecl())) |
| 10611 | return Error(E); |
| 10612 | return true; |
| 10613 | } |
| 10614 | |
| 10615 | case CK_DerivedToBaseMemberPointer: |
| 10616 | if (!Visit(S: E->getSubExpr())) |
| 10617 | return false; |
| 10618 | for (CastExpr::path_const_iterator PathI = E->path_begin(), |
| 10619 | PathE = E->path_end(); PathI != PathE; ++PathI) { |
| 10620 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase" ); |
| 10621 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); |
| 10622 | if (!Result.castToBase(Base)) |
| 10623 | return Error(E); |
| 10624 | } |
| 10625 | return true; |
| 10626 | } |
| 10627 | } |
| 10628 | |
| 10629 | bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { |
| 10630 | // C++11 [expr.unary.op]p3 has very strict rules on how the address of a |
| 10631 | // member can be formed. |
| 10632 | return Success(D: cast<DeclRefExpr>(Val: E->getSubExpr())->getDecl()); |
| 10633 | } |
| 10634 | |
| 10635 | //===----------------------------------------------------------------------===// |
| 10636 | // Record Evaluation |
| 10637 | //===----------------------------------------------------------------------===// |
| 10638 | |
| 10639 | namespace { |
| 10640 | class RecordExprEvaluator |
| 10641 | : public ExprEvaluatorBase<RecordExprEvaluator> { |
| 10642 | const LValue &This; |
| 10643 | APValue &Result; |
| 10644 | public: |
| 10645 | |
| 10646 | RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) |
| 10647 | : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} |
| 10648 | |
| 10649 | bool Success(const APValue &V, const Expr *E) { |
| 10650 | Result = V; |
| 10651 | return true; |
| 10652 | } |
| 10653 | bool ZeroInitialization(const Expr *E) { |
| 10654 | return ZeroInitialization(E, T: E->getType()); |
| 10655 | } |
| 10656 | bool ZeroInitialization(const Expr *E, QualType T); |
| 10657 | |
| 10658 | bool VisitCallExpr(const CallExpr *E) { |
| 10659 | return handleCallExpr(E, Result, ResultSlot: &This); |
| 10660 | } |
| 10661 | bool VisitCastExpr(const CastExpr *E); |
| 10662 | bool VisitInitListExpr(const InitListExpr *E); |
| 10663 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { |
| 10664 | return VisitCXXConstructExpr(E, T: E->getType()); |
| 10665 | } |
| 10666 | bool VisitLambdaExpr(const LambdaExpr *E); |
| 10667 | bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); |
| 10668 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); |
| 10669 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); |
| 10670 | bool VisitBinCmp(const BinaryOperator *E); |
| 10671 | bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); |
| 10672 | bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, |
| 10673 | ArrayRef<Expr *> Args); |
| 10674 | }; |
| 10675 | } |
| 10676 | |
| 10677 | /// Perform zero-initialization on an object of non-union class type. |
| 10678 | /// C++11 [dcl.init]p5: |
| 10679 | /// To zero-initialize an object or reference of type T means: |
| 10680 | /// [...] |
| 10681 | /// -- if T is a (possibly cv-qualified) non-union class type, |
| 10682 | /// each non-static data member and each base-class subobject is |
| 10683 | /// zero-initialized |
| 10684 | static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, |
| 10685 | const RecordDecl *RD, |
| 10686 | const LValue &This, APValue &Result) { |
| 10687 | assert(!RD->isUnion() && "Expected non-union class type" ); |
| 10688 | const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(Val: RD); |
| 10689 | Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, |
| 10690 | std::distance(first: RD->field_begin(), last: RD->field_end())); |
| 10691 | |
| 10692 | if (RD->isInvalidDecl()) return false; |
| 10693 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD); |
| 10694 | |
| 10695 | if (CD) { |
| 10696 | unsigned Index = 0; |
| 10697 | for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), |
| 10698 | End = CD->bases_end(); I != End; ++I, ++Index) { |
| 10699 | const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); |
| 10700 | LValue Subobject = This; |
| 10701 | if (!HandleLValueDirectBase(Info, E, Obj&: Subobject, Derived: CD, Base, RL: &Layout)) |
| 10702 | return false; |
| 10703 | if (!HandleClassZeroInitialization(Info, E, RD: Base, This: Subobject, |
| 10704 | Result&: Result.getStructBase(i: Index))) |
| 10705 | return false; |
| 10706 | } |
| 10707 | } |
| 10708 | |
| 10709 | for (const auto *I : RD->fields()) { |
| 10710 | // -- if T is a reference type, no initialization is performed. |
| 10711 | if (I->isUnnamedBitField() || I->getType()->isReferenceType()) |
| 10712 | continue; |
| 10713 | |
| 10714 | LValue Subobject = This; |
| 10715 | if (!HandleLValueMember(Info, E, LVal&: Subobject, FD: I, RL: &Layout)) |
| 10716 | return false; |
| 10717 | |
| 10718 | ImplicitValueInitExpr VIE(I->getType()); |
| 10719 | if (!EvaluateInPlace( |
| 10720 | Result&: Result.getStructField(i: I->getFieldIndex()), Info, This: Subobject, E: &VIE)) |
| 10721 | return false; |
| 10722 | } |
| 10723 | |
| 10724 | return true; |
| 10725 | } |
| 10726 | |
| 10727 | bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { |
| 10728 | const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); |
| 10729 | if (RD->isInvalidDecl()) return false; |
| 10730 | if (RD->isUnion()) { |
| 10731 | // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the |
| 10732 | // object's first non-static named data member is zero-initialized |
| 10733 | RecordDecl::field_iterator I = RD->field_begin(); |
| 10734 | while (I != RD->field_end() && (*I)->isUnnamedBitField()) |
| 10735 | ++I; |
| 10736 | if (I == RD->field_end()) { |
| 10737 | Result = APValue((const FieldDecl*)nullptr); |
| 10738 | return true; |
| 10739 | } |
| 10740 | |
| 10741 | LValue Subobject = This; |
| 10742 | if (!HandleLValueMember(Info, E, LVal&: Subobject, FD: *I)) |
| 10743 | return false; |
| 10744 | Result = APValue(*I); |
| 10745 | ImplicitValueInitExpr VIE(I->getType()); |
| 10746 | return EvaluateInPlace(Result&: Result.getUnionValue(), Info, This: Subobject, E: &VIE); |
| 10747 | } |
| 10748 | |
| 10749 | if (isa<CXXRecordDecl>(Val: RD) && cast<CXXRecordDecl>(Val: RD)->getNumVBases()) { |
| 10750 | Info.FFDiag(E, DiagId: diag::note_constexpr_virtual_base) << RD; |
| 10751 | return false; |
| 10752 | } |
| 10753 | |
| 10754 | return HandleClassZeroInitialization(Info, E, RD, This, Result); |
| 10755 | } |
| 10756 | |
| 10757 | bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 10758 | switch (E->getCastKind()) { |
| 10759 | default: |
| 10760 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 10761 | |
| 10762 | case CK_ConstructorConversion: |
| 10763 | return Visit(S: E->getSubExpr()); |
| 10764 | |
| 10765 | case CK_DerivedToBase: |
| 10766 | case CK_UncheckedDerivedToBase: { |
| 10767 | APValue DerivedObject; |
| 10768 | if (!Evaluate(Result&: DerivedObject, Info, E: E->getSubExpr())) |
| 10769 | return false; |
| 10770 | if (!DerivedObject.isStruct()) |
| 10771 | return Error(E: E->getSubExpr()); |
| 10772 | |
| 10773 | // Derived-to-base rvalue conversion: just slice off the derived part. |
| 10774 | APValue *Value = &DerivedObject; |
| 10775 | const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); |
| 10776 | for (CastExpr::path_const_iterator PathI = E->path_begin(), |
| 10777 | PathE = E->path_end(); PathI != PathE; ++PathI) { |
| 10778 | assert(!(*PathI)->isVirtual() && "record rvalue with virtual base" ); |
| 10779 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); |
| 10780 | Value = &Value->getStructBase(i: getBaseIndex(Derived: RD, Base)); |
| 10781 | RD = Base; |
| 10782 | } |
| 10783 | Result = *Value; |
| 10784 | return true; |
| 10785 | } |
| 10786 | } |
| 10787 | } |
| 10788 | |
| 10789 | bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { |
| 10790 | if (E->isTransparent()) |
| 10791 | return Visit(S: E->getInit(Init: 0)); |
| 10792 | return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->inits()); |
| 10793 | } |
| 10794 | |
| 10795 | bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr( |
| 10796 | const Expr *ExprToVisit, ArrayRef<Expr *> Args) { |
| 10797 | const RecordDecl *RD = |
| 10798 | ExprToVisit->getType()->castAs<RecordType>()->getDecl(); |
| 10799 | if (RD->isInvalidDecl()) return false; |
| 10800 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD); |
| 10801 | auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD); |
| 10802 | |
| 10803 | EvalInfo::EvaluatingConstructorRAII EvalObj( |
| 10804 | Info, |
| 10805 | ObjectUnderConstruction{.Base: This.getLValueBase(), .Path: This.Designator.Entries}, |
| 10806 | CXXRD && CXXRD->getNumBases()); |
| 10807 | |
| 10808 | if (RD->isUnion()) { |
| 10809 | const FieldDecl *Field; |
| 10810 | if (auto *ILE = dyn_cast<InitListExpr>(Val: ExprToVisit)) { |
| 10811 | Field = ILE->getInitializedFieldInUnion(); |
| 10812 | } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(Val: ExprToVisit)) { |
| 10813 | Field = PLIE->getInitializedFieldInUnion(); |
| 10814 | } else { |
| 10815 | llvm_unreachable( |
| 10816 | "Expression is neither an init list nor a C++ paren list" ); |
| 10817 | } |
| 10818 | |
| 10819 | Result = APValue(Field); |
| 10820 | if (!Field) |
| 10821 | return true; |
| 10822 | |
| 10823 | // If the initializer list for a union does not contain any elements, the |
| 10824 | // first element of the union is value-initialized. |
| 10825 | // FIXME: The element should be initialized from an initializer list. |
| 10826 | // Is this difference ever observable for initializer lists which |
| 10827 | // we don't build? |
| 10828 | ImplicitValueInitExpr VIE(Field->getType()); |
| 10829 | const Expr *InitExpr = Args.empty() ? &VIE : Args[0]; |
| 10830 | |
| 10831 | LValue Subobject = This; |
| 10832 | if (!HandleLValueMember(Info, E: InitExpr, LVal&: Subobject, FD: Field, RL: &Layout)) |
| 10833 | return false; |
| 10834 | |
| 10835 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. |
| 10836 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, |
| 10837 | isa<CXXDefaultInitExpr>(Val: InitExpr)); |
| 10838 | |
| 10839 | if (EvaluateInPlace(Result&: Result.getUnionValue(), Info, This: Subobject, E: InitExpr)) { |
| 10840 | if (Field->isBitField()) |
| 10841 | return truncateBitfieldValue(Info, E: InitExpr, Value&: Result.getUnionValue(), |
| 10842 | FD: Field); |
| 10843 | return true; |
| 10844 | } |
| 10845 | |
| 10846 | return false; |
| 10847 | } |
| 10848 | |
| 10849 | if (!Result.hasValue()) |
| 10850 | Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, |
| 10851 | std::distance(first: RD->field_begin(), last: RD->field_end())); |
| 10852 | unsigned ElementNo = 0; |
| 10853 | bool Success = true; |
| 10854 | |
| 10855 | // Initialize base classes. |
| 10856 | if (CXXRD && CXXRD->getNumBases()) { |
| 10857 | for (const auto &Base : CXXRD->bases()) { |
| 10858 | assert(ElementNo < Args.size() && "missing init for base class" ); |
| 10859 | const Expr *Init = Args[ElementNo]; |
| 10860 | |
| 10861 | LValue Subobject = This; |
| 10862 | if (!HandleLValueBase(Info, E: Init, Obj&: Subobject, DerivedDecl: CXXRD, Base: &Base)) |
| 10863 | return false; |
| 10864 | |
| 10865 | APValue &FieldVal = Result.getStructBase(i: ElementNo); |
| 10866 | if (!EvaluateInPlace(Result&: FieldVal, Info, This: Subobject, E: Init)) { |
| 10867 | if (!Info.noteFailure()) |
| 10868 | return false; |
| 10869 | Success = false; |
| 10870 | } |
| 10871 | ++ElementNo; |
| 10872 | } |
| 10873 | |
| 10874 | EvalObj.finishedConstructingBases(); |
| 10875 | } |
| 10876 | |
| 10877 | // Initialize members. |
| 10878 | for (const auto *Field : RD->fields()) { |
| 10879 | // Anonymous bit-fields are not considered members of the class for |
| 10880 | // purposes of aggregate initialization. |
| 10881 | if (Field->isUnnamedBitField()) |
| 10882 | continue; |
| 10883 | |
| 10884 | LValue Subobject = This; |
| 10885 | |
| 10886 | bool HaveInit = ElementNo < Args.size(); |
| 10887 | |
| 10888 | // FIXME: Diagnostics here should point to the end of the initializer |
| 10889 | // list, not the start. |
| 10890 | if (!HandleLValueMember(Info, E: HaveInit ? Args[ElementNo] : ExprToVisit, |
| 10891 | LVal&: Subobject, FD: Field, RL: &Layout)) |
| 10892 | return false; |
| 10893 | |
| 10894 | // Perform an implicit value-initialization for members beyond the end of |
| 10895 | // the initializer list. |
| 10896 | ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); |
| 10897 | const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE; |
| 10898 | |
| 10899 | if (Field->getType()->isIncompleteArrayType()) { |
| 10900 | if (auto *CAT = Info.Ctx.getAsConstantArrayType(T: Init->getType())) { |
| 10901 | if (!CAT->isZeroSize()) { |
| 10902 | // Bail out for now. This might sort of "work", but the rest of the |
| 10903 | // code isn't really prepared to handle it. |
| 10904 | Info.FFDiag(E: Init, DiagId: diag::note_constexpr_unsupported_flexible_array); |
| 10905 | return false; |
| 10906 | } |
| 10907 | } |
| 10908 | } |
| 10909 | |
| 10910 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. |
| 10911 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, |
| 10912 | isa<CXXDefaultInitExpr>(Val: Init)); |
| 10913 | |
| 10914 | APValue &FieldVal = Result.getStructField(i: Field->getFieldIndex()); |
| 10915 | if (!EvaluateInPlace(Result&: FieldVal, Info, This: Subobject, E: Init) || |
| 10916 | (Field->isBitField() && !truncateBitfieldValue(Info, E: Init, |
| 10917 | Value&: FieldVal, FD: Field))) { |
| 10918 | if (!Info.noteFailure()) |
| 10919 | return false; |
| 10920 | Success = false; |
| 10921 | } |
| 10922 | } |
| 10923 | |
| 10924 | EvalObj.finishedConstructingFields(); |
| 10925 | |
| 10926 | return Success; |
| 10927 | } |
| 10928 | |
| 10929 | bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, |
| 10930 | QualType T) { |
| 10931 | // Note that E's type is not necessarily the type of our class here; we might |
| 10932 | // be initializing an array element instead. |
| 10933 | const CXXConstructorDecl *FD = E->getConstructor(); |
| 10934 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; |
| 10935 | |
| 10936 | bool ZeroInit = E->requiresZeroInitialization(); |
| 10937 | if (CheckTrivialDefaultConstructor(Info, Loc: E->getExprLoc(), CD: FD, IsValueInitialization: ZeroInit)) { |
| 10938 | // If we've already performed zero-initialization, we're already done. |
| 10939 | if (Result.hasValue()) |
| 10940 | return true; |
| 10941 | |
| 10942 | if (ZeroInit) |
| 10943 | return ZeroInitialization(E, T); |
| 10944 | |
| 10945 | return handleDefaultInitValue(T, Result); |
| 10946 | } |
| 10947 | |
| 10948 | const FunctionDecl *Definition = nullptr; |
| 10949 | auto Body = FD->getBody(Definition); |
| 10950 | |
| 10951 | if (!CheckConstexprFunction(Info, CallLoc: E->getExprLoc(), Declaration: FD, Definition, Body)) |
| 10952 | return false; |
| 10953 | |
| 10954 | // Avoid materializing a temporary for an elidable copy/move constructor. |
| 10955 | if (E->isElidable() && !ZeroInit) { |
| 10956 | // FIXME: This only handles the simplest case, where the source object |
| 10957 | // is passed directly as the first argument to the constructor. |
| 10958 | // This should also handle stepping though implicit casts and |
| 10959 | // and conversion sequences which involve two steps, with a |
| 10960 | // conversion operator followed by a converting constructor. |
| 10961 | const Expr *SrcObj = E->getArg(Arg: 0); |
| 10962 | assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); |
| 10963 | assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); |
| 10964 | if (const MaterializeTemporaryExpr *ME = |
| 10965 | dyn_cast<MaterializeTemporaryExpr>(Val: SrcObj)) |
| 10966 | return Visit(S: ME->getSubExpr()); |
| 10967 | } |
| 10968 | |
| 10969 | if (ZeroInit && !ZeroInitialization(E, T)) |
| 10970 | return false; |
| 10971 | |
| 10972 | auto Args = ArrayRef(E->getArgs(), E->getNumArgs()); |
| 10973 | return HandleConstructorCall(E, This, Args, |
| 10974 | Definition: cast<CXXConstructorDecl>(Val: Definition), Info, |
| 10975 | Result); |
| 10976 | } |
| 10977 | |
| 10978 | bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( |
| 10979 | const CXXInheritedCtorInitExpr *E) { |
| 10980 | if (!Info.CurrentCall) { |
| 10981 | assert(Info.checkingPotentialConstantExpression()); |
| 10982 | return false; |
| 10983 | } |
| 10984 | |
| 10985 | const CXXConstructorDecl *FD = E->getConstructor(); |
| 10986 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) |
| 10987 | return false; |
| 10988 | |
| 10989 | const FunctionDecl *Definition = nullptr; |
| 10990 | auto Body = FD->getBody(Definition); |
| 10991 | |
| 10992 | if (!CheckConstexprFunction(Info, CallLoc: E->getExprLoc(), Declaration: FD, Definition, Body)) |
| 10993 | return false; |
| 10994 | |
| 10995 | return HandleConstructorCall(E, This, Call: Info.CurrentCall->Arguments, |
| 10996 | Definition: cast<CXXConstructorDecl>(Val: Definition), Info, |
| 10997 | Result); |
| 10998 | } |
| 10999 | |
| 11000 | bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( |
| 11001 | const CXXStdInitializerListExpr *E) { |
| 11002 | const ConstantArrayType *ArrayType = |
| 11003 | Info.Ctx.getAsConstantArrayType(T: E->getSubExpr()->getType()); |
| 11004 | |
| 11005 | LValue Array; |
| 11006 | if (!EvaluateLValue(E: E->getSubExpr(), Result&: Array, Info)) |
| 11007 | return false; |
| 11008 | |
| 11009 | assert(ArrayType && "unexpected type for array initializer" ); |
| 11010 | |
| 11011 | // Get a pointer to the first element of the array. |
| 11012 | Array.addArray(Info, E, CAT: ArrayType); |
| 11013 | |
| 11014 | // FIXME: What if the initializer_list type has base classes, etc? |
| 11015 | Result = APValue(APValue::UninitStruct(), 0, 2); |
| 11016 | Array.moveInto(V&: Result.getStructField(i: 0)); |
| 11017 | |
| 11018 | RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); |
| 11019 | RecordDecl::field_iterator Field = Record->field_begin(); |
| 11020 | assert(Field != Record->field_end() && |
| 11021 | Info.Ctx.hasSameType(Field->getType()->getPointeeType(), |
| 11022 | ArrayType->getElementType()) && |
| 11023 | "Expected std::initializer_list first field to be const E *" ); |
| 11024 | ++Field; |
| 11025 | assert(Field != Record->field_end() && |
| 11026 | "Expected std::initializer_list to have two fields" ); |
| 11027 | |
| 11028 | if (Info.Ctx.hasSameType(T1: Field->getType(), T2: Info.Ctx.getSizeType())) { |
| 11029 | // Length. |
| 11030 | Result.getStructField(i: 1) = APValue(APSInt(ArrayType->getSize())); |
| 11031 | } else { |
| 11032 | // End pointer. |
| 11033 | assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(), |
| 11034 | ArrayType->getElementType()) && |
| 11035 | "Expected std::initializer_list second field to be const E *" ); |
| 11036 | if (!HandleLValueArrayAdjustment(Info, E, LVal&: Array, |
| 11037 | EltTy: ArrayType->getElementType(), |
| 11038 | Adjustment: ArrayType->getZExtSize())) |
| 11039 | return false; |
| 11040 | Array.moveInto(V&: Result.getStructField(i: 1)); |
| 11041 | } |
| 11042 | |
| 11043 | assert(++Field == Record->field_end() && |
| 11044 | "Expected std::initializer_list to only have two fields" ); |
| 11045 | |
| 11046 | return true; |
| 11047 | } |
| 11048 | |
| 11049 | bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { |
| 11050 | const CXXRecordDecl *ClosureClass = E->getLambdaClass(); |
| 11051 | if (ClosureClass->isInvalidDecl()) |
| 11052 | return false; |
| 11053 | |
| 11054 | const size_t NumFields = |
| 11055 | std::distance(first: ClosureClass->field_begin(), last: ClosureClass->field_end()); |
| 11056 | |
| 11057 | assert(NumFields == (size_t)std::distance(E->capture_init_begin(), |
| 11058 | E->capture_init_end()) && |
| 11059 | "The number of lambda capture initializers should equal the number of " |
| 11060 | "fields within the closure type" ); |
| 11061 | |
| 11062 | Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); |
| 11063 | // Iterate through all the lambda's closure object's fields and initialize |
| 11064 | // them. |
| 11065 | auto *CaptureInitIt = E->capture_init_begin(); |
| 11066 | bool Success = true; |
| 11067 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: ClosureClass); |
| 11068 | for (const auto *Field : ClosureClass->fields()) { |
| 11069 | assert(CaptureInitIt != E->capture_init_end()); |
| 11070 | // Get the initializer for this field |
| 11071 | Expr *const CurFieldInit = *CaptureInitIt++; |
| 11072 | |
| 11073 | // If there is no initializer, either this is a VLA or an error has |
| 11074 | // occurred. |
| 11075 | if (!CurFieldInit || CurFieldInit->containsErrors()) |
| 11076 | return Error(E); |
| 11077 | |
| 11078 | LValue Subobject = This; |
| 11079 | |
| 11080 | if (!HandleLValueMember(Info, E, LVal&: Subobject, FD: Field, RL: &Layout)) |
| 11081 | return false; |
| 11082 | |
| 11083 | APValue &FieldVal = Result.getStructField(i: Field->getFieldIndex()); |
| 11084 | if (!EvaluateInPlace(Result&: FieldVal, Info, This: Subobject, E: CurFieldInit)) { |
| 11085 | if (!Info.keepEvaluatingAfterFailure()) |
| 11086 | return false; |
| 11087 | Success = false; |
| 11088 | } |
| 11089 | } |
| 11090 | return Success; |
| 11091 | } |
| 11092 | |
| 11093 | static bool EvaluateRecord(const Expr *E, const LValue &This, |
| 11094 | APValue &Result, EvalInfo &Info) { |
| 11095 | assert(!E->isValueDependent()); |
| 11096 | assert(E->isPRValue() && E->getType()->isRecordType() && |
| 11097 | "can't evaluate expression as a record rvalue" ); |
| 11098 | return RecordExprEvaluator(Info, This, Result).Visit(S: E); |
| 11099 | } |
| 11100 | |
| 11101 | //===----------------------------------------------------------------------===// |
| 11102 | // Temporary Evaluation |
| 11103 | // |
| 11104 | // Temporaries are represented in the AST as rvalues, but generally behave like |
| 11105 | // lvalues. The full-object of which the temporary is a subobject is implicitly |
| 11106 | // materialized so that a reference can bind to it. |
| 11107 | //===----------------------------------------------------------------------===// |
| 11108 | namespace { |
| 11109 | class TemporaryExprEvaluator |
| 11110 | : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { |
| 11111 | public: |
| 11112 | TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : |
| 11113 | LValueExprEvaluatorBaseTy(Info, Result, false) {} |
| 11114 | |
| 11115 | /// Visit an expression which constructs the value of this temporary. |
| 11116 | bool VisitConstructExpr(const Expr *E) { |
| 11117 | APValue &Value = Info.CurrentCall->createTemporary( |
| 11118 | Key: E, T: E->getType(), Scope: ScopeKind::FullExpression, LV&: Result); |
| 11119 | return EvaluateInPlace(Result&: Value, Info, This: Result, E); |
| 11120 | } |
| 11121 | |
| 11122 | bool VisitCastExpr(const CastExpr *E) { |
| 11123 | switch (E->getCastKind()) { |
| 11124 | default: |
| 11125 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); |
| 11126 | |
| 11127 | case CK_ConstructorConversion: |
| 11128 | return VisitConstructExpr(E: E->getSubExpr()); |
| 11129 | } |
| 11130 | } |
| 11131 | bool VisitInitListExpr(const InitListExpr *E) { |
| 11132 | return VisitConstructExpr(E); |
| 11133 | } |
| 11134 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { |
| 11135 | return VisitConstructExpr(E); |
| 11136 | } |
| 11137 | bool VisitCallExpr(const CallExpr *E) { |
| 11138 | return VisitConstructExpr(E); |
| 11139 | } |
| 11140 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { |
| 11141 | return VisitConstructExpr(E); |
| 11142 | } |
| 11143 | bool VisitLambdaExpr(const LambdaExpr *E) { |
| 11144 | return VisitConstructExpr(E); |
| 11145 | } |
| 11146 | }; |
| 11147 | } // end anonymous namespace |
| 11148 | |
| 11149 | /// Evaluate an expression of record type as a temporary. |
| 11150 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { |
| 11151 | assert(!E->isValueDependent()); |
| 11152 | assert(E->isPRValue() && E->getType()->isRecordType()); |
| 11153 | return TemporaryExprEvaluator(Info, Result).Visit(S: E); |
| 11154 | } |
| 11155 | |
| 11156 | //===----------------------------------------------------------------------===// |
| 11157 | // Vector Evaluation |
| 11158 | //===----------------------------------------------------------------------===// |
| 11159 | |
| 11160 | namespace { |
| 11161 | class VectorExprEvaluator |
| 11162 | : public ExprEvaluatorBase<VectorExprEvaluator> { |
| 11163 | APValue &Result; |
| 11164 | public: |
| 11165 | |
| 11166 | VectorExprEvaluator(EvalInfo &info, APValue &Result) |
| 11167 | : ExprEvaluatorBaseTy(info), Result(Result) {} |
| 11168 | |
| 11169 | bool Success(ArrayRef<APValue> V, const Expr *E) { |
| 11170 | assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); |
| 11171 | // FIXME: remove this APValue copy. |
| 11172 | Result = APValue(V.data(), V.size()); |
| 11173 | return true; |
| 11174 | } |
| 11175 | bool Success(const APValue &V, const Expr *E) { |
| 11176 | assert(V.isVector()); |
| 11177 | Result = V; |
| 11178 | return true; |
| 11179 | } |
| 11180 | bool ZeroInitialization(const Expr *E); |
| 11181 | |
| 11182 | bool VisitUnaryReal(const UnaryOperator *E) |
| 11183 | { return Visit(S: E->getSubExpr()); } |
| 11184 | bool VisitCastExpr(const CastExpr* E); |
| 11185 | bool VisitInitListExpr(const InitListExpr *E); |
| 11186 | bool VisitUnaryImag(const UnaryOperator *E); |
| 11187 | bool VisitBinaryOperator(const BinaryOperator *E); |
| 11188 | bool VisitUnaryOperator(const UnaryOperator *E); |
| 11189 | bool VisitCallExpr(const CallExpr *E); |
| 11190 | bool VisitConvertVectorExpr(const ConvertVectorExpr *E); |
| 11191 | bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E); |
| 11192 | |
| 11193 | // FIXME: Missing: conditional operator (for GNU |
| 11194 | // conditional select), ExtVectorElementExpr |
| 11195 | }; |
| 11196 | } // end anonymous namespace |
| 11197 | |
| 11198 | static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { |
| 11199 | assert(E->isPRValue() && E->getType()->isVectorType() && |
| 11200 | "not a vector prvalue" ); |
| 11201 | return VectorExprEvaluator(Info, Result).Visit(S: E); |
| 11202 | } |
| 11203 | |
| 11204 | bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 11205 | const VectorType *VTy = E->getType()->castAs<VectorType>(); |
| 11206 | unsigned NElts = VTy->getNumElements(); |
| 11207 | |
| 11208 | const Expr *SE = E->getSubExpr(); |
| 11209 | QualType SETy = SE->getType(); |
| 11210 | |
| 11211 | switch (E->getCastKind()) { |
| 11212 | case CK_VectorSplat: { |
| 11213 | APValue Val = APValue(); |
| 11214 | if (SETy->isIntegerType()) { |
| 11215 | APSInt IntResult; |
| 11216 | if (!EvaluateInteger(E: SE, Result&: IntResult, Info)) |
| 11217 | return false; |
| 11218 | Val = APValue(std::move(IntResult)); |
| 11219 | } else if (SETy->isRealFloatingType()) { |
| 11220 | APFloat FloatResult(0.0); |
| 11221 | if (!EvaluateFloat(E: SE, Result&: FloatResult, Info)) |
| 11222 | return false; |
| 11223 | Val = APValue(std::move(FloatResult)); |
| 11224 | } else { |
| 11225 | return Error(E); |
| 11226 | } |
| 11227 | |
| 11228 | // Splat and create vector APValue. |
| 11229 | SmallVector<APValue, 4> Elts(NElts, Val); |
| 11230 | return Success(V: Elts, E); |
| 11231 | } |
| 11232 | case CK_BitCast: { |
| 11233 | APValue SVal; |
| 11234 | if (!Evaluate(Result&: SVal, Info, E: SE)) |
| 11235 | return false; |
| 11236 | |
| 11237 | if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) { |
| 11238 | // Give up if the input isn't an int, float, or vector. For example, we |
| 11239 | // reject "(v4i16)(intptr_t)&a". |
| 11240 | Info.FFDiag(E, DiagId: diag::note_constexpr_invalid_cast) |
| 11241 | << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret |
| 11242 | << Info.Ctx.getLangOpts().CPlusPlus; |
| 11243 | return false; |
| 11244 | } |
| 11245 | |
| 11246 | if (!handleRValueToRValueBitCast(Info, DestValue&: Result, SourceRValue: SVal, BCE: E)) |
| 11247 | return false; |
| 11248 | |
| 11249 | return true; |
| 11250 | } |
| 11251 | case CK_HLSLVectorTruncation: { |
| 11252 | APValue Val; |
| 11253 | SmallVector<APValue, 4> Elements; |
| 11254 | if (!EvaluateVector(E: SE, Result&: Val, Info)) |
| 11255 | return Error(E); |
| 11256 | for (unsigned I = 0; I < NElts; I++) |
| 11257 | Elements.push_back(Elt: Val.getVectorElt(I)); |
| 11258 | return Success(V: Elements, E); |
| 11259 | } |
| 11260 | default: |
| 11261 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 11262 | } |
| 11263 | } |
| 11264 | |
| 11265 | bool |
| 11266 | VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { |
| 11267 | const VectorType *VT = E->getType()->castAs<VectorType>(); |
| 11268 | unsigned NumInits = E->getNumInits(); |
| 11269 | unsigned NumElements = VT->getNumElements(); |
| 11270 | |
| 11271 | QualType EltTy = VT->getElementType(); |
| 11272 | SmallVector<APValue, 4> Elements; |
| 11273 | |
| 11274 | // MFloat8 type doesn't have constants and thus constant folding |
| 11275 | // is impossible. |
| 11276 | if (EltTy->isMFloat8Type()) |
| 11277 | return false; |
| 11278 | |
| 11279 | // The number of initializers can be less than the number of |
| 11280 | // vector elements. For OpenCL, this can be due to nested vector |
| 11281 | // initialization. For GCC compatibility, missing trailing elements |
| 11282 | // should be initialized with zeroes. |
| 11283 | unsigned CountInits = 0, CountElts = 0; |
| 11284 | while (CountElts < NumElements) { |
| 11285 | // Handle nested vector initialization. |
| 11286 | if (CountInits < NumInits |
| 11287 | && E->getInit(Init: CountInits)->getType()->isVectorType()) { |
| 11288 | APValue v; |
| 11289 | if (!EvaluateVector(E: E->getInit(Init: CountInits), Result&: v, Info)) |
| 11290 | return Error(E); |
| 11291 | unsigned vlen = v.getVectorLength(); |
| 11292 | for (unsigned j = 0; j < vlen; j++) |
| 11293 | Elements.push_back(Elt: v.getVectorElt(I: j)); |
| 11294 | CountElts += vlen; |
| 11295 | } else if (EltTy->isIntegerType()) { |
| 11296 | llvm::APSInt sInt(32); |
| 11297 | if (CountInits < NumInits) { |
| 11298 | if (!EvaluateInteger(E: E->getInit(Init: CountInits), Result&: sInt, Info)) |
| 11299 | return false; |
| 11300 | } else // trailing integer zero. |
| 11301 | sInt = Info.Ctx.MakeIntValue(Value: 0, Type: EltTy); |
| 11302 | Elements.push_back(Elt: APValue(sInt)); |
| 11303 | CountElts++; |
| 11304 | } else { |
| 11305 | llvm::APFloat f(0.0); |
| 11306 | if (CountInits < NumInits) { |
| 11307 | if (!EvaluateFloat(E: E->getInit(Init: CountInits), Result&: f, Info)) |
| 11308 | return false; |
| 11309 | } else // trailing float zero. |
| 11310 | f = APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: EltTy)); |
| 11311 | Elements.push_back(Elt: APValue(f)); |
| 11312 | CountElts++; |
| 11313 | } |
| 11314 | CountInits++; |
| 11315 | } |
| 11316 | return Success(V: Elements, E); |
| 11317 | } |
| 11318 | |
| 11319 | bool |
| 11320 | VectorExprEvaluator::ZeroInitialization(const Expr *E) { |
| 11321 | const auto *VT = E->getType()->castAs<VectorType>(); |
| 11322 | QualType EltTy = VT->getElementType(); |
| 11323 | APValue ZeroElement; |
| 11324 | if (EltTy->isIntegerType()) |
| 11325 | ZeroElement = APValue(Info.Ctx.MakeIntValue(Value: 0, Type: EltTy)); |
| 11326 | else |
| 11327 | ZeroElement = |
| 11328 | APValue(APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: EltTy))); |
| 11329 | |
| 11330 | SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); |
| 11331 | return Success(V: Elements, E); |
| 11332 | } |
| 11333 | |
| 11334 | bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { |
| 11335 | VisitIgnoredValue(E: E->getSubExpr()); |
| 11336 | return ZeroInitialization(E); |
| 11337 | } |
| 11338 | |
| 11339 | bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { |
| 11340 | BinaryOperatorKind Op = E->getOpcode(); |
| 11341 | assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && |
| 11342 | "Operation not supported on vector types" ); |
| 11343 | |
| 11344 | if (Op == BO_Comma) |
| 11345 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 11346 | |
| 11347 | Expr *LHS = E->getLHS(); |
| 11348 | Expr *RHS = E->getRHS(); |
| 11349 | |
| 11350 | assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && |
| 11351 | "Must both be vector types" ); |
| 11352 | // Checking JUST the types are the same would be fine, except shifts don't |
| 11353 | // need to have their types be the same (since you always shift by an int). |
| 11354 | assert(LHS->getType()->castAs<VectorType>()->getNumElements() == |
| 11355 | E->getType()->castAs<VectorType>()->getNumElements() && |
| 11356 | RHS->getType()->castAs<VectorType>()->getNumElements() == |
| 11357 | E->getType()->castAs<VectorType>()->getNumElements() && |
| 11358 | "All operands must be the same size." ); |
| 11359 | |
| 11360 | APValue LHSValue; |
| 11361 | APValue RHSValue; |
| 11362 | bool LHSOK = Evaluate(Result&: LHSValue, Info, E: LHS); |
| 11363 | if (!LHSOK && !Info.noteFailure()) |
| 11364 | return false; |
| 11365 | if (!Evaluate(Result&: RHSValue, Info, E: RHS) || !LHSOK) |
| 11366 | return false; |
| 11367 | |
| 11368 | if (!handleVectorVectorBinOp(Info, E, Opcode: Op, LHSValue, RHSValue)) |
| 11369 | return false; |
| 11370 | |
| 11371 | return Success(V: LHSValue, E); |
| 11372 | } |
| 11373 | |
| 11374 | static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, |
| 11375 | QualType ResultTy, |
| 11376 | UnaryOperatorKind Op, |
| 11377 | APValue Elt) { |
| 11378 | switch (Op) { |
| 11379 | case UO_Plus: |
| 11380 | // Nothing to do here. |
| 11381 | return Elt; |
| 11382 | case UO_Minus: |
| 11383 | if (Elt.getKind() == APValue::Int) { |
| 11384 | Elt.getInt().negate(); |
| 11385 | } else { |
| 11386 | assert(Elt.getKind() == APValue::Float && |
| 11387 | "Vector can only be int or float type" ); |
| 11388 | Elt.getFloat().changeSign(); |
| 11389 | } |
| 11390 | return Elt; |
| 11391 | case UO_Not: |
| 11392 | // This is only valid for integral types anyway, so we don't have to handle |
| 11393 | // float here. |
| 11394 | assert(Elt.getKind() == APValue::Int && |
| 11395 | "Vector operator ~ can only be int" ); |
| 11396 | Elt.getInt().flipAllBits(); |
| 11397 | return Elt; |
| 11398 | case UO_LNot: { |
| 11399 | if (Elt.getKind() == APValue::Int) { |
| 11400 | Elt.getInt() = !Elt.getInt(); |
| 11401 | // operator ! on vectors returns -1 for 'truth', so negate it. |
| 11402 | Elt.getInt().negate(); |
| 11403 | return Elt; |
| 11404 | } |
| 11405 | assert(Elt.getKind() == APValue::Float && |
| 11406 | "Vector can only be int or float type" ); |
| 11407 | // Float types result in an int of the same size, but -1 for true, or 0 for |
| 11408 | // false. |
| 11409 | APSInt EltResult{Ctx.getIntWidth(T: ResultTy), |
| 11410 | ResultTy->isUnsignedIntegerType()}; |
| 11411 | if (Elt.getFloat().isZero()) |
| 11412 | EltResult.setAllBits(); |
| 11413 | else |
| 11414 | EltResult.clearAllBits(); |
| 11415 | |
| 11416 | return APValue{EltResult}; |
| 11417 | } |
| 11418 | default: |
| 11419 | // FIXME: Implement the rest of the unary operators. |
| 11420 | return std::nullopt; |
| 11421 | } |
| 11422 | } |
| 11423 | |
| 11424 | bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { |
| 11425 | Expr *SubExpr = E->getSubExpr(); |
| 11426 | const auto *VD = SubExpr->getType()->castAs<VectorType>(); |
| 11427 | // This result element type differs in the case of negating a floating point |
| 11428 | // vector, since the result type is the a vector of the equivilant sized |
| 11429 | // integer. |
| 11430 | const QualType ResultEltTy = VD->getElementType(); |
| 11431 | UnaryOperatorKind Op = E->getOpcode(); |
| 11432 | |
| 11433 | APValue SubExprValue; |
| 11434 | if (!Evaluate(Result&: SubExprValue, Info, E: SubExpr)) |
| 11435 | return false; |
| 11436 | |
| 11437 | // FIXME: This vector evaluator someday needs to be changed to be LValue |
| 11438 | // aware/keep LValue information around, rather than dealing with just vector |
| 11439 | // types directly. Until then, we cannot handle cases where the operand to |
| 11440 | // these unary operators is an LValue. The only case I've been able to see |
| 11441 | // cause this is operator++ assigning to a member expression (only valid in |
| 11442 | // altivec compilations) in C mode, so this shouldn't limit us too much. |
| 11443 | if (SubExprValue.isLValue()) |
| 11444 | return false; |
| 11445 | |
| 11446 | assert(SubExprValue.getVectorLength() == VD->getNumElements() && |
| 11447 | "Vector length doesn't match type?" ); |
| 11448 | |
| 11449 | SmallVector<APValue, 4> ResultElements; |
| 11450 | for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { |
| 11451 | std::optional<APValue> Elt = handleVectorUnaryOperator( |
| 11452 | Ctx&: Info.Ctx, ResultTy: ResultEltTy, Op, Elt: SubExprValue.getVectorElt(I: EltNum)); |
| 11453 | if (!Elt) |
| 11454 | return false; |
| 11455 | ResultElements.push_back(Elt: *Elt); |
| 11456 | } |
| 11457 | return Success(V: APValue(ResultElements.data(), ResultElements.size()), E); |
| 11458 | } |
| 11459 | |
| 11460 | static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, |
| 11461 | const Expr *E, QualType SourceTy, |
| 11462 | QualType DestTy, APValue const &Original, |
| 11463 | APValue &Result) { |
| 11464 | if (SourceTy->isIntegerType()) { |
| 11465 | if (DestTy->isRealFloatingType()) { |
| 11466 | Result = APValue(APFloat(0.0)); |
| 11467 | return HandleIntToFloatCast(Info, E, FPO, SrcType: SourceTy, Value: Original.getInt(), |
| 11468 | DestType: DestTy, Result&: Result.getFloat()); |
| 11469 | } |
| 11470 | if (DestTy->isIntegerType()) { |
| 11471 | Result = APValue( |
| 11472 | HandleIntToIntCast(Info, E, DestType: DestTy, SrcType: SourceTy, Value: Original.getInt())); |
| 11473 | return true; |
| 11474 | } |
| 11475 | } else if (SourceTy->isRealFloatingType()) { |
| 11476 | if (DestTy->isRealFloatingType()) { |
| 11477 | Result = Original; |
| 11478 | return HandleFloatToFloatCast(Info, E, SrcType: SourceTy, DestType: DestTy, |
| 11479 | Result&: Result.getFloat()); |
| 11480 | } |
| 11481 | if (DestTy->isIntegerType()) { |
| 11482 | Result = APValue(APSInt()); |
| 11483 | return HandleFloatToIntCast(Info, E, SrcType: SourceTy, Value: Original.getFloat(), |
| 11484 | DestType: DestTy, Result&: Result.getInt()); |
| 11485 | } |
| 11486 | } |
| 11487 | |
| 11488 | Info.FFDiag(E, DiagId: diag::err_convertvector_constexpr_unsupported_vector_cast) |
| 11489 | << SourceTy << DestTy; |
| 11490 | return false; |
| 11491 | } |
| 11492 | |
| 11493 | bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) { |
| 11494 | if (!IsConstantEvaluatedBuiltinCall(E)) |
| 11495 | return ExprEvaluatorBaseTy::VisitCallExpr(E); |
| 11496 | |
| 11497 | switch (E->getBuiltinCallee()) { |
| 11498 | default: |
| 11499 | return false; |
| 11500 | case Builtin::BI__builtin_elementwise_popcount: |
| 11501 | case Builtin::BI__builtin_elementwise_bitreverse: { |
| 11502 | APValue Source; |
| 11503 | if (!EvaluateAsRValue(Info, E: E->getArg(Arg: 0), Result&: Source)) |
| 11504 | return false; |
| 11505 | |
| 11506 | QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType(); |
| 11507 | unsigned SourceLen = Source.getVectorLength(); |
| 11508 | SmallVector<APValue, 4> ResultElements; |
| 11509 | ResultElements.reserve(N: SourceLen); |
| 11510 | |
| 11511 | for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) { |
| 11512 | APSInt Elt = Source.getVectorElt(I: EltNum).getInt(); |
| 11513 | switch (E->getBuiltinCallee()) { |
| 11514 | case Builtin::BI__builtin_elementwise_popcount: |
| 11515 | ResultElements.push_back(Elt: APValue( |
| 11516 | APSInt(APInt(Info.Ctx.getIntWidth(T: DestEltTy), Elt.popcount()), |
| 11517 | DestEltTy->isUnsignedIntegerOrEnumerationType()))); |
| 11518 | break; |
| 11519 | case Builtin::BI__builtin_elementwise_bitreverse: |
| 11520 | ResultElements.push_back( |
| 11521 | Elt: APValue(APSInt(Elt.reverseBits(), |
| 11522 | DestEltTy->isUnsignedIntegerOrEnumerationType()))); |
| 11523 | break; |
| 11524 | } |
| 11525 | } |
| 11526 | |
| 11527 | return Success(V: APValue(ResultElements.data(), ResultElements.size()), E); |
| 11528 | } |
| 11529 | case Builtin::BI__builtin_elementwise_add_sat: |
| 11530 | case Builtin::BI__builtin_elementwise_sub_sat: { |
| 11531 | APValue SourceLHS, SourceRHS; |
| 11532 | if (!EvaluateAsRValue(Info, E: E->getArg(Arg: 0), Result&: SourceLHS) || |
| 11533 | !EvaluateAsRValue(Info, E: E->getArg(Arg: 1), Result&: SourceRHS)) |
| 11534 | return false; |
| 11535 | |
| 11536 | QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType(); |
| 11537 | unsigned SourceLen = SourceLHS.getVectorLength(); |
| 11538 | SmallVector<APValue, 4> ResultElements; |
| 11539 | ResultElements.reserve(N: SourceLen); |
| 11540 | |
| 11541 | for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) { |
| 11542 | APSInt LHS = SourceLHS.getVectorElt(I: EltNum).getInt(); |
| 11543 | APSInt RHS = SourceRHS.getVectorElt(I: EltNum).getInt(); |
| 11544 | switch (E->getBuiltinCallee()) { |
| 11545 | case Builtin::BI__builtin_elementwise_add_sat: |
| 11546 | ResultElements.push_back(Elt: APValue( |
| 11547 | APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : RHS.uadd_sat(RHS), |
| 11548 | DestEltTy->isUnsignedIntegerOrEnumerationType()))); |
| 11549 | break; |
| 11550 | case Builtin::BI__builtin_elementwise_sub_sat: |
| 11551 | ResultElements.push_back(Elt: APValue( |
| 11552 | APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : RHS.usub_sat(RHS), |
| 11553 | DestEltTy->isUnsignedIntegerOrEnumerationType()))); |
| 11554 | break; |
| 11555 | } |
| 11556 | } |
| 11557 | |
| 11558 | return Success(V: APValue(ResultElements.data(), ResultElements.size()), E); |
| 11559 | } |
| 11560 | } |
| 11561 | } |
| 11562 | |
| 11563 | bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) { |
| 11564 | APValue Source; |
| 11565 | QualType SourceVecType = E->getSrcExpr()->getType(); |
| 11566 | if (!EvaluateAsRValue(Info, E: E->getSrcExpr(), Result&: Source)) |
| 11567 | return false; |
| 11568 | |
| 11569 | QualType DestTy = E->getType()->castAs<VectorType>()->getElementType(); |
| 11570 | QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType(); |
| 11571 | |
| 11572 | const FPOptions FPO = E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts()); |
| 11573 | |
| 11574 | auto SourceLen = Source.getVectorLength(); |
| 11575 | SmallVector<APValue, 4> ResultElements; |
| 11576 | ResultElements.reserve(N: SourceLen); |
| 11577 | for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) { |
| 11578 | APValue Elt; |
| 11579 | if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy, |
| 11580 | Original: Source.getVectorElt(I: EltNum), Result&: Elt)) |
| 11581 | return false; |
| 11582 | ResultElements.push_back(Elt: std::move(Elt)); |
| 11583 | } |
| 11584 | |
| 11585 | return Success(V: APValue(ResultElements.data(), ResultElements.size()), E); |
| 11586 | } |
| 11587 | |
| 11588 | static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, |
| 11589 | QualType ElemType, APValue const &VecVal1, |
| 11590 | APValue const &VecVal2, unsigned EltNum, |
| 11591 | APValue &Result) { |
| 11592 | unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength(); |
| 11593 | unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength(); |
| 11594 | |
| 11595 | APSInt IndexVal = E->getShuffleMaskIdx(N: EltNum); |
| 11596 | int64_t index = IndexVal.getExtValue(); |
| 11597 | // The spec says that -1 should be treated as undef for optimizations, |
| 11598 | // but in constexpr we'd have to produce an APValue::Indeterminate, |
| 11599 | // which is prohibited from being a top-level constant value. Emit a |
| 11600 | // diagnostic instead. |
| 11601 | if (index == -1) { |
| 11602 | Info.FFDiag( |
| 11603 | E, DiagId: diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr) |
| 11604 | << EltNum; |
| 11605 | return false; |
| 11606 | } |
| 11607 | |
| 11608 | if (index < 0 || |
| 11609 | index >= TotalElementsInInputVector1 + TotalElementsInInputVector2) |
| 11610 | llvm_unreachable("Out of bounds shuffle index" ); |
| 11611 | |
| 11612 | if (index >= TotalElementsInInputVector1) |
| 11613 | Result = VecVal2.getVectorElt(I: index - TotalElementsInInputVector1); |
| 11614 | else |
| 11615 | Result = VecVal1.getVectorElt(I: index); |
| 11616 | return true; |
| 11617 | } |
| 11618 | |
| 11619 | bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) { |
| 11620 | APValue VecVal1; |
| 11621 | const Expr *Vec1 = E->getExpr(Index: 0); |
| 11622 | if (!EvaluateAsRValue(Info, E: Vec1, Result&: VecVal1)) |
| 11623 | return false; |
| 11624 | APValue VecVal2; |
| 11625 | const Expr *Vec2 = E->getExpr(Index: 1); |
| 11626 | if (!EvaluateAsRValue(Info, E: Vec2, Result&: VecVal2)) |
| 11627 | return false; |
| 11628 | |
| 11629 | VectorType const *DestVecTy = E->getType()->castAs<VectorType>(); |
| 11630 | QualType DestElTy = DestVecTy->getElementType(); |
| 11631 | |
| 11632 | auto TotalElementsInOutputVector = DestVecTy->getNumElements(); |
| 11633 | |
| 11634 | SmallVector<APValue, 4> ResultElements; |
| 11635 | ResultElements.reserve(N: TotalElementsInOutputVector); |
| 11636 | for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) { |
| 11637 | APValue Elt; |
| 11638 | if (!handleVectorShuffle(Info, E, ElemType: DestElTy, VecVal1, VecVal2, EltNum, Result&: Elt)) |
| 11639 | return false; |
| 11640 | ResultElements.push_back(Elt: std::move(Elt)); |
| 11641 | } |
| 11642 | |
| 11643 | return Success(V: APValue(ResultElements.data(), ResultElements.size()), E); |
| 11644 | } |
| 11645 | |
| 11646 | //===----------------------------------------------------------------------===// |
| 11647 | // Array Evaluation |
| 11648 | //===----------------------------------------------------------------------===// |
| 11649 | |
| 11650 | namespace { |
| 11651 | class ArrayExprEvaluator |
| 11652 | : public ExprEvaluatorBase<ArrayExprEvaluator> { |
| 11653 | const LValue &This; |
| 11654 | APValue &Result; |
| 11655 | public: |
| 11656 | |
| 11657 | ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) |
| 11658 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} |
| 11659 | |
| 11660 | bool Success(const APValue &V, const Expr *E) { |
| 11661 | assert(V.isArray() && "expected array" ); |
| 11662 | Result = V; |
| 11663 | return true; |
| 11664 | } |
| 11665 | |
| 11666 | bool ZeroInitialization(const Expr *E) { |
| 11667 | const ConstantArrayType *CAT = |
| 11668 | Info.Ctx.getAsConstantArrayType(T: E->getType()); |
| 11669 | if (!CAT) { |
| 11670 | if (E->getType()->isIncompleteArrayType()) { |
| 11671 | // We can be asked to zero-initialize a flexible array member; this |
| 11672 | // is represented as an ImplicitValueInitExpr of incomplete array |
| 11673 | // type. In this case, the array has zero elements. |
| 11674 | Result = APValue(APValue::UninitArray(), 0, 0); |
| 11675 | return true; |
| 11676 | } |
| 11677 | // FIXME: We could handle VLAs here. |
| 11678 | return Error(E); |
| 11679 | } |
| 11680 | |
| 11681 | Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize()); |
| 11682 | if (!Result.hasArrayFiller()) |
| 11683 | return true; |
| 11684 | |
| 11685 | // Zero-initialize all elements. |
| 11686 | LValue Subobject = This; |
| 11687 | Subobject.addArray(Info, E, CAT); |
| 11688 | ImplicitValueInitExpr VIE(CAT->getElementType()); |
| 11689 | return EvaluateInPlace(Result&: Result.getArrayFiller(), Info, This: Subobject, E: &VIE); |
| 11690 | } |
| 11691 | |
| 11692 | bool VisitCallExpr(const CallExpr *E) { |
| 11693 | return handleCallExpr(E, Result, ResultSlot: &This); |
| 11694 | } |
| 11695 | bool VisitInitListExpr(const InitListExpr *E, |
| 11696 | QualType AllocType = QualType()); |
| 11697 | bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); |
| 11698 | bool VisitCXXConstructExpr(const CXXConstructExpr *E); |
| 11699 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, |
| 11700 | const LValue &Subobject, |
| 11701 | APValue *Value, QualType Type); |
| 11702 | bool VisitStringLiteral(const StringLiteral *E, |
| 11703 | QualType AllocType = QualType()) { |
| 11704 | expandStringLiteral(Info, S: E, Result, AllocType); |
| 11705 | return true; |
| 11706 | } |
| 11707 | bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); |
| 11708 | bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, |
| 11709 | ArrayRef<Expr *> Args, |
| 11710 | const Expr *ArrayFiller, |
| 11711 | QualType AllocType = QualType()); |
| 11712 | }; |
| 11713 | } // end anonymous namespace |
| 11714 | |
| 11715 | static bool EvaluateArray(const Expr *E, const LValue &This, |
| 11716 | APValue &Result, EvalInfo &Info) { |
| 11717 | assert(!E->isValueDependent()); |
| 11718 | assert(E->isPRValue() && E->getType()->isArrayType() && |
| 11719 | "not an array prvalue" ); |
| 11720 | return ArrayExprEvaluator(Info, This, Result).Visit(S: E); |
| 11721 | } |
| 11722 | |
| 11723 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, |
| 11724 | APValue &Result, const InitListExpr *ILE, |
| 11725 | QualType AllocType) { |
| 11726 | assert(!ILE->isValueDependent()); |
| 11727 | assert(ILE->isPRValue() && ILE->getType()->isArrayType() && |
| 11728 | "not an array prvalue" ); |
| 11729 | return ArrayExprEvaluator(Info, This, Result) |
| 11730 | .VisitInitListExpr(E: ILE, AllocType); |
| 11731 | } |
| 11732 | |
| 11733 | static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, |
| 11734 | APValue &Result, |
| 11735 | const CXXConstructExpr *CCE, |
| 11736 | QualType AllocType) { |
| 11737 | assert(!CCE->isValueDependent()); |
| 11738 | assert(CCE->isPRValue() && CCE->getType()->isArrayType() && |
| 11739 | "not an array prvalue" ); |
| 11740 | return ArrayExprEvaluator(Info, This, Result) |
| 11741 | .VisitCXXConstructExpr(E: CCE, Subobject: This, Value: &Result, Type: AllocType); |
| 11742 | } |
| 11743 | |
| 11744 | // Return true iff the given array filler may depend on the element index. |
| 11745 | static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { |
| 11746 | // For now, just allow non-class value-initialization and initialization |
| 11747 | // lists comprised of them. |
| 11748 | if (isa<ImplicitValueInitExpr>(Val: FillerExpr)) |
| 11749 | return false; |
| 11750 | if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Val: FillerExpr)) { |
| 11751 | for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { |
| 11752 | if (MaybeElementDependentArrayFiller(FillerExpr: ILE->getInit(Init: I))) |
| 11753 | return true; |
| 11754 | } |
| 11755 | |
| 11756 | if (ILE->hasArrayFiller() && |
| 11757 | MaybeElementDependentArrayFiller(FillerExpr: ILE->getArrayFiller())) |
| 11758 | return true; |
| 11759 | |
| 11760 | return false; |
| 11761 | } |
| 11762 | return true; |
| 11763 | } |
| 11764 | |
| 11765 | bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, |
| 11766 | QualType AllocType) { |
| 11767 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( |
| 11768 | T: AllocType.isNull() ? E->getType() : AllocType); |
| 11769 | if (!CAT) |
| 11770 | return Error(E); |
| 11771 | |
| 11772 | // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] |
| 11773 | // an appropriately-typed string literal enclosed in braces. |
| 11774 | if (E->isStringLiteralInit()) { |
| 11775 | auto *SL = dyn_cast<StringLiteral>(Val: E->getInit(Init: 0)->IgnoreParenImpCasts()); |
| 11776 | // FIXME: Support ObjCEncodeExpr here once we support it in |
| 11777 | // ArrayExprEvaluator generally. |
| 11778 | if (!SL) |
| 11779 | return Error(E); |
| 11780 | return VisitStringLiteral(E: SL, AllocType); |
| 11781 | } |
| 11782 | // Any other transparent list init will need proper handling of the |
| 11783 | // AllocType; we can't just recurse to the inner initializer. |
| 11784 | assert(!E->isTransparent() && |
| 11785 | "transparent array list initialization is not string literal init?" ); |
| 11786 | |
| 11787 | return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->inits(), ArrayFiller: E->getArrayFiller(), |
| 11788 | AllocType); |
| 11789 | } |
| 11790 | |
| 11791 | bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr( |
| 11792 | const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller, |
| 11793 | QualType AllocType) { |
| 11794 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( |
| 11795 | T: AllocType.isNull() ? ExprToVisit->getType() : AllocType); |
| 11796 | |
| 11797 | bool Success = true; |
| 11798 | |
| 11799 | assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && |
| 11800 | "zero-initialized array shouldn't have any initialized elts" ); |
| 11801 | APValue Filler; |
| 11802 | if (Result.isArray() && Result.hasArrayFiller()) |
| 11803 | Filler = Result.getArrayFiller(); |
| 11804 | |
| 11805 | unsigned NumEltsToInit = Args.size(); |
| 11806 | unsigned NumElts = CAT->getZExtSize(); |
| 11807 | |
| 11808 | // If the initializer might depend on the array index, run it for each |
| 11809 | // array element. |
| 11810 | if (NumEltsToInit != NumElts && |
| 11811 | MaybeElementDependentArrayFiller(FillerExpr: ArrayFiller)) { |
| 11812 | NumEltsToInit = NumElts; |
| 11813 | } else { |
| 11814 | for (auto *Init : Args) { |
| 11815 | if (auto *EmbedS = dyn_cast<EmbedExpr>(Val: Init->IgnoreParenImpCasts())) |
| 11816 | NumEltsToInit += EmbedS->getDataElementCount() - 1; |
| 11817 | } |
| 11818 | if (NumEltsToInit > NumElts) |
| 11819 | NumEltsToInit = NumElts; |
| 11820 | } |
| 11821 | |
| 11822 | LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " |
| 11823 | << NumEltsToInit << ".\n" ); |
| 11824 | |
| 11825 | Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); |
| 11826 | |
| 11827 | // If the array was previously zero-initialized, preserve the |
| 11828 | // zero-initialized values. |
| 11829 | if (Filler.hasValue()) { |
| 11830 | for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) |
| 11831 | Result.getArrayInitializedElt(I) = Filler; |
| 11832 | if (Result.hasArrayFiller()) |
| 11833 | Result.getArrayFiller() = Filler; |
| 11834 | } |
| 11835 | |
| 11836 | LValue Subobject = This; |
| 11837 | Subobject.addArray(Info, E: ExprToVisit, CAT); |
| 11838 | auto Eval = [&](const Expr *Init, unsigned ArrayIndex) { |
| 11839 | if (Init->isValueDependent()) |
| 11840 | return EvaluateDependentExpr(E: Init, Info); |
| 11841 | |
| 11842 | if (!EvaluateInPlace(Result&: Result.getArrayInitializedElt(I: ArrayIndex), Info, |
| 11843 | This: Subobject, E: Init) || |
| 11844 | !HandleLValueArrayAdjustment(Info, E: Init, LVal&: Subobject, |
| 11845 | EltTy: CAT->getElementType(), Adjustment: 1)) { |
| 11846 | if (!Info.noteFailure()) |
| 11847 | return false; |
| 11848 | Success = false; |
| 11849 | } |
| 11850 | return true; |
| 11851 | }; |
| 11852 | unsigned ArrayIndex = 0; |
| 11853 | QualType DestTy = CAT->getElementType(); |
| 11854 | APSInt Value(Info.Ctx.getTypeSize(T: DestTy), DestTy->isUnsignedIntegerType()); |
| 11855 | for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { |
| 11856 | const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller; |
| 11857 | if (ArrayIndex >= NumEltsToInit) |
| 11858 | break; |
| 11859 | if (auto *EmbedS = dyn_cast<EmbedExpr>(Val: Init->IgnoreParenImpCasts())) { |
| 11860 | StringLiteral *SL = EmbedS->getDataStringLiteral(); |
| 11861 | for (unsigned I = EmbedS->getStartingElementPos(), |
| 11862 | N = EmbedS->getDataElementCount(); |
| 11863 | I != EmbedS->getStartingElementPos() + N; ++I) { |
| 11864 | Value = SL->getCodeUnit(i: I); |
| 11865 | if (DestTy->isIntegerType()) { |
| 11866 | Result.getArrayInitializedElt(I: ArrayIndex) = APValue(Value); |
| 11867 | } else { |
| 11868 | assert(DestTy->isFloatingType() && "unexpected type" ); |
| 11869 | const FPOptions FPO = |
| 11870 | Init->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts()); |
| 11871 | APFloat FValue(0.0); |
| 11872 | if (!HandleIntToFloatCast(Info, E: Init, FPO, SrcType: EmbedS->getType(), Value, |
| 11873 | DestType: DestTy, Result&: FValue)) |
| 11874 | return false; |
| 11875 | Result.getArrayInitializedElt(I: ArrayIndex) = APValue(FValue); |
| 11876 | } |
| 11877 | ArrayIndex++; |
| 11878 | } |
| 11879 | } else { |
| 11880 | if (!Eval(Init, ArrayIndex)) |
| 11881 | return false; |
| 11882 | ++ArrayIndex; |
| 11883 | } |
| 11884 | } |
| 11885 | |
| 11886 | if (!Result.hasArrayFiller()) |
| 11887 | return Success; |
| 11888 | |
| 11889 | // If we get here, we have a trivial filler, which we can just evaluate |
| 11890 | // once and splat over the rest of the array elements. |
| 11891 | assert(ArrayFiller && "no array filler for incomplete init list" ); |
| 11892 | return EvaluateInPlace(Result&: Result.getArrayFiller(), Info, This: Subobject, |
| 11893 | E: ArrayFiller) && |
| 11894 | Success; |
| 11895 | } |
| 11896 | |
| 11897 | bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { |
| 11898 | LValue CommonLV; |
| 11899 | if (E->getCommonExpr() && |
| 11900 | !Evaluate(Result&: Info.CurrentCall->createTemporary( |
| 11901 | Key: E->getCommonExpr(), |
| 11902 | T: getStorageType(Ctx: Info.Ctx, E: E->getCommonExpr()), |
| 11903 | Scope: ScopeKind::FullExpression, LV&: CommonLV), |
| 11904 | Info, E: E->getCommonExpr()->getSourceExpr())) |
| 11905 | return false; |
| 11906 | |
| 11907 | auto *CAT = cast<ConstantArrayType>(Val: E->getType()->castAsArrayTypeUnsafe()); |
| 11908 | |
| 11909 | uint64_t Elements = CAT->getZExtSize(); |
| 11910 | Result = APValue(APValue::UninitArray(), Elements, Elements); |
| 11911 | |
| 11912 | LValue Subobject = This; |
| 11913 | Subobject.addArray(Info, E, CAT); |
| 11914 | |
| 11915 | bool Success = true; |
| 11916 | for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { |
| 11917 | // C++ [class.temporary]/5 |
| 11918 | // There are four contexts in which temporaries are destroyed at a different |
| 11919 | // point than the end of the full-expression. [...] The second context is |
| 11920 | // when a copy constructor is called to copy an element of an array while |
| 11921 | // the entire array is copied [...]. In either case, if the constructor has |
| 11922 | // one or more default arguments, the destruction of every temporary created |
| 11923 | // in a default argument is sequenced before the construction of the next |
| 11924 | // array element, if any. |
| 11925 | FullExpressionRAII Scope(Info); |
| 11926 | |
| 11927 | if (!EvaluateInPlace(Result&: Result.getArrayInitializedElt(I: Index), |
| 11928 | Info, This: Subobject, E: E->getSubExpr()) || |
| 11929 | !HandleLValueArrayAdjustment(Info, E, LVal&: Subobject, |
| 11930 | EltTy: CAT->getElementType(), Adjustment: 1)) { |
| 11931 | if (!Info.noteFailure()) |
| 11932 | return false; |
| 11933 | Success = false; |
| 11934 | } |
| 11935 | |
| 11936 | // Make sure we run the destructors too. |
| 11937 | Scope.destroy(); |
| 11938 | } |
| 11939 | |
| 11940 | return Success; |
| 11941 | } |
| 11942 | |
| 11943 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { |
| 11944 | return VisitCXXConstructExpr(E, Subobject: This, Value: &Result, Type: E->getType()); |
| 11945 | } |
| 11946 | |
| 11947 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, |
| 11948 | const LValue &Subobject, |
| 11949 | APValue *Value, |
| 11950 | QualType Type) { |
| 11951 | bool HadZeroInit = Value->hasValue(); |
| 11952 | |
| 11953 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T: Type)) { |
| 11954 | unsigned FinalSize = CAT->getZExtSize(); |
| 11955 | |
| 11956 | // Preserve the array filler if we had prior zero-initialization. |
| 11957 | APValue Filler = |
| 11958 | HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() |
| 11959 | : APValue(); |
| 11960 | |
| 11961 | *Value = APValue(APValue::UninitArray(), 0, FinalSize); |
| 11962 | if (FinalSize == 0) |
| 11963 | return true; |
| 11964 | |
| 11965 | bool HasTrivialConstructor = CheckTrivialDefaultConstructor( |
| 11966 | Info, Loc: E->getExprLoc(), CD: E->getConstructor(), |
| 11967 | IsValueInitialization: E->requiresZeroInitialization()); |
| 11968 | LValue ArrayElt = Subobject; |
| 11969 | ArrayElt.addArray(Info, E, CAT); |
| 11970 | // We do the whole initialization in two passes, first for just one element, |
| 11971 | // then for the whole array. It's possible we may find out we can't do const |
| 11972 | // init in the first pass, in which case we avoid allocating a potentially |
| 11973 | // large array. We don't do more passes because expanding array requires |
| 11974 | // copying the data, which is wasteful. |
| 11975 | for (const unsigned N : {1u, FinalSize}) { |
| 11976 | unsigned OldElts = Value->getArrayInitializedElts(); |
| 11977 | if (OldElts == N) |
| 11978 | break; |
| 11979 | |
| 11980 | // Expand the array to appropriate size. |
| 11981 | APValue NewValue(APValue::UninitArray(), N, FinalSize); |
| 11982 | for (unsigned I = 0; I < OldElts; ++I) |
| 11983 | NewValue.getArrayInitializedElt(I).swap( |
| 11984 | RHS&: Value->getArrayInitializedElt(I)); |
| 11985 | Value->swap(RHS&: NewValue); |
| 11986 | |
| 11987 | if (HadZeroInit) |
| 11988 | for (unsigned I = OldElts; I < N; ++I) |
| 11989 | Value->getArrayInitializedElt(I) = Filler; |
| 11990 | |
| 11991 | if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) { |
| 11992 | // If we have a trivial constructor, only evaluate it once and copy |
| 11993 | // the result into all the array elements. |
| 11994 | APValue &FirstResult = Value->getArrayInitializedElt(I: 0); |
| 11995 | for (unsigned I = OldElts; I < FinalSize; ++I) |
| 11996 | Value->getArrayInitializedElt(I) = FirstResult; |
| 11997 | } else { |
| 11998 | for (unsigned I = OldElts; I < N; ++I) { |
| 11999 | if (!VisitCXXConstructExpr(E, Subobject: ArrayElt, |
| 12000 | Value: &Value->getArrayInitializedElt(I), |
| 12001 | Type: CAT->getElementType()) || |
| 12002 | !HandleLValueArrayAdjustment(Info, E, LVal&: ArrayElt, |
| 12003 | EltTy: CAT->getElementType(), Adjustment: 1)) |
| 12004 | return false; |
| 12005 | // When checking for const initilization any diagnostic is considered |
| 12006 | // an error. |
| 12007 | if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && |
| 12008 | !Info.keepEvaluatingAfterFailure()) |
| 12009 | return false; |
| 12010 | } |
| 12011 | } |
| 12012 | } |
| 12013 | |
| 12014 | return true; |
| 12015 | } |
| 12016 | |
| 12017 | if (!Type->isRecordType()) |
| 12018 | return Error(E); |
| 12019 | |
| 12020 | return RecordExprEvaluator(Info, Subobject, *Value) |
| 12021 | .VisitCXXConstructExpr(E, T: Type); |
| 12022 | } |
| 12023 | |
| 12024 | bool ArrayExprEvaluator::VisitCXXParenListInitExpr( |
| 12025 | const CXXParenListInitExpr *E) { |
| 12026 | assert(E->getType()->isConstantArrayType() && |
| 12027 | "Expression result is not a constant array type" ); |
| 12028 | |
| 12029 | return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->getInitExprs(), |
| 12030 | ArrayFiller: E->getArrayFiller()); |
| 12031 | } |
| 12032 | |
| 12033 | //===----------------------------------------------------------------------===// |
| 12034 | // Integer Evaluation |
| 12035 | // |
| 12036 | // As a GNU extension, we support casting pointers to sufficiently-wide integer |
| 12037 | // types and back in constant folding. Integer values are thus represented |
| 12038 | // either as an integer-valued APValue, or as an lvalue-valued APValue. |
| 12039 | //===----------------------------------------------------------------------===// |
| 12040 | |
| 12041 | namespace { |
| 12042 | class IntExprEvaluator |
| 12043 | : public ExprEvaluatorBase<IntExprEvaluator> { |
| 12044 | APValue &Result; |
| 12045 | public: |
| 12046 | IntExprEvaluator(EvalInfo &info, APValue &result) |
| 12047 | : ExprEvaluatorBaseTy(info), Result(result) {} |
| 12048 | |
| 12049 | bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { |
| 12050 | assert(E->getType()->isIntegralOrEnumerationType() && |
| 12051 | "Invalid evaluation result." ); |
| 12052 | assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && |
| 12053 | "Invalid evaluation result." ); |
| 12054 | assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && |
| 12055 | "Invalid evaluation result." ); |
| 12056 | Result = APValue(SI); |
| 12057 | return true; |
| 12058 | } |
| 12059 | bool Success(const llvm::APSInt &SI, const Expr *E) { |
| 12060 | return Success(SI, E, Result); |
| 12061 | } |
| 12062 | |
| 12063 | bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { |
| 12064 | assert(E->getType()->isIntegralOrEnumerationType() && |
| 12065 | "Invalid evaluation result." ); |
| 12066 | assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && |
| 12067 | "Invalid evaluation result." ); |
| 12068 | Result = APValue(APSInt(I)); |
| 12069 | Result.getInt().setIsUnsigned( |
| 12070 | E->getType()->isUnsignedIntegerOrEnumerationType()); |
| 12071 | return true; |
| 12072 | } |
| 12073 | bool Success(const llvm::APInt &I, const Expr *E) { |
| 12074 | return Success(I, E, Result); |
| 12075 | } |
| 12076 | |
| 12077 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { |
| 12078 | assert(E->getType()->isIntegralOrEnumerationType() && |
| 12079 | "Invalid evaluation result." ); |
| 12080 | Result = APValue(Info.Ctx.MakeIntValue(Value, Type: E->getType())); |
| 12081 | return true; |
| 12082 | } |
| 12083 | bool Success(uint64_t Value, const Expr *E) { |
| 12084 | return Success(Value, E, Result); |
| 12085 | } |
| 12086 | |
| 12087 | bool Success(CharUnits Size, const Expr *E) { |
| 12088 | return Success(Value: Size.getQuantity(), E); |
| 12089 | } |
| 12090 | |
| 12091 | bool Success(const APValue &V, const Expr *E) { |
| 12092 | // C++23 [expr.const]p8 If we have a variable that is unknown reference or |
| 12093 | // pointer allow further evaluation of the value. |
| 12094 | if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() || |
| 12095 | V.allowConstexprUnknown()) { |
| 12096 | Result = V; |
| 12097 | return true; |
| 12098 | } |
| 12099 | return Success(SI: V.getInt(), E); |
| 12100 | } |
| 12101 | |
| 12102 | bool ZeroInitialization(const Expr *E) { return Success(Value: 0, E); } |
| 12103 | |
| 12104 | friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &, |
| 12105 | const CallExpr *); |
| 12106 | |
| 12107 | //===--------------------------------------------------------------------===// |
| 12108 | // Visitor Methods |
| 12109 | //===--------------------------------------------------------------------===// |
| 12110 | |
| 12111 | bool VisitIntegerLiteral(const IntegerLiteral *E) { |
| 12112 | return Success(I: E->getValue(), E); |
| 12113 | } |
| 12114 | bool VisitCharacterLiteral(const CharacterLiteral *E) { |
| 12115 | return Success(Value: E->getValue(), E); |
| 12116 | } |
| 12117 | |
| 12118 | bool CheckReferencedDecl(const Expr *E, const Decl *D); |
| 12119 | bool VisitDeclRefExpr(const DeclRefExpr *E) { |
| 12120 | if (CheckReferencedDecl(E, D: E->getDecl())) |
| 12121 | return true; |
| 12122 | |
| 12123 | return ExprEvaluatorBaseTy::VisitDeclRefExpr(S: E); |
| 12124 | } |
| 12125 | bool VisitMemberExpr(const MemberExpr *E) { |
| 12126 | if (CheckReferencedDecl(E, D: E->getMemberDecl())) { |
| 12127 | VisitIgnoredBaseExpression(E: E->getBase()); |
| 12128 | return true; |
| 12129 | } |
| 12130 | |
| 12131 | return ExprEvaluatorBaseTy::VisitMemberExpr(E); |
| 12132 | } |
| 12133 | |
| 12134 | bool VisitCallExpr(const CallExpr *E); |
| 12135 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); |
| 12136 | bool VisitBinaryOperator(const BinaryOperator *E); |
| 12137 | bool VisitOffsetOfExpr(const OffsetOfExpr *E); |
| 12138 | bool VisitUnaryOperator(const UnaryOperator *E); |
| 12139 | |
| 12140 | bool VisitCastExpr(const CastExpr* E); |
| 12141 | bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); |
| 12142 | |
| 12143 | bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { |
| 12144 | return Success(Value: E->getValue(), E); |
| 12145 | } |
| 12146 | |
| 12147 | bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { |
| 12148 | return Success(Value: E->getValue(), E); |
| 12149 | } |
| 12150 | |
| 12151 | bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { |
| 12152 | if (Info.ArrayInitIndex == uint64_t(-1)) { |
| 12153 | // We were asked to evaluate this subexpression independent of the |
| 12154 | // enclosing ArrayInitLoopExpr. We can't do that. |
| 12155 | Info.FFDiag(E); |
| 12156 | return false; |
| 12157 | } |
| 12158 | return Success(Value: Info.ArrayInitIndex, E); |
| 12159 | } |
| 12160 | |
| 12161 | // Note, GNU defines __null as an integer, not a pointer. |
| 12162 | bool VisitGNUNullExpr(const GNUNullExpr *E) { |
| 12163 | return ZeroInitialization(E); |
| 12164 | } |
| 12165 | |
| 12166 | bool VisitTypeTraitExpr(const TypeTraitExpr *E) { |
| 12167 | if (E->isStoredAsBoolean()) |
| 12168 | return Success(Value: E->getBoolValue(), E); |
| 12169 | if (E->getAPValue().isAbsent()) |
| 12170 | return false; |
| 12171 | assert(E->getAPValue().isInt() && "APValue type not supported" ); |
| 12172 | return Success(SI: E->getAPValue().getInt(), E); |
| 12173 | } |
| 12174 | |
| 12175 | bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { |
| 12176 | return Success(Value: E->getValue(), E); |
| 12177 | } |
| 12178 | |
| 12179 | bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { |
| 12180 | return Success(Value: E->getValue(), E); |
| 12181 | } |
| 12182 | |
| 12183 | bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) { |
| 12184 | // This should not be evaluated during constant expr evaluation, as it |
| 12185 | // should always be in an unevaluated context (the args list of a 'gang' or |
| 12186 | // 'tile' clause). |
| 12187 | return Error(E); |
| 12188 | } |
| 12189 | |
| 12190 | bool VisitUnaryReal(const UnaryOperator *E); |
| 12191 | bool VisitUnaryImag(const UnaryOperator *E); |
| 12192 | |
| 12193 | bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); |
| 12194 | bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); |
| 12195 | bool VisitSourceLocExpr(const SourceLocExpr *E); |
| 12196 | bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); |
| 12197 | bool VisitRequiresExpr(const RequiresExpr *E); |
| 12198 | // FIXME: Missing: array subscript of vector, member of vector |
| 12199 | }; |
| 12200 | |
| 12201 | class FixedPointExprEvaluator |
| 12202 | : public ExprEvaluatorBase<FixedPointExprEvaluator> { |
| 12203 | APValue &Result; |
| 12204 | |
| 12205 | public: |
| 12206 | FixedPointExprEvaluator(EvalInfo &info, APValue &result) |
| 12207 | : ExprEvaluatorBaseTy(info), Result(result) {} |
| 12208 | |
| 12209 | bool Success(const llvm::APInt &I, const Expr *E) { |
| 12210 | return Success( |
| 12211 | V: APFixedPoint(I, Info.Ctx.getFixedPointSemantics(Ty: E->getType())), E); |
| 12212 | } |
| 12213 | |
| 12214 | bool Success(uint64_t Value, const Expr *E) { |
| 12215 | return Success( |
| 12216 | V: APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(Ty: E->getType())), E); |
| 12217 | } |
| 12218 | |
| 12219 | bool Success(const APValue &V, const Expr *E) { |
| 12220 | return Success(V: V.getFixedPoint(), E); |
| 12221 | } |
| 12222 | |
| 12223 | bool Success(const APFixedPoint &V, const Expr *E) { |
| 12224 | assert(E->getType()->isFixedPointType() && "Invalid evaluation result." ); |
| 12225 | assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && |
| 12226 | "Invalid evaluation result." ); |
| 12227 | Result = APValue(V); |
| 12228 | return true; |
| 12229 | } |
| 12230 | |
| 12231 | bool ZeroInitialization(const Expr *E) { |
| 12232 | return Success(Value: 0, E); |
| 12233 | } |
| 12234 | |
| 12235 | //===--------------------------------------------------------------------===// |
| 12236 | // Visitor Methods |
| 12237 | //===--------------------------------------------------------------------===// |
| 12238 | |
| 12239 | bool VisitFixedPointLiteral(const FixedPointLiteral *E) { |
| 12240 | return Success(I: E->getValue(), E); |
| 12241 | } |
| 12242 | |
| 12243 | bool VisitCastExpr(const CastExpr *E); |
| 12244 | bool VisitUnaryOperator(const UnaryOperator *E); |
| 12245 | bool VisitBinaryOperator(const BinaryOperator *E); |
| 12246 | }; |
| 12247 | } // end anonymous namespace |
| 12248 | |
| 12249 | /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and |
| 12250 | /// produce either the integer value or a pointer. |
| 12251 | /// |
| 12252 | /// GCC has a heinous extension which folds casts between pointer types and |
| 12253 | /// pointer-sized integral types. We support this by allowing the evaluation of |
| 12254 | /// an integer rvalue to produce a pointer (represented as an lvalue) instead. |
| 12255 | /// Some simple arithmetic on such values is supported (they are treated much |
| 12256 | /// like char*). |
| 12257 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, |
| 12258 | EvalInfo &Info) { |
| 12259 | assert(!E->isValueDependent()); |
| 12260 | assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); |
| 12261 | return IntExprEvaluator(Info, Result).Visit(S: E); |
| 12262 | } |
| 12263 | |
| 12264 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { |
| 12265 | assert(!E->isValueDependent()); |
| 12266 | APValue Val; |
| 12267 | if (!EvaluateIntegerOrLValue(E, Result&: Val, Info)) |
| 12268 | return false; |
| 12269 | if (!Val.isInt()) { |
| 12270 | // FIXME: It would be better to produce the diagnostic for casting |
| 12271 | // a pointer to an integer. |
| 12272 | Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 12273 | return false; |
| 12274 | } |
| 12275 | Result = Val.getInt(); |
| 12276 | return true; |
| 12277 | } |
| 12278 | |
| 12279 | bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { |
| 12280 | APValue Evaluated = E->EvaluateInContext( |
| 12281 | Ctx: Info.Ctx, DefaultExpr: Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); |
| 12282 | return Success(V: Evaluated, E); |
| 12283 | } |
| 12284 | |
| 12285 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, |
| 12286 | EvalInfo &Info) { |
| 12287 | assert(!E->isValueDependent()); |
| 12288 | if (E->getType()->isFixedPointType()) { |
| 12289 | APValue Val; |
| 12290 | if (!FixedPointExprEvaluator(Info, Val).Visit(S: E)) |
| 12291 | return false; |
| 12292 | if (!Val.isFixedPoint()) |
| 12293 | return false; |
| 12294 | |
| 12295 | Result = Val.getFixedPoint(); |
| 12296 | return true; |
| 12297 | } |
| 12298 | return false; |
| 12299 | } |
| 12300 | |
| 12301 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, |
| 12302 | EvalInfo &Info) { |
| 12303 | assert(!E->isValueDependent()); |
| 12304 | if (E->getType()->isIntegerType()) { |
| 12305 | auto FXSema = Info.Ctx.getFixedPointSemantics(Ty: E->getType()); |
| 12306 | APSInt Val; |
| 12307 | if (!EvaluateInteger(E, Result&: Val, Info)) |
| 12308 | return false; |
| 12309 | Result = APFixedPoint(Val, FXSema); |
| 12310 | return true; |
| 12311 | } else if (E->getType()->isFixedPointType()) { |
| 12312 | return EvaluateFixedPoint(E, Result, Info); |
| 12313 | } |
| 12314 | return false; |
| 12315 | } |
| 12316 | |
| 12317 | /// Check whether the given declaration can be directly converted to an integral |
| 12318 | /// rvalue. If not, no diagnostic is produced; there are other things we can |
| 12319 | /// try. |
| 12320 | bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { |
| 12321 | // Enums are integer constant exprs. |
| 12322 | if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(Val: D)) { |
| 12323 | // Check for signedness/width mismatches between E type and ECD value. |
| 12324 | bool SameSign = (ECD->getInitVal().isSigned() |
| 12325 | == E->getType()->isSignedIntegerOrEnumerationType()); |
| 12326 | bool SameWidth = (ECD->getInitVal().getBitWidth() |
| 12327 | == Info.Ctx.getIntWidth(T: E->getType())); |
| 12328 | if (SameSign && SameWidth) |
| 12329 | return Success(SI: ECD->getInitVal(), E); |
| 12330 | else { |
| 12331 | // Get rid of mismatch (otherwise Success assertions will fail) |
| 12332 | // by computing a new value matching the type of E. |
| 12333 | llvm::APSInt Val = ECD->getInitVal(); |
| 12334 | if (!SameSign) |
| 12335 | Val.setIsSigned(!ECD->getInitVal().isSigned()); |
| 12336 | if (!SameWidth) |
| 12337 | Val = Val.extOrTrunc(width: Info.Ctx.getIntWidth(T: E->getType())); |
| 12338 | return Success(SI: Val, E); |
| 12339 | } |
| 12340 | } |
| 12341 | return false; |
| 12342 | } |
| 12343 | |
| 12344 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way |
| 12345 | /// as GCC. |
| 12346 | GCCTypeClass EvaluateBuiltinClassifyType(QualType T, |
| 12347 | const LangOptions &LangOpts) { |
| 12348 | assert(!T->isDependentType() && "unexpected dependent type" ); |
| 12349 | |
| 12350 | QualType CanTy = T.getCanonicalType(); |
| 12351 | |
| 12352 | switch (CanTy->getTypeClass()) { |
| 12353 | #define TYPE(ID, BASE) |
| 12354 | #define DEPENDENT_TYPE(ID, BASE) case Type::ID: |
| 12355 | #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: |
| 12356 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: |
| 12357 | #include "clang/AST/TypeNodes.inc" |
| 12358 | case Type::Auto: |
| 12359 | case Type::DeducedTemplateSpecialization: |
| 12360 | llvm_unreachable("unexpected non-canonical or dependent type" ); |
| 12361 | |
| 12362 | case Type::Builtin: |
| 12363 | switch (cast<BuiltinType>(Val&: CanTy)->getKind()) { |
| 12364 | #define BUILTIN_TYPE(ID, SINGLETON_ID) |
| 12365 | #define SIGNED_TYPE(ID, SINGLETON_ID) \ |
| 12366 | case BuiltinType::ID: return GCCTypeClass::Integer; |
| 12367 | #define FLOATING_TYPE(ID, SINGLETON_ID) \ |
| 12368 | case BuiltinType::ID: return GCCTypeClass::RealFloat; |
| 12369 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ |
| 12370 | case BuiltinType::ID: break; |
| 12371 | #include "clang/AST/BuiltinTypes.def" |
| 12372 | case BuiltinType::Void: |
| 12373 | return GCCTypeClass::Void; |
| 12374 | |
| 12375 | case BuiltinType::Bool: |
| 12376 | return GCCTypeClass::Bool; |
| 12377 | |
| 12378 | case BuiltinType::Char_U: |
| 12379 | case BuiltinType::UChar: |
| 12380 | case BuiltinType::WChar_U: |
| 12381 | case BuiltinType::Char8: |
| 12382 | case BuiltinType::Char16: |
| 12383 | case BuiltinType::Char32: |
| 12384 | case BuiltinType::UShort: |
| 12385 | case BuiltinType::UInt: |
| 12386 | case BuiltinType::ULong: |
| 12387 | case BuiltinType::ULongLong: |
| 12388 | case BuiltinType::UInt128: |
| 12389 | return GCCTypeClass::Integer; |
| 12390 | |
| 12391 | case BuiltinType::UShortAccum: |
| 12392 | case BuiltinType::UAccum: |
| 12393 | case BuiltinType::ULongAccum: |
| 12394 | case BuiltinType::UShortFract: |
| 12395 | case BuiltinType::UFract: |
| 12396 | case BuiltinType::ULongFract: |
| 12397 | case BuiltinType::SatUShortAccum: |
| 12398 | case BuiltinType::SatUAccum: |
| 12399 | case BuiltinType::SatULongAccum: |
| 12400 | case BuiltinType::SatUShortFract: |
| 12401 | case BuiltinType::SatUFract: |
| 12402 | case BuiltinType::SatULongFract: |
| 12403 | return GCCTypeClass::None; |
| 12404 | |
| 12405 | case BuiltinType::NullPtr: |
| 12406 | |
| 12407 | case BuiltinType::ObjCId: |
| 12408 | case BuiltinType::ObjCClass: |
| 12409 | case BuiltinType::ObjCSel: |
| 12410 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
| 12411 | case BuiltinType::Id: |
| 12412 | #include "clang/Basic/OpenCLImageTypes.def" |
| 12413 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
| 12414 | case BuiltinType::Id: |
| 12415 | #include "clang/Basic/OpenCLExtensionTypes.def" |
| 12416 | case BuiltinType::OCLSampler: |
| 12417 | case BuiltinType::OCLEvent: |
| 12418 | case BuiltinType::OCLClkEvent: |
| 12419 | case BuiltinType::OCLQueue: |
| 12420 | case BuiltinType::OCLReserveID: |
| 12421 | #define SVE_TYPE(Name, Id, SingletonId) \ |
| 12422 | case BuiltinType::Id: |
| 12423 | #include "clang/Basic/AArch64ACLETypes.def" |
| 12424 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
| 12425 | case BuiltinType::Id: |
| 12426 | #include "clang/Basic/PPCTypes.def" |
| 12427 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 12428 | #include "clang/Basic/RISCVVTypes.def" |
| 12429 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 12430 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
| 12431 | #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id: |
| 12432 | #include "clang/Basic/AMDGPUTypes.def" |
| 12433 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 12434 | #include "clang/Basic/HLSLIntangibleTypes.def" |
| 12435 | return GCCTypeClass::None; |
| 12436 | |
| 12437 | case BuiltinType::Dependent: |
| 12438 | llvm_unreachable("unexpected dependent type" ); |
| 12439 | }; |
| 12440 | llvm_unreachable("unexpected placeholder type" ); |
| 12441 | |
| 12442 | case Type::Enum: |
| 12443 | return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; |
| 12444 | |
| 12445 | case Type::Pointer: |
| 12446 | case Type::ConstantArray: |
| 12447 | case Type::VariableArray: |
| 12448 | case Type::IncompleteArray: |
| 12449 | case Type::FunctionNoProto: |
| 12450 | case Type::FunctionProto: |
| 12451 | case Type::ArrayParameter: |
| 12452 | return GCCTypeClass::Pointer; |
| 12453 | |
| 12454 | case Type::MemberPointer: |
| 12455 | return CanTy->isMemberDataPointerType() |
| 12456 | ? GCCTypeClass::PointerToDataMember |
| 12457 | : GCCTypeClass::PointerToMemberFunction; |
| 12458 | |
| 12459 | case Type::Complex: |
| 12460 | return GCCTypeClass::Complex; |
| 12461 | |
| 12462 | case Type::Record: |
| 12463 | return CanTy->isUnionType() ? GCCTypeClass::Union |
| 12464 | : GCCTypeClass::ClassOrStruct; |
| 12465 | |
| 12466 | case Type::Atomic: |
| 12467 | // GCC classifies _Atomic T the same as T. |
| 12468 | return EvaluateBuiltinClassifyType( |
| 12469 | T: CanTy->castAs<AtomicType>()->getValueType(), LangOpts); |
| 12470 | |
| 12471 | case Type::Vector: |
| 12472 | case Type::ExtVector: |
| 12473 | return GCCTypeClass::Vector; |
| 12474 | |
| 12475 | case Type::BlockPointer: |
| 12476 | case Type::ConstantMatrix: |
| 12477 | case Type::ObjCObject: |
| 12478 | case Type::ObjCInterface: |
| 12479 | case Type::ObjCObjectPointer: |
| 12480 | case Type::Pipe: |
| 12481 | case Type::HLSLAttributedResource: |
| 12482 | case Type::HLSLInlineSpirv: |
| 12483 | // Classify all other types that don't fit into the regular |
| 12484 | // classification the same way. |
| 12485 | return GCCTypeClass::None; |
| 12486 | |
| 12487 | case Type::BitInt: |
| 12488 | return GCCTypeClass::BitInt; |
| 12489 | |
| 12490 | case Type::LValueReference: |
| 12491 | case Type::RValueReference: |
| 12492 | llvm_unreachable("invalid type for expression" ); |
| 12493 | } |
| 12494 | |
| 12495 | llvm_unreachable("unexpected type class" ); |
| 12496 | } |
| 12497 | |
| 12498 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way |
| 12499 | /// as GCC. |
| 12500 | static GCCTypeClass |
| 12501 | EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { |
| 12502 | // If no argument was supplied, default to None. This isn't |
| 12503 | // ideal, however it is what gcc does. |
| 12504 | if (E->getNumArgs() == 0) |
| 12505 | return GCCTypeClass::None; |
| 12506 | |
| 12507 | // FIXME: Bizarrely, GCC treats a call with more than one argument as not |
| 12508 | // being an ICE, but still folds it to a constant using the type of the first |
| 12509 | // argument. |
| 12510 | return EvaluateBuiltinClassifyType(T: E->getArg(Arg: 0)->getType(), LangOpts); |
| 12511 | } |
| 12512 | |
| 12513 | /// EvaluateBuiltinConstantPForLValue - Determine the result of |
| 12514 | /// __builtin_constant_p when applied to the given pointer. |
| 12515 | /// |
| 12516 | /// A pointer is only "constant" if it is null (or a pointer cast to integer) |
| 12517 | /// or it points to the first character of a string literal. |
| 12518 | static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { |
| 12519 | APValue::LValueBase Base = LV.getLValueBase(); |
| 12520 | if (Base.isNull()) { |
| 12521 | // A null base is acceptable. |
| 12522 | return true; |
| 12523 | } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { |
| 12524 | if (!isa<StringLiteral>(Val: E)) |
| 12525 | return false; |
| 12526 | return LV.getLValueOffset().isZero(); |
| 12527 | } else if (Base.is<TypeInfoLValue>()) { |
| 12528 | // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to |
| 12529 | // evaluate to true. |
| 12530 | return true; |
| 12531 | } else { |
| 12532 | // Any other base is not constant enough for GCC. |
| 12533 | return false; |
| 12534 | } |
| 12535 | } |
| 12536 | |
| 12537 | /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to |
| 12538 | /// GCC as we can manage. |
| 12539 | static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { |
| 12540 | // This evaluation is not permitted to have side-effects, so evaluate it in |
| 12541 | // a speculative evaluation context. |
| 12542 | SpeculativeEvaluationRAII SpeculativeEval(Info); |
| 12543 | |
| 12544 | // Constant-folding is always enabled for the operand of __builtin_constant_p |
| 12545 | // (even when the enclosing evaluation context otherwise requires a strict |
| 12546 | // language-specific constant expression). |
| 12547 | FoldConstant Fold(Info, true); |
| 12548 | |
| 12549 | QualType ArgType = Arg->getType(); |
| 12550 | |
| 12551 | // __builtin_constant_p always has one operand. The rules which gcc follows |
| 12552 | // are not precisely documented, but are as follows: |
| 12553 | // |
| 12554 | // - If the operand is of integral, floating, complex or enumeration type, |
| 12555 | // and can be folded to a known value of that type, it returns 1. |
| 12556 | // - If the operand can be folded to a pointer to the first character |
| 12557 | // of a string literal (or such a pointer cast to an integral type) |
| 12558 | // or to a null pointer or an integer cast to a pointer, it returns 1. |
| 12559 | // |
| 12560 | // Otherwise, it returns 0. |
| 12561 | // |
| 12562 | // FIXME: GCC also intends to return 1 for literals of aggregate types, but |
| 12563 | // its support for this did not work prior to GCC 9 and is not yet well |
| 12564 | // understood. |
| 12565 | if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || |
| 12566 | ArgType->isAnyComplexType() || ArgType->isPointerType() || |
| 12567 | ArgType->isNullPtrType()) { |
| 12568 | APValue V; |
| 12569 | if (!::EvaluateAsRValue(Info, E: Arg, Result&: V) || Info.EvalStatus.HasSideEffects) { |
| 12570 | Fold.keepDiagnostics(); |
| 12571 | return false; |
| 12572 | } |
| 12573 | |
| 12574 | // For a pointer (possibly cast to integer), there are special rules. |
| 12575 | if (V.getKind() == APValue::LValue) |
| 12576 | return EvaluateBuiltinConstantPForLValue(LV: V); |
| 12577 | |
| 12578 | // Otherwise, any constant value is good enough. |
| 12579 | return V.hasValue(); |
| 12580 | } |
| 12581 | |
| 12582 | // Anything else isn't considered to be sufficiently constant. |
| 12583 | return false; |
| 12584 | } |
| 12585 | |
| 12586 | /// Retrieves the "underlying object type" of the given expression, |
| 12587 | /// as used by __builtin_object_size. |
| 12588 | static QualType getObjectType(APValue::LValueBase B) { |
| 12589 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { |
| 12590 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) |
| 12591 | return VD->getType(); |
| 12592 | } else if (const Expr *E = B.dyn_cast<const Expr*>()) { |
| 12593 | if (isa<CompoundLiteralExpr>(Val: E)) |
| 12594 | return E->getType(); |
| 12595 | } else if (B.is<TypeInfoLValue>()) { |
| 12596 | return B.getTypeInfoType(); |
| 12597 | } else if (B.is<DynamicAllocLValue>()) { |
| 12598 | return B.getDynamicAllocType(); |
| 12599 | } |
| 12600 | |
| 12601 | return QualType(); |
| 12602 | } |
| 12603 | |
| 12604 | /// A more selective version of E->IgnoreParenCasts for |
| 12605 | /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only |
| 12606 | /// to change the type of E. |
| 12607 | /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` |
| 12608 | /// |
| 12609 | /// Always returns an RValue with a pointer representation. |
| 12610 | static const Expr *ignorePointerCastsAndParens(const Expr *E) { |
| 12611 | assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); |
| 12612 | |
| 12613 | const Expr *NoParens = E->IgnoreParens(); |
| 12614 | const auto *Cast = dyn_cast<CastExpr>(Val: NoParens); |
| 12615 | if (Cast == nullptr) |
| 12616 | return NoParens; |
| 12617 | |
| 12618 | // We only conservatively allow a few kinds of casts, because this code is |
| 12619 | // inherently a simple solution that seeks to support the common case. |
| 12620 | auto CastKind = Cast->getCastKind(); |
| 12621 | if (CastKind != CK_NoOp && CastKind != CK_BitCast && |
| 12622 | CastKind != CK_AddressSpaceConversion) |
| 12623 | return NoParens; |
| 12624 | |
| 12625 | const auto *SubExpr = Cast->getSubExpr(); |
| 12626 | if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) |
| 12627 | return NoParens; |
| 12628 | return ignorePointerCastsAndParens(E: SubExpr); |
| 12629 | } |
| 12630 | |
| 12631 | /// Checks to see if the given LValue's Designator is at the end of the LValue's |
| 12632 | /// record layout. e.g. |
| 12633 | /// struct { struct { int a, b; } fst, snd; } obj; |
| 12634 | /// obj.fst // no |
| 12635 | /// obj.snd // yes |
| 12636 | /// obj.fst.a // no |
| 12637 | /// obj.fst.b // no |
| 12638 | /// obj.snd.a // no |
| 12639 | /// obj.snd.b // yes |
| 12640 | /// |
| 12641 | /// Please note: this function is specialized for how __builtin_object_size |
| 12642 | /// views "objects". |
| 12643 | /// |
| 12644 | /// If this encounters an invalid RecordDecl or otherwise cannot determine the |
| 12645 | /// correct result, it will always return true. |
| 12646 | static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { |
| 12647 | assert(!LVal.Designator.Invalid); |
| 12648 | |
| 12649 | auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) { |
| 12650 | const RecordDecl *Parent = FD->getParent(); |
| 12651 | if (Parent->isInvalidDecl() || Parent->isUnion()) |
| 12652 | return true; |
| 12653 | const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: Parent); |
| 12654 | return FD->getFieldIndex() + 1 == Layout.getFieldCount(); |
| 12655 | }; |
| 12656 | |
| 12657 | auto &Base = LVal.getLValueBase(); |
| 12658 | if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: Base.dyn_cast<const Expr *>())) { |
| 12659 | if (auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) { |
| 12660 | if (!IsLastOrInvalidFieldDecl(FD)) |
| 12661 | return false; |
| 12662 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: ME->getMemberDecl())) { |
| 12663 | for (auto *FD : IFD->chain()) { |
| 12664 | if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(Val: FD))) |
| 12665 | return false; |
| 12666 | } |
| 12667 | } |
| 12668 | } |
| 12669 | |
| 12670 | unsigned I = 0; |
| 12671 | QualType BaseType = getType(B: Base); |
| 12672 | if (LVal.Designator.FirstEntryIsAnUnsizedArray) { |
| 12673 | // If we don't know the array bound, conservatively assume we're looking at |
| 12674 | // the final array element. |
| 12675 | ++I; |
| 12676 | if (BaseType->isIncompleteArrayType()) |
| 12677 | BaseType = Ctx.getAsArrayType(T: BaseType)->getElementType(); |
| 12678 | else |
| 12679 | BaseType = BaseType->castAs<PointerType>()->getPointeeType(); |
| 12680 | } |
| 12681 | |
| 12682 | for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { |
| 12683 | const auto &Entry = LVal.Designator.Entries[I]; |
| 12684 | if (BaseType->isArrayType()) { |
| 12685 | // Because __builtin_object_size treats arrays as objects, we can ignore |
| 12686 | // the index iff this is the last array in the Designator. |
| 12687 | if (I + 1 == E) |
| 12688 | return true; |
| 12689 | const auto *CAT = cast<ConstantArrayType>(Val: Ctx.getAsArrayType(T: BaseType)); |
| 12690 | uint64_t Index = Entry.getAsArrayIndex(); |
| 12691 | if (Index + 1 != CAT->getZExtSize()) |
| 12692 | return false; |
| 12693 | BaseType = CAT->getElementType(); |
| 12694 | } else if (BaseType->isAnyComplexType()) { |
| 12695 | const auto *CT = BaseType->castAs<ComplexType>(); |
| 12696 | uint64_t Index = Entry.getAsArrayIndex(); |
| 12697 | if (Index != 1) |
| 12698 | return false; |
| 12699 | BaseType = CT->getElementType(); |
| 12700 | } else if (auto *FD = getAsField(E: Entry)) { |
| 12701 | if (!IsLastOrInvalidFieldDecl(FD)) |
| 12702 | return false; |
| 12703 | BaseType = FD->getType(); |
| 12704 | } else { |
| 12705 | assert(getAsBaseClass(Entry) && "Expecting cast to a base class" ); |
| 12706 | return false; |
| 12707 | } |
| 12708 | } |
| 12709 | return true; |
| 12710 | } |
| 12711 | |
| 12712 | /// Tests to see if the LValue has a user-specified designator (that isn't |
| 12713 | /// necessarily valid). Note that this always returns 'true' if the LValue has |
| 12714 | /// an unsized array as its first designator entry, because there's currently no |
| 12715 | /// way to tell if the user typed *foo or foo[0]. |
| 12716 | static bool refersToCompleteObject(const LValue &LVal) { |
| 12717 | if (LVal.Designator.Invalid) |
| 12718 | return false; |
| 12719 | |
| 12720 | if (!LVal.Designator.Entries.empty()) |
| 12721 | return LVal.Designator.isMostDerivedAnUnsizedArray(); |
| 12722 | |
| 12723 | if (!LVal.InvalidBase) |
| 12724 | return true; |
| 12725 | |
| 12726 | // If `E` is a MemberExpr, then the first part of the designator is hiding in |
| 12727 | // the LValueBase. |
| 12728 | const auto *E = LVal.Base.dyn_cast<const Expr *>(); |
| 12729 | return !E || !isa<MemberExpr>(Val: E); |
| 12730 | } |
| 12731 | |
| 12732 | /// Attempts to detect a user writing into a piece of memory that's impossible |
| 12733 | /// to figure out the size of by just using types. |
| 12734 | static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { |
| 12735 | const SubobjectDesignator &Designator = LVal.Designator; |
| 12736 | // Notes: |
| 12737 | // - Users can only write off of the end when we have an invalid base. Invalid |
| 12738 | // bases imply we don't know where the memory came from. |
| 12739 | // - We used to be a bit more aggressive here; we'd only be conservative if |
| 12740 | // the array at the end was flexible, or if it had 0 or 1 elements. This |
| 12741 | // broke some common standard library extensions (PR30346), but was |
| 12742 | // otherwise seemingly fine. It may be useful to reintroduce this behavior |
| 12743 | // with some sort of list. OTOH, it seems that GCC is always |
| 12744 | // conservative with the last element in structs (if it's an array), so our |
| 12745 | // current behavior is more compatible than an explicit list approach would |
| 12746 | // be. |
| 12747 | auto isFlexibleArrayMember = [&] { |
| 12748 | using FAMKind = LangOptions::StrictFlexArraysLevelKind; |
| 12749 | FAMKind StrictFlexArraysLevel = |
| 12750 | Ctx.getLangOpts().getStrictFlexArraysLevel(); |
| 12751 | |
| 12752 | if (Designator.isMostDerivedAnUnsizedArray()) |
| 12753 | return true; |
| 12754 | |
| 12755 | if (StrictFlexArraysLevel == FAMKind::Default) |
| 12756 | return true; |
| 12757 | |
| 12758 | if (Designator.getMostDerivedArraySize() == 0 && |
| 12759 | StrictFlexArraysLevel != FAMKind::IncompleteOnly) |
| 12760 | return true; |
| 12761 | |
| 12762 | if (Designator.getMostDerivedArraySize() == 1 && |
| 12763 | StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete) |
| 12764 | return true; |
| 12765 | |
| 12766 | return false; |
| 12767 | }; |
| 12768 | |
| 12769 | return LVal.InvalidBase && |
| 12770 | Designator.Entries.size() == Designator.MostDerivedPathLength && |
| 12771 | Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() && |
| 12772 | isDesignatorAtObjectEnd(Ctx, LVal); |
| 12773 | } |
| 12774 | |
| 12775 | /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. |
| 12776 | /// Fails if the conversion would cause loss of precision. |
| 12777 | static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, |
| 12778 | CharUnits &Result) { |
| 12779 | auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); |
| 12780 | if (Int.ugt(RHS: CharUnitsMax)) |
| 12781 | return false; |
| 12782 | Result = CharUnits::fromQuantity(Quantity: Int.getZExtValue()); |
| 12783 | return true; |
| 12784 | } |
| 12785 | |
| 12786 | /// If we're evaluating the object size of an instance of a struct that |
| 12787 | /// contains a flexible array member, add the size of the initializer. |
| 12788 | static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, |
| 12789 | const LValue &LV, CharUnits &Size) { |
| 12790 | if (!T.isNull() && T->isStructureType() && |
| 12791 | T->getAsStructureType()->getDecl()->hasFlexibleArrayMember()) |
| 12792 | if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>()) |
| 12793 | if (const auto *VD = dyn_cast<VarDecl>(Val: V)) |
| 12794 | if (VD->hasInit()) |
| 12795 | Size += VD->getFlexibleArrayInitChars(Ctx: Info.Ctx); |
| 12796 | } |
| 12797 | |
| 12798 | /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will |
| 12799 | /// determine how many bytes exist from the beginning of the object to either |
| 12800 | /// the end of the current subobject, or the end of the object itself, depending |
| 12801 | /// on what the LValue looks like + the value of Type. |
| 12802 | /// |
| 12803 | /// If this returns false, the value of Result is undefined. |
| 12804 | static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, |
| 12805 | unsigned Type, const LValue &LVal, |
| 12806 | CharUnits &EndOffset) { |
| 12807 | bool DetermineForCompleteObject = refersToCompleteObject(LVal); |
| 12808 | |
| 12809 | auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { |
| 12810 | if (Ty.isNull()) |
| 12811 | return false; |
| 12812 | |
| 12813 | Ty = Ty.getNonReferenceType(); |
| 12814 | |
| 12815 | if (Ty->isIncompleteType() || Ty->isFunctionType()) |
| 12816 | return false; |
| 12817 | |
| 12818 | return HandleSizeof(Info, Loc: ExprLoc, Type: Ty, Size&: Result); |
| 12819 | }; |
| 12820 | |
| 12821 | // We want to evaluate the size of the entire object. This is a valid fallback |
| 12822 | // for when Type=1 and the designator is invalid, because we're asked for an |
| 12823 | // upper-bound. |
| 12824 | if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { |
| 12825 | // Type=3 wants a lower bound, so we can't fall back to this. |
| 12826 | if (Type == 3 && !DetermineForCompleteObject) |
| 12827 | return false; |
| 12828 | |
| 12829 | llvm::APInt APEndOffset; |
| 12830 | if (isBaseAnAllocSizeCall(Base: LVal.getLValueBase()) && |
| 12831 | getBytesReturnedByAllocSizeCall(Ctx: Info.Ctx, LVal, Result&: APEndOffset)) |
| 12832 | return convertUnsignedAPIntToCharUnits(Int: APEndOffset, Result&: EndOffset); |
| 12833 | |
| 12834 | if (LVal.InvalidBase) |
| 12835 | return false; |
| 12836 | |
| 12837 | QualType BaseTy = getObjectType(B: LVal.getLValueBase()); |
| 12838 | const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset); |
| 12839 | addFlexibleArrayMemberInitSize(Info, T: BaseTy, LV: LVal, Size&: EndOffset); |
| 12840 | return Ret; |
| 12841 | } |
| 12842 | |
| 12843 | // We want to evaluate the size of a subobject. |
| 12844 | const SubobjectDesignator &Designator = LVal.Designator; |
| 12845 | |
| 12846 | // The following is a moderately common idiom in C: |
| 12847 | // |
| 12848 | // struct Foo { int a; char c[1]; }; |
| 12849 | // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); |
| 12850 | // strcpy(&F->c[0], Bar); |
| 12851 | // |
| 12852 | // In order to not break too much legacy code, we need to support it. |
| 12853 | if (isUserWritingOffTheEnd(Ctx: Info.Ctx, LVal)) { |
| 12854 | // If we can resolve this to an alloc_size call, we can hand that back, |
| 12855 | // because we know for certain how many bytes there are to write to. |
| 12856 | llvm::APInt APEndOffset; |
| 12857 | if (isBaseAnAllocSizeCall(Base: LVal.getLValueBase()) && |
| 12858 | getBytesReturnedByAllocSizeCall(Ctx: Info.Ctx, LVal, Result&: APEndOffset)) |
| 12859 | return convertUnsignedAPIntToCharUnits(Int: APEndOffset, Result&: EndOffset); |
| 12860 | |
| 12861 | // If we cannot determine the size of the initial allocation, then we can't |
| 12862 | // given an accurate upper-bound. However, we are still able to give |
| 12863 | // conservative lower-bounds for Type=3. |
| 12864 | if (Type == 1) |
| 12865 | return false; |
| 12866 | } |
| 12867 | |
| 12868 | CharUnits BytesPerElem; |
| 12869 | if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) |
| 12870 | return false; |
| 12871 | |
| 12872 | // According to the GCC documentation, we want the size of the subobject |
| 12873 | // denoted by the pointer. But that's not quite right -- what we actually |
| 12874 | // want is the size of the immediately-enclosing array, if there is one. |
| 12875 | int64_t ElemsRemaining; |
| 12876 | if (Designator.MostDerivedIsArrayElement && |
| 12877 | Designator.Entries.size() == Designator.MostDerivedPathLength) { |
| 12878 | uint64_t ArraySize = Designator.getMostDerivedArraySize(); |
| 12879 | uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); |
| 12880 | ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; |
| 12881 | } else { |
| 12882 | ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; |
| 12883 | } |
| 12884 | |
| 12885 | EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; |
| 12886 | return true; |
| 12887 | } |
| 12888 | |
| 12889 | /// Tries to evaluate the __builtin_object_size for @p E. If successful, |
| 12890 | /// returns true and stores the result in @p Size. |
| 12891 | /// |
| 12892 | /// If @p WasError is non-null, this will report whether the failure to evaluate |
| 12893 | /// is to be treated as an Error in IntExprEvaluator. |
| 12894 | static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, |
| 12895 | EvalInfo &Info, uint64_t &Size) { |
| 12896 | // Determine the denoted object. |
| 12897 | LValue LVal; |
| 12898 | { |
| 12899 | // The operand of __builtin_object_size is never evaluated for side-effects. |
| 12900 | // If there are any, but we can determine the pointed-to object anyway, then |
| 12901 | // ignore the side-effects. |
| 12902 | SpeculativeEvaluationRAII SpeculativeEval(Info); |
| 12903 | IgnoreSideEffectsRAII Fold(Info); |
| 12904 | |
| 12905 | if (E->isGLValue()) { |
| 12906 | // It's possible for us to be given GLValues if we're called via |
| 12907 | // Expr::tryEvaluateObjectSize. |
| 12908 | APValue RVal; |
| 12909 | if (!EvaluateAsRValue(Info, E, Result&: RVal)) |
| 12910 | return false; |
| 12911 | LVal.setFrom(Ctx&: Info.Ctx, V: RVal); |
| 12912 | } else if (!EvaluatePointer(E: ignorePointerCastsAndParens(E), Result&: LVal, Info, |
| 12913 | /*InvalidBaseOK=*/true)) |
| 12914 | return false; |
| 12915 | } |
| 12916 | |
| 12917 | // If we point to before the start of the object, there are no accessible |
| 12918 | // bytes. |
| 12919 | if (LVal.getLValueOffset().isNegative()) { |
| 12920 | Size = 0; |
| 12921 | return true; |
| 12922 | } |
| 12923 | |
| 12924 | CharUnits EndOffset; |
| 12925 | if (!determineEndOffset(Info, ExprLoc: E->getExprLoc(), Type, LVal, EndOffset)) |
| 12926 | return false; |
| 12927 | |
| 12928 | // If we've fallen outside of the end offset, just pretend there's nothing to |
| 12929 | // write to/read from. |
| 12930 | if (EndOffset <= LVal.getLValueOffset()) |
| 12931 | Size = 0; |
| 12932 | else |
| 12933 | Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); |
| 12934 | return true; |
| 12935 | } |
| 12936 | |
| 12937 | bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { |
| 12938 | if (!IsConstantEvaluatedBuiltinCall(E)) |
| 12939 | return ExprEvaluatorBaseTy::VisitCallExpr(E); |
| 12940 | return VisitBuiltinCallExpr(E, BuiltinOp: E->getBuiltinCallee()); |
| 12941 | } |
| 12942 | |
| 12943 | static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, |
| 12944 | APValue &Val, APSInt &Alignment) { |
| 12945 | QualType SrcTy = E->getArg(Arg: 0)->getType(); |
| 12946 | if (!getAlignmentArgument(E: E->getArg(Arg: 1), ForType: SrcTy, Info, Alignment)) |
| 12947 | return false; |
| 12948 | // Even though we are evaluating integer expressions we could get a pointer |
| 12949 | // argument for the __builtin_is_aligned() case. |
| 12950 | if (SrcTy->isPointerType()) { |
| 12951 | LValue Ptr; |
| 12952 | if (!EvaluatePointer(E: E->getArg(Arg: 0), Result&: Ptr, Info)) |
| 12953 | return false; |
| 12954 | Ptr.moveInto(V&: Val); |
| 12955 | } else if (!SrcTy->isIntegralOrEnumerationType()) { |
| 12956 | Info.FFDiag(E: E->getArg(Arg: 0)); |
| 12957 | return false; |
| 12958 | } else { |
| 12959 | APSInt SrcInt; |
| 12960 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: SrcInt, Info)) |
| 12961 | return false; |
| 12962 | assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && |
| 12963 | "Bit widths must be the same" ); |
| 12964 | Val = APValue(SrcInt); |
| 12965 | } |
| 12966 | assert(Val.hasValue()); |
| 12967 | return true; |
| 12968 | } |
| 12969 | |
| 12970 | bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, |
| 12971 | unsigned BuiltinOp) { |
| 12972 | switch (BuiltinOp) { |
| 12973 | default: |
| 12974 | return false; |
| 12975 | |
| 12976 | case Builtin::BI__builtin_dynamic_object_size: |
| 12977 | case Builtin::BI__builtin_object_size: { |
| 12978 | // The type was checked when we built the expression. |
| 12979 | unsigned Type = |
| 12980 | E->getArg(Arg: 1)->EvaluateKnownConstInt(Ctx: Info.Ctx).getZExtValue(); |
| 12981 | assert(Type <= 3 && "unexpected type" ); |
| 12982 | |
| 12983 | uint64_t Size; |
| 12984 | if (tryEvaluateBuiltinObjectSize(E: E->getArg(Arg: 0), Type, Info, Size)) |
| 12985 | return Success(Value: Size, E); |
| 12986 | |
| 12987 | if (E->getArg(Arg: 0)->HasSideEffects(Ctx: Info.Ctx)) |
| 12988 | return Success(Value: (Type & 2) ? 0 : -1, E); |
| 12989 | |
| 12990 | // Expression had no side effects, but we couldn't statically determine the |
| 12991 | // size of the referenced object. |
| 12992 | switch (Info.EvalMode) { |
| 12993 | case EvalInfo::EM_ConstantExpression: |
| 12994 | case EvalInfo::EM_ConstantFold: |
| 12995 | case EvalInfo::EM_IgnoreSideEffects: |
| 12996 | // Leave it to IR generation. |
| 12997 | return Error(E); |
| 12998 | case EvalInfo::EM_ConstantExpressionUnevaluated: |
| 12999 | // Reduce it to a constant now. |
| 13000 | return Success(Value: (Type & 2) ? 0 : -1, E); |
| 13001 | } |
| 13002 | |
| 13003 | llvm_unreachable("unexpected EvalMode" ); |
| 13004 | } |
| 13005 | |
| 13006 | case Builtin::BI__builtin_os_log_format_buffer_size: { |
| 13007 | analyze_os_log::OSLogBufferLayout Layout; |
| 13008 | analyze_os_log::computeOSLogBufferLayout(Ctx&: Info.Ctx, E, layout&: Layout); |
| 13009 | return Success(Value: Layout.size().getQuantity(), E); |
| 13010 | } |
| 13011 | |
| 13012 | case Builtin::BI__builtin_is_aligned: { |
| 13013 | APValue Src; |
| 13014 | APSInt Alignment; |
| 13015 | if (!getBuiltinAlignArguments(E, Info, Val&: Src, Alignment)) |
| 13016 | return false; |
| 13017 | if (Src.isLValue()) { |
| 13018 | // If we evaluated a pointer, check the minimum known alignment. |
| 13019 | LValue Ptr; |
| 13020 | Ptr.setFrom(Ctx&: Info.Ctx, V: Src); |
| 13021 | CharUnits BaseAlignment = getBaseAlignment(Info, Value: Ptr); |
| 13022 | CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(offset: Ptr.Offset); |
| 13023 | // We can return true if the known alignment at the computed offset is |
| 13024 | // greater than the requested alignment. |
| 13025 | assert(PtrAlign.isPowerOfTwo()); |
| 13026 | assert(Alignment.isPowerOf2()); |
| 13027 | if (PtrAlign.getQuantity() >= Alignment) |
| 13028 | return Success(Value: 1, E); |
| 13029 | // If the alignment is not known to be sufficient, some cases could still |
| 13030 | // be aligned at run time. However, if the requested alignment is less or |
| 13031 | // equal to the base alignment and the offset is not aligned, we know that |
| 13032 | // the run-time value can never be aligned. |
| 13033 | if (BaseAlignment.getQuantity() >= Alignment && |
| 13034 | PtrAlign.getQuantity() < Alignment) |
| 13035 | return Success(Value: 0, E); |
| 13036 | // Otherwise we can't infer whether the value is sufficiently aligned. |
| 13037 | // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) |
| 13038 | // in cases where we can't fully evaluate the pointer. |
| 13039 | Info.FFDiag(E: E->getArg(Arg: 0), DiagId: diag::note_constexpr_alignment_compute) |
| 13040 | << Alignment; |
| 13041 | return false; |
| 13042 | } |
| 13043 | assert(Src.isInt()); |
| 13044 | return Success(Value: (Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); |
| 13045 | } |
| 13046 | case Builtin::BI__builtin_align_up: { |
| 13047 | APValue Src; |
| 13048 | APSInt Alignment; |
| 13049 | if (!getBuiltinAlignArguments(E, Info, Val&: Src, Alignment)) |
| 13050 | return false; |
| 13051 | if (!Src.isInt()) |
| 13052 | return Error(E); |
| 13053 | APSInt AlignedVal = |
| 13054 | APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), |
| 13055 | Src.getInt().isUnsigned()); |
| 13056 | assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); |
| 13057 | return Success(SI: AlignedVal, E); |
| 13058 | } |
| 13059 | case Builtin::BI__builtin_align_down: { |
| 13060 | APValue Src; |
| 13061 | APSInt Alignment; |
| 13062 | if (!getBuiltinAlignArguments(E, Info, Val&: Src, Alignment)) |
| 13063 | return false; |
| 13064 | if (!Src.isInt()) |
| 13065 | return Error(E); |
| 13066 | APSInt AlignedVal = |
| 13067 | APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); |
| 13068 | assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); |
| 13069 | return Success(SI: AlignedVal, E); |
| 13070 | } |
| 13071 | |
| 13072 | case Builtin::BI__builtin_bitreverse8: |
| 13073 | case Builtin::BI__builtin_bitreverse16: |
| 13074 | case Builtin::BI__builtin_bitreverse32: |
| 13075 | case Builtin::BI__builtin_bitreverse64: |
| 13076 | case Builtin::BI__builtin_elementwise_bitreverse: { |
| 13077 | APSInt Val; |
| 13078 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13079 | return false; |
| 13080 | |
| 13081 | return Success(I: Val.reverseBits(), E); |
| 13082 | } |
| 13083 | |
| 13084 | case Builtin::BI__builtin_bswap16: |
| 13085 | case Builtin::BI__builtin_bswap32: |
| 13086 | case Builtin::BI__builtin_bswap64: { |
| 13087 | APSInt Val; |
| 13088 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13089 | return false; |
| 13090 | |
| 13091 | return Success(I: Val.byteSwap(), E); |
| 13092 | } |
| 13093 | |
| 13094 | case Builtin::BI__builtin_classify_type: |
| 13095 | return Success(Value: (int)EvaluateBuiltinClassifyType(E, LangOpts: Info.getLangOpts()), E); |
| 13096 | |
| 13097 | case Builtin::BI__builtin_clrsb: |
| 13098 | case Builtin::BI__builtin_clrsbl: |
| 13099 | case Builtin::BI__builtin_clrsbll: { |
| 13100 | APSInt Val; |
| 13101 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13102 | return false; |
| 13103 | |
| 13104 | return Success(Value: Val.getBitWidth() - Val.getSignificantBits(), E); |
| 13105 | } |
| 13106 | |
| 13107 | case Builtin::BI__builtin_clz: |
| 13108 | case Builtin::BI__builtin_clzl: |
| 13109 | case Builtin::BI__builtin_clzll: |
| 13110 | case Builtin::BI__builtin_clzs: |
| 13111 | case Builtin::BI__builtin_clzg: |
| 13112 | case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes |
| 13113 | case Builtin::BI__lzcnt: |
| 13114 | case Builtin::BI__lzcnt64: { |
| 13115 | APSInt Val; |
| 13116 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13117 | return false; |
| 13118 | |
| 13119 | std::optional<APSInt> Fallback; |
| 13120 | if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) { |
| 13121 | APSInt FallbackTemp; |
| 13122 | if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: FallbackTemp, Info)) |
| 13123 | return false; |
| 13124 | Fallback = FallbackTemp; |
| 13125 | } |
| 13126 | |
| 13127 | if (!Val) { |
| 13128 | if (Fallback) |
| 13129 | return Success(SI: *Fallback, E); |
| 13130 | |
| 13131 | // When the argument is 0, the result of GCC builtins is undefined, |
| 13132 | // whereas for Microsoft intrinsics, the result is the bit-width of the |
| 13133 | // argument. |
| 13134 | bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 && |
| 13135 | BuiltinOp != Builtin::BI__lzcnt && |
| 13136 | BuiltinOp != Builtin::BI__lzcnt64; |
| 13137 | |
| 13138 | if (ZeroIsUndefined) |
| 13139 | return Error(E); |
| 13140 | } |
| 13141 | |
| 13142 | return Success(Value: Val.countl_zero(), E); |
| 13143 | } |
| 13144 | |
| 13145 | case Builtin::BI__builtin_constant_p: { |
| 13146 | const Expr *Arg = E->getArg(Arg: 0); |
| 13147 | if (EvaluateBuiltinConstantP(Info, Arg)) |
| 13148 | return Success(Value: true, E); |
| 13149 | if (Info.InConstantContext || Arg->HasSideEffects(Ctx: Info.Ctx)) { |
| 13150 | // Outside a constant context, eagerly evaluate to false in the presence |
| 13151 | // of side-effects in order to avoid -Wunsequenced false-positives in |
| 13152 | // a branch on __builtin_constant_p(expr). |
| 13153 | return Success(Value: false, E); |
| 13154 | } |
| 13155 | Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 13156 | return false; |
| 13157 | } |
| 13158 | |
| 13159 | case Builtin::BI__noop: |
| 13160 | // __noop always evaluates successfully and returns 0. |
| 13161 | return Success(Value: 0, E); |
| 13162 | |
| 13163 | case Builtin::BI__builtin_is_constant_evaluated: { |
| 13164 | const auto *Callee = Info.CurrentCall->getCallee(); |
| 13165 | if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && |
| 13166 | (Info.CallStackDepth == 1 || |
| 13167 | (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && |
| 13168 | Callee->getIdentifier() && |
| 13169 | Callee->getIdentifier()->isStr(Str: "is_constant_evaluated" )))) { |
| 13170 | // FIXME: Find a better way to avoid duplicated diagnostics. |
| 13171 | if (Info.EvalStatus.Diag) |
| 13172 | Info.report(Loc: (Info.CallStackDepth == 1) |
| 13173 | ? E->getExprLoc() |
| 13174 | : Info.CurrentCall->getCallRange().getBegin(), |
| 13175 | DiagId: diag::warn_is_constant_evaluated_always_true_constexpr) |
| 13176 | << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" |
| 13177 | : "std::is_constant_evaluated" ); |
| 13178 | } |
| 13179 | |
| 13180 | return Success(Value: Info.InConstantContext, E); |
| 13181 | } |
| 13182 | |
| 13183 | case Builtin::BI__builtin_is_within_lifetime: |
| 13184 | if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E)) |
| 13185 | return Success(Value: *result, E); |
| 13186 | return false; |
| 13187 | |
| 13188 | case Builtin::BI__builtin_ctz: |
| 13189 | case Builtin::BI__builtin_ctzl: |
| 13190 | case Builtin::BI__builtin_ctzll: |
| 13191 | case Builtin::BI__builtin_ctzs: |
| 13192 | case Builtin::BI__builtin_ctzg: { |
| 13193 | APSInt Val; |
| 13194 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13195 | return false; |
| 13196 | |
| 13197 | std::optional<APSInt> Fallback; |
| 13198 | if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) { |
| 13199 | APSInt FallbackTemp; |
| 13200 | if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: FallbackTemp, Info)) |
| 13201 | return false; |
| 13202 | Fallback = FallbackTemp; |
| 13203 | } |
| 13204 | |
| 13205 | if (!Val) { |
| 13206 | if (Fallback) |
| 13207 | return Success(SI: *Fallback, E); |
| 13208 | |
| 13209 | return Error(E); |
| 13210 | } |
| 13211 | |
| 13212 | return Success(Value: Val.countr_zero(), E); |
| 13213 | } |
| 13214 | |
| 13215 | case Builtin::BI__builtin_eh_return_data_regno: { |
| 13216 | int Operand = E->getArg(Arg: 0)->EvaluateKnownConstInt(Ctx: Info.Ctx).getZExtValue(); |
| 13217 | Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(RegNo: Operand); |
| 13218 | return Success(Value: Operand, E); |
| 13219 | } |
| 13220 | |
| 13221 | case Builtin::BI__builtin_expect: |
| 13222 | case Builtin::BI__builtin_expect_with_probability: |
| 13223 | return Visit(S: E->getArg(Arg: 0)); |
| 13224 | |
| 13225 | case Builtin::BI__builtin_ptrauth_string_discriminator: { |
| 13226 | const auto *Literal = |
| 13227 | cast<StringLiteral>(Val: E->getArg(Arg: 0)->IgnoreParenImpCasts()); |
| 13228 | uint64_t Result = getPointerAuthStableSipHash(S: Literal->getString()); |
| 13229 | return Success(Value: Result, E); |
| 13230 | } |
| 13231 | |
| 13232 | case Builtin::BI__builtin_ffs: |
| 13233 | case Builtin::BI__builtin_ffsl: |
| 13234 | case Builtin::BI__builtin_ffsll: { |
| 13235 | APSInt Val; |
| 13236 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13237 | return false; |
| 13238 | |
| 13239 | unsigned N = Val.countr_zero(); |
| 13240 | return Success(Value: N == Val.getBitWidth() ? 0 : N + 1, E); |
| 13241 | } |
| 13242 | |
| 13243 | case Builtin::BI__builtin_fpclassify: { |
| 13244 | APFloat Val(0.0); |
| 13245 | if (!EvaluateFloat(E: E->getArg(Arg: 5), Result&: Val, Info)) |
| 13246 | return false; |
| 13247 | unsigned Arg; |
| 13248 | switch (Val.getCategory()) { |
| 13249 | case APFloat::fcNaN: Arg = 0; break; |
| 13250 | case APFloat::fcInfinity: Arg = 1; break; |
| 13251 | case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; |
| 13252 | case APFloat::fcZero: Arg = 4; break; |
| 13253 | } |
| 13254 | return Visit(S: E->getArg(Arg)); |
| 13255 | } |
| 13256 | |
| 13257 | case Builtin::BI__builtin_isinf_sign: { |
| 13258 | APFloat Val(0.0); |
| 13259 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13260 | Success(Value: Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); |
| 13261 | } |
| 13262 | |
| 13263 | case Builtin::BI__builtin_isinf: { |
| 13264 | APFloat Val(0.0); |
| 13265 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13266 | Success(Value: Val.isInfinity() ? 1 : 0, E); |
| 13267 | } |
| 13268 | |
| 13269 | case Builtin::BI__builtin_isfinite: { |
| 13270 | APFloat Val(0.0); |
| 13271 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13272 | Success(Value: Val.isFinite() ? 1 : 0, E); |
| 13273 | } |
| 13274 | |
| 13275 | case Builtin::BI__builtin_isnan: { |
| 13276 | APFloat Val(0.0); |
| 13277 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13278 | Success(Value: Val.isNaN() ? 1 : 0, E); |
| 13279 | } |
| 13280 | |
| 13281 | case Builtin::BI__builtin_isnormal: { |
| 13282 | APFloat Val(0.0); |
| 13283 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13284 | Success(Value: Val.isNormal() ? 1 : 0, E); |
| 13285 | } |
| 13286 | |
| 13287 | case Builtin::BI__builtin_issubnormal: { |
| 13288 | APFloat Val(0.0); |
| 13289 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13290 | Success(Value: Val.isDenormal() ? 1 : 0, E); |
| 13291 | } |
| 13292 | |
| 13293 | case Builtin::BI__builtin_iszero: { |
| 13294 | APFloat Val(0.0); |
| 13295 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13296 | Success(Value: Val.isZero() ? 1 : 0, E); |
| 13297 | } |
| 13298 | |
| 13299 | case Builtin::BI__builtin_signbit: |
| 13300 | case Builtin::BI__builtin_signbitf: |
| 13301 | case Builtin::BI__builtin_signbitl: { |
| 13302 | APFloat Val(0.0); |
| 13303 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13304 | Success(Value: Val.isNegative() ? 1 : 0, E); |
| 13305 | } |
| 13306 | |
| 13307 | case Builtin::BI__builtin_isgreater: |
| 13308 | case Builtin::BI__builtin_isgreaterequal: |
| 13309 | case Builtin::BI__builtin_isless: |
| 13310 | case Builtin::BI__builtin_islessequal: |
| 13311 | case Builtin::BI__builtin_islessgreater: |
| 13312 | case Builtin::BI__builtin_isunordered: { |
| 13313 | APFloat LHS(0.0); |
| 13314 | APFloat RHS(0.0); |
| 13315 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result&: LHS, Info) || |
| 13316 | !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 13317 | return false; |
| 13318 | |
| 13319 | return Success( |
| 13320 | Value: [&] { |
| 13321 | switch (BuiltinOp) { |
| 13322 | case Builtin::BI__builtin_isgreater: |
| 13323 | return LHS > RHS; |
| 13324 | case Builtin::BI__builtin_isgreaterequal: |
| 13325 | return LHS >= RHS; |
| 13326 | case Builtin::BI__builtin_isless: |
| 13327 | return LHS < RHS; |
| 13328 | case Builtin::BI__builtin_islessequal: |
| 13329 | return LHS <= RHS; |
| 13330 | case Builtin::BI__builtin_islessgreater: { |
| 13331 | APFloat::cmpResult cmp = LHS.compare(RHS); |
| 13332 | return cmp == APFloat::cmpResult::cmpLessThan || |
| 13333 | cmp == APFloat::cmpResult::cmpGreaterThan; |
| 13334 | } |
| 13335 | case Builtin::BI__builtin_isunordered: |
| 13336 | return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered; |
| 13337 | default: |
| 13338 | llvm_unreachable("Unexpected builtin ID: Should be a floating " |
| 13339 | "point comparison function" ); |
| 13340 | } |
| 13341 | }() |
| 13342 | ? 1 |
| 13343 | : 0, |
| 13344 | E); |
| 13345 | } |
| 13346 | |
| 13347 | case Builtin::BI__builtin_issignaling: { |
| 13348 | APFloat Val(0.0); |
| 13349 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13350 | Success(Value: Val.isSignaling() ? 1 : 0, E); |
| 13351 | } |
| 13352 | |
| 13353 | case Builtin::BI__builtin_isfpclass: { |
| 13354 | APSInt MaskVal; |
| 13355 | if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: MaskVal, Info)) |
| 13356 | return false; |
| 13357 | unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue()); |
| 13358 | APFloat Val(0.0); |
| 13359 | return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) && |
| 13360 | Success(Value: (Val.classify() & Test) ? 1 : 0, E); |
| 13361 | } |
| 13362 | |
| 13363 | case Builtin::BI__builtin_parity: |
| 13364 | case Builtin::BI__builtin_parityl: |
| 13365 | case Builtin::BI__builtin_parityll: { |
| 13366 | APSInt Val; |
| 13367 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13368 | return false; |
| 13369 | |
| 13370 | return Success(Value: Val.popcount() % 2, E); |
| 13371 | } |
| 13372 | |
| 13373 | case Builtin::BI__builtin_abs: |
| 13374 | case Builtin::BI__builtin_labs: |
| 13375 | case Builtin::BI__builtin_llabs: { |
| 13376 | APSInt Val; |
| 13377 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13378 | return false; |
| 13379 | if (Val == APSInt(APInt::getSignedMinValue(numBits: Val.getBitWidth()), |
| 13380 | /*IsUnsigned=*/false)) |
| 13381 | return false; |
| 13382 | if (Val.isNegative()) |
| 13383 | Val.negate(); |
| 13384 | return Success(SI: Val, E); |
| 13385 | } |
| 13386 | |
| 13387 | case Builtin::BI__builtin_popcount: |
| 13388 | case Builtin::BI__builtin_popcountl: |
| 13389 | case Builtin::BI__builtin_popcountll: |
| 13390 | case Builtin::BI__builtin_popcountg: |
| 13391 | case Builtin::BI__builtin_elementwise_popcount: |
| 13392 | case Builtin::BI__popcnt16: // Microsoft variants of popcount |
| 13393 | case Builtin::BI__popcnt: |
| 13394 | case Builtin::BI__popcnt64: { |
| 13395 | APSInt Val; |
| 13396 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13397 | return false; |
| 13398 | |
| 13399 | return Success(Value: Val.popcount(), E); |
| 13400 | } |
| 13401 | |
| 13402 | case Builtin::BI__builtin_rotateleft8: |
| 13403 | case Builtin::BI__builtin_rotateleft16: |
| 13404 | case Builtin::BI__builtin_rotateleft32: |
| 13405 | case Builtin::BI__builtin_rotateleft64: |
| 13406 | case Builtin::BI_rotl8: // Microsoft variants of rotate right |
| 13407 | case Builtin::BI_rotl16: |
| 13408 | case Builtin::BI_rotl: |
| 13409 | case Builtin::BI_lrotl: |
| 13410 | case Builtin::BI_rotl64: { |
| 13411 | APSInt Val, Amt; |
| 13412 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) || |
| 13413 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Amt, Info)) |
| 13414 | return false; |
| 13415 | |
| 13416 | return Success(I: Val.rotl(rotateAmt: Amt.urem(RHS: Val.getBitWidth())), E); |
| 13417 | } |
| 13418 | |
| 13419 | case Builtin::BI__builtin_rotateright8: |
| 13420 | case Builtin::BI__builtin_rotateright16: |
| 13421 | case Builtin::BI__builtin_rotateright32: |
| 13422 | case Builtin::BI__builtin_rotateright64: |
| 13423 | case Builtin::BI_rotr8: // Microsoft variants of rotate right |
| 13424 | case Builtin::BI_rotr16: |
| 13425 | case Builtin::BI_rotr: |
| 13426 | case Builtin::BI_lrotr: |
| 13427 | case Builtin::BI_rotr64: { |
| 13428 | APSInt Val, Amt; |
| 13429 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) || |
| 13430 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Amt, Info)) |
| 13431 | return false; |
| 13432 | |
| 13433 | return Success(I: Val.rotr(rotateAmt: Amt.urem(RHS: Val.getBitWidth())), E); |
| 13434 | } |
| 13435 | |
| 13436 | case Builtin::BI__builtin_elementwise_add_sat: { |
| 13437 | APSInt LHS, RHS; |
| 13438 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: LHS, Info) || |
| 13439 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 13440 | return false; |
| 13441 | |
| 13442 | APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS); |
| 13443 | return Success(SI: APSInt(Result, !LHS.isSigned()), E); |
| 13444 | } |
| 13445 | case Builtin::BI__builtin_elementwise_sub_sat: { |
| 13446 | APSInt LHS, RHS; |
| 13447 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: LHS, Info) || |
| 13448 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 13449 | return false; |
| 13450 | |
| 13451 | APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS); |
| 13452 | return Success(SI: APSInt(Result, !LHS.isSigned()), E); |
| 13453 | } |
| 13454 | |
| 13455 | case Builtin::BIstrlen: |
| 13456 | case Builtin::BIwcslen: |
| 13457 | // A call to strlen is not a constant expression. |
| 13458 | if (Info.getLangOpts().CPlusPlus11) |
| 13459 | Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function) |
| 13460 | << /*isConstexpr*/ 0 << /*isConstructor*/ 0 |
| 13461 | << Info.Ctx.BuiltinInfo.getQuotedName(ID: BuiltinOp); |
| 13462 | else |
| 13463 | Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 13464 | [[fallthrough]]; |
| 13465 | case Builtin::BI__builtin_strlen: |
| 13466 | case Builtin::BI__builtin_wcslen: { |
| 13467 | // As an extension, we support __builtin_strlen() as a constant expression, |
| 13468 | // and support folding strlen() to a constant. |
| 13469 | uint64_t StrLen; |
| 13470 | if (EvaluateBuiltinStrLen(E: E->getArg(Arg: 0), Result&: StrLen, Info)) |
| 13471 | return Success(Value: StrLen, E); |
| 13472 | return false; |
| 13473 | } |
| 13474 | |
| 13475 | case Builtin::BIstrcmp: |
| 13476 | case Builtin::BIwcscmp: |
| 13477 | case Builtin::BIstrncmp: |
| 13478 | case Builtin::BIwcsncmp: |
| 13479 | case Builtin::BImemcmp: |
| 13480 | case Builtin::BIbcmp: |
| 13481 | case Builtin::BIwmemcmp: |
| 13482 | // A call to strlen is not a constant expression. |
| 13483 | if (Info.getLangOpts().CPlusPlus11) |
| 13484 | Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function) |
| 13485 | << /*isConstexpr*/ 0 << /*isConstructor*/ 0 |
| 13486 | << Info.Ctx.BuiltinInfo.getQuotedName(ID: BuiltinOp); |
| 13487 | else |
| 13488 | Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 13489 | [[fallthrough]]; |
| 13490 | case Builtin::BI__builtin_strcmp: |
| 13491 | case Builtin::BI__builtin_wcscmp: |
| 13492 | case Builtin::BI__builtin_strncmp: |
| 13493 | case Builtin::BI__builtin_wcsncmp: |
| 13494 | case Builtin::BI__builtin_memcmp: |
| 13495 | case Builtin::BI__builtin_bcmp: |
| 13496 | case Builtin::BI__builtin_wmemcmp: { |
| 13497 | LValue String1, String2; |
| 13498 | if (!EvaluatePointer(E: E->getArg(Arg: 0), Result&: String1, Info) || |
| 13499 | !EvaluatePointer(E: E->getArg(Arg: 1), Result&: String2, Info)) |
| 13500 | return false; |
| 13501 | |
| 13502 | uint64_t MaxLength = uint64_t(-1); |
| 13503 | if (BuiltinOp != Builtin::BIstrcmp && |
| 13504 | BuiltinOp != Builtin::BIwcscmp && |
| 13505 | BuiltinOp != Builtin::BI__builtin_strcmp && |
| 13506 | BuiltinOp != Builtin::BI__builtin_wcscmp) { |
| 13507 | APSInt N; |
| 13508 | if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: N, Info)) |
| 13509 | return false; |
| 13510 | MaxLength = N.getZExtValue(); |
| 13511 | } |
| 13512 | |
| 13513 | // Empty substrings compare equal by definition. |
| 13514 | if (MaxLength == 0u) |
| 13515 | return Success(Value: 0, E); |
| 13516 | |
| 13517 | if (!String1.checkNullPointerForFoldAccess(Info, E, AK: AK_Read) || |
| 13518 | !String2.checkNullPointerForFoldAccess(Info, E, AK: AK_Read) || |
| 13519 | String1.Designator.Invalid || String2.Designator.Invalid) |
| 13520 | return false; |
| 13521 | |
| 13522 | QualType CharTy1 = String1.Designator.getType(Ctx&: Info.Ctx); |
| 13523 | QualType CharTy2 = String2.Designator.getType(Ctx&: Info.Ctx); |
| 13524 | |
| 13525 | bool IsRawByte = BuiltinOp == Builtin::BImemcmp || |
| 13526 | BuiltinOp == Builtin::BIbcmp || |
| 13527 | BuiltinOp == Builtin::BI__builtin_memcmp || |
| 13528 | BuiltinOp == Builtin::BI__builtin_bcmp; |
| 13529 | |
| 13530 | assert(IsRawByte || |
| 13531 | (Info.Ctx.hasSameUnqualifiedType( |
| 13532 | CharTy1, E->getArg(0)->getType()->getPointeeType()) && |
| 13533 | Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); |
| 13534 | |
| 13535 | // For memcmp, allow comparing any arrays of '[[un]signed] char' or |
| 13536 | // 'char8_t', but no other types. |
| 13537 | if (IsRawByte && |
| 13538 | !(isOneByteCharacterType(T: CharTy1) && isOneByteCharacterType(T: CharTy2))) { |
| 13539 | // FIXME: Consider using our bit_cast implementation to support this. |
| 13540 | Info.FFDiag(E, DiagId: diag::note_constexpr_memcmp_unsupported) |
| 13541 | << Info.Ctx.BuiltinInfo.getQuotedName(ID: BuiltinOp) << CharTy1 |
| 13542 | << CharTy2; |
| 13543 | return false; |
| 13544 | } |
| 13545 | |
| 13546 | const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { |
| 13547 | return handleLValueToRValueConversion(Info, Conv: E, Type: CharTy1, LVal: String1, RVal&: Char1) && |
| 13548 | handleLValueToRValueConversion(Info, Conv: E, Type: CharTy2, LVal: String2, RVal&: Char2) && |
| 13549 | Char1.isInt() && Char2.isInt(); |
| 13550 | }; |
| 13551 | const auto &AdvanceElems = [&] { |
| 13552 | return HandleLValueArrayAdjustment(Info, E, LVal&: String1, EltTy: CharTy1, Adjustment: 1) && |
| 13553 | HandleLValueArrayAdjustment(Info, E, LVal&: String2, EltTy: CharTy2, Adjustment: 1); |
| 13554 | }; |
| 13555 | |
| 13556 | bool StopAtNull = |
| 13557 | (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && |
| 13558 | BuiltinOp != Builtin::BIwmemcmp && |
| 13559 | BuiltinOp != Builtin::BI__builtin_memcmp && |
| 13560 | BuiltinOp != Builtin::BI__builtin_bcmp && |
| 13561 | BuiltinOp != Builtin::BI__builtin_wmemcmp); |
| 13562 | bool IsWide = BuiltinOp == Builtin::BIwcscmp || |
| 13563 | BuiltinOp == Builtin::BIwcsncmp || |
| 13564 | BuiltinOp == Builtin::BIwmemcmp || |
| 13565 | BuiltinOp == Builtin::BI__builtin_wcscmp || |
| 13566 | BuiltinOp == Builtin::BI__builtin_wcsncmp || |
| 13567 | BuiltinOp == Builtin::BI__builtin_wmemcmp; |
| 13568 | |
| 13569 | for (; MaxLength; --MaxLength) { |
| 13570 | APValue Char1, Char2; |
| 13571 | if (!ReadCurElems(Char1, Char2)) |
| 13572 | return false; |
| 13573 | if (Char1.getInt().ne(RHS: Char2.getInt())) { |
| 13574 | if (IsWide) // wmemcmp compares with wchar_t signedness. |
| 13575 | return Success(Value: Char1.getInt() < Char2.getInt() ? -1 : 1, E); |
| 13576 | // memcmp always compares unsigned chars. |
| 13577 | return Success(Value: Char1.getInt().ult(RHS: Char2.getInt()) ? -1 : 1, E); |
| 13578 | } |
| 13579 | if (StopAtNull && !Char1.getInt()) |
| 13580 | return Success(Value: 0, E); |
| 13581 | assert(!(StopAtNull && !Char2.getInt())); |
| 13582 | if (!AdvanceElems()) |
| 13583 | return false; |
| 13584 | } |
| 13585 | // We hit the strncmp / memcmp limit. |
| 13586 | return Success(Value: 0, E); |
| 13587 | } |
| 13588 | |
| 13589 | case Builtin::BI__atomic_always_lock_free: |
| 13590 | case Builtin::BI__atomic_is_lock_free: |
| 13591 | case Builtin::BI__c11_atomic_is_lock_free: { |
| 13592 | APSInt SizeVal; |
| 13593 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: SizeVal, Info)) |
| 13594 | return false; |
| 13595 | |
| 13596 | // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power |
| 13597 | // of two less than or equal to the maximum inline atomic width, we know it |
| 13598 | // is lock-free. If the size isn't a power of two, or greater than the |
| 13599 | // maximum alignment where we promote atomics, we know it is not lock-free |
| 13600 | // (at least not in the sense of atomic_is_lock_free). Otherwise, |
| 13601 | // the answer can only be determined at runtime; for example, 16-byte |
| 13602 | // atomics have lock-free implementations on some, but not all, |
| 13603 | // x86-64 processors. |
| 13604 | |
| 13605 | // Check power-of-two. |
| 13606 | CharUnits Size = CharUnits::fromQuantity(Quantity: SizeVal.getZExtValue()); |
| 13607 | if (Size.isPowerOfTwo()) { |
| 13608 | // Check against inlining width. |
| 13609 | unsigned InlineWidthBits = |
| 13610 | Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); |
| 13611 | if (Size <= Info.Ctx.toCharUnitsFromBits(BitSize: InlineWidthBits)) { |
| 13612 | if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || |
| 13613 | Size == CharUnits::One()) |
| 13614 | return Success(Value: 1, E); |
| 13615 | |
| 13616 | // If the pointer argument can be evaluated to a compile-time constant |
| 13617 | // integer (or nullptr), check if that value is appropriately aligned. |
| 13618 | const Expr *PtrArg = E->getArg(Arg: 1); |
| 13619 | Expr::EvalResult ExprResult; |
| 13620 | APSInt IntResult; |
| 13621 | if (PtrArg->EvaluateAsRValue(Result&: ExprResult, Ctx: Info.Ctx) && |
| 13622 | ExprResult.Val.toIntegralConstant(Result&: IntResult, SrcTy: PtrArg->getType(), |
| 13623 | Ctx: Info.Ctx) && |
| 13624 | IntResult.isAligned(A: Size.getAsAlign())) |
| 13625 | return Success(Value: 1, E); |
| 13626 | |
| 13627 | // Otherwise, check if the type's alignment against Size. |
| 13628 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: PtrArg)) { |
| 13629 | // Drop the potential implicit-cast to 'const volatile void*', getting |
| 13630 | // the underlying type. |
| 13631 | if (ICE->getCastKind() == CK_BitCast) |
| 13632 | PtrArg = ICE->getSubExpr(); |
| 13633 | } |
| 13634 | |
| 13635 | if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) { |
| 13636 | QualType PointeeType = PtrTy->getPointeeType(); |
| 13637 | if (!PointeeType->isIncompleteType() && |
| 13638 | Info.Ctx.getTypeAlignInChars(T: PointeeType) >= Size) { |
| 13639 | // OK, we will inline operations on this object. |
| 13640 | return Success(Value: 1, E); |
| 13641 | } |
| 13642 | } |
| 13643 | } |
| 13644 | } |
| 13645 | |
| 13646 | return BuiltinOp == Builtin::BI__atomic_always_lock_free ? |
| 13647 | Success(Value: 0, E) : Error(E); |
| 13648 | } |
| 13649 | case Builtin::BI__builtin_addcb: |
| 13650 | case Builtin::BI__builtin_addcs: |
| 13651 | case Builtin::BI__builtin_addc: |
| 13652 | case Builtin::BI__builtin_addcl: |
| 13653 | case Builtin::BI__builtin_addcll: |
| 13654 | case Builtin::BI__builtin_subcb: |
| 13655 | case Builtin::BI__builtin_subcs: |
| 13656 | case Builtin::BI__builtin_subc: |
| 13657 | case Builtin::BI__builtin_subcl: |
| 13658 | case Builtin::BI__builtin_subcll: { |
| 13659 | LValue CarryOutLValue; |
| 13660 | APSInt LHS, RHS, CarryIn, CarryOut, Result; |
| 13661 | QualType ResultType = E->getArg(Arg: 0)->getType(); |
| 13662 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: LHS, Info) || |
| 13663 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: RHS, Info) || |
| 13664 | !EvaluateInteger(E: E->getArg(Arg: 2), Result&: CarryIn, Info) || |
| 13665 | !EvaluatePointer(E: E->getArg(Arg: 3), Result&: CarryOutLValue, Info)) |
| 13666 | return false; |
| 13667 | // Copy the number of bits and sign. |
| 13668 | Result = LHS; |
| 13669 | CarryOut = LHS; |
| 13670 | |
| 13671 | bool FirstOverflowed = false; |
| 13672 | bool SecondOverflowed = false; |
| 13673 | switch (BuiltinOp) { |
| 13674 | default: |
| 13675 | llvm_unreachable("Invalid value for BuiltinOp" ); |
| 13676 | case Builtin::BI__builtin_addcb: |
| 13677 | case Builtin::BI__builtin_addcs: |
| 13678 | case Builtin::BI__builtin_addc: |
| 13679 | case Builtin::BI__builtin_addcl: |
| 13680 | case Builtin::BI__builtin_addcll: |
| 13681 | Result = |
| 13682 | LHS.uadd_ov(RHS, Overflow&: FirstOverflowed).uadd_ov(RHS: CarryIn, Overflow&: SecondOverflowed); |
| 13683 | break; |
| 13684 | case Builtin::BI__builtin_subcb: |
| 13685 | case Builtin::BI__builtin_subcs: |
| 13686 | case Builtin::BI__builtin_subc: |
| 13687 | case Builtin::BI__builtin_subcl: |
| 13688 | case Builtin::BI__builtin_subcll: |
| 13689 | Result = |
| 13690 | LHS.usub_ov(RHS, Overflow&: FirstOverflowed).usub_ov(RHS: CarryIn, Overflow&: SecondOverflowed); |
| 13691 | break; |
| 13692 | } |
| 13693 | |
| 13694 | // It is possible for both overflows to happen but CGBuiltin uses an OR so |
| 13695 | // this is consistent. |
| 13696 | CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed); |
| 13697 | APValue APV{CarryOut}; |
| 13698 | if (!handleAssignment(Info, E, LVal: CarryOutLValue, LValType: ResultType, Val&: APV)) |
| 13699 | return false; |
| 13700 | return Success(SI: Result, E); |
| 13701 | } |
| 13702 | case Builtin::BI__builtin_add_overflow: |
| 13703 | case Builtin::BI__builtin_sub_overflow: |
| 13704 | case Builtin::BI__builtin_mul_overflow: |
| 13705 | case Builtin::BI__builtin_sadd_overflow: |
| 13706 | case Builtin::BI__builtin_uadd_overflow: |
| 13707 | case Builtin::BI__builtin_uaddl_overflow: |
| 13708 | case Builtin::BI__builtin_uaddll_overflow: |
| 13709 | case Builtin::BI__builtin_usub_overflow: |
| 13710 | case Builtin::BI__builtin_usubl_overflow: |
| 13711 | case Builtin::BI__builtin_usubll_overflow: |
| 13712 | case Builtin::BI__builtin_umul_overflow: |
| 13713 | case Builtin::BI__builtin_umull_overflow: |
| 13714 | case Builtin::BI__builtin_umulll_overflow: |
| 13715 | case Builtin::BI__builtin_saddl_overflow: |
| 13716 | case Builtin::BI__builtin_saddll_overflow: |
| 13717 | case Builtin::BI__builtin_ssub_overflow: |
| 13718 | case Builtin::BI__builtin_ssubl_overflow: |
| 13719 | case Builtin::BI__builtin_ssubll_overflow: |
| 13720 | case Builtin::BI__builtin_smul_overflow: |
| 13721 | case Builtin::BI__builtin_smull_overflow: |
| 13722 | case Builtin::BI__builtin_smulll_overflow: { |
| 13723 | LValue ResultLValue; |
| 13724 | APSInt LHS, RHS; |
| 13725 | |
| 13726 | QualType ResultType = E->getArg(Arg: 2)->getType()->getPointeeType(); |
| 13727 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: LHS, Info) || |
| 13728 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: RHS, Info) || |
| 13729 | !EvaluatePointer(E: E->getArg(Arg: 2), Result&: ResultLValue, Info)) |
| 13730 | return false; |
| 13731 | |
| 13732 | APSInt Result; |
| 13733 | bool DidOverflow = false; |
| 13734 | |
| 13735 | // If the types don't have to match, enlarge all 3 to the largest of them. |
| 13736 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || |
| 13737 | BuiltinOp == Builtin::BI__builtin_sub_overflow || |
| 13738 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { |
| 13739 | bool IsSigned = LHS.isSigned() || RHS.isSigned() || |
| 13740 | ResultType->isSignedIntegerOrEnumerationType(); |
| 13741 | bool AllSigned = LHS.isSigned() && RHS.isSigned() && |
| 13742 | ResultType->isSignedIntegerOrEnumerationType(); |
| 13743 | uint64_t LHSSize = LHS.getBitWidth(); |
| 13744 | uint64_t RHSSize = RHS.getBitWidth(); |
| 13745 | uint64_t ResultSize = Info.Ctx.getTypeSize(T: ResultType); |
| 13746 | uint64_t MaxBits = std::max(a: std::max(a: LHSSize, b: RHSSize), b: ResultSize); |
| 13747 | |
| 13748 | // Add an additional bit if the signedness isn't uniformly agreed to. We |
| 13749 | // could do this ONLY if there is a signed and an unsigned that both have |
| 13750 | // MaxBits, but the code to check that is pretty nasty. The issue will be |
| 13751 | // caught in the shrink-to-result later anyway. |
| 13752 | if (IsSigned && !AllSigned) |
| 13753 | ++MaxBits; |
| 13754 | |
| 13755 | LHS = APSInt(LHS.extOrTrunc(width: MaxBits), !IsSigned); |
| 13756 | RHS = APSInt(RHS.extOrTrunc(width: MaxBits), !IsSigned); |
| 13757 | Result = APSInt(MaxBits, !IsSigned); |
| 13758 | } |
| 13759 | |
| 13760 | // Find largest int. |
| 13761 | switch (BuiltinOp) { |
| 13762 | default: |
| 13763 | llvm_unreachable("Invalid value for BuiltinOp" ); |
| 13764 | case Builtin::BI__builtin_add_overflow: |
| 13765 | case Builtin::BI__builtin_sadd_overflow: |
| 13766 | case Builtin::BI__builtin_saddl_overflow: |
| 13767 | case Builtin::BI__builtin_saddll_overflow: |
| 13768 | case Builtin::BI__builtin_uadd_overflow: |
| 13769 | case Builtin::BI__builtin_uaddl_overflow: |
| 13770 | case Builtin::BI__builtin_uaddll_overflow: |
| 13771 | Result = LHS.isSigned() ? LHS.sadd_ov(RHS, Overflow&: DidOverflow) |
| 13772 | : LHS.uadd_ov(RHS, Overflow&: DidOverflow); |
| 13773 | break; |
| 13774 | case Builtin::BI__builtin_sub_overflow: |
| 13775 | case Builtin::BI__builtin_ssub_overflow: |
| 13776 | case Builtin::BI__builtin_ssubl_overflow: |
| 13777 | case Builtin::BI__builtin_ssubll_overflow: |
| 13778 | case Builtin::BI__builtin_usub_overflow: |
| 13779 | case Builtin::BI__builtin_usubl_overflow: |
| 13780 | case Builtin::BI__builtin_usubll_overflow: |
| 13781 | Result = LHS.isSigned() ? LHS.ssub_ov(RHS, Overflow&: DidOverflow) |
| 13782 | : LHS.usub_ov(RHS, Overflow&: DidOverflow); |
| 13783 | break; |
| 13784 | case Builtin::BI__builtin_mul_overflow: |
| 13785 | case Builtin::BI__builtin_smul_overflow: |
| 13786 | case Builtin::BI__builtin_smull_overflow: |
| 13787 | case Builtin::BI__builtin_smulll_overflow: |
| 13788 | case Builtin::BI__builtin_umul_overflow: |
| 13789 | case Builtin::BI__builtin_umull_overflow: |
| 13790 | case Builtin::BI__builtin_umulll_overflow: |
| 13791 | Result = LHS.isSigned() ? LHS.smul_ov(RHS, Overflow&: DidOverflow) |
| 13792 | : LHS.umul_ov(RHS, Overflow&: DidOverflow); |
| 13793 | break; |
| 13794 | } |
| 13795 | |
| 13796 | // In the case where multiple sizes are allowed, truncate and see if |
| 13797 | // the values are the same. |
| 13798 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || |
| 13799 | BuiltinOp == Builtin::BI__builtin_sub_overflow || |
| 13800 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { |
| 13801 | // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, |
| 13802 | // since it will give us the behavior of a TruncOrSelf in the case where |
| 13803 | // its parameter <= its size. We previously set Result to be at least the |
| 13804 | // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth |
| 13805 | // will work exactly like TruncOrSelf. |
| 13806 | APSInt Temp = Result.extOrTrunc(width: Info.Ctx.getTypeSize(T: ResultType)); |
| 13807 | Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); |
| 13808 | |
| 13809 | if (!APSInt::isSameValue(I1: Temp, I2: Result)) |
| 13810 | DidOverflow = true; |
| 13811 | Result = Temp; |
| 13812 | } |
| 13813 | |
| 13814 | APValue APV{Result}; |
| 13815 | if (!handleAssignment(Info, E, LVal: ResultLValue, LValType: ResultType, Val&: APV)) |
| 13816 | return false; |
| 13817 | return Success(Value: DidOverflow, E); |
| 13818 | } |
| 13819 | |
| 13820 | case Builtin::BI__builtin_reduce_add: |
| 13821 | case Builtin::BI__builtin_reduce_mul: |
| 13822 | case Builtin::BI__builtin_reduce_and: |
| 13823 | case Builtin::BI__builtin_reduce_or: |
| 13824 | case Builtin::BI__builtin_reduce_xor: |
| 13825 | case Builtin::BI__builtin_reduce_min: |
| 13826 | case Builtin::BI__builtin_reduce_max: { |
| 13827 | APValue Source; |
| 13828 | if (!EvaluateAsRValue(Info, E: E->getArg(Arg: 0), Result&: Source)) |
| 13829 | return false; |
| 13830 | |
| 13831 | unsigned SourceLen = Source.getVectorLength(); |
| 13832 | APSInt Reduced = Source.getVectorElt(I: 0).getInt(); |
| 13833 | for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) { |
| 13834 | switch (BuiltinOp) { |
| 13835 | default: |
| 13836 | return false; |
| 13837 | case Builtin::BI__builtin_reduce_add: { |
| 13838 | if (!CheckedIntArithmetic( |
| 13839 | Info, E, LHS: Reduced, RHS: Source.getVectorElt(I: EltNum).getInt(), |
| 13840 | BitWidth: Reduced.getBitWidth() + 1, Op: std::plus<APSInt>(), Result&: Reduced)) |
| 13841 | return false; |
| 13842 | break; |
| 13843 | } |
| 13844 | case Builtin::BI__builtin_reduce_mul: { |
| 13845 | if (!CheckedIntArithmetic( |
| 13846 | Info, E, LHS: Reduced, RHS: Source.getVectorElt(I: EltNum).getInt(), |
| 13847 | BitWidth: Reduced.getBitWidth() * 2, Op: std::multiplies<APSInt>(), Result&: Reduced)) |
| 13848 | return false; |
| 13849 | break; |
| 13850 | } |
| 13851 | case Builtin::BI__builtin_reduce_and: { |
| 13852 | Reduced &= Source.getVectorElt(I: EltNum).getInt(); |
| 13853 | break; |
| 13854 | } |
| 13855 | case Builtin::BI__builtin_reduce_or: { |
| 13856 | Reduced |= Source.getVectorElt(I: EltNum).getInt(); |
| 13857 | break; |
| 13858 | } |
| 13859 | case Builtin::BI__builtin_reduce_xor: { |
| 13860 | Reduced ^= Source.getVectorElt(I: EltNum).getInt(); |
| 13861 | break; |
| 13862 | } |
| 13863 | case Builtin::BI__builtin_reduce_min: { |
| 13864 | Reduced = std::min(a: Reduced, b: Source.getVectorElt(I: EltNum).getInt()); |
| 13865 | break; |
| 13866 | } |
| 13867 | case Builtin::BI__builtin_reduce_max: { |
| 13868 | Reduced = std::max(a: Reduced, b: Source.getVectorElt(I: EltNum).getInt()); |
| 13869 | break; |
| 13870 | } |
| 13871 | } |
| 13872 | } |
| 13873 | |
| 13874 | return Success(SI: Reduced, E); |
| 13875 | } |
| 13876 | |
| 13877 | case clang::X86::BI__builtin_ia32_addcarryx_u32: |
| 13878 | case clang::X86::BI__builtin_ia32_addcarryx_u64: |
| 13879 | case clang::X86::BI__builtin_ia32_subborrow_u32: |
| 13880 | case clang::X86::BI__builtin_ia32_subborrow_u64: { |
| 13881 | LValue ResultLValue; |
| 13882 | APSInt CarryIn, LHS, RHS; |
| 13883 | QualType ResultType = E->getArg(Arg: 3)->getType()->getPointeeType(); |
| 13884 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: CarryIn, Info) || |
| 13885 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: LHS, Info) || |
| 13886 | !EvaluateInteger(E: E->getArg(Arg: 2), Result&: RHS, Info) || |
| 13887 | !EvaluatePointer(E: E->getArg(Arg: 3), Result&: ResultLValue, Info)) |
| 13888 | return false; |
| 13889 | |
| 13890 | bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 || |
| 13891 | BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64; |
| 13892 | |
| 13893 | unsigned BitWidth = LHS.getBitWidth(); |
| 13894 | unsigned CarryInBit = CarryIn.ugt(RHS: 0) ? 1 : 0; |
| 13895 | APInt ExResult = |
| 13896 | IsAdd |
| 13897 | ? (LHS.zext(width: BitWidth + 1) + (RHS.zext(width: BitWidth + 1) + CarryInBit)) |
| 13898 | : (LHS.zext(width: BitWidth + 1) - (RHS.zext(width: BitWidth + 1) + CarryInBit)); |
| 13899 | |
| 13900 | APInt Result = ExResult.extractBits(numBits: BitWidth, bitPosition: 0); |
| 13901 | uint64_t CarryOut = ExResult.extractBitsAsZExtValue(numBits: 1, bitPosition: BitWidth); |
| 13902 | |
| 13903 | APValue APV{APSInt(Result, /*isUnsigned=*/true)}; |
| 13904 | if (!handleAssignment(Info, E, LVal: ResultLValue, LValType: ResultType, Val&: APV)) |
| 13905 | return false; |
| 13906 | return Success(Value: CarryOut, E); |
| 13907 | } |
| 13908 | |
| 13909 | case clang::X86::BI__builtin_ia32_bextr_u32: |
| 13910 | case clang::X86::BI__builtin_ia32_bextr_u64: |
| 13911 | case clang::X86::BI__builtin_ia32_bextri_u32: |
| 13912 | case clang::X86::BI__builtin_ia32_bextri_u64: { |
| 13913 | APSInt Val, Idx; |
| 13914 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) || |
| 13915 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Idx, Info)) |
| 13916 | return false; |
| 13917 | |
| 13918 | unsigned BitWidth = Val.getBitWidth(); |
| 13919 | uint64_t Shift = Idx.extractBitsAsZExtValue(numBits: 8, bitPosition: 0); |
| 13920 | uint64_t Length = Idx.extractBitsAsZExtValue(numBits: 8, bitPosition: 8); |
| 13921 | Length = Length > BitWidth ? BitWidth : Length; |
| 13922 | |
| 13923 | // Handle out of bounds cases. |
| 13924 | if (Length == 0 || Shift >= BitWidth) |
| 13925 | return Success(Value: 0, E); |
| 13926 | |
| 13927 | uint64_t Result = Val.getZExtValue() >> Shift; |
| 13928 | Result &= llvm::maskTrailingOnes<uint64_t>(N: Length); |
| 13929 | return Success(Value: Result, E); |
| 13930 | } |
| 13931 | |
| 13932 | case clang::X86::BI__builtin_ia32_bzhi_si: |
| 13933 | case clang::X86::BI__builtin_ia32_bzhi_di: { |
| 13934 | APSInt Val, Idx; |
| 13935 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) || |
| 13936 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Idx, Info)) |
| 13937 | return false; |
| 13938 | |
| 13939 | unsigned BitWidth = Val.getBitWidth(); |
| 13940 | unsigned Index = Idx.extractBitsAsZExtValue(numBits: 8, bitPosition: 0); |
| 13941 | if (Index < BitWidth) |
| 13942 | Val.clearHighBits(hiBits: BitWidth - Index); |
| 13943 | return Success(SI: Val, E); |
| 13944 | } |
| 13945 | |
| 13946 | case clang::X86::BI__builtin_ia32_lzcnt_u16: |
| 13947 | case clang::X86::BI__builtin_ia32_lzcnt_u32: |
| 13948 | case clang::X86::BI__builtin_ia32_lzcnt_u64: { |
| 13949 | APSInt Val; |
| 13950 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13951 | return false; |
| 13952 | return Success(Value: Val.countLeadingZeros(), E); |
| 13953 | } |
| 13954 | |
| 13955 | case clang::X86::BI__builtin_ia32_tzcnt_u16: |
| 13956 | case clang::X86::BI__builtin_ia32_tzcnt_u32: |
| 13957 | case clang::X86::BI__builtin_ia32_tzcnt_u64: { |
| 13958 | APSInt Val; |
| 13959 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info)) |
| 13960 | return false; |
| 13961 | return Success(Value: Val.countTrailingZeros(), E); |
| 13962 | } |
| 13963 | |
| 13964 | case clang::X86::BI__builtin_ia32_pdep_si: |
| 13965 | case clang::X86::BI__builtin_ia32_pdep_di: { |
| 13966 | APSInt Val, Msk; |
| 13967 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) || |
| 13968 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Msk, Info)) |
| 13969 | return false; |
| 13970 | |
| 13971 | unsigned BitWidth = Val.getBitWidth(); |
| 13972 | APInt Result = APInt::getZero(numBits: BitWidth); |
| 13973 | for (unsigned I = 0, P = 0; I != BitWidth; ++I) |
| 13974 | if (Msk[I]) |
| 13975 | Result.setBitVal(BitPosition: I, BitValue: Val[P++]); |
| 13976 | return Success(I: Result, E); |
| 13977 | } |
| 13978 | |
| 13979 | case clang::X86::BI__builtin_ia32_pext_si: |
| 13980 | case clang::X86::BI__builtin_ia32_pext_di: { |
| 13981 | APSInt Val, Msk; |
| 13982 | if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) || |
| 13983 | !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Msk, Info)) |
| 13984 | return false; |
| 13985 | |
| 13986 | unsigned BitWidth = Val.getBitWidth(); |
| 13987 | APInt Result = APInt::getZero(numBits: BitWidth); |
| 13988 | for (unsigned I = 0, P = 0; I != BitWidth; ++I) |
| 13989 | if (Msk[I]) |
| 13990 | Result.setBitVal(BitPosition: P++, BitValue: Val[I]); |
| 13991 | return Success(I: Result, E); |
| 13992 | } |
| 13993 | } |
| 13994 | } |
| 13995 | |
| 13996 | /// Determine whether this is a pointer past the end of the complete |
| 13997 | /// object referred to by the lvalue. |
| 13998 | static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, |
| 13999 | const LValue &LV) { |
| 14000 | // A null pointer can be viewed as being "past the end" but we don't |
| 14001 | // choose to look at it that way here. |
| 14002 | if (!LV.getLValueBase()) |
| 14003 | return false; |
| 14004 | |
| 14005 | // If the designator is valid and refers to a subobject, we're not pointing |
| 14006 | // past the end. |
| 14007 | if (!LV.getLValueDesignator().Invalid && |
| 14008 | !LV.getLValueDesignator().isOnePastTheEnd()) |
| 14009 | return false; |
| 14010 | |
| 14011 | // A pointer to an incomplete type might be past-the-end if the type's size is |
| 14012 | // zero. We cannot tell because the type is incomplete. |
| 14013 | QualType Ty = getType(B: LV.getLValueBase()); |
| 14014 | if (Ty->isIncompleteType()) |
| 14015 | return true; |
| 14016 | |
| 14017 | // Can't be past the end of an invalid object. |
| 14018 | if (LV.getLValueDesignator().Invalid) |
| 14019 | return false; |
| 14020 | |
| 14021 | // We're a past-the-end pointer if we point to the byte after the object, |
| 14022 | // no matter what our type or path is. |
| 14023 | auto Size = Ctx.getTypeSizeInChars(T: Ty); |
| 14024 | return LV.getLValueOffset() == Size; |
| 14025 | } |
| 14026 | |
| 14027 | namespace { |
| 14028 | |
| 14029 | /// Data recursive integer evaluator of certain binary operators. |
| 14030 | /// |
| 14031 | /// We use a data recursive algorithm for binary operators so that we are able |
| 14032 | /// to handle extreme cases of chained binary operators without causing stack |
| 14033 | /// overflow. |
| 14034 | class DataRecursiveIntBinOpEvaluator { |
| 14035 | struct EvalResult { |
| 14036 | APValue Val; |
| 14037 | bool Failed = false; |
| 14038 | |
| 14039 | EvalResult() = default; |
| 14040 | |
| 14041 | void swap(EvalResult &RHS) { |
| 14042 | Val.swap(RHS&: RHS.Val); |
| 14043 | Failed = RHS.Failed; |
| 14044 | RHS.Failed = false; |
| 14045 | } |
| 14046 | }; |
| 14047 | |
| 14048 | struct Job { |
| 14049 | const Expr *E; |
| 14050 | EvalResult LHSResult; // meaningful only for binary operator expression. |
| 14051 | enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; |
| 14052 | |
| 14053 | Job() = default; |
| 14054 | Job(Job &&) = default; |
| 14055 | |
| 14056 | void startSpeculativeEval(EvalInfo &Info) { |
| 14057 | SpecEvalRAII = SpeculativeEvaluationRAII(Info); |
| 14058 | } |
| 14059 | |
| 14060 | private: |
| 14061 | SpeculativeEvaluationRAII SpecEvalRAII; |
| 14062 | }; |
| 14063 | |
| 14064 | SmallVector<Job, 16> Queue; |
| 14065 | |
| 14066 | IntExprEvaluator &IntEval; |
| 14067 | EvalInfo &Info; |
| 14068 | APValue &FinalResult; |
| 14069 | |
| 14070 | public: |
| 14071 | DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) |
| 14072 | : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } |
| 14073 | |
| 14074 | /// True if \param E is a binary operator that we are going to handle |
| 14075 | /// data recursively. |
| 14076 | /// We handle binary operators that are comma, logical, or that have operands |
| 14077 | /// with integral or enumeration type. |
| 14078 | static bool shouldEnqueue(const BinaryOperator *E) { |
| 14079 | return E->getOpcode() == BO_Comma || E->isLogicalOp() || |
| 14080 | (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && |
| 14081 | E->getLHS()->getType()->isIntegralOrEnumerationType() && |
| 14082 | E->getRHS()->getType()->isIntegralOrEnumerationType()); |
| 14083 | } |
| 14084 | |
| 14085 | bool Traverse(const BinaryOperator *E) { |
| 14086 | enqueue(E); |
| 14087 | EvalResult PrevResult; |
| 14088 | while (!Queue.empty()) |
| 14089 | process(Result&: PrevResult); |
| 14090 | |
| 14091 | if (PrevResult.Failed) return false; |
| 14092 | |
| 14093 | FinalResult.swap(RHS&: PrevResult.Val); |
| 14094 | return true; |
| 14095 | } |
| 14096 | |
| 14097 | private: |
| 14098 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { |
| 14099 | return IntEval.Success(Value, E, Result); |
| 14100 | } |
| 14101 | bool Success(const APSInt &Value, const Expr *E, APValue &Result) { |
| 14102 | return IntEval.Success(SI: Value, E, Result); |
| 14103 | } |
| 14104 | bool Error(const Expr *E) { |
| 14105 | return IntEval.Error(E); |
| 14106 | } |
| 14107 | bool Error(const Expr *E, diag::kind D) { |
| 14108 | return IntEval.Error(E, D); |
| 14109 | } |
| 14110 | |
| 14111 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { |
| 14112 | return Info.CCEDiag(E, DiagId: D); |
| 14113 | } |
| 14114 | |
| 14115 | // Returns true if visiting the RHS is necessary, false otherwise. |
| 14116 | bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, |
| 14117 | bool &SuppressRHSDiags); |
| 14118 | |
| 14119 | bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, |
| 14120 | const BinaryOperator *E, APValue &Result); |
| 14121 | |
| 14122 | void EvaluateExpr(const Expr *E, EvalResult &Result) { |
| 14123 | Result.Failed = !Evaluate(Result&: Result.Val, Info, E); |
| 14124 | if (Result.Failed) |
| 14125 | Result.Val = APValue(); |
| 14126 | } |
| 14127 | |
| 14128 | void process(EvalResult &Result); |
| 14129 | |
| 14130 | void enqueue(const Expr *E) { |
| 14131 | E = E->IgnoreParens(); |
| 14132 | Queue.resize(N: Queue.size()+1); |
| 14133 | Queue.back().E = E; |
| 14134 | Queue.back().Kind = Job::AnyExprKind; |
| 14135 | } |
| 14136 | }; |
| 14137 | |
| 14138 | } |
| 14139 | |
| 14140 | bool DataRecursiveIntBinOpEvaluator:: |
| 14141 | VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, |
| 14142 | bool &SuppressRHSDiags) { |
| 14143 | if (E->getOpcode() == BO_Comma) { |
| 14144 | // Ignore LHS but note if we could not evaluate it. |
| 14145 | if (LHSResult.Failed) |
| 14146 | return Info.noteSideEffect(); |
| 14147 | return true; |
| 14148 | } |
| 14149 | |
| 14150 | if (E->isLogicalOp()) { |
| 14151 | bool LHSAsBool; |
| 14152 | if (!LHSResult.Failed && HandleConversionToBool(Val: LHSResult.Val, Result&: LHSAsBool)) { |
| 14153 | // We were able to evaluate the LHS, see if we can get away with not |
| 14154 | // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 |
| 14155 | if (LHSAsBool == (E->getOpcode() == BO_LOr)) { |
| 14156 | Success(Value: LHSAsBool, E, Result&: LHSResult.Val); |
| 14157 | return false; // Ignore RHS |
| 14158 | } |
| 14159 | } else { |
| 14160 | LHSResult.Failed = true; |
| 14161 | |
| 14162 | // Since we weren't able to evaluate the left hand side, it |
| 14163 | // might have had side effects. |
| 14164 | if (!Info.noteSideEffect()) |
| 14165 | return false; |
| 14166 | |
| 14167 | // We can't evaluate the LHS; however, sometimes the result |
| 14168 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. |
| 14169 | // Don't ignore RHS and suppress diagnostics from this arm. |
| 14170 | SuppressRHSDiags = true; |
| 14171 | } |
| 14172 | |
| 14173 | return true; |
| 14174 | } |
| 14175 | |
| 14176 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && |
| 14177 | E->getRHS()->getType()->isIntegralOrEnumerationType()); |
| 14178 | |
| 14179 | if (LHSResult.Failed && !Info.noteFailure()) |
| 14180 | return false; // Ignore RHS; |
| 14181 | |
| 14182 | return true; |
| 14183 | } |
| 14184 | |
| 14185 | static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, |
| 14186 | bool IsSub) { |
| 14187 | // Compute the new offset in the appropriate width, wrapping at 64 bits. |
| 14188 | // FIXME: When compiling for a 32-bit target, we should use 32-bit |
| 14189 | // offsets. |
| 14190 | assert(!LVal.hasLValuePath() && "have designator for integer lvalue" ); |
| 14191 | CharUnits &Offset = LVal.getLValueOffset(); |
| 14192 | uint64_t Offset64 = Offset.getQuantity(); |
| 14193 | uint64_t Index64 = Index.extOrTrunc(width: 64).getZExtValue(); |
| 14194 | Offset = CharUnits::fromQuantity(Quantity: IsSub ? Offset64 - Index64 |
| 14195 | : Offset64 + Index64); |
| 14196 | } |
| 14197 | |
| 14198 | bool DataRecursiveIntBinOpEvaluator:: |
| 14199 | VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, |
| 14200 | const BinaryOperator *E, APValue &Result) { |
| 14201 | if (E->getOpcode() == BO_Comma) { |
| 14202 | if (RHSResult.Failed) |
| 14203 | return false; |
| 14204 | Result = RHSResult.Val; |
| 14205 | return true; |
| 14206 | } |
| 14207 | |
| 14208 | if (E->isLogicalOp()) { |
| 14209 | bool lhsResult, rhsResult; |
| 14210 | bool LHSIsOK = HandleConversionToBool(Val: LHSResult.Val, Result&: lhsResult); |
| 14211 | bool RHSIsOK = HandleConversionToBool(Val: RHSResult.Val, Result&: rhsResult); |
| 14212 | |
| 14213 | if (LHSIsOK) { |
| 14214 | if (RHSIsOK) { |
| 14215 | if (E->getOpcode() == BO_LOr) |
| 14216 | return Success(Value: lhsResult || rhsResult, E, Result); |
| 14217 | else |
| 14218 | return Success(Value: lhsResult && rhsResult, E, Result); |
| 14219 | } |
| 14220 | } else { |
| 14221 | if (RHSIsOK) { |
| 14222 | // We can't evaluate the LHS; however, sometimes the result |
| 14223 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. |
| 14224 | if (rhsResult == (E->getOpcode() == BO_LOr)) |
| 14225 | return Success(Value: rhsResult, E, Result); |
| 14226 | } |
| 14227 | } |
| 14228 | |
| 14229 | return false; |
| 14230 | } |
| 14231 | |
| 14232 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && |
| 14233 | E->getRHS()->getType()->isIntegralOrEnumerationType()); |
| 14234 | |
| 14235 | if (LHSResult.Failed || RHSResult.Failed) |
| 14236 | return false; |
| 14237 | |
| 14238 | const APValue &LHSVal = LHSResult.Val; |
| 14239 | const APValue &RHSVal = RHSResult.Val; |
| 14240 | |
| 14241 | // Handle cases like (unsigned long)&a + 4. |
| 14242 | if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { |
| 14243 | Result = LHSVal; |
| 14244 | addOrSubLValueAsInteger(LVal&: Result, Index: RHSVal.getInt(), IsSub: E->getOpcode() == BO_Sub); |
| 14245 | return true; |
| 14246 | } |
| 14247 | |
| 14248 | // Handle cases like 4 + (unsigned long)&a |
| 14249 | if (E->getOpcode() == BO_Add && |
| 14250 | RHSVal.isLValue() && LHSVal.isInt()) { |
| 14251 | Result = RHSVal; |
| 14252 | addOrSubLValueAsInteger(LVal&: Result, Index: LHSVal.getInt(), /*IsSub*/false); |
| 14253 | return true; |
| 14254 | } |
| 14255 | |
| 14256 | if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { |
| 14257 | // Handle (intptr_t)&&A - (intptr_t)&&B. |
| 14258 | if (!LHSVal.getLValueOffset().isZero() || |
| 14259 | !RHSVal.getLValueOffset().isZero()) |
| 14260 | return false; |
| 14261 | const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); |
| 14262 | const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); |
| 14263 | if (!LHSExpr || !RHSExpr) |
| 14264 | return false; |
| 14265 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: LHSExpr); |
| 14266 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: RHSExpr); |
| 14267 | if (!LHSAddrExpr || !RHSAddrExpr) |
| 14268 | return false; |
| 14269 | // Make sure both labels come from the same function. |
| 14270 | if (LHSAddrExpr->getLabel()->getDeclContext() != |
| 14271 | RHSAddrExpr->getLabel()->getDeclContext()) |
| 14272 | return false; |
| 14273 | Result = APValue(LHSAddrExpr, RHSAddrExpr); |
| 14274 | return true; |
| 14275 | } |
| 14276 | |
| 14277 | // All the remaining cases expect both operands to be an integer |
| 14278 | if (!LHSVal.isInt() || !RHSVal.isInt()) |
| 14279 | return Error(E); |
| 14280 | |
| 14281 | // Set up the width and signedness manually, in case it can't be deduced |
| 14282 | // from the operation we're performing. |
| 14283 | // FIXME: Don't do this in the cases where we can deduce it. |
| 14284 | APSInt Value(Info.Ctx.getIntWidth(T: E->getType()), |
| 14285 | E->getType()->isUnsignedIntegerOrEnumerationType()); |
| 14286 | if (!handleIntIntBinOp(Info, E, LHS: LHSVal.getInt(), Opcode: E->getOpcode(), |
| 14287 | RHS: RHSVal.getInt(), Result&: Value)) |
| 14288 | return false; |
| 14289 | return Success(Value, E, Result); |
| 14290 | } |
| 14291 | |
| 14292 | void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { |
| 14293 | Job &job = Queue.back(); |
| 14294 | |
| 14295 | switch (job.Kind) { |
| 14296 | case Job::AnyExprKind: { |
| 14297 | if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: job.E)) { |
| 14298 | if (shouldEnqueue(E: Bop)) { |
| 14299 | job.Kind = Job::BinOpKind; |
| 14300 | enqueue(E: Bop->getLHS()); |
| 14301 | return; |
| 14302 | } |
| 14303 | } |
| 14304 | |
| 14305 | EvaluateExpr(E: job.E, Result); |
| 14306 | Queue.pop_back(); |
| 14307 | return; |
| 14308 | } |
| 14309 | |
| 14310 | case Job::BinOpKind: { |
| 14311 | const BinaryOperator *Bop = cast<BinaryOperator>(Val: job.E); |
| 14312 | bool SuppressRHSDiags = false; |
| 14313 | if (!VisitBinOpLHSOnly(LHSResult&: Result, E: Bop, SuppressRHSDiags)) { |
| 14314 | Queue.pop_back(); |
| 14315 | return; |
| 14316 | } |
| 14317 | if (SuppressRHSDiags) |
| 14318 | job.startSpeculativeEval(Info); |
| 14319 | job.LHSResult.swap(RHS&: Result); |
| 14320 | job.Kind = Job::BinOpVisitedLHSKind; |
| 14321 | enqueue(E: Bop->getRHS()); |
| 14322 | return; |
| 14323 | } |
| 14324 | |
| 14325 | case Job::BinOpVisitedLHSKind: { |
| 14326 | const BinaryOperator *Bop = cast<BinaryOperator>(Val: job.E); |
| 14327 | EvalResult RHS; |
| 14328 | RHS.swap(RHS&: Result); |
| 14329 | Result.Failed = !VisitBinOp(LHSResult: job.LHSResult, RHSResult: RHS, E: Bop, Result&: Result.Val); |
| 14330 | Queue.pop_back(); |
| 14331 | return; |
| 14332 | } |
| 14333 | } |
| 14334 | |
| 14335 | llvm_unreachable("Invalid Job::Kind!" ); |
| 14336 | } |
| 14337 | |
| 14338 | namespace { |
| 14339 | enum class CmpResult { |
| 14340 | Unequal, |
| 14341 | Less, |
| 14342 | Equal, |
| 14343 | Greater, |
| 14344 | Unordered, |
| 14345 | }; |
| 14346 | } |
| 14347 | |
| 14348 | template <class SuccessCB, class AfterCB> |
| 14349 | static bool |
| 14350 | EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, |
| 14351 | SuccessCB &&Success, AfterCB &&DoAfter) { |
| 14352 | assert(!E->isValueDependent()); |
| 14353 | assert(E->isComparisonOp() && "expected comparison operator" ); |
| 14354 | assert((E->getOpcode() == BO_Cmp || |
| 14355 | E->getType()->isIntegralOrEnumerationType()) && |
| 14356 | "unsupported binary expression evaluation" ); |
| 14357 | auto Error = [&](const Expr *E) { |
| 14358 | Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 14359 | return false; |
| 14360 | }; |
| 14361 | |
| 14362 | bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; |
| 14363 | bool IsEquality = E->isEqualityOp(); |
| 14364 | |
| 14365 | QualType LHSTy = E->getLHS()->getType(); |
| 14366 | QualType RHSTy = E->getRHS()->getType(); |
| 14367 | |
| 14368 | if (LHSTy->isIntegralOrEnumerationType() && |
| 14369 | RHSTy->isIntegralOrEnumerationType()) { |
| 14370 | APSInt LHS, RHS; |
| 14371 | bool LHSOK = EvaluateInteger(E: E->getLHS(), Result&: LHS, Info); |
| 14372 | if (!LHSOK && !Info.noteFailure()) |
| 14373 | return false; |
| 14374 | if (!EvaluateInteger(E: E->getRHS(), Result&: RHS, Info) || !LHSOK) |
| 14375 | return false; |
| 14376 | if (LHS < RHS) |
| 14377 | return Success(CmpResult::Less, E); |
| 14378 | if (LHS > RHS) |
| 14379 | return Success(CmpResult::Greater, E); |
| 14380 | return Success(CmpResult::Equal, E); |
| 14381 | } |
| 14382 | |
| 14383 | if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { |
| 14384 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(Ty: LHSTy)); |
| 14385 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(Ty: RHSTy)); |
| 14386 | |
| 14387 | bool LHSOK = EvaluateFixedPointOrInteger(E: E->getLHS(), Result&: LHSFX, Info); |
| 14388 | if (!LHSOK && !Info.noteFailure()) |
| 14389 | return false; |
| 14390 | if (!EvaluateFixedPointOrInteger(E: E->getRHS(), Result&: RHSFX, Info) || !LHSOK) |
| 14391 | return false; |
| 14392 | if (LHSFX < RHSFX) |
| 14393 | return Success(CmpResult::Less, E); |
| 14394 | if (LHSFX > RHSFX) |
| 14395 | return Success(CmpResult::Greater, E); |
| 14396 | return Success(CmpResult::Equal, E); |
| 14397 | } |
| 14398 | |
| 14399 | if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { |
| 14400 | ComplexValue LHS, RHS; |
| 14401 | bool LHSOK; |
| 14402 | if (E->isAssignmentOp()) { |
| 14403 | LValue LV; |
| 14404 | EvaluateLValue(E: E->getLHS(), Result&: LV, Info); |
| 14405 | LHSOK = false; |
| 14406 | } else if (LHSTy->isRealFloatingType()) { |
| 14407 | LHSOK = EvaluateFloat(E: E->getLHS(), Result&: LHS.FloatReal, Info); |
| 14408 | if (LHSOK) { |
| 14409 | LHS.makeComplexFloat(); |
| 14410 | LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); |
| 14411 | } |
| 14412 | } else { |
| 14413 | LHSOK = EvaluateComplex(E: E->getLHS(), Res&: LHS, Info); |
| 14414 | } |
| 14415 | if (!LHSOK && !Info.noteFailure()) |
| 14416 | return false; |
| 14417 | |
| 14418 | if (E->getRHS()->getType()->isRealFloatingType()) { |
| 14419 | if (!EvaluateFloat(E: E->getRHS(), Result&: RHS.FloatReal, Info) || !LHSOK) |
| 14420 | return false; |
| 14421 | RHS.makeComplexFloat(); |
| 14422 | RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); |
| 14423 | } else if (!EvaluateComplex(E: E->getRHS(), Res&: RHS, Info) || !LHSOK) |
| 14424 | return false; |
| 14425 | |
| 14426 | if (LHS.isComplexFloat()) { |
| 14427 | APFloat::cmpResult CR_r = |
| 14428 | LHS.getComplexFloatReal().compare(RHS: RHS.getComplexFloatReal()); |
| 14429 | APFloat::cmpResult CR_i = |
| 14430 | LHS.getComplexFloatImag().compare(RHS: RHS.getComplexFloatImag()); |
| 14431 | bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; |
| 14432 | return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); |
| 14433 | } else { |
| 14434 | assert(IsEquality && "invalid complex comparison" ); |
| 14435 | bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && |
| 14436 | LHS.getComplexIntImag() == RHS.getComplexIntImag(); |
| 14437 | return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); |
| 14438 | } |
| 14439 | } |
| 14440 | |
| 14441 | if (LHSTy->isRealFloatingType() && |
| 14442 | RHSTy->isRealFloatingType()) { |
| 14443 | APFloat RHS(0.0), LHS(0.0); |
| 14444 | |
| 14445 | bool LHSOK = EvaluateFloat(E: E->getRHS(), Result&: RHS, Info); |
| 14446 | if (!LHSOK && !Info.noteFailure()) |
| 14447 | return false; |
| 14448 | |
| 14449 | if (!EvaluateFloat(E: E->getLHS(), Result&: LHS, Info) || !LHSOK) |
| 14450 | return false; |
| 14451 | |
| 14452 | assert(E->isComparisonOp() && "Invalid binary operator!" ); |
| 14453 | llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); |
| 14454 | if (!Info.InConstantContext && |
| 14455 | APFloatCmpResult == APFloat::cmpUnordered && |
| 14456 | E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts()).isFPConstrained()) { |
| 14457 | // Note: Compares may raise invalid in some cases involving NaN or sNaN. |
| 14458 | Info.FFDiag(E, DiagId: diag::note_constexpr_float_arithmetic_strict); |
| 14459 | return false; |
| 14460 | } |
| 14461 | auto GetCmpRes = [&]() { |
| 14462 | switch (APFloatCmpResult) { |
| 14463 | case APFloat::cmpEqual: |
| 14464 | return CmpResult::Equal; |
| 14465 | case APFloat::cmpLessThan: |
| 14466 | return CmpResult::Less; |
| 14467 | case APFloat::cmpGreaterThan: |
| 14468 | return CmpResult::Greater; |
| 14469 | case APFloat::cmpUnordered: |
| 14470 | return CmpResult::Unordered; |
| 14471 | } |
| 14472 | llvm_unreachable("Unrecognised APFloat::cmpResult enum" ); |
| 14473 | }; |
| 14474 | return Success(GetCmpRes(), E); |
| 14475 | } |
| 14476 | |
| 14477 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) { |
| 14478 | LValue LHSValue, RHSValue; |
| 14479 | |
| 14480 | bool LHSOK = EvaluatePointer(E: E->getLHS(), Result&: LHSValue, Info); |
| 14481 | if (!LHSOK && !Info.noteFailure()) |
| 14482 | return false; |
| 14483 | |
| 14484 | if (!EvaluatePointer(E: E->getRHS(), Result&: RHSValue, Info) || !LHSOK) |
| 14485 | return false; |
| 14486 | |
| 14487 | // If we have Unknown pointers we should fail if they are not global values. |
| 14488 | if (!(IsGlobalLValue(B: LHSValue.getLValueBase()) && |
| 14489 | IsGlobalLValue(B: RHSValue.getLValueBase())) && |
| 14490 | (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)) |
| 14491 | return false; |
| 14492 | |
| 14493 | // Reject differing bases from the normal codepath; we special-case |
| 14494 | // comparisons to null. |
| 14495 | if (!HasSameBase(A: LHSValue, B: RHSValue)) { |
| 14496 | auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) { |
| 14497 | std::string LHS = LHSValue.toString(Ctx&: Info.Ctx, T: E->getLHS()->getType()); |
| 14498 | std::string RHS = RHSValue.toString(Ctx&: Info.Ctx, T: E->getRHS()->getType()); |
| 14499 | Info.FFDiag(E, DiagId: DiagID) |
| 14500 | << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS); |
| 14501 | return false; |
| 14502 | }; |
| 14503 | // Inequalities and subtractions between unrelated pointers have |
| 14504 | // unspecified or undefined behavior. |
| 14505 | if (!IsEquality) |
| 14506 | return DiagComparison( |
| 14507 | diag::note_constexpr_pointer_comparison_unspecified); |
| 14508 | // A constant address may compare equal to the address of a symbol. |
| 14509 | // The one exception is that address of an object cannot compare equal |
| 14510 | // to a null pointer constant. |
| 14511 | // TODO: Should we restrict this to actual null pointers, and exclude the |
| 14512 | // case of zero cast to pointer type? |
| 14513 | if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || |
| 14514 | (!RHSValue.Base && !RHSValue.Offset.isZero())) |
| 14515 | return DiagComparison(diag::note_constexpr_pointer_constant_comparison, |
| 14516 | !RHSValue.Base); |
| 14517 | // C++2c [intro.object]/10: |
| 14518 | // Two objects [...] may have the same address if [...] they are both |
| 14519 | // potentially non-unique objects. |
| 14520 | // C++2c [intro.object]/9: |
| 14521 | // An object is potentially non-unique if it is a string literal object, |
| 14522 | // the backing array of an initializer list, or a subobject thereof. |
| 14523 | // |
| 14524 | // This makes the comparison result unspecified, so it's not a constant |
| 14525 | // expression. |
| 14526 | // |
| 14527 | // TODO: Do we need to handle the initializer list case here? |
| 14528 | if (ArePotentiallyOverlappingStringLiterals(Info, LHS: LHSValue, RHS: RHSValue)) |
| 14529 | return DiagComparison(diag::note_constexpr_literal_comparison); |
| 14530 | if (IsOpaqueConstantCall(LVal: LHSValue) || IsOpaqueConstantCall(LVal: RHSValue)) |
| 14531 | return DiagComparison(diag::note_constexpr_opaque_call_comparison, |
| 14532 | !IsOpaqueConstantCall(LVal: LHSValue)); |
| 14533 | // We can't tell whether weak symbols will end up pointing to the same |
| 14534 | // object. |
| 14535 | if (IsWeakLValue(Value: LHSValue) || IsWeakLValue(Value: RHSValue)) |
| 14536 | return DiagComparison(diag::note_constexpr_pointer_weak_comparison, |
| 14537 | !IsWeakLValue(Value: LHSValue)); |
| 14538 | // We can't compare the address of the start of one object with the |
| 14539 | // past-the-end address of another object, per C++ DR1652. |
| 14540 | if (LHSValue.Base && LHSValue.Offset.isZero() && |
| 14541 | isOnePastTheEndOfCompleteObject(Ctx: Info.Ctx, LV: RHSValue)) |
| 14542 | return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, |
| 14543 | true); |
| 14544 | if (RHSValue.Base && RHSValue.Offset.isZero() && |
| 14545 | isOnePastTheEndOfCompleteObject(Ctx: Info.Ctx, LV: LHSValue)) |
| 14546 | return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, |
| 14547 | false); |
| 14548 | // We can't tell whether an object is at the same address as another |
| 14549 | // zero sized object. |
| 14550 | if ((RHSValue.Base && isZeroSized(Value: LHSValue)) || |
| 14551 | (LHSValue.Base && isZeroSized(Value: RHSValue))) |
| 14552 | return DiagComparison( |
| 14553 | diag::note_constexpr_pointer_comparison_zero_sized); |
| 14554 | return Success(CmpResult::Unequal, E); |
| 14555 | } |
| 14556 | |
| 14557 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); |
| 14558 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); |
| 14559 | |
| 14560 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); |
| 14561 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); |
| 14562 | |
| 14563 | // C++11 [expr.rel]p2: |
| 14564 | // - If two pointers point to non-static data members of the same object, |
| 14565 | // or to subobjects or array elements fo such members, recursively, the |
| 14566 | // pointer to the later declared member compares greater provided the |
| 14567 | // two members have the same access control and provided their class is |
| 14568 | // not a union. |
| 14569 | // [...] |
| 14570 | // - Otherwise pointer comparisons are unspecified. |
| 14571 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { |
| 14572 | bool WasArrayIndex; |
| 14573 | unsigned Mismatch = FindDesignatorMismatch( |
| 14574 | ObjType: getType(B: LHSValue.Base), A: LHSDesignator, B: RHSDesignator, WasArrayIndex); |
| 14575 | // At the point where the designators diverge, the comparison has a |
| 14576 | // specified value if: |
| 14577 | // - we are comparing array indices |
| 14578 | // - we are comparing fields of a union, or fields with the same access |
| 14579 | // Otherwise, the result is unspecified and thus the comparison is not a |
| 14580 | // constant expression. |
| 14581 | if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && |
| 14582 | Mismatch < RHSDesignator.Entries.size()) { |
| 14583 | const FieldDecl *LF = getAsField(E: LHSDesignator.Entries[Mismatch]); |
| 14584 | const FieldDecl *RF = getAsField(E: RHSDesignator.Entries[Mismatch]); |
| 14585 | if (!LF && !RF) |
| 14586 | Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_comparison_base_classes); |
| 14587 | else if (!LF) |
| 14588 | Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_comparison_base_field) |
| 14589 | << getAsBaseClass(E: LHSDesignator.Entries[Mismatch]) |
| 14590 | << RF->getParent() << RF; |
| 14591 | else if (!RF) |
| 14592 | Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_comparison_base_field) |
| 14593 | << getAsBaseClass(E: RHSDesignator.Entries[Mismatch]) |
| 14594 | << LF->getParent() << LF; |
| 14595 | else if (!LF->getParent()->isUnion() && |
| 14596 | LF->getAccess() != RF->getAccess()) |
| 14597 | Info.CCEDiag(E, |
| 14598 | DiagId: diag::note_constexpr_pointer_comparison_differing_access) |
| 14599 | << LF << LF->getAccess() << RF << RF->getAccess() |
| 14600 | << LF->getParent(); |
| 14601 | } |
| 14602 | } |
| 14603 | |
| 14604 | // The comparison here must be unsigned, and performed with the same |
| 14605 | // width as the pointer. |
| 14606 | unsigned PtrSize = Info.Ctx.getTypeSize(T: LHSTy); |
| 14607 | uint64_t CompareLHS = LHSOffset.getQuantity(); |
| 14608 | uint64_t CompareRHS = RHSOffset.getQuantity(); |
| 14609 | assert(PtrSize <= 64 && "Unexpected pointer width" ); |
| 14610 | uint64_t Mask = ~0ULL >> (64 - PtrSize); |
| 14611 | CompareLHS &= Mask; |
| 14612 | CompareRHS &= Mask; |
| 14613 | |
| 14614 | // If there is a base and this is a relational operator, we can only |
| 14615 | // compare pointers within the object in question; otherwise, the result |
| 14616 | // depends on where the object is located in memory. |
| 14617 | if (!LHSValue.Base.isNull() && IsRelational) { |
| 14618 | QualType BaseTy = getType(B: LHSValue.Base); |
| 14619 | if (BaseTy->isIncompleteType()) |
| 14620 | return Error(E); |
| 14621 | CharUnits Size = Info.Ctx.getTypeSizeInChars(T: BaseTy); |
| 14622 | uint64_t OffsetLimit = Size.getQuantity(); |
| 14623 | if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) |
| 14624 | return Error(E); |
| 14625 | } |
| 14626 | |
| 14627 | if (CompareLHS < CompareRHS) |
| 14628 | return Success(CmpResult::Less, E); |
| 14629 | if (CompareLHS > CompareRHS) |
| 14630 | return Success(CmpResult::Greater, E); |
| 14631 | return Success(CmpResult::Equal, E); |
| 14632 | } |
| 14633 | |
| 14634 | if (LHSTy->isMemberPointerType()) { |
| 14635 | assert(IsEquality && "unexpected member pointer operation" ); |
| 14636 | assert(RHSTy->isMemberPointerType() && "invalid comparison" ); |
| 14637 | |
| 14638 | MemberPtr LHSValue, RHSValue; |
| 14639 | |
| 14640 | bool LHSOK = EvaluateMemberPointer(E: E->getLHS(), Result&: LHSValue, Info); |
| 14641 | if (!LHSOK && !Info.noteFailure()) |
| 14642 | return false; |
| 14643 | |
| 14644 | if (!EvaluateMemberPointer(E: E->getRHS(), Result&: RHSValue, Info) || !LHSOK) |
| 14645 | return false; |
| 14646 | |
| 14647 | // If either operand is a pointer to a weak function, the comparison is not |
| 14648 | // constant. |
| 14649 | if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) { |
| 14650 | Info.FFDiag(E, DiagId: diag::note_constexpr_mem_pointer_weak_comparison) |
| 14651 | << LHSValue.getDecl(); |
| 14652 | return false; |
| 14653 | } |
| 14654 | if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) { |
| 14655 | Info.FFDiag(E, DiagId: diag::note_constexpr_mem_pointer_weak_comparison) |
| 14656 | << RHSValue.getDecl(); |
| 14657 | return false; |
| 14658 | } |
| 14659 | |
| 14660 | // C++11 [expr.eq]p2: |
| 14661 | // If both operands are null, they compare equal. Otherwise if only one is |
| 14662 | // null, they compare unequal. |
| 14663 | if (!LHSValue.getDecl() || !RHSValue.getDecl()) { |
| 14664 | bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); |
| 14665 | return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); |
| 14666 | } |
| 14667 | |
| 14668 | // Otherwise if either is a pointer to a virtual member function, the |
| 14669 | // result is unspecified. |
| 14670 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: LHSValue.getDecl())) |
| 14671 | if (MD->isVirtual()) |
| 14672 | Info.CCEDiag(E, DiagId: diag::note_constexpr_compare_virtual_mem_ptr) << MD; |
| 14673 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: RHSValue.getDecl())) |
| 14674 | if (MD->isVirtual()) |
| 14675 | Info.CCEDiag(E, DiagId: diag::note_constexpr_compare_virtual_mem_ptr) << MD; |
| 14676 | |
| 14677 | // Otherwise they compare equal if and only if they would refer to the |
| 14678 | // same member of the same most derived object or the same subobject if |
| 14679 | // they were dereferenced with a hypothetical object of the associated |
| 14680 | // class type. |
| 14681 | bool Equal = LHSValue == RHSValue; |
| 14682 | return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); |
| 14683 | } |
| 14684 | |
| 14685 | if (LHSTy->isNullPtrType()) { |
| 14686 | assert(E->isComparisonOp() && "unexpected nullptr operation" ); |
| 14687 | assert(RHSTy->isNullPtrType() && "missing pointer conversion" ); |
| 14688 | // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t |
| 14689 | // are compared, the result is true of the operator is <=, >= or ==, and |
| 14690 | // false otherwise. |
| 14691 | LValue Res; |
| 14692 | if (!EvaluatePointer(E: E->getLHS(), Result&: Res, Info) || |
| 14693 | !EvaluatePointer(E: E->getRHS(), Result&: Res, Info)) |
| 14694 | return false; |
| 14695 | return Success(CmpResult::Equal, E); |
| 14696 | } |
| 14697 | |
| 14698 | return DoAfter(); |
| 14699 | } |
| 14700 | |
| 14701 | bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { |
| 14702 | if (!CheckLiteralType(Info, E)) |
| 14703 | return false; |
| 14704 | |
| 14705 | auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { |
| 14706 | ComparisonCategoryResult CCR; |
| 14707 | switch (CR) { |
| 14708 | case CmpResult::Unequal: |
| 14709 | llvm_unreachable("should never produce Unequal for three-way comparison" ); |
| 14710 | case CmpResult::Less: |
| 14711 | CCR = ComparisonCategoryResult::Less; |
| 14712 | break; |
| 14713 | case CmpResult::Equal: |
| 14714 | CCR = ComparisonCategoryResult::Equal; |
| 14715 | break; |
| 14716 | case CmpResult::Greater: |
| 14717 | CCR = ComparisonCategoryResult::Greater; |
| 14718 | break; |
| 14719 | case CmpResult::Unordered: |
| 14720 | CCR = ComparisonCategoryResult::Unordered; |
| 14721 | break; |
| 14722 | } |
| 14723 | // Evaluation succeeded. Lookup the information for the comparison category |
| 14724 | // type and fetch the VarDecl for the result. |
| 14725 | const ComparisonCategoryInfo &CmpInfo = |
| 14726 | Info.Ctx.CompCategories.getInfoForType(Ty: E->getType()); |
| 14727 | const VarDecl *VD = CmpInfo.getValueInfo(ValueKind: CmpInfo.makeWeakResult(Res: CCR))->VD; |
| 14728 | // Check and evaluate the result as a constant expression. |
| 14729 | LValue LV; |
| 14730 | LV.set(B: VD); |
| 14731 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getType(), LVal: LV, RVal&: Result)) |
| 14732 | return false; |
| 14733 | return CheckConstantExpression(Info, DiagLoc: E->getExprLoc(), Type: E->getType(), Value: Result, |
| 14734 | Kind: ConstantExprKind::Normal); |
| 14735 | }; |
| 14736 | return EvaluateComparisonBinaryOperator(Info, E, Success&: OnSuccess, DoAfter: [&]() { |
| 14737 | return ExprEvaluatorBaseTy::VisitBinCmp(S: E); |
| 14738 | }); |
| 14739 | } |
| 14740 | |
| 14741 | bool RecordExprEvaluator::VisitCXXParenListInitExpr( |
| 14742 | const CXXParenListInitExpr *E) { |
| 14743 | return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->getInitExprs()); |
| 14744 | } |
| 14745 | |
| 14746 | bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { |
| 14747 | // We don't support assignment in C. C++ assignments don't get here because |
| 14748 | // assignment is an lvalue in C++. |
| 14749 | if (E->isAssignmentOp()) { |
| 14750 | Error(E); |
| 14751 | if (!Info.noteFailure()) |
| 14752 | return false; |
| 14753 | } |
| 14754 | |
| 14755 | if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) |
| 14756 | return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); |
| 14757 | |
| 14758 | assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || |
| 14759 | !E->getRHS()->getType()->isIntegralOrEnumerationType()) && |
| 14760 | "DataRecursiveIntBinOpEvaluator should have handled integral types" ); |
| 14761 | |
| 14762 | if (E->isComparisonOp()) { |
| 14763 | // Evaluate builtin binary comparisons by evaluating them as three-way |
| 14764 | // comparisons and then translating the result. |
| 14765 | auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { |
| 14766 | assert((CR != CmpResult::Unequal || E->isEqualityOp()) && |
| 14767 | "should only produce Unequal for equality comparisons" ); |
| 14768 | bool IsEqual = CR == CmpResult::Equal, |
| 14769 | IsLess = CR == CmpResult::Less, |
| 14770 | IsGreater = CR == CmpResult::Greater; |
| 14771 | auto Op = E->getOpcode(); |
| 14772 | switch (Op) { |
| 14773 | default: |
| 14774 | llvm_unreachable("unsupported binary operator" ); |
| 14775 | case BO_EQ: |
| 14776 | case BO_NE: |
| 14777 | return Success(Value: IsEqual == (Op == BO_EQ), E); |
| 14778 | case BO_LT: |
| 14779 | return Success(Value: IsLess, E); |
| 14780 | case BO_GT: |
| 14781 | return Success(Value: IsGreater, E); |
| 14782 | case BO_LE: |
| 14783 | return Success(Value: IsEqual || IsLess, E); |
| 14784 | case BO_GE: |
| 14785 | return Success(Value: IsEqual || IsGreater, E); |
| 14786 | } |
| 14787 | }; |
| 14788 | return EvaluateComparisonBinaryOperator(Info, E, Success&: OnSuccess, DoAfter: [&]() { |
| 14789 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 14790 | }); |
| 14791 | } |
| 14792 | |
| 14793 | QualType LHSTy = E->getLHS()->getType(); |
| 14794 | QualType RHSTy = E->getRHS()->getType(); |
| 14795 | |
| 14796 | if (LHSTy->isPointerType() && RHSTy->isPointerType() && |
| 14797 | E->getOpcode() == BO_Sub) { |
| 14798 | LValue LHSValue, RHSValue; |
| 14799 | |
| 14800 | bool LHSOK = EvaluatePointer(E: E->getLHS(), Result&: LHSValue, Info); |
| 14801 | if (!LHSOK && !Info.noteFailure()) |
| 14802 | return false; |
| 14803 | |
| 14804 | if (!EvaluatePointer(E: E->getRHS(), Result&: RHSValue, Info) || !LHSOK) |
| 14805 | return false; |
| 14806 | |
| 14807 | // Reject differing bases from the normal codepath; we special-case |
| 14808 | // comparisons to null. |
| 14809 | if (!HasSameBase(A: LHSValue, B: RHSValue)) { |
| 14810 | const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); |
| 14811 | const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); |
| 14812 | |
| 14813 | auto DiagArith = [&](unsigned DiagID) { |
| 14814 | std::string LHS = LHSValue.toString(Ctx&: Info.Ctx, T: E->getLHS()->getType()); |
| 14815 | std::string RHS = RHSValue.toString(Ctx&: Info.Ctx, T: E->getRHS()->getType()); |
| 14816 | Info.FFDiag(E, DiagId: DiagID) << LHS << RHS; |
| 14817 | if (LHSExpr && LHSExpr == RHSExpr) |
| 14818 | Info.Note(Loc: LHSExpr->getExprLoc(), |
| 14819 | DiagId: diag::note_constexpr_repeated_literal_eval) |
| 14820 | << LHSExpr->getSourceRange(); |
| 14821 | return false; |
| 14822 | }; |
| 14823 | |
| 14824 | if (!LHSExpr || !RHSExpr) |
| 14825 | return DiagArith(diag::note_constexpr_pointer_arith_unspecified); |
| 14826 | |
| 14827 | if (ArePotentiallyOverlappingStringLiterals(Info, LHS: LHSValue, RHS: RHSValue)) |
| 14828 | return DiagArith(diag::note_constexpr_literal_arith); |
| 14829 | |
| 14830 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: LHSExpr); |
| 14831 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: RHSExpr); |
| 14832 | if (!LHSAddrExpr || !RHSAddrExpr) |
| 14833 | return Error(E); |
| 14834 | // Make sure both labels come from the same function. |
| 14835 | if (LHSAddrExpr->getLabel()->getDeclContext() != |
| 14836 | RHSAddrExpr->getLabel()->getDeclContext()) |
| 14837 | return Error(E); |
| 14838 | return Success(V: APValue(LHSAddrExpr, RHSAddrExpr), E); |
| 14839 | } |
| 14840 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); |
| 14841 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); |
| 14842 | |
| 14843 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); |
| 14844 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); |
| 14845 | |
| 14846 | // C++11 [expr.add]p6: |
| 14847 | // Unless both pointers point to elements of the same array object, or |
| 14848 | // one past the last element of the array object, the behavior is |
| 14849 | // undefined. |
| 14850 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && |
| 14851 | !AreElementsOfSameArray(ObjType: getType(B: LHSValue.Base), A: LHSDesignator, |
| 14852 | B: RHSDesignator)) |
| 14853 | Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_subtraction_not_same_array); |
| 14854 | |
| 14855 | QualType Type = E->getLHS()->getType(); |
| 14856 | QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); |
| 14857 | |
| 14858 | CharUnits ElementSize; |
| 14859 | if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: ElementType, Size&: ElementSize)) |
| 14860 | return false; |
| 14861 | |
| 14862 | // As an extension, a type may have zero size (empty struct or union in |
| 14863 | // C, array of zero length). Pointer subtraction in such cases has |
| 14864 | // undefined behavior, so is not constant. |
| 14865 | if (ElementSize.isZero()) { |
| 14866 | Info.FFDiag(E, DiagId: diag::note_constexpr_pointer_subtraction_zero_size) |
| 14867 | << ElementType; |
| 14868 | return false; |
| 14869 | } |
| 14870 | |
| 14871 | // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, |
| 14872 | // and produce incorrect results when it overflows. Such behavior |
| 14873 | // appears to be non-conforming, but is common, so perhaps we should |
| 14874 | // assume the standard intended for such cases to be undefined behavior |
| 14875 | // and check for them. |
| 14876 | |
| 14877 | // Compute (LHSOffset - RHSOffset) / Size carefully, checking for |
| 14878 | // overflow in the final conversion to ptrdiff_t. |
| 14879 | APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); |
| 14880 | APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); |
| 14881 | APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), |
| 14882 | false); |
| 14883 | APSInt TrueResult = (LHS - RHS) / ElemSize; |
| 14884 | APSInt Result = TrueResult.trunc(width: Info.Ctx.getIntWidth(T: E->getType())); |
| 14885 | |
| 14886 | if (Result.extend(width: 65) != TrueResult && |
| 14887 | !HandleOverflow(Info, E, SrcValue: TrueResult, DestType: E->getType())) |
| 14888 | return false; |
| 14889 | return Success(SI: Result, E); |
| 14890 | } |
| 14891 | |
| 14892 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 14893 | } |
| 14894 | |
| 14895 | /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with |
| 14896 | /// a result as the expression's type. |
| 14897 | bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( |
| 14898 | const UnaryExprOrTypeTraitExpr *E) { |
| 14899 | switch(E->getKind()) { |
| 14900 | case UETT_PreferredAlignOf: |
| 14901 | case UETT_AlignOf: { |
| 14902 | if (E->isArgumentType()) |
| 14903 | return Success( |
| 14904 | Size: GetAlignOfType(Ctx: Info.Ctx, T: E->getArgumentType(), ExprKind: E->getKind()), E); |
| 14905 | else |
| 14906 | return Success( |
| 14907 | Size: GetAlignOfExpr(Ctx: Info.Ctx, E: E->getArgumentExpr(), ExprKind: E->getKind()), E); |
| 14908 | } |
| 14909 | |
| 14910 | case UETT_PtrAuthTypeDiscriminator: { |
| 14911 | if (E->getArgumentType()->isDependentType()) |
| 14912 | return false; |
| 14913 | return Success( |
| 14914 | Value: Info.Ctx.getPointerAuthTypeDiscriminator(T: E->getArgumentType()), E); |
| 14915 | } |
| 14916 | case UETT_VecStep: { |
| 14917 | QualType Ty = E->getTypeOfArgument(); |
| 14918 | |
| 14919 | if (Ty->isVectorType()) { |
| 14920 | unsigned n = Ty->castAs<VectorType>()->getNumElements(); |
| 14921 | |
| 14922 | // The vec_step built-in functions that take a 3-component |
| 14923 | // vector return 4. (OpenCL 1.1 spec 6.11.12) |
| 14924 | if (n == 3) |
| 14925 | n = 4; |
| 14926 | |
| 14927 | return Success(Value: n, E); |
| 14928 | } else |
| 14929 | return Success(Value: 1, E); |
| 14930 | } |
| 14931 | |
| 14932 | case UETT_DataSizeOf: |
| 14933 | case UETT_SizeOf: { |
| 14934 | QualType SrcTy = E->getTypeOfArgument(); |
| 14935 | // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, |
| 14936 | // the result is the size of the referenced type." |
| 14937 | if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) |
| 14938 | SrcTy = Ref->getPointeeType(); |
| 14939 | |
| 14940 | CharUnits Sizeof; |
| 14941 | if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: SrcTy, Size&: Sizeof, |
| 14942 | SOT: E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf |
| 14943 | : SizeOfType::SizeOf)) { |
| 14944 | return false; |
| 14945 | } |
| 14946 | return Success(Size: Sizeof, E); |
| 14947 | } |
| 14948 | case UETT_OpenMPRequiredSimdAlign: |
| 14949 | assert(E->isArgumentType()); |
| 14950 | return Success( |
| 14951 | Value: Info.Ctx.toCharUnitsFromBits( |
| 14952 | BitSize: Info.Ctx.getOpenMPDefaultSimdAlign(T: E->getArgumentType())) |
| 14953 | .getQuantity(), |
| 14954 | E); |
| 14955 | case UETT_VectorElements: { |
| 14956 | QualType Ty = E->getTypeOfArgument(); |
| 14957 | // If the vector has a fixed size, we can determine the number of elements |
| 14958 | // at compile time. |
| 14959 | if (const auto *VT = Ty->getAs<VectorType>()) |
| 14960 | return Success(Value: VT->getNumElements(), E); |
| 14961 | |
| 14962 | assert(Ty->isSizelessVectorType()); |
| 14963 | if (Info.InConstantContext) |
| 14964 | Info.CCEDiag(E, DiagId: diag::note_constexpr_non_const_vectorelements) |
| 14965 | << E->getSourceRange(); |
| 14966 | |
| 14967 | return false; |
| 14968 | } |
| 14969 | case UETT_CountOf: { |
| 14970 | QualType Ty = E->getTypeOfArgument(); |
| 14971 | assert(Ty->isArrayType()); |
| 14972 | |
| 14973 | // We don't need to worry about array element qualifiers, so getting the |
| 14974 | // unsafe array type is fine. |
| 14975 | if (const auto *CAT = |
| 14976 | dyn_cast<ConstantArrayType>(Val: Ty->getAsArrayTypeUnsafe())) { |
| 14977 | return Success(I: CAT->getSize(), E); |
| 14978 | } |
| 14979 | |
| 14980 | assert(!Ty->isConstantSizeType()); |
| 14981 | |
| 14982 | // If it's a variable-length array type, we need to check whether it is a |
| 14983 | // multidimensional array. If so, we need to check the size expression of |
| 14984 | // the VLA to see if it's a constant size. If so, we can return that value. |
| 14985 | const auto *VAT = Info.Ctx.getAsVariableArrayType(T: Ty); |
| 14986 | assert(VAT); |
| 14987 | if (VAT->getElementType()->isArrayType()) { |
| 14988 | std::optional<APSInt> Res = |
| 14989 | VAT->getSizeExpr()->getIntegerConstantExpr(Ctx: Info.Ctx); |
| 14990 | if (Res) { |
| 14991 | // The resulting value always has type size_t, so we need to make the |
| 14992 | // returned APInt have the correct sign and bit-width. |
| 14993 | APInt Val{ |
| 14994 | static_cast<unsigned>(Info.Ctx.getTypeSize(T: Info.Ctx.getSizeType())), |
| 14995 | Res->getZExtValue()}; |
| 14996 | return Success(I: Val, E); |
| 14997 | } |
| 14998 | } |
| 14999 | |
| 15000 | // Definitely a variable-length type, which is not an ICE. |
| 15001 | // FIXME: Better diagnostic. |
| 15002 | Info.FFDiag(Loc: E->getBeginLoc()); |
| 15003 | return false; |
| 15004 | } |
| 15005 | } |
| 15006 | |
| 15007 | llvm_unreachable("unknown expr/type trait" ); |
| 15008 | } |
| 15009 | |
| 15010 | bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { |
| 15011 | CharUnits Result; |
| 15012 | unsigned n = OOE->getNumComponents(); |
| 15013 | if (n == 0) |
| 15014 | return Error(E: OOE); |
| 15015 | QualType CurrentType = OOE->getTypeSourceInfo()->getType(); |
| 15016 | for (unsigned i = 0; i != n; ++i) { |
| 15017 | OffsetOfNode ON = OOE->getComponent(Idx: i); |
| 15018 | switch (ON.getKind()) { |
| 15019 | case OffsetOfNode::Array: { |
| 15020 | const Expr *Idx = OOE->getIndexExpr(Idx: ON.getArrayExprIndex()); |
| 15021 | APSInt IdxResult; |
| 15022 | if (!EvaluateInteger(E: Idx, Result&: IdxResult, Info)) |
| 15023 | return false; |
| 15024 | const ArrayType *AT = Info.Ctx.getAsArrayType(T: CurrentType); |
| 15025 | if (!AT) |
| 15026 | return Error(E: OOE); |
| 15027 | CurrentType = AT->getElementType(); |
| 15028 | CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(T: CurrentType); |
| 15029 | Result += IdxResult.getSExtValue() * ElementSize; |
| 15030 | break; |
| 15031 | } |
| 15032 | |
| 15033 | case OffsetOfNode::Field: { |
| 15034 | FieldDecl *MemberDecl = ON.getField(); |
| 15035 | const RecordType *RT = CurrentType->getAs<RecordType>(); |
| 15036 | if (!RT) |
| 15037 | return Error(E: OOE); |
| 15038 | RecordDecl *RD = RT->getDecl(); |
| 15039 | if (RD->isInvalidDecl()) return false; |
| 15040 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(D: RD); |
| 15041 | unsigned i = MemberDecl->getFieldIndex(); |
| 15042 | assert(i < RL.getFieldCount() && "offsetof field in wrong type" ); |
| 15043 | Result += Info.Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: i)); |
| 15044 | CurrentType = MemberDecl->getType().getNonReferenceType(); |
| 15045 | break; |
| 15046 | } |
| 15047 | |
| 15048 | case OffsetOfNode::Identifier: |
| 15049 | llvm_unreachable("dependent __builtin_offsetof" ); |
| 15050 | |
| 15051 | case OffsetOfNode::Base: { |
| 15052 | CXXBaseSpecifier *BaseSpec = ON.getBase(); |
| 15053 | if (BaseSpec->isVirtual()) |
| 15054 | return Error(E: OOE); |
| 15055 | |
| 15056 | // Find the layout of the class whose base we are looking into. |
| 15057 | const RecordType *RT = CurrentType->getAs<RecordType>(); |
| 15058 | if (!RT) |
| 15059 | return Error(E: OOE); |
| 15060 | RecordDecl *RD = RT->getDecl(); |
| 15061 | if (RD->isInvalidDecl()) return false; |
| 15062 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(D: RD); |
| 15063 | |
| 15064 | // Find the base class itself. |
| 15065 | CurrentType = BaseSpec->getType(); |
| 15066 | const RecordType *BaseRT = CurrentType->getAs<RecordType>(); |
| 15067 | if (!BaseRT) |
| 15068 | return Error(E: OOE); |
| 15069 | |
| 15070 | // Add the offset to the base. |
| 15071 | Result += RL.getBaseClassOffset(Base: cast<CXXRecordDecl>(Val: BaseRT->getDecl())); |
| 15072 | break; |
| 15073 | } |
| 15074 | } |
| 15075 | } |
| 15076 | return Success(Size: Result, E: OOE); |
| 15077 | } |
| 15078 | |
| 15079 | bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { |
| 15080 | switch (E->getOpcode()) { |
| 15081 | default: |
| 15082 | // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. |
| 15083 | // See C99 6.6p3. |
| 15084 | return Error(E); |
| 15085 | case UO_Extension: |
| 15086 | // FIXME: Should extension allow i-c-e extension expressions in its scope? |
| 15087 | // If so, we could clear the diagnostic ID. |
| 15088 | return Visit(S: E->getSubExpr()); |
| 15089 | case UO_Plus: |
| 15090 | // The result is just the value. |
| 15091 | return Visit(S: E->getSubExpr()); |
| 15092 | case UO_Minus: { |
| 15093 | if (!Visit(S: E->getSubExpr())) |
| 15094 | return false; |
| 15095 | if (!Result.isInt()) return Error(E); |
| 15096 | const APSInt &Value = Result.getInt(); |
| 15097 | if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { |
| 15098 | if (Info.checkingForUndefinedBehavior()) |
| 15099 | Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(), |
| 15100 | DiagID: diag::warn_integer_constant_overflow) |
| 15101 | << toString(I: Value, Radix: 10, Signed: Value.isSigned(), /*formatAsCLiteral=*/false, |
| 15102 | /*UpperCase=*/true, /*InsertSeparators=*/true) |
| 15103 | << E->getType() << E->getSourceRange(); |
| 15104 | |
| 15105 | if (!HandleOverflow(Info, E, SrcValue: -Value.extend(width: Value.getBitWidth() + 1), |
| 15106 | DestType: E->getType())) |
| 15107 | return false; |
| 15108 | } |
| 15109 | return Success(SI: -Value, E); |
| 15110 | } |
| 15111 | case UO_Not: { |
| 15112 | if (!Visit(S: E->getSubExpr())) |
| 15113 | return false; |
| 15114 | if (!Result.isInt()) return Error(E); |
| 15115 | return Success(SI: ~Result.getInt(), E); |
| 15116 | } |
| 15117 | case UO_LNot: { |
| 15118 | bool bres; |
| 15119 | if (!EvaluateAsBooleanCondition(E: E->getSubExpr(), Result&: bres, Info)) |
| 15120 | return false; |
| 15121 | return Success(Value: !bres, E); |
| 15122 | } |
| 15123 | } |
| 15124 | } |
| 15125 | |
| 15126 | /// HandleCast - This is used to evaluate implicit or explicit casts where the |
| 15127 | /// result type is integer. |
| 15128 | bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 15129 | const Expr *SubExpr = E->getSubExpr(); |
| 15130 | QualType DestType = E->getType(); |
| 15131 | QualType SrcType = SubExpr->getType(); |
| 15132 | |
| 15133 | switch (E->getCastKind()) { |
| 15134 | case CK_BaseToDerived: |
| 15135 | case CK_DerivedToBase: |
| 15136 | case CK_UncheckedDerivedToBase: |
| 15137 | case CK_Dynamic: |
| 15138 | case CK_ToUnion: |
| 15139 | case CK_ArrayToPointerDecay: |
| 15140 | case CK_FunctionToPointerDecay: |
| 15141 | case CK_NullToPointer: |
| 15142 | case CK_NullToMemberPointer: |
| 15143 | case CK_BaseToDerivedMemberPointer: |
| 15144 | case CK_DerivedToBaseMemberPointer: |
| 15145 | case CK_ReinterpretMemberPointer: |
| 15146 | case CK_ConstructorConversion: |
| 15147 | case CK_IntegralToPointer: |
| 15148 | case CK_ToVoid: |
| 15149 | case CK_VectorSplat: |
| 15150 | case CK_IntegralToFloating: |
| 15151 | case CK_FloatingCast: |
| 15152 | case CK_CPointerToObjCPointerCast: |
| 15153 | case CK_BlockPointerToObjCPointerCast: |
| 15154 | case CK_AnyPointerToBlockPointerCast: |
| 15155 | case CK_ObjCObjectLValueCast: |
| 15156 | case CK_FloatingRealToComplex: |
| 15157 | case CK_FloatingComplexToReal: |
| 15158 | case CK_FloatingComplexCast: |
| 15159 | case CK_FloatingComplexToIntegralComplex: |
| 15160 | case CK_IntegralRealToComplex: |
| 15161 | case CK_IntegralComplexCast: |
| 15162 | case CK_IntegralComplexToFloatingComplex: |
| 15163 | case CK_BuiltinFnToFnPtr: |
| 15164 | case CK_ZeroToOCLOpaqueType: |
| 15165 | case CK_NonAtomicToAtomic: |
| 15166 | case CK_AddressSpaceConversion: |
| 15167 | case CK_IntToOCLSampler: |
| 15168 | case CK_FloatingToFixedPoint: |
| 15169 | case CK_FixedPointToFloating: |
| 15170 | case CK_FixedPointCast: |
| 15171 | case CK_IntegralToFixedPoint: |
| 15172 | case CK_MatrixCast: |
| 15173 | case CK_HLSLAggregateSplatCast: |
| 15174 | llvm_unreachable("invalid cast kind for integral value" ); |
| 15175 | |
| 15176 | case CK_BitCast: |
| 15177 | case CK_Dependent: |
| 15178 | case CK_LValueBitCast: |
| 15179 | case CK_ARCProduceObject: |
| 15180 | case CK_ARCConsumeObject: |
| 15181 | case CK_ARCReclaimReturnedObject: |
| 15182 | case CK_ARCExtendBlockObject: |
| 15183 | case CK_CopyAndAutoreleaseBlockObject: |
| 15184 | return Error(E); |
| 15185 | |
| 15186 | case CK_UserDefinedConversion: |
| 15187 | case CK_LValueToRValue: |
| 15188 | case CK_AtomicToNonAtomic: |
| 15189 | case CK_NoOp: |
| 15190 | case CK_LValueToRValueBitCast: |
| 15191 | case CK_HLSLArrayRValue: |
| 15192 | case CK_HLSLElementwiseCast: |
| 15193 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 15194 | |
| 15195 | case CK_MemberPointerToBoolean: |
| 15196 | case CK_PointerToBoolean: |
| 15197 | case CK_IntegralToBoolean: |
| 15198 | case CK_FloatingToBoolean: |
| 15199 | case CK_BooleanToSignedIntegral: |
| 15200 | case CK_FloatingComplexToBoolean: |
| 15201 | case CK_IntegralComplexToBoolean: { |
| 15202 | bool BoolResult; |
| 15203 | if (!EvaluateAsBooleanCondition(E: SubExpr, Result&: BoolResult, Info)) |
| 15204 | return false; |
| 15205 | uint64_t IntResult = BoolResult; |
| 15206 | if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) |
| 15207 | IntResult = (uint64_t)-1; |
| 15208 | return Success(Value: IntResult, E); |
| 15209 | } |
| 15210 | |
| 15211 | case CK_FixedPointToIntegral: { |
| 15212 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(Ty: SrcType)); |
| 15213 | if (!EvaluateFixedPoint(E: SubExpr, Result&: Src, Info)) |
| 15214 | return false; |
| 15215 | bool Overflowed; |
| 15216 | llvm::APSInt Result = Src.convertToInt( |
| 15217 | DstWidth: Info.Ctx.getIntWidth(T: DestType), |
| 15218 | DstSign: DestType->isSignedIntegerOrEnumerationType(), Overflow: &Overflowed); |
| 15219 | if (Overflowed && !HandleOverflow(Info, E, SrcValue: Result, DestType)) |
| 15220 | return false; |
| 15221 | return Success(SI: Result, E); |
| 15222 | } |
| 15223 | |
| 15224 | case CK_FixedPointToBoolean: { |
| 15225 | // Unsigned padding does not affect this. |
| 15226 | APValue Val; |
| 15227 | if (!Evaluate(Result&: Val, Info, E: SubExpr)) |
| 15228 | return false; |
| 15229 | return Success(Value: Val.getFixedPoint().getBoolValue(), E); |
| 15230 | } |
| 15231 | |
| 15232 | case CK_IntegralCast: { |
| 15233 | if (!Visit(S: SubExpr)) |
| 15234 | return false; |
| 15235 | |
| 15236 | if (!Result.isInt()) { |
| 15237 | // Allow casts of address-of-label differences if they are no-ops |
| 15238 | // or narrowing. (The narrowing case isn't actually guaranteed to |
| 15239 | // be constant-evaluatable except in some narrow cases which are hard |
| 15240 | // to detect here. We let it through on the assumption the user knows |
| 15241 | // what they are doing.) |
| 15242 | if (Result.isAddrLabelDiff()) |
| 15243 | return Info.Ctx.getTypeSize(T: DestType) <= Info.Ctx.getTypeSize(T: SrcType); |
| 15244 | // Only allow casts of lvalues if they are lossless. |
| 15245 | return Info.Ctx.getTypeSize(T: DestType) == Info.Ctx.getTypeSize(T: SrcType); |
| 15246 | } |
| 15247 | |
| 15248 | if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) { |
| 15249 | const EnumType *ET = dyn_cast<EnumType>(Val: DestType.getCanonicalType()); |
| 15250 | const EnumDecl *ED = ET->getDecl(); |
| 15251 | // Check that the value is within the range of the enumeration values. |
| 15252 | // |
| 15253 | // This corressponds to [expr.static.cast]p10 which says: |
| 15254 | // A value of integral or enumeration type can be explicitly converted |
| 15255 | // to a complete enumeration type ... If the enumeration type does not |
| 15256 | // have a fixed underlying type, the value is unchanged if the original |
| 15257 | // value is within the range of the enumeration values ([dcl.enum]), and |
| 15258 | // otherwise, the behavior is undefined. |
| 15259 | // |
| 15260 | // This was resolved as part of DR2338 which has CD5 status. |
| 15261 | if (!ED->isFixed()) { |
| 15262 | llvm::APInt Min; |
| 15263 | llvm::APInt Max; |
| 15264 | |
| 15265 | ED->getValueRange(Max, Min); |
| 15266 | --Max; |
| 15267 | |
| 15268 | if (ED->getNumNegativeBits() && |
| 15269 | (Max.slt(RHS: Result.getInt().getSExtValue()) || |
| 15270 | Min.sgt(RHS: Result.getInt().getSExtValue()))) |
| 15271 | Info.CCEDiag(E, DiagId: diag::note_constexpr_unscoped_enum_out_of_range) |
| 15272 | << llvm::toString(I: Result.getInt(), Radix: 10) << Min.getSExtValue() |
| 15273 | << Max.getSExtValue() << ED; |
| 15274 | else if (!ED->getNumNegativeBits() && |
| 15275 | Max.ult(RHS: Result.getInt().getZExtValue())) |
| 15276 | Info.CCEDiag(E, DiagId: diag::note_constexpr_unscoped_enum_out_of_range) |
| 15277 | << llvm::toString(I: Result.getInt(), Radix: 10) << Min.getZExtValue() |
| 15278 | << Max.getZExtValue() << ED; |
| 15279 | } |
| 15280 | } |
| 15281 | |
| 15282 | return Success(SI: HandleIntToIntCast(Info, E, DestType, SrcType, |
| 15283 | Value: Result.getInt()), E); |
| 15284 | } |
| 15285 | |
| 15286 | case CK_PointerToIntegral: { |
| 15287 | CCEDiag(E, D: diag::note_constexpr_invalid_cast) |
| 15288 | << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret |
| 15289 | << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange(); |
| 15290 | |
| 15291 | LValue LV; |
| 15292 | if (!EvaluatePointer(E: SubExpr, Result&: LV, Info)) |
| 15293 | return false; |
| 15294 | |
| 15295 | if (LV.getLValueBase()) { |
| 15296 | // Only allow based lvalue casts if they are lossless. |
| 15297 | // FIXME: Allow a larger integer size than the pointer size, and allow |
| 15298 | // narrowing back down to pointer width in subsequent integral casts. |
| 15299 | // FIXME: Check integer type's active bits, not its type size. |
| 15300 | if (Info.Ctx.getTypeSize(T: DestType) != Info.Ctx.getTypeSize(T: SrcType)) |
| 15301 | return Error(E); |
| 15302 | |
| 15303 | LV.Designator.setInvalid(); |
| 15304 | LV.moveInto(V&: Result); |
| 15305 | return true; |
| 15306 | } |
| 15307 | |
| 15308 | APSInt AsInt; |
| 15309 | APValue V; |
| 15310 | LV.moveInto(V); |
| 15311 | if (!V.toIntegralConstant(Result&: AsInt, SrcTy: SrcType, Ctx: Info.Ctx)) |
| 15312 | llvm_unreachable("Can't cast this!" ); |
| 15313 | |
| 15314 | return Success(SI: HandleIntToIntCast(Info, E, DestType, SrcType, Value: AsInt), E); |
| 15315 | } |
| 15316 | |
| 15317 | case CK_IntegralComplexToReal: { |
| 15318 | ComplexValue C; |
| 15319 | if (!EvaluateComplex(E: SubExpr, Res&: C, Info)) |
| 15320 | return false; |
| 15321 | return Success(SI: C.getComplexIntReal(), E); |
| 15322 | } |
| 15323 | |
| 15324 | case CK_FloatingToIntegral: { |
| 15325 | APFloat F(0.0); |
| 15326 | if (!EvaluateFloat(E: SubExpr, Result&: F, Info)) |
| 15327 | return false; |
| 15328 | |
| 15329 | APSInt Value; |
| 15330 | if (!HandleFloatToIntCast(Info, E, SrcType, Value: F, DestType, Result&: Value)) |
| 15331 | return false; |
| 15332 | return Success(SI: Value, E); |
| 15333 | } |
| 15334 | case CK_HLSLVectorTruncation: { |
| 15335 | APValue Val; |
| 15336 | if (!EvaluateVector(E: SubExpr, Result&: Val, Info)) |
| 15337 | return Error(E); |
| 15338 | return Success(V: Val.getVectorElt(I: 0), E); |
| 15339 | } |
| 15340 | } |
| 15341 | |
| 15342 | llvm_unreachable("unknown cast resulting in integral value" ); |
| 15343 | } |
| 15344 | |
| 15345 | bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { |
| 15346 | if (E->getSubExpr()->getType()->isAnyComplexType()) { |
| 15347 | ComplexValue LV; |
| 15348 | if (!EvaluateComplex(E: E->getSubExpr(), Res&: LV, Info)) |
| 15349 | return false; |
| 15350 | if (!LV.isComplexInt()) |
| 15351 | return Error(E); |
| 15352 | return Success(SI: LV.getComplexIntReal(), E); |
| 15353 | } |
| 15354 | |
| 15355 | return Visit(S: E->getSubExpr()); |
| 15356 | } |
| 15357 | |
| 15358 | bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { |
| 15359 | if (E->getSubExpr()->getType()->isComplexIntegerType()) { |
| 15360 | ComplexValue LV; |
| 15361 | if (!EvaluateComplex(E: E->getSubExpr(), Res&: LV, Info)) |
| 15362 | return false; |
| 15363 | if (!LV.isComplexInt()) |
| 15364 | return Error(E); |
| 15365 | return Success(SI: LV.getComplexIntImag(), E); |
| 15366 | } |
| 15367 | |
| 15368 | VisitIgnoredValue(E: E->getSubExpr()); |
| 15369 | return Success(Value: 0, E); |
| 15370 | } |
| 15371 | |
| 15372 | bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { |
| 15373 | return Success(Value: E->getPackLength(), E); |
| 15374 | } |
| 15375 | |
| 15376 | bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { |
| 15377 | return Success(Value: E->getValue(), E); |
| 15378 | } |
| 15379 | |
| 15380 | bool IntExprEvaluator::VisitConceptSpecializationExpr( |
| 15381 | const ConceptSpecializationExpr *E) { |
| 15382 | return Success(Value: E->isSatisfied(), E); |
| 15383 | } |
| 15384 | |
| 15385 | bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { |
| 15386 | return Success(Value: E->isSatisfied(), E); |
| 15387 | } |
| 15388 | |
| 15389 | bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { |
| 15390 | switch (E->getOpcode()) { |
| 15391 | default: |
| 15392 | // Invalid unary operators |
| 15393 | return Error(E); |
| 15394 | case UO_Plus: |
| 15395 | // The result is just the value. |
| 15396 | return Visit(S: E->getSubExpr()); |
| 15397 | case UO_Minus: { |
| 15398 | if (!Visit(S: E->getSubExpr())) return false; |
| 15399 | if (!Result.isFixedPoint()) |
| 15400 | return Error(E); |
| 15401 | bool Overflowed; |
| 15402 | APFixedPoint Negated = Result.getFixedPoint().negate(Overflow: &Overflowed); |
| 15403 | if (Overflowed && !HandleOverflow(Info, E, SrcValue: Negated, DestType: E->getType())) |
| 15404 | return false; |
| 15405 | return Success(V: Negated, E); |
| 15406 | } |
| 15407 | case UO_LNot: { |
| 15408 | bool bres; |
| 15409 | if (!EvaluateAsBooleanCondition(E: E->getSubExpr(), Result&: bres, Info)) |
| 15410 | return false; |
| 15411 | return Success(Value: !bres, E); |
| 15412 | } |
| 15413 | } |
| 15414 | } |
| 15415 | |
| 15416 | bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 15417 | const Expr *SubExpr = E->getSubExpr(); |
| 15418 | QualType DestType = E->getType(); |
| 15419 | assert(DestType->isFixedPointType() && |
| 15420 | "Expected destination type to be a fixed point type" ); |
| 15421 | auto DestFXSema = Info.Ctx.getFixedPointSemantics(Ty: DestType); |
| 15422 | |
| 15423 | switch (E->getCastKind()) { |
| 15424 | case CK_FixedPointCast: { |
| 15425 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(Ty: SubExpr->getType())); |
| 15426 | if (!EvaluateFixedPoint(E: SubExpr, Result&: Src, Info)) |
| 15427 | return false; |
| 15428 | bool Overflowed; |
| 15429 | APFixedPoint Result = Src.convert(DstSema: DestFXSema, Overflow: &Overflowed); |
| 15430 | if (Overflowed) { |
| 15431 | if (Info.checkingForUndefinedBehavior()) |
| 15432 | Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(), |
| 15433 | DiagID: diag::warn_fixedpoint_constant_overflow) |
| 15434 | << Result.toString() << E->getType(); |
| 15435 | if (!HandleOverflow(Info, E, SrcValue: Result, DestType: E->getType())) |
| 15436 | return false; |
| 15437 | } |
| 15438 | return Success(V: Result, E); |
| 15439 | } |
| 15440 | case CK_IntegralToFixedPoint: { |
| 15441 | APSInt Src; |
| 15442 | if (!EvaluateInteger(E: SubExpr, Result&: Src, Info)) |
| 15443 | return false; |
| 15444 | |
| 15445 | bool Overflowed; |
| 15446 | APFixedPoint IntResult = APFixedPoint::getFromIntValue( |
| 15447 | Value: Src, DstFXSema: Info.Ctx.getFixedPointSemantics(Ty: DestType), Overflow: &Overflowed); |
| 15448 | |
| 15449 | if (Overflowed) { |
| 15450 | if (Info.checkingForUndefinedBehavior()) |
| 15451 | Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(), |
| 15452 | DiagID: diag::warn_fixedpoint_constant_overflow) |
| 15453 | << IntResult.toString() << E->getType(); |
| 15454 | if (!HandleOverflow(Info, E, SrcValue: IntResult, DestType: E->getType())) |
| 15455 | return false; |
| 15456 | } |
| 15457 | |
| 15458 | return Success(V: IntResult, E); |
| 15459 | } |
| 15460 | case CK_FloatingToFixedPoint: { |
| 15461 | APFloat Src(0.0); |
| 15462 | if (!EvaluateFloat(E: SubExpr, Result&: Src, Info)) |
| 15463 | return false; |
| 15464 | |
| 15465 | bool Overflowed; |
| 15466 | APFixedPoint Result = APFixedPoint::getFromFloatValue( |
| 15467 | Value: Src, DstFXSema: Info.Ctx.getFixedPointSemantics(Ty: DestType), Overflow: &Overflowed); |
| 15468 | |
| 15469 | if (Overflowed) { |
| 15470 | if (Info.checkingForUndefinedBehavior()) |
| 15471 | Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(), |
| 15472 | DiagID: diag::warn_fixedpoint_constant_overflow) |
| 15473 | << Result.toString() << E->getType(); |
| 15474 | if (!HandleOverflow(Info, E, SrcValue: Result, DestType: E->getType())) |
| 15475 | return false; |
| 15476 | } |
| 15477 | |
| 15478 | return Success(V: Result, E); |
| 15479 | } |
| 15480 | case CK_NoOp: |
| 15481 | case CK_LValueToRValue: |
| 15482 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 15483 | default: |
| 15484 | return Error(E); |
| 15485 | } |
| 15486 | } |
| 15487 | |
| 15488 | bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { |
| 15489 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) |
| 15490 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 15491 | |
| 15492 | const Expr *LHS = E->getLHS(); |
| 15493 | const Expr *RHS = E->getRHS(); |
| 15494 | FixedPointSemantics ResultFXSema = |
| 15495 | Info.Ctx.getFixedPointSemantics(Ty: E->getType()); |
| 15496 | |
| 15497 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(Ty: LHS->getType())); |
| 15498 | if (!EvaluateFixedPointOrInteger(E: LHS, Result&: LHSFX, Info)) |
| 15499 | return false; |
| 15500 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(Ty: RHS->getType())); |
| 15501 | if (!EvaluateFixedPointOrInteger(E: RHS, Result&: RHSFX, Info)) |
| 15502 | return false; |
| 15503 | |
| 15504 | bool OpOverflow = false, ConversionOverflow = false; |
| 15505 | APFixedPoint Result(LHSFX.getSemantics()); |
| 15506 | switch (E->getOpcode()) { |
| 15507 | case BO_Add: { |
| 15508 | Result = LHSFX.add(Other: RHSFX, Overflow: &OpOverflow) |
| 15509 | .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow); |
| 15510 | break; |
| 15511 | } |
| 15512 | case BO_Sub: { |
| 15513 | Result = LHSFX.sub(Other: RHSFX, Overflow: &OpOverflow) |
| 15514 | .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow); |
| 15515 | break; |
| 15516 | } |
| 15517 | case BO_Mul: { |
| 15518 | Result = LHSFX.mul(Other: RHSFX, Overflow: &OpOverflow) |
| 15519 | .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow); |
| 15520 | break; |
| 15521 | } |
| 15522 | case BO_Div: { |
| 15523 | if (RHSFX.getValue() == 0) { |
| 15524 | Info.FFDiag(E, DiagId: diag::note_expr_divide_by_zero); |
| 15525 | return false; |
| 15526 | } |
| 15527 | Result = LHSFX.div(Other: RHSFX, Overflow: &OpOverflow) |
| 15528 | .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow); |
| 15529 | break; |
| 15530 | } |
| 15531 | case BO_Shl: |
| 15532 | case BO_Shr: { |
| 15533 | FixedPointSemantics LHSSema = LHSFX.getSemantics(); |
| 15534 | llvm::APSInt RHSVal = RHSFX.getValue(); |
| 15535 | |
| 15536 | unsigned ShiftBW = |
| 15537 | LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); |
| 15538 | unsigned Amt = RHSVal.getLimitedValue(Limit: ShiftBW - 1); |
| 15539 | // Embedded-C 4.1.6.2.2: |
| 15540 | // The right operand must be nonnegative and less than the total number |
| 15541 | // of (nonpadding) bits of the fixed-point operand ... |
| 15542 | if (RHSVal.isNegative()) |
| 15543 | Info.CCEDiag(E, DiagId: diag::note_constexpr_negative_shift) << RHSVal; |
| 15544 | else if (Amt != RHSVal) |
| 15545 | Info.CCEDiag(E, DiagId: diag::note_constexpr_large_shift) |
| 15546 | << RHSVal << E->getType() << ShiftBW; |
| 15547 | |
| 15548 | if (E->getOpcode() == BO_Shl) |
| 15549 | Result = LHSFX.shl(Amt, Overflow: &OpOverflow); |
| 15550 | else |
| 15551 | Result = LHSFX.shr(Amt, Overflow: &OpOverflow); |
| 15552 | break; |
| 15553 | } |
| 15554 | default: |
| 15555 | return false; |
| 15556 | } |
| 15557 | if (OpOverflow || ConversionOverflow) { |
| 15558 | if (Info.checkingForUndefinedBehavior()) |
| 15559 | Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(), |
| 15560 | DiagID: diag::warn_fixedpoint_constant_overflow) |
| 15561 | << Result.toString() << E->getType(); |
| 15562 | if (!HandleOverflow(Info, E, SrcValue: Result, DestType: E->getType())) |
| 15563 | return false; |
| 15564 | } |
| 15565 | return Success(V: Result, E); |
| 15566 | } |
| 15567 | |
| 15568 | //===----------------------------------------------------------------------===// |
| 15569 | // Float Evaluation |
| 15570 | //===----------------------------------------------------------------------===// |
| 15571 | |
| 15572 | namespace { |
| 15573 | class FloatExprEvaluator |
| 15574 | : public ExprEvaluatorBase<FloatExprEvaluator> { |
| 15575 | APFloat &Result; |
| 15576 | public: |
| 15577 | FloatExprEvaluator(EvalInfo &info, APFloat &result) |
| 15578 | : ExprEvaluatorBaseTy(info), Result(result) {} |
| 15579 | |
| 15580 | bool Success(const APValue &V, const Expr *e) { |
| 15581 | Result = V.getFloat(); |
| 15582 | return true; |
| 15583 | } |
| 15584 | |
| 15585 | bool ZeroInitialization(const Expr *E) { |
| 15586 | Result = APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: E->getType())); |
| 15587 | return true; |
| 15588 | } |
| 15589 | |
| 15590 | bool VisitCallExpr(const CallExpr *E); |
| 15591 | |
| 15592 | bool VisitUnaryOperator(const UnaryOperator *E); |
| 15593 | bool VisitBinaryOperator(const BinaryOperator *E); |
| 15594 | bool VisitFloatingLiteral(const FloatingLiteral *E); |
| 15595 | bool VisitCastExpr(const CastExpr *E); |
| 15596 | |
| 15597 | bool VisitUnaryReal(const UnaryOperator *E); |
| 15598 | bool VisitUnaryImag(const UnaryOperator *E); |
| 15599 | |
| 15600 | // FIXME: Missing: array subscript of vector, member of vector |
| 15601 | }; |
| 15602 | } // end anonymous namespace |
| 15603 | |
| 15604 | static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { |
| 15605 | assert(!E->isValueDependent()); |
| 15606 | assert(E->isPRValue() && E->getType()->isRealFloatingType()); |
| 15607 | return FloatExprEvaluator(Info, Result).Visit(S: E); |
| 15608 | } |
| 15609 | |
| 15610 | static bool TryEvaluateBuiltinNaN(const ASTContext &Context, |
| 15611 | QualType ResultTy, |
| 15612 | const Expr *Arg, |
| 15613 | bool SNaN, |
| 15614 | llvm::APFloat &Result) { |
| 15615 | const StringLiteral *S = dyn_cast<StringLiteral>(Val: Arg->IgnoreParenCasts()); |
| 15616 | if (!S) return false; |
| 15617 | |
| 15618 | const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(T: ResultTy); |
| 15619 | |
| 15620 | llvm::APInt fill; |
| 15621 | |
| 15622 | // Treat empty strings as if they were zero. |
| 15623 | if (S->getString().empty()) |
| 15624 | fill = llvm::APInt(32, 0); |
| 15625 | else if (S->getString().getAsInteger(Radix: 0, Result&: fill)) |
| 15626 | return false; |
| 15627 | |
| 15628 | if (Context.getTargetInfo().isNan2008()) { |
| 15629 | if (SNaN) |
| 15630 | Result = llvm::APFloat::getSNaN(Sem, Negative: false, payload: &fill); |
| 15631 | else |
| 15632 | Result = llvm::APFloat::getQNaN(Sem, Negative: false, payload: &fill); |
| 15633 | } else { |
| 15634 | // Prior to IEEE 754-2008, architectures were allowed to choose whether |
| 15635 | // the first bit of their significand was set for qNaN or sNaN. MIPS chose |
| 15636 | // a different encoding to what became a standard in 2008, and for pre- |
| 15637 | // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as |
| 15638 | // sNaN. This is now known as "legacy NaN" encoding. |
| 15639 | if (SNaN) |
| 15640 | Result = llvm::APFloat::getQNaN(Sem, Negative: false, payload: &fill); |
| 15641 | else |
| 15642 | Result = llvm::APFloat::getSNaN(Sem, Negative: false, payload: &fill); |
| 15643 | } |
| 15644 | |
| 15645 | return true; |
| 15646 | } |
| 15647 | |
| 15648 | bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { |
| 15649 | if (!IsConstantEvaluatedBuiltinCall(E)) |
| 15650 | return ExprEvaluatorBaseTy::VisitCallExpr(E); |
| 15651 | |
| 15652 | switch (E->getBuiltinCallee()) { |
| 15653 | default: |
| 15654 | return false; |
| 15655 | |
| 15656 | case Builtin::BI__builtin_huge_val: |
| 15657 | case Builtin::BI__builtin_huge_valf: |
| 15658 | case Builtin::BI__builtin_huge_vall: |
| 15659 | case Builtin::BI__builtin_huge_valf16: |
| 15660 | case Builtin::BI__builtin_huge_valf128: |
| 15661 | case Builtin::BI__builtin_inf: |
| 15662 | case Builtin::BI__builtin_inff: |
| 15663 | case Builtin::BI__builtin_infl: |
| 15664 | case Builtin::BI__builtin_inff16: |
| 15665 | case Builtin::BI__builtin_inff128: { |
| 15666 | const llvm::fltSemantics &Sem = |
| 15667 | Info.Ctx.getFloatTypeSemantics(T: E->getType()); |
| 15668 | Result = llvm::APFloat::getInf(Sem); |
| 15669 | return true; |
| 15670 | } |
| 15671 | |
| 15672 | case Builtin::BI__builtin_nans: |
| 15673 | case Builtin::BI__builtin_nansf: |
| 15674 | case Builtin::BI__builtin_nansl: |
| 15675 | case Builtin::BI__builtin_nansf16: |
| 15676 | case Builtin::BI__builtin_nansf128: |
| 15677 | if (!TryEvaluateBuiltinNaN(Context: Info.Ctx, ResultTy: E->getType(), Arg: E->getArg(Arg: 0), |
| 15678 | SNaN: true, Result)) |
| 15679 | return Error(E); |
| 15680 | return true; |
| 15681 | |
| 15682 | case Builtin::BI__builtin_nan: |
| 15683 | case Builtin::BI__builtin_nanf: |
| 15684 | case Builtin::BI__builtin_nanl: |
| 15685 | case Builtin::BI__builtin_nanf16: |
| 15686 | case Builtin::BI__builtin_nanf128: |
| 15687 | // If this is __builtin_nan() turn this into a nan, otherwise we |
| 15688 | // can't constant fold it. |
| 15689 | if (!TryEvaluateBuiltinNaN(Context: Info.Ctx, ResultTy: E->getType(), Arg: E->getArg(Arg: 0), |
| 15690 | SNaN: false, Result)) |
| 15691 | return Error(E); |
| 15692 | return true; |
| 15693 | |
| 15694 | case Builtin::BI__builtin_fabs: |
| 15695 | case Builtin::BI__builtin_fabsf: |
| 15696 | case Builtin::BI__builtin_fabsl: |
| 15697 | case Builtin::BI__builtin_fabsf128: |
| 15698 | // The C standard says "fabs raises no floating-point exceptions, |
| 15699 | // even if x is a signaling NaN. The returned value is independent of |
| 15700 | // the current rounding direction mode." Therefore constant folding can |
| 15701 | // proceed without regard to the floating point settings. |
| 15702 | // Reference, WG14 N2478 F.10.4.3 |
| 15703 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info)) |
| 15704 | return false; |
| 15705 | |
| 15706 | if (Result.isNegative()) |
| 15707 | Result.changeSign(); |
| 15708 | return true; |
| 15709 | |
| 15710 | case Builtin::BI__arithmetic_fence: |
| 15711 | return EvaluateFloat(E: E->getArg(Arg: 0), Result, Info); |
| 15712 | |
| 15713 | // FIXME: Builtin::BI__builtin_powi |
| 15714 | // FIXME: Builtin::BI__builtin_powif |
| 15715 | // FIXME: Builtin::BI__builtin_powil |
| 15716 | |
| 15717 | case Builtin::BI__builtin_copysign: |
| 15718 | case Builtin::BI__builtin_copysignf: |
| 15719 | case Builtin::BI__builtin_copysignl: |
| 15720 | case Builtin::BI__builtin_copysignf128: { |
| 15721 | APFloat RHS(0.); |
| 15722 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) || |
| 15723 | !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 15724 | return false; |
| 15725 | Result.copySign(RHS); |
| 15726 | return true; |
| 15727 | } |
| 15728 | |
| 15729 | case Builtin::BI__builtin_fmax: |
| 15730 | case Builtin::BI__builtin_fmaxf: |
| 15731 | case Builtin::BI__builtin_fmaxl: |
| 15732 | case Builtin::BI__builtin_fmaxf16: |
| 15733 | case Builtin::BI__builtin_fmaxf128: { |
| 15734 | APFloat RHS(0.); |
| 15735 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) || |
| 15736 | !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 15737 | return false; |
| 15738 | Result = maxnum(A: Result, B: RHS); |
| 15739 | return true; |
| 15740 | } |
| 15741 | |
| 15742 | case Builtin::BI__builtin_fmin: |
| 15743 | case Builtin::BI__builtin_fminf: |
| 15744 | case Builtin::BI__builtin_fminl: |
| 15745 | case Builtin::BI__builtin_fminf16: |
| 15746 | case Builtin::BI__builtin_fminf128: { |
| 15747 | APFloat RHS(0.); |
| 15748 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) || |
| 15749 | !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 15750 | return false; |
| 15751 | Result = minnum(A: Result, B: RHS); |
| 15752 | return true; |
| 15753 | } |
| 15754 | |
| 15755 | case Builtin::BI__builtin_fmaximum_num: |
| 15756 | case Builtin::BI__builtin_fmaximum_numf: |
| 15757 | case Builtin::BI__builtin_fmaximum_numl: |
| 15758 | case Builtin::BI__builtin_fmaximum_numf16: |
| 15759 | case Builtin::BI__builtin_fmaximum_numf128: { |
| 15760 | APFloat RHS(0.); |
| 15761 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) || |
| 15762 | !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 15763 | return false; |
| 15764 | Result = maximumnum(A: Result, B: RHS); |
| 15765 | return true; |
| 15766 | } |
| 15767 | |
| 15768 | case Builtin::BI__builtin_fminimum_num: |
| 15769 | case Builtin::BI__builtin_fminimum_numf: |
| 15770 | case Builtin::BI__builtin_fminimum_numl: |
| 15771 | case Builtin::BI__builtin_fminimum_numf16: |
| 15772 | case Builtin::BI__builtin_fminimum_numf128: { |
| 15773 | APFloat RHS(0.); |
| 15774 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) || |
| 15775 | !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info)) |
| 15776 | return false; |
| 15777 | Result = minimumnum(A: Result, B: RHS); |
| 15778 | return true; |
| 15779 | } |
| 15780 | } |
| 15781 | } |
| 15782 | |
| 15783 | bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { |
| 15784 | if (E->getSubExpr()->getType()->isAnyComplexType()) { |
| 15785 | ComplexValue CV; |
| 15786 | if (!EvaluateComplex(E: E->getSubExpr(), Res&: CV, Info)) |
| 15787 | return false; |
| 15788 | Result = CV.FloatReal; |
| 15789 | return true; |
| 15790 | } |
| 15791 | |
| 15792 | return Visit(S: E->getSubExpr()); |
| 15793 | } |
| 15794 | |
| 15795 | bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { |
| 15796 | if (E->getSubExpr()->getType()->isAnyComplexType()) { |
| 15797 | ComplexValue CV; |
| 15798 | if (!EvaluateComplex(E: E->getSubExpr(), Res&: CV, Info)) |
| 15799 | return false; |
| 15800 | Result = CV.FloatImag; |
| 15801 | return true; |
| 15802 | } |
| 15803 | |
| 15804 | VisitIgnoredValue(E: E->getSubExpr()); |
| 15805 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(T: E->getType()); |
| 15806 | Result = llvm::APFloat::getZero(Sem); |
| 15807 | return true; |
| 15808 | } |
| 15809 | |
| 15810 | bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { |
| 15811 | switch (E->getOpcode()) { |
| 15812 | default: return Error(E); |
| 15813 | case UO_Plus: |
| 15814 | return EvaluateFloat(E: E->getSubExpr(), Result, Info); |
| 15815 | case UO_Minus: |
| 15816 | // In C standard, WG14 N2478 F.3 p4 |
| 15817 | // "the unary - raises no floating point exceptions, |
| 15818 | // even if the operand is signalling." |
| 15819 | if (!EvaluateFloat(E: E->getSubExpr(), Result, Info)) |
| 15820 | return false; |
| 15821 | Result.changeSign(); |
| 15822 | return true; |
| 15823 | } |
| 15824 | } |
| 15825 | |
| 15826 | bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { |
| 15827 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) |
| 15828 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 15829 | |
| 15830 | APFloat RHS(0.0); |
| 15831 | bool LHSOK = EvaluateFloat(E: E->getLHS(), Result, Info); |
| 15832 | if (!LHSOK && !Info.noteFailure()) |
| 15833 | return false; |
| 15834 | return EvaluateFloat(E: E->getRHS(), Result&: RHS, Info) && LHSOK && |
| 15835 | handleFloatFloatBinOp(Info, E, LHS&: Result, Opcode: E->getOpcode(), RHS); |
| 15836 | } |
| 15837 | |
| 15838 | bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { |
| 15839 | Result = E->getValue(); |
| 15840 | return true; |
| 15841 | } |
| 15842 | |
| 15843 | bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 15844 | const Expr* SubExpr = E->getSubExpr(); |
| 15845 | |
| 15846 | switch (E->getCastKind()) { |
| 15847 | default: |
| 15848 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 15849 | |
| 15850 | case CK_IntegralToFloating: { |
| 15851 | APSInt IntResult; |
| 15852 | const FPOptions FPO = E->getFPFeaturesInEffect( |
| 15853 | LO: Info.Ctx.getLangOpts()); |
| 15854 | return EvaluateInteger(E: SubExpr, Result&: IntResult, Info) && |
| 15855 | HandleIntToFloatCast(Info, E, FPO, SrcType: SubExpr->getType(), |
| 15856 | Value: IntResult, DestType: E->getType(), Result); |
| 15857 | } |
| 15858 | |
| 15859 | case CK_FixedPointToFloating: { |
| 15860 | APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(Ty: SubExpr->getType())); |
| 15861 | if (!EvaluateFixedPoint(E: SubExpr, Result&: FixResult, Info)) |
| 15862 | return false; |
| 15863 | Result = |
| 15864 | FixResult.convertToFloat(FloatSema: Info.Ctx.getFloatTypeSemantics(T: E->getType())); |
| 15865 | return true; |
| 15866 | } |
| 15867 | |
| 15868 | case CK_FloatingCast: { |
| 15869 | if (!Visit(S: SubExpr)) |
| 15870 | return false; |
| 15871 | return HandleFloatToFloatCast(Info, E, SrcType: SubExpr->getType(), DestType: E->getType(), |
| 15872 | Result); |
| 15873 | } |
| 15874 | |
| 15875 | case CK_FloatingComplexToReal: { |
| 15876 | ComplexValue V; |
| 15877 | if (!EvaluateComplex(E: SubExpr, Res&: V, Info)) |
| 15878 | return false; |
| 15879 | Result = V.getComplexFloatReal(); |
| 15880 | return true; |
| 15881 | } |
| 15882 | case CK_HLSLVectorTruncation: { |
| 15883 | APValue Val; |
| 15884 | if (!EvaluateVector(E: SubExpr, Result&: Val, Info)) |
| 15885 | return Error(E); |
| 15886 | return Success(V: Val.getVectorElt(I: 0), e: E); |
| 15887 | } |
| 15888 | } |
| 15889 | } |
| 15890 | |
| 15891 | //===----------------------------------------------------------------------===// |
| 15892 | // Complex Evaluation (for float and integer) |
| 15893 | //===----------------------------------------------------------------------===// |
| 15894 | |
| 15895 | namespace { |
| 15896 | class ComplexExprEvaluator |
| 15897 | : public ExprEvaluatorBase<ComplexExprEvaluator> { |
| 15898 | ComplexValue &Result; |
| 15899 | |
| 15900 | public: |
| 15901 | ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) |
| 15902 | : ExprEvaluatorBaseTy(info), Result(Result) {} |
| 15903 | |
| 15904 | bool Success(const APValue &V, const Expr *e) { |
| 15905 | Result.setFrom(V); |
| 15906 | return true; |
| 15907 | } |
| 15908 | |
| 15909 | bool ZeroInitialization(const Expr *E); |
| 15910 | |
| 15911 | //===--------------------------------------------------------------------===// |
| 15912 | // Visitor Methods |
| 15913 | //===--------------------------------------------------------------------===// |
| 15914 | |
| 15915 | bool VisitImaginaryLiteral(const ImaginaryLiteral *E); |
| 15916 | bool VisitCastExpr(const CastExpr *E); |
| 15917 | bool VisitBinaryOperator(const BinaryOperator *E); |
| 15918 | bool VisitUnaryOperator(const UnaryOperator *E); |
| 15919 | bool VisitInitListExpr(const InitListExpr *E); |
| 15920 | bool VisitCallExpr(const CallExpr *E); |
| 15921 | }; |
| 15922 | } // end anonymous namespace |
| 15923 | |
| 15924 | static bool EvaluateComplex(const Expr *E, ComplexValue &Result, |
| 15925 | EvalInfo &Info) { |
| 15926 | assert(!E->isValueDependent()); |
| 15927 | assert(E->isPRValue() && E->getType()->isAnyComplexType()); |
| 15928 | return ComplexExprEvaluator(Info, Result).Visit(S: E); |
| 15929 | } |
| 15930 | |
| 15931 | bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { |
| 15932 | QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); |
| 15933 | if (ElemTy->isRealFloatingType()) { |
| 15934 | Result.makeComplexFloat(); |
| 15935 | APFloat Zero = APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: ElemTy)); |
| 15936 | Result.FloatReal = Zero; |
| 15937 | Result.FloatImag = Zero; |
| 15938 | } else { |
| 15939 | Result.makeComplexInt(); |
| 15940 | APSInt Zero = Info.Ctx.MakeIntValue(Value: 0, Type: ElemTy); |
| 15941 | Result.IntReal = Zero; |
| 15942 | Result.IntImag = Zero; |
| 15943 | } |
| 15944 | return true; |
| 15945 | } |
| 15946 | |
| 15947 | bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { |
| 15948 | const Expr* SubExpr = E->getSubExpr(); |
| 15949 | |
| 15950 | if (SubExpr->getType()->isRealFloatingType()) { |
| 15951 | Result.makeComplexFloat(); |
| 15952 | APFloat &Imag = Result.FloatImag; |
| 15953 | if (!EvaluateFloat(E: SubExpr, Result&: Imag, Info)) |
| 15954 | return false; |
| 15955 | |
| 15956 | Result.FloatReal = APFloat(Imag.getSemantics()); |
| 15957 | return true; |
| 15958 | } else { |
| 15959 | assert(SubExpr->getType()->isIntegerType() && |
| 15960 | "Unexpected imaginary literal." ); |
| 15961 | |
| 15962 | Result.makeComplexInt(); |
| 15963 | APSInt &Imag = Result.IntImag; |
| 15964 | if (!EvaluateInteger(E: SubExpr, Result&: Imag, Info)) |
| 15965 | return false; |
| 15966 | |
| 15967 | Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); |
| 15968 | return true; |
| 15969 | } |
| 15970 | } |
| 15971 | |
| 15972 | bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { |
| 15973 | |
| 15974 | switch (E->getCastKind()) { |
| 15975 | case CK_BitCast: |
| 15976 | case CK_BaseToDerived: |
| 15977 | case CK_DerivedToBase: |
| 15978 | case CK_UncheckedDerivedToBase: |
| 15979 | case CK_Dynamic: |
| 15980 | case CK_ToUnion: |
| 15981 | case CK_ArrayToPointerDecay: |
| 15982 | case CK_FunctionToPointerDecay: |
| 15983 | case CK_NullToPointer: |
| 15984 | case CK_NullToMemberPointer: |
| 15985 | case CK_BaseToDerivedMemberPointer: |
| 15986 | case CK_DerivedToBaseMemberPointer: |
| 15987 | case CK_MemberPointerToBoolean: |
| 15988 | case CK_ReinterpretMemberPointer: |
| 15989 | case CK_ConstructorConversion: |
| 15990 | case CK_IntegralToPointer: |
| 15991 | case CK_PointerToIntegral: |
| 15992 | case CK_PointerToBoolean: |
| 15993 | case CK_ToVoid: |
| 15994 | case CK_VectorSplat: |
| 15995 | case CK_IntegralCast: |
| 15996 | case CK_BooleanToSignedIntegral: |
| 15997 | case CK_IntegralToBoolean: |
| 15998 | case CK_IntegralToFloating: |
| 15999 | case CK_FloatingToIntegral: |
| 16000 | case CK_FloatingToBoolean: |
| 16001 | case CK_FloatingCast: |
| 16002 | case CK_CPointerToObjCPointerCast: |
| 16003 | case CK_BlockPointerToObjCPointerCast: |
| 16004 | case CK_AnyPointerToBlockPointerCast: |
| 16005 | case CK_ObjCObjectLValueCast: |
| 16006 | case CK_FloatingComplexToReal: |
| 16007 | case CK_FloatingComplexToBoolean: |
| 16008 | case CK_IntegralComplexToReal: |
| 16009 | case CK_IntegralComplexToBoolean: |
| 16010 | case CK_ARCProduceObject: |
| 16011 | case CK_ARCConsumeObject: |
| 16012 | case CK_ARCReclaimReturnedObject: |
| 16013 | case CK_ARCExtendBlockObject: |
| 16014 | case CK_CopyAndAutoreleaseBlockObject: |
| 16015 | case CK_BuiltinFnToFnPtr: |
| 16016 | case CK_ZeroToOCLOpaqueType: |
| 16017 | case CK_NonAtomicToAtomic: |
| 16018 | case CK_AddressSpaceConversion: |
| 16019 | case CK_IntToOCLSampler: |
| 16020 | case CK_FloatingToFixedPoint: |
| 16021 | case CK_FixedPointToFloating: |
| 16022 | case CK_FixedPointCast: |
| 16023 | case CK_FixedPointToBoolean: |
| 16024 | case CK_FixedPointToIntegral: |
| 16025 | case CK_IntegralToFixedPoint: |
| 16026 | case CK_MatrixCast: |
| 16027 | case CK_HLSLVectorTruncation: |
| 16028 | case CK_HLSLElementwiseCast: |
| 16029 | case CK_HLSLAggregateSplatCast: |
| 16030 | llvm_unreachable("invalid cast kind for complex value" ); |
| 16031 | |
| 16032 | case CK_LValueToRValue: |
| 16033 | case CK_AtomicToNonAtomic: |
| 16034 | case CK_NoOp: |
| 16035 | case CK_LValueToRValueBitCast: |
| 16036 | case CK_HLSLArrayRValue: |
| 16037 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 16038 | |
| 16039 | case CK_Dependent: |
| 16040 | case CK_LValueBitCast: |
| 16041 | case CK_UserDefinedConversion: |
| 16042 | return Error(E); |
| 16043 | |
| 16044 | case CK_FloatingRealToComplex: { |
| 16045 | APFloat &Real = Result.FloatReal; |
| 16046 | if (!EvaluateFloat(E: E->getSubExpr(), Result&: Real, Info)) |
| 16047 | return false; |
| 16048 | |
| 16049 | Result.makeComplexFloat(); |
| 16050 | Result.FloatImag = APFloat(Real.getSemantics()); |
| 16051 | return true; |
| 16052 | } |
| 16053 | |
| 16054 | case CK_FloatingComplexCast: { |
| 16055 | if (!Visit(S: E->getSubExpr())) |
| 16056 | return false; |
| 16057 | |
| 16058 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); |
| 16059 | QualType From |
| 16060 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); |
| 16061 | |
| 16062 | return HandleFloatToFloatCast(Info, E, SrcType: From, DestType: To, Result&: Result.FloatReal) && |
| 16063 | HandleFloatToFloatCast(Info, E, SrcType: From, DestType: To, Result&: Result.FloatImag); |
| 16064 | } |
| 16065 | |
| 16066 | case CK_FloatingComplexToIntegralComplex: { |
| 16067 | if (!Visit(S: E->getSubExpr())) |
| 16068 | return false; |
| 16069 | |
| 16070 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); |
| 16071 | QualType From |
| 16072 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); |
| 16073 | Result.makeComplexInt(); |
| 16074 | return HandleFloatToIntCast(Info, E, SrcType: From, Value: Result.FloatReal, |
| 16075 | DestType: To, Result&: Result.IntReal) && |
| 16076 | HandleFloatToIntCast(Info, E, SrcType: From, Value: Result.FloatImag, |
| 16077 | DestType: To, Result&: Result.IntImag); |
| 16078 | } |
| 16079 | |
| 16080 | case CK_IntegralRealToComplex: { |
| 16081 | APSInt &Real = Result.IntReal; |
| 16082 | if (!EvaluateInteger(E: E->getSubExpr(), Result&: Real, Info)) |
| 16083 | return false; |
| 16084 | |
| 16085 | Result.makeComplexInt(); |
| 16086 | Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); |
| 16087 | return true; |
| 16088 | } |
| 16089 | |
| 16090 | case CK_IntegralComplexCast: { |
| 16091 | if (!Visit(S: E->getSubExpr())) |
| 16092 | return false; |
| 16093 | |
| 16094 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); |
| 16095 | QualType From |
| 16096 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); |
| 16097 | |
| 16098 | Result.IntReal = HandleIntToIntCast(Info, E, DestType: To, SrcType: From, Value: Result.IntReal); |
| 16099 | Result.IntImag = HandleIntToIntCast(Info, E, DestType: To, SrcType: From, Value: Result.IntImag); |
| 16100 | return true; |
| 16101 | } |
| 16102 | |
| 16103 | case CK_IntegralComplexToFloatingComplex: { |
| 16104 | if (!Visit(S: E->getSubExpr())) |
| 16105 | return false; |
| 16106 | |
| 16107 | const FPOptions FPO = E->getFPFeaturesInEffect( |
| 16108 | LO: Info.Ctx.getLangOpts()); |
| 16109 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); |
| 16110 | QualType From |
| 16111 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); |
| 16112 | Result.makeComplexFloat(); |
| 16113 | return HandleIntToFloatCast(Info, E, FPO, SrcType: From, Value: Result.IntReal, |
| 16114 | DestType: To, Result&: Result.FloatReal) && |
| 16115 | HandleIntToFloatCast(Info, E, FPO, SrcType: From, Value: Result.IntImag, |
| 16116 | DestType: To, Result&: Result.FloatImag); |
| 16117 | } |
| 16118 | } |
| 16119 | |
| 16120 | llvm_unreachable("unknown cast resulting in complex value" ); |
| 16121 | } |
| 16122 | |
| 16123 | void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, |
| 16124 | APFloat &ResR, APFloat &ResI) { |
| 16125 | // This is an implementation of complex multiplication according to the |
| 16126 | // constraints laid out in C11 Annex G. The implementation uses the |
| 16127 | // following naming scheme: |
| 16128 | // (a + ib) * (c + id) |
| 16129 | |
| 16130 | APFloat AC = A * C; |
| 16131 | APFloat BD = B * D; |
| 16132 | APFloat AD = A * D; |
| 16133 | APFloat BC = B * C; |
| 16134 | ResR = AC - BD; |
| 16135 | ResI = AD + BC; |
| 16136 | if (ResR.isNaN() && ResI.isNaN()) { |
| 16137 | bool Recalc = false; |
| 16138 | if (A.isInfinity() || B.isInfinity()) { |
| 16139 | A = APFloat::copySign(Value: APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), |
| 16140 | Sign: A); |
| 16141 | B = APFloat::copySign(Value: APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), |
| 16142 | Sign: B); |
| 16143 | if (C.isNaN()) |
| 16144 | C = APFloat::copySign(Value: APFloat(C.getSemantics()), Sign: C); |
| 16145 | if (D.isNaN()) |
| 16146 | D = APFloat::copySign(Value: APFloat(D.getSemantics()), Sign: D); |
| 16147 | Recalc = true; |
| 16148 | } |
| 16149 | if (C.isInfinity() || D.isInfinity()) { |
| 16150 | C = APFloat::copySign(Value: APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), |
| 16151 | Sign: C); |
| 16152 | D = APFloat::copySign(Value: APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), |
| 16153 | Sign: D); |
| 16154 | if (A.isNaN()) |
| 16155 | A = APFloat::copySign(Value: APFloat(A.getSemantics()), Sign: A); |
| 16156 | if (B.isNaN()) |
| 16157 | B = APFloat::copySign(Value: APFloat(B.getSemantics()), Sign: B); |
| 16158 | Recalc = true; |
| 16159 | } |
| 16160 | if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() || |
| 16161 | BC.isInfinity())) { |
| 16162 | if (A.isNaN()) |
| 16163 | A = APFloat::copySign(Value: APFloat(A.getSemantics()), Sign: A); |
| 16164 | if (B.isNaN()) |
| 16165 | B = APFloat::copySign(Value: APFloat(B.getSemantics()), Sign: B); |
| 16166 | if (C.isNaN()) |
| 16167 | C = APFloat::copySign(Value: APFloat(C.getSemantics()), Sign: C); |
| 16168 | if (D.isNaN()) |
| 16169 | D = APFloat::copySign(Value: APFloat(D.getSemantics()), Sign: D); |
| 16170 | Recalc = true; |
| 16171 | } |
| 16172 | if (Recalc) { |
| 16173 | ResR = APFloat::getInf(Sem: A.getSemantics()) * (A * C - B * D); |
| 16174 | ResI = APFloat::getInf(Sem: A.getSemantics()) * (A * D + B * C); |
| 16175 | } |
| 16176 | } |
| 16177 | } |
| 16178 | |
| 16179 | void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, |
| 16180 | APFloat &ResR, APFloat &ResI) { |
| 16181 | // This is an implementation of complex division according to the |
| 16182 | // constraints laid out in C11 Annex G. The implementation uses the |
| 16183 | // following naming scheme: |
| 16184 | // (a + ib) / (c + id) |
| 16185 | |
| 16186 | int DenomLogB = 0; |
| 16187 | APFloat MaxCD = maxnum(A: abs(X: C), B: abs(X: D)); |
| 16188 | if (MaxCD.isFinite()) { |
| 16189 | DenomLogB = ilogb(Arg: MaxCD); |
| 16190 | C = scalbn(X: C, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven); |
| 16191 | D = scalbn(X: D, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven); |
| 16192 | } |
| 16193 | APFloat Denom = C * C + D * D; |
| 16194 | ResR = |
| 16195 | scalbn(X: (A * C + B * D) / Denom, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven); |
| 16196 | ResI = |
| 16197 | scalbn(X: (B * C - A * D) / Denom, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven); |
| 16198 | if (ResR.isNaN() && ResI.isNaN()) { |
| 16199 | if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { |
| 16200 | ResR = APFloat::getInf(Sem: ResR.getSemantics(), Negative: C.isNegative()) * A; |
| 16201 | ResI = APFloat::getInf(Sem: ResR.getSemantics(), Negative: C.isNegative()) * B; |
| 16202 | } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && |
| 16203 | D.isFinite()) { |
| 16204 | A = APFloat::copySign(Value: APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), |
| 16205 | Sign: A); |
| 16206 | B = APFloat::copySign(Value: APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), |
| 16207 | Sign: B); |
| 16208 | ResR = APFloat::getInf(Sem: ResR.getSemantics()) * (A * C + B * D); |
| 16209 | ResI = APFloat::getInf(Sem: ResI.getSemantics()) * (B * C - A * D); |
| 16210 | } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { |
| 16211 | C = APFloat::copySign(Value: APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), |
| 16212 | Sign: C); |
| 16213 | D = APFloat::copySign(Value: APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), |
| 16214 | Sign: D); |
| 16215 | ResR = APFloat::getZero(Sem: ResR.getSemantics()) * (A * C + B * D); |
| 16216 | ResI = APFloat::getZero(Sem: ResI.getSemantics()) * (B * C - A * D); |
| 16217 | } |
| 16218 | } |
| 16219 | } |
| 16220 | |
| 16221 | bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { |
| 16222 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) |
| 16223 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); |
| 16224 | |
| 16225 | // Track whether the LHS or RHS is real at the type system level. When this is |
| 16226 | // the case we can simplify our evaluation strategy. |
| 16227 | bool LHSReal = false, RHSReal = false; |
| 16228 | |
| 16229 | bool LHSOK; |
| 16230 | if (E->getLHS()->getType()->isRealFloatingType()) { |
| 16231 | LHSReal = true; |
| 16232 | APFloat &Real = Result.FloatReal; |
| 16233 | LHSOK = EvaluateFloat(E: E->getLHS(), Result&: Real, Info); |
| 16234 | if (LHSOK) { |
| 16235 | Result.makeComplexFloat(); |
| 16236 | Result.FloatImag = APFloat(Real.getSemantics()); |
| 16237 | } |
| 16238 | } else { |
| 16239 | LHSOK = Visit(S: E->getLHS()); |
| 16240 | } |
| 16241 | if (!LHSOK && !Info.noteFailure()) |
| 16242 | return false; |
| 16243 | |
| 16244 | ComplexValue RHS; |
| 16245 | if (E->getRHS()->getType()->isRealFloatingType()) { |
| 16246 | RHSReal = true; |
| 16247 | APFloat &Real = RHS.FloatReal; |
| 16248 | if (!EvaluateFloat(E: E->getRHS(), Result&: Real, Info) || !LHSOK) |
| 16249 | return false; |
| 16250 | RHS.makeComplexFloat(); |
| 16251 | RHS.FloatImag = APFloat(Real.getSemantics()); |
| 16252 | } else if (!EvaluateComplex(E: E->getRHS(), Result&: RHS, Info) || !LHSOK) |
| 16253 | return false; |
| 16254 | |
| 16255 | assert(!(LHSReal && RHSReal) && |
| 16256 | "Cannot have both operands of a complex operation be real." ); |
| 16257 | switch (E->getOpcode()) { |
| 16258 | default: return Error(E); |
| 16259 | case BO_Add: |
| 16260 | if (Result.isComplexFloat()) { |
| 16261 | Result.getComplexFloatReal().add(RHS: RHS.getComplexFloatReal(), |
| 16262 | RM: APFloat::rmNearestTiesToEven); |
| 16263 | if (LHSReal) |
| 16264 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); |
| 16265 | else if (!RHSReal) |
| 16266 | Result.getComplexFloatImag().add(RHS: RHS.getComplexFloatImag(), |
| 16267 | RM: APFloat::rmNearestTiesToEven); |
| 16268 | } else { |
| 16269 | Result.getComplexIntReal() += RHS.getComplexIntReal(); |
| 16270 | Result.getComplexIntImag() += RHS.getComplexIntImag(); |
| 16271 | } |
| 16272 | break; |
| 16273 | case BO_Sub: |
| 16274 | if (Result.isComplexFloat()) { |
| 16275 | Result.getComplexFloatReal().subtract(RHS: RHS.getComplexFloatReal(), |
| 16276 | RM: APFloat::rmNearestTiesToEven); |
| 16277 | if (LHSReal) { |
| 16278 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); |
| 16279 | Result.getComplexFloatImag().changeSign(); |
| 16280 | } else if (!RHSReal) { |
| 16281 | Result.getComplexFloatImag().subtract(RHS: RHS.getComplexFloatImag(), |
| 16282 | RM: APFloat::rmNearestTiesToEven); |
| 16283 | } |
| 16284 | } else { |
| 16285 | Result.getComplexIntReal() -= RHS.getComplexIntReal(); |
| 16286 | Result.getComplexIntImag() -= RHS.getComplexIntImag(); |
| 16287 | } |
| 16288 | break; |
| 16289 | case BO_Mul: |
| 16290 | if (Result.isComplexFloat()) { |
| 16291 | // This is an implementation of complex multiplication according to the |
| 16292 | // constraints laid out in C11 Annex G. The implementation uses the |
| 16293 | // following naming scheme: |
| 16294 | // (a + ib) * (c + id) |
| 16295 | ComplexValue LHS = Result; |
| 16296 | APFloat &A = LHS.getComplexFloatReal(); |
| 16297 | APFloat &B = LHS.getComplexFloatImag(); |
| 16298 | APFloat &C = RHS.getComplexFloatReal(); |
| 16299 | APFloat &D = RHS.getComplexFloatImag(); |
| 16300 | APFloat &ResR = Result.getComplexFloatReal(); |
| 16301 | APFloat &ResI = Result.getComplexFloatImag(); |
| 16302 | if (LHSReal) { |
| 16303 | assert(!RHSReal && "Cannot have two real operands for a complex op!" ); |
| 16304 | ResR = A; |
| 16305 | ResI = A; |
| 16306 | // ResR = A * C; |
| 16307 | // ResI = A * D; |
| 16308 | if (!handleFloatFloatBinOp(Info, E, LHS&: ResR, Opcode: BO_Mul, RHS: C) || |
| 16309 | !handleFloatFloatBinOp(Info, E, LHS&: ResI, Opcode: BO_Mul, RHS: D)) |
| 16310 | return false; |
| 16311 | } else if (RHSReal) { |
| 16312 | // ResR = C * A; |
| 16313 | // ResI = C * B; |
| 16314 | ResR = C; |
| 16315 | ResI = C; |
| 16316 | if (!handleFloatFloatBinOp(Info, E, LHS&: ResR, Opcode: BO_Mul, RHS: A) || |
| 16317 | !handleFloatFloatBinOp(Info, E, LHS&: ResI, Opcode: BO_Mul, RHS: B)) |
| 16318 | return false; |
| 16319 | } else { |
| 16320 | HandleComplexComplexMul(A, B, C, D, ResR, ResI); |
| 16321 | } |
| 16322 | } else { |
| 16323 | ComplexValue LHS = Result; |
| 16324 | Result.getComplexIntReal() = |
| 16325 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() - |
| 16326 | LHS.getComplexIntImag() * RHS.getComplexIntImag()); |
| 16327 | Result.getComplexIntImag() = |
| 16328 | (LHS.getComplexIntReal() * RHS.getComplexIntImag() + |
| 16329 | LHS.getComplexIntImag() * RHS.getComplexIntReal()); |
| 16330 | } |
| 16331 | break; |
| 16332 | case BO_Div: |
| 16333 | if (Result.isComplexFloat()) { |
| 16334 | // This is an implementation of complex division according to the |
| 16335 | // constraints laid out in C11 Annex G. The implementation uses the |
| 16336 | // following naming scheme: |
| 16337 | // (a + ib) / (c + id) |
| 16338 | ComplexValue LHS = Result; |
| 16339 | APFloat &A = LHS.getComplexFloatReal(); |
| 16340 | APFloat &B = LHS.getComplexFloatImag(); |
| 16341 | APFloat &C = RHS.getComplexFloatReal(); |
| 16342 | APFloat &D = RHS.getComplexFloatImag(); |
| 16343 | APFloat &ResR = Result.getComplexFloatReal(); |
| 16344 | APFloat &ResI = Result.getComplexFloatImag(); |
| 16345 | if (RHSReal) { |
| 16346 | ResR = A; |
| 16347 | ResI = B; |
| 16348 | // ResR = A / C; |
| 16349 | // ResI = B / C; |
| 16350 | if (!handleFloatFloatBinOp(Info, E, LHS&: ResR, Opcode: BO_Div, RHS: C) || |
| 16351 | !handleFloatFloatBinOp(Info, E, LHS&: ResI, Opcode: BO_Div, RHS: C)) |
| 16352 | return false; |
| 16353 | } else { |
| 16354 | if (LHSReal) { |
| 16355 | // No real optimizations we can do here, stub out with zero. |
| 16356 | B = APFloat::getZero(Sem: A.getSemantics()); |
| 16357 | } |
| 16358 | HandleComplexComplexDiv(A, B, C, D, ResR, ResI); |
| 16359 | } |
| 16360 | } else { |
| 16361 | ComplexValue LHS = Result; |
| 16362 | APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + |
| 16363 | RHS.getComplexIntImag() * RHS.getComplexIntImag(); |
| 16364 | if (Den.isZero()) |
| 16365 | return Error(E, D: diag::note_expr_divide_by_zero); |
| 16366 | |
| 16367 | Result.getComplexIntReal() = |
| 16368 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() + |
| 16369 | LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; |
| 16370 | Result.getComplexIntImag() = |
| 16371 | (LHS.getComplexIntImag() * RHS.getComplexIntReal() - |
| 16372 | LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; |
| 16373 | } |
| 16374 | break; |
| 16375 | } |
| 16376 | |
| 16377 | return true; |
| 16378 | } |
| 16379 | |
| 16380 | bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { |
| 16381 | // Get the operand value into 'Result'. |
| 16382 | if (!Visit(S: E->getSubExpr())) |
| 16383 | return false; |
| 16384 | |
| 16385 | switch (E->getOpcode()) { |
| 16386 | default: |
| 16387 | return Error(E); |
| 16388 | case UO_Extension: |
| 16389 | return true; |
| 16390 | case UO_Plus: |
| 16391 | // The result is always just the subexpr. |
| 16392 | return true; |
| 16393 | case UO_Minus: |
| 16394 | if (Result.isComplexFloat()) { |
| 16395 | Result.getComplexFloatReal().changeSign(); |
| 16396 | Result.getComplexFloatImag().changeSign(); |
| 16397 | } |
| 16398 | else { |
| 16399 | Result.getComplexIntReal() = -Result.getComplexIntReal(); |
| 16400 | Result.getComplexIntImag() = -Result.getComplexIntImag(); |
| 16401 | } |
| 16402 | return true; |
| 16403 | case UO_Not: |
| 16404 | if (Result.isComplexFloat()) |
| 16405 | Result.getComplexFloatImag().changeSign(); |
| 16406 | else |
| 16407 | Result.getComplexIntImag() = -Result.getComplexIntImag(); |
| 16408 | return true; |
| 16409 | } |
| 16410 | } |
| 16411 | |
| 16412 | bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { |
| 16413 | if (E->getNumInits() == 2) { |
| 16414 | if (E->getType()->isComplexType()) { |
| 16415 | Result.makeComplexFloat(); |
| 16416 | if (!EvaluateFloat(E: E->getInit(Init: 0), Result&: Result.FloatReal, Info)) |
| 16417 | return false; |
| 16418 | if (!EvaluateFloat(E: E->getInit(Init: 1), Result&: Result.FloatImag, Info)) |
| 16419 | return false; |
| 16420 | } else { |
| 16421 | Result.makeComplexInt(); |
| 16422 | if (!EvaluateInteger(E: E->getInit(Init: 0), Result&: Result.IntReal, Info)) |
| 16423 | return false; |
| 16424 | if (!EvaluateInteger(E: E->getInit(Init: 1), Result&: Result.IntImag, Info)) |
| 16425 | return false; |
| 16426 | } |
| 16427 | return true; |
| 16428 | } |
| 16429 | return ExprEvaluatorBaseTy::VisitInitListExpr(E); |
| 16430 | } |
| 16431 | |
| 16432 | bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { |
| 16433 | if (!IsConstantEvaluatedBuiltinCall(E)) |
| 16434 | return ExprEvaluatorBaseTy::VisitCallExpr(E); |
| 16435 | |
| 16436 | switch (E->getBuiltinCallee()) { |
| 16437 | case Builtin::BI__builtin_complex: |
| 16438 | Result.makeComplexFloat(); |
| 16439 | if (!EvaluateFloat(E: E->getArg(Arg: 0), Result&: Result.FloatReal, Info)) |
| 16440 | return false; |
| 16441 | if (!EvaluateFloat(E: E->getArg(Arg: 1), Result&: Result.FloatImag, Info)) |
| 16442 | return false; |
| 16443 | return true; |
| 16444 | |
| 16445 | default: |
| 16446 | return false; |
| 16447 | } |
| 16448 | } |
| 16449 | |
| 16450 | //===----------------------------------------------------------------------===// |
| 16451 | // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic |
| 16452 | // implicit conversion. |
| 16453 | //===----------------------------------------------------------------------===// |
| 16454 | |
| 16455 | namespace { |
| 16456 | class AtomicExprEvaluator : |
| 16457 | public ExprEvaluatorBase<AtomicExprEvaluator> { |
| 16458 | const LValue *This; |
| 16459 | APValue &Result; |
| 16460 | public: |
| 16461 | AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) |
| 16462 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} |
| 16463 | |
| 16464 | bool Success(const APValue &V, const Expr *E) { |
| 16465 | Result = V; |
| 16466 | return true; |
| 16467 | } |
| 16468 | |
| 16469 | bool ZeroInitialization(const Expr *E) { |
| 16470 | ImplicitValueInitExpr VIE( |
| 16471 | E->getType()->castAs<AtomicType>()->getValueType()); |
| 16472 | // For atomic-qualified class (and array) types in C++, initialize the |
| 16473 | // _Atomic-wrapped subobject directly, in-place. |
| 16474 | return This ? EvaluateInPlace(Result, Info, This: *This, E: &VIE) |
| 16475 | : Evaluate(Result, Info, E: &VIE); |
| 16476 | } |
| 16477 | |
| 16478 | bool VisitCastExpr(const CastExpr *E) { |
| 16479 | switch (E->getCastKind()) { |
| 16480 | default: |
| 16481 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 16482 | case CK_NullToPointer: |
| 16483 | VisitIgnoredValue(E: E->getSubExpr()); |
| 16484 | return ZeroInitialization(E); |
| 16485 | case CK_NonAtomicToAtomic: |
| 16486 | return This ? EvaluateInPlace(Result, Info, This: *This, E: E->getSubExpr()) |
| 16487 | : Evaluate(Result, Info, E: E->getSubExpr()); |
| 16488 | } |
| 16489 | } |
| 16490 | }; |
| 16491 | } // end anonymous namespace |
| 16492 | |
| 16493 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, |
| 16494 | EvalInfo &Info) { |
| 16495 | assert(!E->isValueDependent()); |
| 16496 | assert(E->isPRValue() && E->getType()->isAtomicType()); |
| 16497 | return AtomicExprEvaluator(Info, This, Result).Visit(S: E); |
| 16498 | } |
| 16499 | |
| 16500 | //===----------------------------------------------------------------------===// |
| 16501 | // Void expression evaluation, primarily for a cast to void on the LHS of a |
| 16502 | // comma operator |
| 16503 | //===----------------------------------------------------------------------===// |
| 16504 | |
| 16505 | namespace { |
| 16506 | class VoidExprEvaluator |
| 16507 | : public ExprEvaluatorBase<VoidExprEvaluator> { |
| 16508 | public: |
| 16509 | VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} |
| 16510 | |
| 16511 | bool Success(const APValue &V, const Expr *e) { return true; } |
| 16512 | |
| 16513 | bool ZeroInitialization(const Expr *E) { return true; } |
| 16514 | |
| 16515 | bool VisitCastExpr(const CastExpr *E) { |
| 16516 | switch (E->getCastKind()) { |
| 16517 | default: |
| 16518 | return ExprEvaluatorBaseTy::VisitCastExpr(E); |
| 16519 | case CK_ToVoid: |
| 16520 | VisitIgnoredValue(E: E->getSubExpr()); |
| 16521 | return true; |
| 16522 | } |
| 16523 | } |
| 16524 | |
| 16525 | bool VisitCallExpr(const CallExpr *E) { |
| 16526 | if (!IsConstantEvaluatedBuiltinCall(E)) |
| 16527 | return ExprEvaluatorBaseTy::VisitCallExpr(E); |
| 16528 | |
| 16529 | switch (E->getBuiltinCallee()) { |
| 16530 | case Builtin::BI__assume: |
| 16531 | case Builtin::BI__builtin_assume: |
| 16532 | // The argument is not evaluated! |
| 16533 | return true; |
| 16534 | |
| 16535 | case Builtin::BI__builtin_operator_delete: |
| 16536 | return HandleOperatorDeleteCall(Info, E); |
| 16537 | |
| 16538 | default: |
| 16539 | return false; |
| 16540 | } |
| 16541 | } |
| 16542 | |
| 16543 | bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); |
| 16544 | }; |
| 16545 | } // end anonymous namespace |
| 16546 | |
| 16547 | bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { |
| 16548 | // We cannot speculatively evaluate a delete expression. |
| 16549 | if (Info.SpeculativeEvaluationDepth) |
| 16550 | return false; |
| 16551 | |
| 16552 | FunctionDecl *OperatorDelete = E->getOperatorDelete(); |
| 16553 | if (!OperatorDelete |
| 16554 | ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) { |
| 16555 | Info.FFDiag(E, DiagId: diag::note_constexpr_new_non_replaceable) |
| 16556 | << isa<CXXMethodDecl>(Val: OperatorDelete) << OperatorDelete; |
| 16557 | return false; |
| 16558 | } |
| 16559 | |
| 16560 | const Expr *Arg = E->getArgument(); |
| 16561 | |
| 16562 | LValue Pointer; |
| 16563 | if (!EvaluatePointer(E: Arg, Result&: Pointer, Info)) |
| 16564 | return false; |
| 16565 | if (Pointer.Designator.Invalid) |
| 16566 | return false; |
| 16567 | |
| 16568 | // Deleting a null pointer has no effect. |
| 16569 | if (Pointer.isNullPointer()) { |
| 16570 | // This is the only case where we need to produce an extension warning: |
| 16571 | // the only other way we can succeed is if we find a dynamic allocation, |
| 16572 | // and we will have warned when we allocated it in that case. |
| 16573 | if (!Info.getLangOpts().CPlusPlus20) |
| 16574 | Info.CCEDiag(E, DiagId: diag::note_constexpr_new); |
| 16575 | return true; |
| 16576 | } |
| 16577 | |
| 16578 | std::optional<DynAlloc *> Alloc = CheckDeleteKind( |
| 16579 | Info, E, Pointer, DeallocKind: E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); |
| 16580 | if (!Alloc) |
| 16581 | return false; |
| 16582 | QualType AllocType = Pointer.Base.getDynamicAllocType(); |
| 16583 | |
| 16584 | // For the non-array case, the designator must be empty if the static type |
| 16585 | // does not have a virtual destructor. |
| 16586 | if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && |
| 16587 | !hasVirtualDestructor(T: Arg->getType()->getPointeeType())) { |
| 16588 | Info.FFDiag(E, DiagId: diag::note_constexpr_delete_base_nonvirt_dtor) |
| 16589 | << Arg->getType()->getPointeeType() << AllocType; |
| 16590 | return false; |
| 16591 | } |
| 16592 | |
| 16593 | // For a class type with a virtual destructor, the selected operator delete |
| 16594 | // is the one looked up when building the destructor. |
| 16595 | if (!E->isArrayForm() && !E->isGlobalDelete()) { |
| 16596 | const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(T: AllocType); |
| 16597 | if (VirtualDelete && |
| 16598 | !VirtualDelete |
| 16599 | ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) { |
| 16600 | Info.FFDiag(E, DiagId: diag::note_constexpr_new_non_replaceable) |
| 16601 | << isa<CXXMethodDecl>(Val: VirtualDelete) << VirtualDelete; |
| 16602 | return false; |
| 16603 | } |
| 16604 | } |
| 16605 | |
| 16606 | if (!HandleDestruction(Info, Loc: E->getExprLoc(), LVBase: Pointer.getLValueBase(), |
| 16607 | Value&: (*Alloc)->Value, T: AllocType)) |
| 16608 | return false; |
| 16609 | |
| 16610 | if (!Info.HeapAllocs.erase(x: Pointer.Base.dyn_cast<DynamicAllocLValue>())) { |
| 16611 | // The element was already erased. This means the destructor call also |
| 16612 | // deleted the object. |
| 16613 | // FIXME: This probably results in undefined behavior before we get this |
| 16614 | // far, and should be diagnosed elsewhere first. |
| 16615 | Info.FFDiag(E, DiagId: diag::note_constexpr_double_delete); |
| 16616 | return false; |
| 16617 | } |
| 16618 | |
| 16619 | return true; |
| 16620 | } |
| 16621 | |
| 16622 | static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { |
| 16623 | assert(!E->isValueDependent()); |
| 16624 | assert(E->isPRValue() && E->getType()->isVoidType()); |
| 16625 | return VoidExprEvaluator(Info).Visit(S: E); |
| 16626 | } |
| 16627 | |
| 16628 | //===----------------------------------------------------------------------===// |
| 16629 | // Top level Expr::EvaluateAsRValue method. |
| 16630 | //===----------------------------------------------------------------------===// |
| 16631 | |
| 16632 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { |
| 16633 | assert(!E->isValueDependent()); |
| 16634 | // In C, function designators are not lvalues, but we evaluate them as if they |
| 16635 | // are. |
| 16636 | QualType T = E->getType(); |
| 16637 | if (E->isGLValue() || T->isFunctionType()) { |
| 16638 | LValue LV; |
| 16639 | if (!EvaluateLValue(E, Result&: LV, Info)) |
| 16640 | return false; |
| 16641 | LV.moveInto(V&: Result); |
| 16642 | } else if (T->isVectorType()) { |
| 16643 | if (!EvaluateVector(E, Result, Info)) |
| 16644 | return false; |
| 16645 | } else if (T->isIntegralOrEnumerationType()) { |
| 16646 | if (!IntExprEvaluator(Info, Result).Visit(S: E)) |
| 16647 | return false; |
| 16648 | } else if (T->hasPointerRepresentation()) { |
| 16649 | LValue LV; |
| 16650 | if (!EvaluatePointer(E, Result&: LV, Info)) |
| 16651 | return false; |
| 16652 | LV.moveInto(V&: Result); |
| 16653 | } else if (T->isRealFloatingType()) { |
| 16654 | llvm::APFloat F(0.0); |
| 16655 | if (!EvaluateFloat(E, Result&: F, Info)) |
| 16656 | return false; |
| 16657 | Result = APValue(F); |
| 16658 | } else if (T->isAnyComplexType()) { |
| 16659 | ComplexValue C; |
| 16660 | if (!EvaluateComplex(E, Result&: C, Info)) |
| 16661 | return false; |
| 16662 | C.moveInto(v&: Result); |
| 16663 | } else if (T->isFixedPointType()) { |
| 16664 | if (!FixedPointExprEvaluator(Info, Result).Visit(S: E)) return false; |
| 16665 | } else if (T->isMemberPointerType()) { |
| 16666 | MemberPtr P; |
| 16667 | if (!EvaluateMemberPointer(E, Result&: P, Info)) |
| 16668 | return false; |
| 16669 | P.moveInto(V&: Result); |
| 16670 | return true; |
| 16671 | } else if (T->isArrayType()) { |
| 16672 | LValue LV; |
| 16673 | APValue &Value = |
| 16674 | Info.CurrentCall->createTemporary(Key: E, T, Scope: ScopeKind::FullExpression, LV); |
| 16675 | if (!EvaluateArray(E, This: LV, Result&: Value, Info)) |
| 16676 | return false; |
| 16677 | Result = Value; |
| 16678 | } else if (T->isRecordType()) { |
| 16679 | LValue LV; |
| 16680 | APValue &Value = |
| 16681 | Info.CurrentCall->createTemporary(Key: E, T, Scope: ScopeKind::FullExpression, LV); |
| 16682 | if (!EvaluateRecord(E, This: LV, Result&: Value, Info)) |
| 16683 | return false; |
| 16684 | Result = Value; |
| 16685 | } else if (T->isVoidType()) { |
| 16686 | if (!Info.getLangOpts().CPlusPlus11) |
| 16687 | Info.CCEDiag(E, DiagId: diag::note_constexpr_nonliteral) |
| 16688 | << E->getType(); |
| 16689 | if (!EvaluateVoid(E, Info)) |
| 16690 | return false; |
| 16691 | } else if (T->isAtomicType()) { |
| 16692 | QualType Unqual = T.getAtomicUnqualifiedType(); |
| 16693 | if (Unqual->isArrayType() || Unqual->isRecordType()) { |
| 16694 | LValue LV; |
| 16695 | APValue &Value = Info.CurrentCall->createTemporary( |
| 16696 | Key: E, T: Unqual, Scope: ScopeKind::FullExpression, LV); |
| 16697 | if (!EvaluateAtomic(E, This: &LV, Result&: Value, Info)) |
| 16698 | return false; |
| 16699 | Result = Value; |
| 16700 | } else { |
| 16701 | if (!EvaluateAtomic(E, This: nullptr, Result, Info)) |
| 16702 | return false; |
| 16703 | } |
| 16704 | } else if (Info.getLangOpts().CPlusPlus11) { |
| 16705 | Info.FFDiag(E, DiagId: diag::note_constexpr_nonliteral) << E->getType(); |
| 16706 | return false; |
| 16707 | } else { |
| 16708 | Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr); |
| 16709 | return false; |
| 16710 | } |
| 16711 | |
| 16712 | return true; |
| 16713 | } |
| 16714 | |
| 16715 | /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some |
| 16716 | /// cases, the in-place evaluation is essential, since later initializers for |
| 16717 | /// an object can indirectly refer to subobjects which were initialized earlier. |
| 16718 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, |
| 16719 | const Expr *E, bool AllowNonLiteralTypes) { |
| 16720 | assert(!E->isValueDependent()); |
| 16721 | |
| 16722 | // Normally expressions passed to EvaluateInPlace have a type, but not when |
| 16723 | // a VarDecl initializer is evaluated before the untyped ParenListExpr is |
| 16724 | // replaced with a CXXConstructExpr. This can happen in LLDB. |
| 16725 | if (E->getType().isNull()) |
| 16726 | return false; |
| 16727 | |
| 16728 | if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, This: &This)) |
| 16729 | return false; |
| 16730 | |
| 16731 | if (E->isPRValue()) { |
| 16732 | // Evaluate arrays and record types in-place, so that later initializers can |
| 16733 | // refer to earlier-initialized members of the object. |
| 16734 | QualType T = E->getType(); |
| 16735 | if (T->isArrayType()) |
| 16736 | return EvaluateArray(E, This, Result, Info); |
| 16737 | else if (T->isRecordType()) |
| 16738 | return EvaluateRecord(E, This, Result, Info); |
| 16739 | else if (T->isAtomicType()) { |
| 16740 | QualType Unqual = T.getAtomicUnqualifiedType(); |
| 16741 | if (Unqual->isArrayType() || Unqual->isRecordType()) |
| 16742 | return EvaluateAtomic(E, This: &This, Result, Info); |
| 16743 | } |
| 16744 | } |
| 16745 | |
| 16746 | // For any other type, in-place evaluation is unimportant. |
| 16747 | return Evaluate(Result, Info, E); |
| 16748 | } |
| 16749 | |
| 16750 | /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit |
| 16751 | /// lvalue-to-rvalue cast if it is an lvalue. |
| 16752 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { |
| 16753 | assert(!E->isValueDependent()); |
| 16754 | |
| 16755 | if (E->getType().isNull()) |
| 16756 | return false; |
| 16757 | |
| 16758 | if (!CheckLiteralType(Info, E)) |
| 16759 | return false; |
| 16760 | |
| 16761 | if (Info.EnableNewConstInterp) { |
| 16762 | if (!Info.Ctx.getInterpContext().evaluateAsRValue(Parent&: Info, E, Result)) |
| 16763 | return false; |
| 16764 | return CheckConstantExpression(Info, DiagLoc: E->getExprLoc(), Type: E->getType(), Value: Result, |
| 16765 | Kind: ConstantExprKind::Normal); |
| 16766 | } |
| 16767 | |
| 16768 | if (!::Evaluate(Result, Info, E)) |
| 16769 | return false; |
| 16770 | |
| 16771 | // Implicit lvalue-to-rvalue cast. |
| 16772 | if (E->isGLValue()) { |
| 16773 | LValue LV; |
| 16774 | LV.setFrom(Ctx&: Info.Ctx, V: Result); |
| 16775 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getType(), LVal: LV, RVal&: Result)) |
| 16776 | return false; |
| 16777 | } |
| 16778 | |
| 16779 | // Check this core constant expression is a constant expression. |
| 16780 | return CheckConstantExpression(Info, DiagLoc: E->getExprLoc(), Type: E->getType(), Value: Result, |
| 16781 | Kind: ConstantExprKind::Normal) && |
| 16782 | CheckMemoryLeaks(Info); |
| 16783 | } |
| 16784 | |
| 16785 | static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, |
| 16786 | const ASTContext &Ctx, bool &IsConst) { |
| 16787 | // Fast-path evaluations of integer literals, since we sometimes see files |
| 16788 | // containing vast quantities of these. |
| 16789 | if (const auto *L = dyn_cast<IntegerLiteral>(Val: Exp)) { |
| 16790 | Result.Val = APValue(APSInt(L->getValue(), |
| 16791 | L->getType()->isUnsignedIntegerType())); |
| 16792 | IsConst = true; |
| 16793 | return true; |
| 16794 | } |
| 16795 | |
| 16796 | if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Val: Exp)) { |
| 16797 | Result.Val = APValue(APSInt(APInt(1, L->getValue()))); |
| 16798 | IsConst = true; |
| 16799 | return true; |
| 16800 | } |
| 16801 | |
| 16802 | if (const auto *FL = dyn_cast<FloatingLiteral>(Val: Exp)) { |
| 16803 | Result.Val = APValue(FL->getValue()); |
| 16804 | IsConst = true; |
| 16805 | return true; |
| 16806 | } |
| 16807 | |
| 16808 | if (const auto *L = dyn_cast<CharacterLiteral>(Val: Exp)) { |
| 16809 | Result.Val = APValue(Ctx.MakeIntValue(Value: L->getValue(), Type: L->getType())); |
| 16810 | IsConst = true; |
| 16811 | return true; |
| 16812 | } |
| 16813 | |
| 16814 | if (const auto *CE = dyn_cast<ConstantExpr>(Val: Exp)) { |
| 16815 | if (CE->hasAPValueResult()) { |
| 16816 | APValue APV = CE->getAPValueResult(); |
| 16817 | if (!APV.isLValue()) { |
| 16818 | Result.Val = std::move(APV); |
| 16819 | IsConst = true; |
| 16820 | return true; |
| 16821 | } |
| 16822 | } |
| 16823 | |
| 16824 | // The SubExpr is usually just an IntegerLiteral. |
| 16825 | return FastEvaluateAsRValue(Exp: CE->getSubExpr(), Result, Ctx, IsConst); |
| 16826 | } |
| 16827 | |
| 16828 | // This case should be rare, but we need to check it before we check on |
| 16829 | // the type below. |
| 16830 | if (Exp->getType().isNull()) { |
| 16831 | IsConst = false; |
| 16832 | return true; |
| 16833 | } |
| 16834 | |
| 16835 | return false; |
| 16836 | } |
| 16837 | |
| 16838 | static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, |
| 16839 | Expr::SideEffectsKind SEK) { |
| 16840 | return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || |
| 16841 | (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); |
| 16842 | } |
| 16843 | |
| 16844 | static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, |
| 16845 | const ASTContext &Ctx, EvalInfo &Info) { |
| 16846 | assert(!E->isValueDependent()); |
| 16847 | bool IsConst; |
| 16848 | if (FastEvaluateAsRValue(Exp: E, Result, Ctx, IsConst)) |
| 16849 | return IsConst; |
| 16850 | |
| 16851 | return EvaluateAsRValue(Info, E, Result&: Result.Val); |
| 16852 | } |
| 16853 | |
| 16854 | static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, |
| 16855 | const ASTContext &Ctx, |
| 16856 | Expr::SideEffectsKind AllowSideEffects, |
| 16857 | EvalInfo &Info) { |
| 16858 | assert(!E->isValueDependent()); |
| 16859 | if (!E->getType()->isIntegralOrEnumerationType()) |
| 16860 | return false; |
| 16861 | |
| 16862 | if (!::EvaluateAsRValue(E, Result&: ExprResult, Ctx, Info) || |
| 16863 | !ExprResult.Val.isInt() || |
| 16864 | hasUnacceptableSideEffect(Result&: ExprResult, SEK: AllowSideEffects)) |
| 16865 | return false; |
| 16866 | |
| 16867 | return true; |
| 16868 | } |
| 16869 | |
| 16870 | static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, |
| 16871 | const ASTContext &Ctx, |
| 16872 | Expr::SideEffectsKind AllowSideEffects, |
| 16873 | EvalInfo &Info) { |
| 16874 | assert(!E->isValueDependent()); |
| 16875 | if (!E->getType()->isFixedPointType()) |
| 16876 | return false; |
| 16877 | |
| 16878 | if (!::EvaluateAsRValue(E, Result&: ExprResult, Ctx, Info)) |
| 16879 | return false; |
| 16880 | |
| 16881 | if (!ExprResult.Val.isFixedPoint() || |
| 16882 | hasUnacceptableSideEffect(Result&: ExprResult, SEK: AllowSideEffects)) |
| 16883 | return false; |
| 16884 | |
| 16885 | return true; |
| 16886 | } |
| 16887 | |
| 16888 | /// EvaluateAsRValue - Return true if this is a constant which we can fold using |
| 16889 | /// any crazy technique (that has nothing to do with language standards) that |
| 16890 | /// we want to. If this function returns true, it returns the folded constant |
| 16891 | /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion |
| 16892 | /// will be applied to the result. |
| 16893 | bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, |
| 16894 | bool InConstantContext) const { |
| 16895 | assert(!isValueDependent() && |
| 16896 | "Expression evaluator can't be called on a dependent expression." ); |
| 16897 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue" ); |
| 16898 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); |
| 16899 | Info.InConstantContext = InConstantContext; |
| 16900 | return ::EvaluateAsRValue(E: this, Result, Ctx, Info); |
| 16901 | } |
| 16902 | |
| 16903 | bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, |
| 16904 | bool InConstantContext) const { |
| 16905 | assert(!isValueDependent() && |
| 16906 | "Expression evaluator can't be called on a dependent expression." ); |
| 16907 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition" ); |
| 16908 | EvalResult Scratch; |
| 16909 | return EvaluateAsRValue(Result&: Scratch, Ctx, InConstantContext) && |
| 16910 | HandleConversionToBool(Val: Scratch.Val, Result); |
| 16911 | } |
| 16912 | |
| 16913 | bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, |
| 16914 | SideEffectsKind AllowSideEffects, |
| 16915 | bool InConstantContext) const { |
| 16916 | assert(!isValueDependent() && |
| 16917 | "Expression evaluator can't be called on a dependent expression." ); |
| 16918 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt" ); |
| 16919 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); |
| 16920 | Info.InConstantContext = InConstantContext; |
| 16921 | return ::EvaluateAsInt(E: this, ExprResult&: Result, Ctx, AllowSideEffects, Info); |
| 16922 | } |
| 16923 | |
| 16924 | bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, |
| 16925 | SideEffectsKind AllowSideEffects, |
| 16926 | bool InConstantContext) const { |
| 16927 | assert(!isValueDependent() && |
| 16928 | "Expression evaluator can't be called on a dependent expression." ); |
| 16929 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint" ); |
| 16930 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); |
| 16931 | Info.InConstantContext = InConstantContext; |
| 16932 | return ::EvaluateAsFixedPoint(E: this, ExprResult&: Result, Ctx, AllowSideEffects, Info); |
| 16933 | } |
| 16934 | |
| 16935 | bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, |
| 16936 | SideEffectsKind AllowSideEffects, |
| 16937 | bool InConstantContext) const { |
| 16938 | assert(!isValueDependent() && |
| 16939 | "Expression evaluator can't be called on a dependent expression." ); |
| 16940 | |
| 16941 | if (!getType()->isRealFloatingType()) |
| 16942 | return false; |
| 16943 | |
| 16944 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat" ); |
| 16945 | EvalResult ExprResult; |
| 16946 | if (!EvaluateAsRValue(Result&: ExprResult, Ctx, InConstantContext) || |
| 16947 | !ExprResult.Val.isFloat() || |
| 16948 | hasUnacceptableSideEffect(Result&: ExprResult, SEK: AllowSideEffects)) |
| 16949 | return false; |
| 16950 | |
| 16951 | Result = ExprResult.Val.getFloat(); |
| 16952 | return true; |
| 16953 | } |
| 16954 | |
| 16955 | bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, |
| 16956 | bool InConstantContext) const { |
| 16957 | assert(!isValueDependent() && |
| 16958 | "Expression evaluator can't be called on a dependent expression." ); |
| 16959 | |
| 16960 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue" ); |
| 16961 | EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); |
| 16962 | Info.InConstantContext = InConstantContext; |
| 16963 | LValue LV; |
| 16964 | CheckedTemporaries CheckedTemps; |
| 16965 | if (!EvaluateLValue(E: this, Result&: LV, Info) || !Info.discardCleanups() || |
| 16966 | Result.HasSideEffects || |
| 16967 | !CheckLValueConstantExpression(Info, Loc: getExprLoc(), |
| 16968 | Type: Ctx.getLValueReferenceType(T: getType()), LVal: LV, |
| 16969 | Kind: ConstantExprKind::Normal, CheckedTemps)) |
| 16970 | return false; |
| 16971 | |
| 16972 | LV.moveInto(V&: Result.Val); |
| 16973 | return true; |
| 16974 | } |
| 16975 | |
| 16976 | static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, |
| 16977 | APValue DestroyedValue, QualType Type, |
| 16978 | SourceLocation Loc, Expr::EvalStatus &EStatus, |
| 16979 | bool IsConstantDestruction) { |
| 16980 | EvalInfo Info(Ctx, EStatus, |
| 16981 | IsConstantDestruction ? EvalInfo::EM_ConstantExpression |
| 16982 | : EvalInfo::EM_ConstantFold); |
| 16983 | Info.setEvaluatingDecl(Base, Value&: DestroyedValue, |
| 16984 | EDK: EvalInfo::EvaluatingDeclKind::Dtor); |
| 16985 | Info.InConstantContext = IsConstantDestruction; |
| 16986 | |
| 16987 | LValue LVal; |
| 16988 | LVal.set(B: Base); |
| 16989 | |
| 16990 | if (!HandleDestruction(Info, Loc, LVBase: Base, Value&: DestroyedValue, T: Type) || |
| 16991 | EStatus.HasSideEffects) |
| 16992 | return false; |
| 16993 | |
| 16994 | if (!Info.discardCleanups()) |
| 16995 | llvm_unreachable("Unhandled cleanup; missing full expression marker?" ); |
| 16996 | |
| 16997 | return true; |
| 16998 | } |
| 16999 | |
| 17000 | bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, |
| 17001 | ConstantExprKind Kind) const { |
| 17002 | assert(!isValueDependent() && |
| 17003 | "Expression evaluator can't be called on a dependent expression." ); |
| 17004 | bool IsConst; |
| 17005 | if (FastEvaluateAsRValue(Exp: this, Result, Ctx, IsConst) && Result.Val.hasValue()) |
| 17006 | return true; |
| 17007 | |
| 17008 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr" ); |
| 17009 | EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; |
| 17010 | EvalInfo Info(Ctx, Result, EM); |
| 17011 | Info.InConstantContext = true; |
| 17012 | |
| 17013 | if (Info.EnableNewConstInterp) { |
| 17014 | if (!Info.Ctx.getInterpContext().evaluate(Parent&: Info, E: this, Result&: Result.Val, Kind)) |
| 17015 | return false; |
| 17016 | return CheckConstantExpression(Info, DiagLoc: getExprLoc(), |
| 17017 | Type: getStorageType(Ctx, E: this), Value: Result.Val, Kind); |
| 17018 | } |
| 17019 | |
| 17020 | // The type of the object we're initializing is 'const T' for a class NTTP. |
| 17021 | QualType T = getType(); |
| 17022 | if (Kind == ConstantExprKind::ClassTemplateArgument) |
| 17023 | T.addConst(); |
| 17024 | |
| 17025 | // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to |
| 17026 | // represent the result of the evaluation. CheckConstantExpression ensures |
| 17027 | // this doesn't escape. |
| 17028 | MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); |
| 17029 | APValue::LValueBase Base(&BaseMTE); |
| 17030 | Info.setEvaluatingDecl(Base, Value&: Result.Val); |
| 17031 | |
| 17032 | LValue LVal; |
| 17033 | LVal.set(B: Base); |
| 17034 | // C++23 [intro.execution]/p5 |
| 17035 | // A full-expression is [...] a constant-expression |
| 17036 | // So we need to make sure temporary objects are destroyed after having |
| 17037 | // evaluating the expression (per C++23 [class.temporary]/p4). |
| 17038 | FullExpressionRAII Scope(Info); |
| 17039 | if (!::EvaluateInPlace(Result&: Result.Val, Info, This: LVal, E: this) || |
| 17040 | Result.HasSideEffects || !Scope.destroy()) |
| 17041 | return false; |
| 17042 | |
| 17043 | if (!Info.discardCleanups()) |
| 17044 | llvm_unreachable("Unhandled cleanup; missing full expression marker?" ); |
| 17045 | |
| 17046 | if (!CheckConstantExpression(Info, DiagLoc: getExprLoc(), Type: getStorageType(Ctx, E: this), |
| 17047 | Value: Result.Val, Kind)) |
| 17048 | return false; |
| 17049 | if (!CheckMemoryLeaks(Info)) |
| 17050 | return false; |
| 17051 | |
| 17052 | // If this is a class template argument, it's required to have constant |
| 17053 | // destruction too. |
| 17054 | if (Kind == ConstantExprKind::ClassTemplateArgument && |
| 17055 | (!EvaluateDestruction(Ctx, Base, DestroyedValue: Result.Val, Type: T, Loc: getBeginLoc(), EStatus&: Result, |
| 17056 | IsConstantDestruction: true) || |
| 17057 | Result.HasSideEffects)) { |
| 17058 | // FIXME: Prefix a note to indicate that the problem is lack of constant |
| 17059 | // destruction. |
| 17060 | return false; |
| 17061 | } |
| 17062 | |
| 17063 | return true; |
| 17064 | } |
| 17065 | |
| 17066 | bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, |
| 17067 | const VarDecl *VD, |
| 17068 | SmallVectorImpl<PartialDiagnosticAt> &Notes, |
| 17069 | bool IsConstantInitialization) const { |
| 17070 | assert(!isValueDependent() && |
| 17071 | "Expression evaluator can't be called on a dependent expression." ); |
| 17072 | |
| 17073 | llvm::TimeTraceScope TimeScope("EvaluateAsInitializer" , [&] { |
| 17074 | std::string Name; |
| 17075 | llvm::raw_string_ostream OS(Name); |
| 17076 | VD->printQualifiedName(OS); |
| 17077 | return Name; |
| 17078 | }); |
| 17079 | |
| 17080 | Expr::EvalStatus EStatus; |
| 17081 | EStatus.Diag = &Notes; |
| 17082 | |
| 17083 | EvalInfo Info(Ctx, EStatus, |
| 17084 | (IsConstantInitialization && |
| 17085 | (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23)) |
| 17086 | ? EvalInfo::EM_ConstantExpression |
| 17087 | : EvalInfo::EM_ConstantFold); |
| 17088 | Info.setEvaluatingDecl(Base: VD, Value); |
| 17089 | Info.InConstantContext = IsConstantInitialization; |
| 17090 | |
| 17091 | SourceLocation DeclLoc = VD->getLocation(); |
| 17092 | QualType DeclTy = VD->getType(); |
| 17093 | |
| 17094 | if (Info.EnableNewConstInterp) { |
| 17095 | auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); |
| 17096 | if (!InterpCtx.evaluateAsInitializer(Parent&: Info, VD, Result&: Value)) |
| 17097 | return false; |
| 17098 | |
| 17099 | return CheckConstantExpression(Info, DiagLoc: DeclLoc, Type: DeclTy, Value, |
| 17100 | Kind: ConstantExprKind::Normal); |
| 17101 | } else { |
| 17102 | LValue LVal; |
| 17103 | LVal.set(B: VD); |
| 17104 | |
| 17105 | { |
| 17106 | // C++23 [intro.execution]/p5 |
| 17107 | // A full-expression is ... an init-declarator ([dcl.decl]) or a |
| 17108 | // mem-initializer. |
| 17109 | // So we need to make sure temporary objects are destroyed after having |
| 17110 | // evaluated the expression (per C++23 [class.temporary]/p4). |
| 17111 | // |
| 17112 | // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the |
| 17113 | // serialization code calls ParmVarDecl::getDefaultArg() which strips the |
| 17114 | // outermost FullExpr, such as ExprWithCleanups. |
| 17115 | FullExpressionRAII Scope(Info); |
| 17116 | if (!EvaluateInPlace(Result&: Value, Info, This: LVal, E: this, |
| 17117 | /*AllowNonLiteralTypes=*/true) || |
| 17118 | EStatus.HasSideEffects) |
| 17119 | return false; |
| 17120 | } |
| 17121 | |
| 17122 | // At this point, any lifetime-extended temporaries are completely |
| 17123 | // initialized. |
| 17124 | Info.performLifetimeExtension(); |
| 17125 | |
| 17126 | if (!Info.discardCleanups()) |
| 17127 | llvm_unreachable("Unhandled cleanup; missing full expression marker?" ); |
| 17128 | } |
| 17129 | |
| 17130 | return CheckConstantExpression(Info, DiagLoc: DeclLoc, Type: DeclTy, Value, |
| 17131 | Kind: ConstantExprKind::Normal) && |
| 17132 | CheckMemoryLeaks(Info); |
| 17133 | } |
| 17134 | |
| 17135 | bool VarDecl::evaluateDestruction( |
| 17136 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { |
| 17137 | Expr::EvalStatus EStatus; |
| 17138 | EStatus.Diag = &Notes; |
| 17139 | |
| 17140 | // Only treat the destruction as constant destruction if we formally have |
| 17141 | // constant initialization (or are usable in a constant expression). |
| 17142 | bool IsConstantDestruction = hasConstantInitialization(); |
| 17143 | |
| 17144 | // Make a copy of the value for the destructor to mutate, if we know it. |
| 17145 | // Otherwise, treat the value as default-initialized; if the destructor works |
| 17146 | // anyway, then the destruction is constant (and must be essentially empty). |
| 17147 | APValue DestroyedValue; |
| 17148 | if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) |
| 17149 | DestroyedValue = *getEvaluatedValue(); |
| 17150 | else if (!handleDefaultInitValue(T: getType(), Result&: DestroyedValue)) |
| 17151 | return false; |
| 17152 | |
| 17153 | if (!EvaluateDestruction(Ctx: getASTContext(), Base: this, DestroyedValue: std::move(DestroyedValue), |
| 17154 | Type: getType(), Loc: getLocation(), EStatus, |
| 17155 | IsConstantDestruction) || |
| 17156 | EStatus.HasSideEffects) |
| 17157 | return false; |
| 17158 | |
| 17159 | ensureEvaluatedStmt()->HasConstantDestruction = true; |
| 17160 | return true; |
| 17161 | } |
| 17162 | |
| 17163 | /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be |
| 17164 | /// constant folded, but discard the result. |
| 17165 | bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { |
| 17166 | assert(!isValueDependent() && |
| 17167 | "Expression evaluator can't be called on a dependent expression." ); |
| 17168 | |
| 17169 | EvalResult Result; |
| 17170 | return EvaluateAsRValue(Result, Ctx, /* in constant context */ InConstantContext: true) && |
| 17171 | !hasUnacceptableSideEffect(Result, SEK); |
| 17172 | } |
| 17173 | |
| 17174 | APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, |
| 17175 | SmallVectorImpl<PartialDiagnosticAt> *Diag) const { |
| 17176 | assert(!isValueDependent() && |
| 17177 | "Expression evaluator can't be called on a dependent expression." ); |
| 17178 | |
| 17179 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt" ); |
| 17180 | EvalResult EVResult; |
| 17181 | EVResult.Diag = Diag; |
| 17182 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); |
| 17183 | Info.InConstantContext = true; |
| 17184 | |
| 17185 | bool Result = ::EvaluateAsRValue(E: this, Result&: EVResult, Ctx, Info); |
| 17186 | (void)Result; |
| 17187 | assert(Result && "Could not evaluate expression" ); |
| 17188 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer" ); |
| 17189 | |
| 17190 | return EVResult.Val.getInt(); |
| 17191 | } |
| 17192 | |
| 17193 | APSInt Expr::EvaluateKnownConstIntCheckOverflow( |
| 17194 | const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { |
| 17195 | assert(!isValueDependent() && |
| 17196 | "Expression evaluator can't be called on a dependent expression." ); |
| 17197 | |
| 17198 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow" ); |
| 17199 | EvalResult EVResult; |
| 17200 | EVResult.Diag = Diag; |
| 17201 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); |
| 17202 | Info.InConstantContext = true; |
| 17203 | Info.CheckingForUndefinedBehavior = true; |
| 17204 | |
| 17205 | bool Result = ::EvaluateAsRValue(Info, E: this, Result&: EVResult.Val); |
| 17206 | (void)Result; |
| 17207 | assert(Result && "Could not evaluate expression" ); |
| 17208 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer" ); |
| 17209 | |
| 17210 | return EVResult.Val.getInt(); |
| 17211 | } |
| 17212 | |
| 17213 | void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { |
| 17214 | assert(!isValueDependent() && |
| 17215 | "Expression evaluator can't be called on a dependent expression." ); |
| 17216 | |
| 17217 | ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow" ); |
| 17218 | bool IsConst; |
| 17219 | EvalResult EVResult; |
| 17220 | if (!FastEvaluateAsRValue(Exp: this, Result&: EVResult, Ctx, IsConst)) { |
| 17221 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); |
| 17222 | Info.CheckingForUndefinedBehavior = true; |
| 17223 | (void)::EvaluateAsRValue(Info, E: this, Result&: EVResult.Val); |
| 17224 | } |
| 17225 | } |
| 17226 | |
| 17227 | bool Expr::EvalResult::isGlobalLValue() const { |
| 17228 | assert(Val.isLValue()); |
| 17229 | return IsGlobalLValue(B: Val.getLValueBase()); |
| 17230 | } |
| 17231 | |
| 17232 | /// isIntegerConstantExpr - this recursive routine will test if an expression is |
| 17233 | /// an integer constant expression. |
| 17234 | |
| 17235 | /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, |
| 17236 | /// comma, etc |
| 17237 | |
| 17238 | // CheckICE - This function does the fundamental ICE checking: the returned |
| 17239 | // ICEDiag contains an ICEKind indicating whether the expression is an ICE, |
| 17240 | // and a (possibly null) SourceLocation indicating the location of the problem. |
| 17241 | // |
| 17242 | // Note that to reduce code duplication, this helper does no evaluation |
| 17243 | // itself; the caller checks whether the expression is evaluatable, and |
| 17244 | // in the rare cases where CheckICE actually cares about the evaluated |
| 17245 | // value, it calls into Evaluate. |
| 17246 | |
| 17247 | namespace { |
| 17248 | |
| 17249 | enum ICEKind { |
| 17250 | /// This expression is an ICE. |
| 17251 | IK_ICE, |
| 17252 | /// This expression is not an ICE, but if it isn't evaluated, it's |
| 17253 | /// a legal subexpression for an ICE. This return value is used to handle |
| 17254 | /// the comma operator in C99 mode, and non-constant subexpressions. |
| 17255 | IK_ICEIfUnevaluated, |
| 17256 | /// This expression is not an ICE, and is not a legal subexpression for one. |
| 17257 | IK_NotICE |
| 17258 | }; |
| 17259 | |
| 17260 | struct ICEDiag { |
| 17261 | ICEKind Kind; |
| 17262 | SourceLocation Loc; |
| 17263 | |
| 17264 | ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} |
| 17265 | }; |
| 17266 | |
| 17267 | } |
| 17268 | |
| 17269 | static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } |
| 17270 | |
| 17271 | static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } |
| 17272 | |
| 17273 | static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { |
| 17274 | Expr::EvalResult EVResult; |
| 17275 | Expr::EvalStatus Status; |
| 17276 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); |
| 17277 | |
| 17278 | Info.InConstantContext = true; |
| 17279 | if (!::EvaluateAsRValue(E, Result&: EVResult, Ctx, Info) || EVResult.HasSideEffects || |
| 17280 | !EVResult.Val.isInt()) |
| 17281 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17282 | |
| 17283 | return NoDiag(); |
| 17284 | } |
| 17285 | |
| 17286 | static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { |
| 17287 | assert(!E->isValueDependent() && "Should not see value dependent exprs!" ); |
| 17288 | if (!E->getType()->isIntegralOrEnumerationType()) |
| 17289 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17290 | |
| 17291 | switch (E->getStmtClass()) { |
| 17292 | #define ABSTRACT_STMT(Node) |
| 17293 | #define STMT(Node, Base) case Expr::Node##Class: |
| 17294 | #define EXPR(Node, Base) |
| 17295 | #include "clang/AST/StmtNodes.inc" |
| 17296 | case Expr::PredefinedExprClass: |
| 17297 | case Expr::FloatingLiteralClass: |
| 17298 | case Expr::ImaginaryLiteralClass: |
| 17299 | case Expr::StringLiteralClass: |
| 17300 | case Expr::ArraySubscriptExprClass: |
| 17301 | case Expr::MatrixSubscriptExprClass: |
| 17302 | case Expr::ArraySectionExprClass: |
| 17303 | case Expr::OMPArrayShapingExprClass: |
| 17304 | case Expr::OMPIteratorExprClass: |
| 17305 | case Expr::MemberExprClass: |
| 17306 | case Expr::CompoundAssignOperatorClass: |
| 17307 | case Expr::CompoundLiteralExprClass: |
| 17308 | case Expr::ExtVectorElementExprClass: |
| 17309 | case Expr::DesignatedInitExprClass: |
| 17310 | case Expr::ArrayInitLoopExprClass: |
| 17311 | case Expr::ArrayInitIndexExprClass: |
| 17312 | case Expr::NoInitExprClass: |
| 17313 | case Expr::DesignatedInitUpdateExprClass: |
| 17314 | case Expr::ImplicitValueInitExprClass: |
| 17315 | case Expr::ParenListExprClass: |
| 17316 | case Expr::VAArgExprClass: |
| 17317 | case Expr::AddrLabelExprClass: |
| 17318 | case Expr::StmtExprClass: |
| 17319 | case Expr::CXXMemberCallExprClass: |
| 17320 | case Expr::CUDAKernelCallExprClass: |
| 17321 | case Expr::CXXAddrspaceCastExprClass: |
| 17322 | case Expr::CXXDynamicCastExprClass: |
| 17323 | case Expr::CXXTypeidExprClass: |
| 17324 | case Expr::CXXUuidofExprClass: |
| 17325 | case Expr::MSPropertyRefExprClass: |
| 17326 | case Expr::MSPropertySubscriptExprClass: |
| 17327 | case Expr::CXXNullPtrLiteralExprClass: |
| 17328 | case Expr::UserDefinedLiteralClass: |
| 17329 | case Expr::CXXThisExprClass: |
| 17330 | case Expr::CXXThrowExprClass: |
| 17331 | case Expr::CXXNewExprClass: |
| 17332 | case Expr::CXXDeleteExprClass: |
| 17333 | case Expr::CXXPseudoDestructorExprClass: |
| 17334 | case Expr::UnresolvedLookupExprClass: |
| 17335 | case Expr::RecoveryExprClass: |
| 17336 | case Expr::DependentScopeDeclRefExprClass: |
| 17337 | case Expr::CXXConstructExprClass: |
| 17338 | case Expr::CXXInheritedCtorInitExprClass: |
| 17339 | case Expr::CXXStdInitializerListExprClass: |
| 17340 | case Expr::CXXBindTemporaryExprClass: |
| 17341 | case Expr::ExprWithCleanupsClass: |
| 17342 | case Expr::CXXTemporaryObjectExprClass: |
| 17343 | case Expr::CXXUnresolvedConstructExprClass: |
| 17344 | case Expr::CXXDependentScopeMemberExprClass: |
| 17345 | case Expr::UnresolvedMemberExprClass: |
| 17346 | case Expr::ObjCStringLiteralClass: |
| 17347 | case Expr::ObjCBoxedExprClass: |
| 17348 | case Expr::ObjCArrayLiteralClass: |
| 17349 | case Expr::ObjCDictionaryLiteralClass: |
| 17350 | case Expr::ObjCEncodeExprClass: |
| 17351 | case Expr::ObjCMessageExprClass: |
| 17352 | case Expr::ObjCSelectorExprClass: |
| 17353 | case Expr::ObjCProtocolExprClass: |
| 17354 | case Expr::ObjCIvarRefExprClass: |
| 17355 | case Expr::ObjCPropertyRefExprClass: |
| 17356 | case Expr::ObjCSubscriptRefExprClass: |
| 17357 | case Expr::ObjCIsaExprClass: |
| 17358 | case Expr::ObjCAvailabilityCheckExprClass: |
| 17359 | case Expr::ShuffleVectorExprClass: |
| 17360 | case Expr::ConvertVectorExprClass: |
| 17361 | case Expr::BlockExprClass: |
| 17362 | case Expr::NoStmtClass: |
| 17363 | case Expr::OpaqueValueExprClass: |
| 17364 | case Expr::PackExpansionExprClass: |
| 17365 | case Expr::SubstNonTypeTemplateParmPackExprClass: |
| 17366 | case Expr::FunctionParmPackExprClass: |
| 17367 | case Expr::AsTypeExprClass: |
| 17368 | case Expr::ObjCIndirectCopyRestoreExprClass: |
| 17369 | case Expr::MaterializeTemporaryExprClass: |
| 17370 | case Expr::PseudoObjectExprClass: |
| 17371 | case Expr::AtomicExprClass: |
| 17372 | case Expr::LambdaExprClass: |
| 17373 | case Expr::CXXFoldExprClass: |
| 17374 | case Expr::CoawaitExprClass: |
| 17375 | case Expr::DependentCoawaitExprClass: |
| 17376 | case Expr::CoyieldExprClass: |
| 17377 | case Expr::SYCLUniqueStableNameExprClass: |
| 17378 | case Expr::CXXParenListInitExprClass: |
| 17379 | case Expr::HLSLOutArgExprClass: |
| 17380 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17381 | |
| 17382 | case Expr::InitListExprClass: { |
| 17383 | // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the |
| 17384 | // form "T x = { a };" is equivalent to "T x = a;". |
| 17385 | // Unless we're initializing a reference, T is a scalar as it is known to be |
| 17386 | // of integral or enumeration type. |
| 17387 | if (E->isPRValue()) |
| 17388 | if (cast<InitListExpr>(Val: E)->getNumInits() == 1) |
| 17389 | return CheckICE(E: cast<InitListExpr>(Val: E)->getInit(Init: 0), Ctx); |
| 17390 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17391 | } |
| 17392 | |
| 17393 | case Expr::SizeOfPackExprClass: |
| 17394 | case Expr::GNUNullExprClass: |
| 17395 | case Expr::SourceLocExprClass: |
| 17396 | case Expr::EmbedExprClass: |
| 17397 | case Expr::OpenACCAsteriskSizeExprClass: |
| 17398 | return NoDiag(); |
| 17399 | |
| 17400 | case Expr::PackIndexingExprClass: |
| 17401 | return CheckICE(E: cast<PackIndexingExpr>(Val: E)->getSelectedExpr(), Ctx); |
| 17402 | |
| 17403 | case Expr::SubstNonTypeTemplateParmExprClass: |
| 17404 | return |
| 17405 | CheckICE(E: cast<SubstNonTypeTemplateParmExpr>(Val: E)->getReplacement(), Ctx); |
| 17406 | |
| 17407 | case Expr::ConstantExprClass: |
| 17408 | return CheckICE(E: cast<ConstantExpr>(Val: E)->getSubExpr(), Ctx); |
| 17409 | |
| 17410 | case Expr::ParenExprClass: |
| 17411 | return CheckICE(E: cast<ParenExpr>(Val: E)->getSubExpr(), Ctx); |
| 17412 | case Expr::GenericSelectionExprClass: |
| 17413 | return CheckICE(E: cast<GenericSelectionExpr>(Val: E)->getResultExpr(), Ctx); |
| 17414 | case Expr::IntegerLiteralClass: |
| 17415 | case Expr::FixedPointLiteralClass: |
| 17416 | case Expr::CharacterLiteralClass: |
| 17417 | case Expr::ObjCBoolLiteralExprClass: |
| 17418 | case Expr::CXXBoolLiteralExprClass: |
| 17419 | case Expr::CXXScalarValueInitExprClass: |
| 17420 | case Expr::TypeTraitExprClass: |
| 17421 | case Expr::ConceptSpecializationExprClass: |
| 17422 | case Expr::RequiresExprClass: |
| 17423 | case Expr::ArrayTypeTraitExprClass: |
| 17424 | case Expr::ExpressionTraitExprClass: |
| 17425 | case Expr::CXXNoexceptExprClass: |
| 17426 | return NoDiag(); |
| 17427 | case Expr::CallExprClass: |
| 17428 | case Expr::CXXOperatorCallExprClass: { |
| 17429 | // C99 6.6/3 allows function calls within unevaluated subexpressions of |
| 17430 | // constant expressions, but they can never be ICEs because an ICE cannot |
| 17431 | // contain an operand of (pointer to) function type. |
| 17432 | const CallExpr *CE = cast<CallExpr>(Val: E); |
| 17433 | if (CE->getBuiltinCallee()) |
| 17434 | return CheckEvalInICE(E, Ctx); |
| 17435 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17436 | } |
| 17437 | case Expr::CXXRewrittenBinaryOperatorClass: |
| 17438 | return CheckICE(E: cast<CXXRewrittenBinaryOperator>(Val: E)->getSemanticForm(), |
| 17439 | Ctx); |
| 17440 | case Expr::DeclRefExprClass: { |
| 17441 | const NamedDecl *D = cast<DeclRefExpr>(Val: E)->getDecl(); |
| 17442 | if (isa<EnumConstantDecl>(Val: D)) |
| 17443 | return NoDiag(); |
| 17444 | |
| 17445 | // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified |
| 17446 | // integer variables in constant expressions: |
| 17447 | // |
| 17448 | // C++ 7.1.5.1p2 |
| 17449 | // A variable of non-volatile const-qualified integral or enumeration |
| 17450 | // type initialized by an ICE can be used in ICEs. |
| 17451 | // |
| 17452 | // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In |
| 17453 | // that mode, use of reference variables should not be allowed. |
| 17454 | const VarDecl *VD = dyn_cast<VarDecl>(Val: D); |
| 17455 | if (VD && VD->isUsableInConstantExpressions(C: Ctx) && |
| 17456 | !VD->getType()->isReferenceType()) |
| 17457 | return NoDiag(); |
| 17458 | |
| 17459 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17460 | } |
| 17461 | case Expr::UnaryOperatorClass: { |
| 17462 | const UnaryOperator *Exp = cast<UnaryOperator>(Val: E); |
| 17463 | switch (Exp->getOpcode()) { |
| 17464 | case UO_PostInc: |
| 17465 | case UO_PostDec: |
| 17466 | case UO_PreInc: |
| 17467 | case UO_PreDec: |
| 17468 | case UO_AddrOf: |
| 17469 | case UO_Deref: |
| 17470 | case UO_Coawait: |
| 17471 | // C99 6.6/3 allows increment and decrement within unevaluated |
| 17472 | // subexpressions of constant expressions, but they can never be ICEs |
| 17473 | // because an ICE cannot contain an lvalue operand. |
| 17474 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17475 | case UO_Extension: |
| 17476 | case UO_LNot: |
| 17477 | case UO_Plus: |
| 17478 | case UO_Minus: |
| 17479 | case UO_Not: |
| 17480 | case UO_Real: |
| 17481 | case UO_Imag: |
| 17482 | return CheckICE(E: Exp->getSubExpr(), Ctx); |
| 17483 | } |
| 17484 | llvm_unreachable("invalid unary operator class" ); |
| 17485 | } |
| 17486 | case Expr::OffsetOfExprClass: { |
| 17487 | // Note that per C99, offsetof must be an ICE. And AFAIK, using |
| 17488 | // EvaluateAsRValue matches the proposed gcc behavior for cases like |
| 17489 | // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect |
| 17490 | // compliance: we should warn earlier for offsetof expressions with |
| 17491 | // array subscripts that aren't ICEs, and if the array subscripts |
| 17492 | // are ICEs, the value of the offsetof must be an integer constant. |
| 17493 | return CheckEvalInICE(E, Ctx); |
| 17494 | } |
| 17495 | case Expr::UnaryExprOrTypeTraitExprClass: { |
| 17496 | const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(Val: E); |
| 17497 | if ((Exp->getKind() == UETT_SizeOf) && |
| 17498 | Exp->getTypeOfArgument()->isVariableArrayType()) |
| 17499 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17500 | if (Exp->getKind() == UETT_CountOf) { |
| 17501 | QualType ArgTy = Exp->getTypeOfArgument(); |
| 17502 | if (ArgTy->isVariableArrayType()) { |
| 17503 | // We need to look whether the array is multidimensional. If it is, |
| 17504 | // then we want to check the size expression manually to see whether |
| 17505 | // it is an ICE or not. |
| 17506 | const auto *VAT = Ctx.getAsVariableArrayType(T: ArgTy); |
| 17507 | if (VAT->getElementType()->isArrayType()) |
| 17508 | return CheckICE(E: VAT->getSizeExpr(), Ctx); |
| 17509 | |
| 17510 | // Otherwise, this is a regular VLA, which is definitely not an ICE. |
| 17511 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17512 | } |
| 17513 | } |
| 17514 | return NoDiag(); |
| 17515 | } |
| 17516 | case Expr::BinaryOperatorClass: { |
| 17517 | const BinaryOperator *Exp = cast<BinaryOperator>(Val: E); |
| 17518 | switch (Exp->getOpcode()) { |
| 17519 | case BO_PtrMemD: |
| 17520 | case BO_PtrMemI: |
| 17521 | case BO_Assign: |
| 17522 | case BO_MulAssign: |
| 17523 | case BO_DivAssign: |
| 17524 | case BO_RemAssign: |
| 17525 | case BO_AddAssign: |
| 17526 | case BO_SubAssign: |
| 17527 | case BO_ShlAssign: |
| 17528 | case BO_ShrAssign: |
| 17529 | case BO_AndAssign: |
| 17530 | case BO_XorAssign: |
| 17531 | case BO_OrAssign: |
| 17532 | // C99 6.6/3 allows assignments within unevaluated subexpressions of |
| 17533 | // constant expressions, but they can never be ICEs because an ICE cannot |
| 17534 | // contain an lvalue operand. |
| 17535 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17536 | |
| 17537 | case BO_Mul: |
| 17538 | case BO_Div: |
| 17539 | case BO_Rem: |
| 17540 | case BO_Add: |
| 17541 | case BO_Sub: |
| 17542 | case BO_Shl: |
| 17543 | case BO_Shr: |
| 17544 | case BO_LT: |
| 17545 | case BO_GT: |
| 17546 | case BO_LE: |
| 17547 | case BO_GE: |
| 17548 | case BO_EQ: |
| 17549 | case BO_NE: |
| 17550 | case BO_And: |
| 17551 | case BO_Xor: |
| 17552 | case BO_Or: |
| 17553 | case BO_Comma: |
| 17554 | case BO_Cmp: { |
| 17555 | ICEDiag LHSResult = CheckICE(E: Exp->getLHS(), Ctx); |
| 17556 | ICEDiag RHSResult = CheckICE(E: Exp->getRHS(), Ctx); |
| 17557 | if (Exp->getOpcode() == BO_Div || |
| 17558 | Exp->getOpcode() == BO_Rem) { |
| 17559 | // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure |
| 17560 | // we don't evaluate one. |
| 17561 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { |
| 17562 | llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); |
| 17563 | if (REval == 0) |
| 17564 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); |
| 17565 | if (REval.isSigned() && REval.isAllOnes()) { |
| 17566 | llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); |
| 17567 | if (LEval.isMinSignedValue()) |
| 17568 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); |
| 17569 | } |
| 17570 | } |
| 17571 | } |
| 17572 | if (Exp->getOpcode() == BO_Comma) { |
| 17573 | if (Ctx.getLangOpts().C99) { |
| 17574 | // C99 6.6p3 introduces a strange edge case: comma can be in an ICE |
| 17575 | // if it isn't evaluated. |
| 17576 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) |
| 17577 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); |
| 17578 | } else { |
| 17579 | // In both C89 and C++, commas in ICEs are illegal. |
| 17580 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17581 | } |
| 17582 | } |
| 17583 | return Worst(A: LHSResult, B: RHSResult); |
| 17584 | } |
| 17585 | case BO_LAnd: |
| 17586 | case BO_LOr: { |
| 17587 | ICEDiag LHSResult = CheckICE(E: Exp->getLHS(), Ctx); |
| 17588 | ICEDiag RHSResult = CheckICE(E: Exp->getRHS(), Ctx); |
| 17589 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { |
| 17590 | // Rare case where the RHS has a comma "side-effect"; we need |
| 17591 | // to actually check the condition to see whether the side |
| 17592 | // with the comma is evaluated. |
| 17593 | if ((Exp->getOpcode() == BO_LAnd) != |
| 17594 | (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) |
| 17595 | return RHSResult; |
| 17596 | return NoDiag(); |
| 17597 | } |
| 17598 | |
| 17599 | return Worst(A: LHSResult, B: RHSResult); |
| 17600 | } |
| 17601 | } |
| 17602 | llvm_unreachable("invalid binary operator kind" ); |
| 17603 | } |
| 17604 | case Expr::ImplicitCastExprClass: |
| 17605 | case Expr::CStyleCastExprClass: |
| 17606 | case Expr::CXXFunctionalCastExprClass: |
| 17607 | case Expr::CXXStaticCastExprClass: |
| 17608 | case Expr::CXXReinterpretCastExprClass: |
| 17609 | case Expr::CXXConstCastExprClass: |
| 17610 | case Expr::ObjCBridgedCastExprClass: { |
| 17611 | const Expr *SubExpr = cast<CastExpr>(Val: E)->getSubExpr(); |
| 17612 | if (isa<ExplicitCastExpr>(Val: E)) { |
| 17613 | if (const FloatingLiteral *FL |
| 17614 | = dyn_cast<FloatingLiteral>(Val: SubExpr->IgnoreParenImpCasts())) { |
| 17615 | unsigned DestWidth = Ctx.getIntWidth(T: E->getType()); |
| 17616 | bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); |
| 17617 | APSInt IgnoredVal(DestWidth, !DestSigned); |
| 17618 | bool Ignored; |
| 17619 | // If the value does not fit in the destination type, the behavior is |
| 17620 | // undefined, so we are not required to treat it as a constant |
| 17621 | // expression. |
| 17622 | if (FL->getValue().convertToInteger(Result&: IgnoredVal, |
| 17623 | RM: llvm::APFloat::rmTowardZero, |
| 17624 | IsExact: &Ignored) & APFloat::opInvalidOp) |
| 17625 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17626 | return NoDiag(); |
| 17627 | } |
| 17628 | } |
| 17629 | switch (cast<CastExpr>(Val: E)->getCastKind()) { |
| 17630 | case CK_LValueToRValue: |
| 17631 | case CK_AtomicToNonAtomic: |
| 17632 | case CK_NonAtomicToAtomic: |
| 17633 | case CK_NoOp: |
| 17634 | case CK_IntegralToBoolean: |
| 17635 | case CK_IntegralCast: |
| 17636 | return CheckICE(E: SubExpr, Ctx); |
| 17637 | default: |
| 17638 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17639 | } |
| 17640 | } |
| 17641 | case Expr::BinaryConditionalOperatorClass: { |
| 17642 | const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(Val: E); |
| 17643 | ICEDiag CommonResult = CheckICE(E: Exp->getCommon(), Ctx); |
| 17644 | if (CommonResult.Kind == IK_NotICE) return CommonResult; |
| 17645 | ICEDiag FalseResult = CheckICE(E: Exp->getFalseExpr(), Ctx); |
| 17646 | if (FalseResult.Kind == IK_NotICE) return FalseResult; |
| 17647 | if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; |
| 17648 | if (FalseResult.Kind == IK_ICEIfUnevaluated && |
| 17649 | Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); |
| 17650 | return FalseResult; |
| 17651 | } |
| 17652 | case Expr::ConditionalOperatorClass: { |
| 17653 | const ConditionalOperator *Exp = cast<ConditionalOperator>(Val: E); |
| 17654 | // If the condition (ignoring parens) is a __builtin_constant_p call, |
| 17655 | // then only the true side is actually considered in an integer constant |
| 17656 | // expression, and it is fully evaluated. This is an important GNU |
| 17657 | // extension. See GCC PR38377 for discussion. |
| 17658 | if (const CallExpr *CallCE |
| 17659 | = dyn_cast<CallExpr>(Val: Exp->getCond()->IgnoreParenCasts())) |
| 17660 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) |
| 17661 | return CheckEvalInICE(E, Ctx); |
| 17662 | ICEDiag CondResult = CheckICE(E: Exp->getCond(), Ctx); |
| 17663 | if (CondResult.Kind == IK_NotICE) |
| 17664 | return CondResult; |
| 17665 | |
| 17666 | ICEDiag TrueResult = CheckICE(E: Exp->getTrueExpr(), Ctx); |
| 17667 | ICEDiag FalseResult = CheckICE(E: Exp->getFalseExpr(), Ctx); |
| 17668 | |
| 17669 | if (TrueResult.Kind == IK_NotICE) |
| 17670 | return TrueResult; |
| 17671 | if (FalseResult.Kind == IK_NotICE) |
| 17672 | return FalseResult; |
| 17673 | if (CondResult.Kind == IK_ICEIfUnevaluated) |
| 17674 | return CondResult; |
| 17675 | if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) |
| 17676 | return NoDiag(); |
| 17677 | // Rare case where the diagnostics depend on which side is evaluated |
| 17678 | // Note that if we get here, CondResult is 0, and at least one of |
| 17679 | // TrueResult and FalseResult is non-zero. |
| 17680 | if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) |
| 17681 | return FalseResult; |
| 17682 | return TrueResult; |
| 17683 | } |
| 17684 | case Expr::CXXDefaultArgExprClass: |
| 17685 | return CheckICE(E: cast<CXXDefaultArgExpr>(Val: E)->getExpr(), Ctx); |
| 17686 | case Expr::CXXDefaultInitExprClass: |
| 17687 | return CheckICE(E: cast<CXXDefaultInitExpr>(Val: E)->getExpr(), Ctx); |
| 17688 | case Expr::ChooseExprClass: { |
| 17689 | return CheckICE(E: cast<ChooseExpr>(Val: E)->getChosenSubExpr(), Ctx); |
| 17690 | } |
| 17691 | case Expr::BuiltinBitCastExprClass: { |
| 17692 | if (!checkBitCastConstexprEligibility(Info: nullptr, Ctx, BCE: cast<CastExpr>(Val: E))) |
| 17693 | return ICEDiag(IK_NotICE, E->getBeginLoc()); |
| 17694 | return CheckICE(E: cast<CastExpr>(Val: E)->getSubExpr(), Ctx); |
| 17695 | } |
| 17696 | } |
| 17697 | |
| 17698 | llvm_unreachable("Invalid StmtClass!" ); |
| 17699 | } |
| 17700 | |
| 17701 | /// Evaluate an expression as a C++11 integral constant expression. |
| 17702 | static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, |
| 17703 | const Expr *E, |
| 17704 | llvm::APSInt *Value, |
| 17705 | SourceLocation *Loc) { |
| 17706 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { |
| 17707 | if (Loc) *Loc = E->getExprLoc(); |
| 17708 | return false; |
| 17709 | } |
| 17710 | |
| 17711 | APValue Result; |
| 17712 | if (!E->isCXX11ConstantExpr(Ctx, Result: &Result, Loc)) |
| 17713 | return false; |
| 17714 | |
| 17715 | if (!Result.isInt()) { |
| 17716 | if (Loc) *Loc = E->getExprLoc(); |
| 17717 | return false; |
| 17718 | } |
| 17719 | |
| 17720 | if (Value) *Value = Result.getInt(); |
| 17721 | return true; |
| 17722 | } |
| 17723 | |
| 17724 | bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, |
| 17725 | SourceLocation *Loc) const { |
| 17726 | assert(!isValueDependent() && |
| 17727 | "Expression evaluator can't be called on a dependent expression." ); |
| 17728 | |
| 17729 | ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr" ); |
| 17730 | |
| 17731 | if (Ctx.getLangOpts().CPlusPlus11) |
| 17732 | return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, E: this, Value: nullptr, Loc); |
| 17733 | |
| 17734 | ICEDiag D = CheckICE(E: this, Ctx); |
| 17735 | if (D.Kind != IK_ICE) { |
| 17736 | if (Loc) *Loc = D.Loc; |
| 17737 | return false; |
| 17738 | } |
| 17739 | return true; |
| 17740 | } |
| 17741 | |
| 17742 | std::optional<llvm::APSInt> |
| 17743 | Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const { |
| 17744 | if (isValueDependent()) { |
| 17745 | // Expression evaluator can't succeed on a dependent expression. |
| 17746 | return std::nullopt; |
| 17747 | } |
| 17748 | |
| 17749 | APSInt Value; |
| 17750 | |
| 17751 | if (Ctx.getLangOpts().CPlusPlus11) { |
| 17752 | if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, E: this, Value: &Value, Loc)) |
| 17753 | return Value; |
| 17754 | return std::nullopt; |
| 17755 | } |
| 17756 | |
| 17757 | if (!isIntegerConstantExpr(Ctx, Loc)) |
| 17758 | return std::nullopt; |
| 17759 | |
| 17760 | // The only possible side-effects here are due to UB discovered in the |
| 17761 | // evaluation (for instance, INT_MAX + 1). In such a case, we are still |
| 17762 | // required to treat the expression as an ICE, so we produce the folded |
| 17763 | // value. |
| 17764 | EvalResult ExprResult; |
| 17765 | Expr::EvalStatus Status; |
| 17766 | EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); |
| 17767 | Info.InConstantContext = true; |
| 17768 | |
| 17769 | if (!::EvaluateAsInt(E: this, ExprResult, Ctx, AllowSideEffects: SE_AllowSideEffects, Info)) |
| 17770 | llvm_unreachable("ICE cannot be evaluated!" ); |
| 17771 | |
| 17772 | return ExprResult.Val.getInt(); |
| 17773 | } |
| 17774 | |
| 17775 | bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { |
| 17776 | assert(!isValueDependent() && |
| 17777 | "Expression evaluator can't be called on a dependent expression." ); |
| 17778 | |
| 17779 | return CheckICE(E: this, Ctx).Kind == IK_ICE; |
| 17780 | } |
| 17781 | |
| 17782 | bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, |
| 17783 | SourceLocation *Loc) const { |
| 17784 | assert(!isValueDependent() && |
| 17785 | "Expression evaluator can't be called on a dependent expression." ); |
| 17786 | |
| 17787 | // We support this checking in C++98 mode in order to diagnose compatibility |
| 17788 | // issues. |
| 17789 | assert(Ctx.getLangOpts().CPlusPlus); |
| 17790 | |
| 17791 | // Build evaluation settings. |
| 17792 | Expr::EvalStatus Status; |
| 17793 | SmallVector<PartialDiagnosticAt, 8> Diags; |
| 17794 | Status.Diag = &Diags; |
| 17795 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); |
| 17796 | |
| 17797 | APValue Scratch; |
| 17798 | bool IsConstExpr = |
| 17799 | ::EvaluateAsRValue(Info, E: this, Result&: Result ? *Result : Scratch) && |
| 17800 | // FIXME: We don't produce a diagnostic for this, but the callers that |
| 17801 | // call us on arbitrary full-expressions should generally not care. |
| 17802 | Info.discardCleanups() && !Status.HasSideEffects; |
| 17803 | |
| 17804 | if (!Diags.empty()) { |
| 17805 | IsConstExpr = false; |
| 17806 | if (Loc) *Loc = Diags[0].first; |
| 17807 | } else if (!IsConstExpr) { |
| 17808 | // FIXME: This shouldn't happen. |
| 17809 | if (Loc) *Loc = getExprLoc(); |
| 17810 | } |
| 17811 | |
| 17812 | return IsConstExpr; |
| 17813 | } |
| 17814 | |
| 17815 | bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, |
| 17816 | const FunctionDecl *Callee, |
| 17817 | ArrayRef<const Expr*> Args, |
| 17818 | const Expr *This) const { |
| 17819 | assert(!isValueDependent() && |
| 17820 | "Expression evaluator can't be called on a dependent expression." ); |
| 17821 | |
| 17822 | llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution" , [&] { |
| 17823 | std::string Name; |
| 17824 | llvm::raw_string_ostream OS(Name); |
| 17825 | Callee->getNameForDiagnostic(OS, Policy: Ctx.getPrintingPolicy(), |
| 17826 | /*Qualified=*/true); |
| 17827 | return Name; |
| 17828 | }); |
| 17829 | |
| 17830 | Expr::EvalStatus Status; |
| 17831 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); |
| 17832 | Info.InConstantContext = true; |
| 17833 | |
| 17834 | LValue ThisVal; |
| 17835 | const LValue *ThisPtr = nullptr; |
| 17836 | if (This) { |
| 17837 | #ifndef NDEBUG |
| 17838 | auto *MD = dyn_cast<CXXMethodDecl>(Callee); |
| 17839 | assert(MD && "Don't provide `this` for non-methods." ); |
| 17840 | assert(MD->isImplicitObjectMemberFunction() && |
| 17841 | "Don't provide `this` for methods without an implicit object." ); |
| 17842 | #endif |
| 17843 | if (!This->isValueDependent() && |
| 17844 | EvaluateObjectArgument(Info, Object: This, This&: ThisVal) && |
| 17845 | !Info.EvalStatus.HasSideEffects) |
| 17846 | ThisPtr = &ThisVal; |
| 17847 | |
| 17848 | // Ignore any side-effects from a failed evaluation. This is safe because |
| 17849 | // they can't interfere with any other argument evaluation. |
| 17850 | Info.EvalStatus.HasSideEffects = false; |
| 17851 | } |
| 17852 | |
| 17853 | CallRef Call = Info.CurrentCall->createCall(Callee); |
| 17854 | for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); |
| 17855 | I != E; ++I) { |
| 17856 | unsigned Idx = I - Args.begin(); |
| 17857 | if (Idx >= Callee->getNumParams()) |
| 17858 | break; |
| 17859 | const ParmVarDecl *PVD = Callee->getParamDecl(i: Idx); |
| 17860 | if ((*I)->isValueDependent() || |
| 17861 | !EvaluateCallArg(PVD, Arg: *I, Call, Info) || |
| 17862 | Info.EvalStatus.HasSideEffects) { |
| 17863 | // If evaluation fails, throw away the argument entirely. |
| 17864 | if (APValue *Slot = Info.getParamSlot(Call, PVD)) |
| 17865 | *Slot = APValue(); |
| 17866 | } |
| 17867 | |
| 17868 | // Ignore any side-effects from a failed evaluation. This is safe because |
| 17869 | // they can't interfere with any other argument evaluation. |
| 17870 | Info.EvalStatus.HasSideEffects = false; |
| 17871 | } |
| 17872 | |
| 17873 | // Parameter cleanups happen in the caller and are not part of this |
| 17874 | // evaluation. |
| 17875 | Info.discardCleanups(); |
| 17876 | Info.EvalStatus.HasSideEffects = false; |
| 17877 | |
| 17878 | // Build fake call to Callee. |
| 17879 | CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This, |
| 17880 | Call); |
| 17881 | // FIXME: Missing ExprWithCleanups in enable_if conditions? |
| 17882 | FullExpressionRAII Scope(Info); |
| 17883 | return Evaluate(Result&: Value, Info, E: this) && Scope.destroy() && |
| 17884 | !Info.EvalStatus.HasSideEffects; |
| 17885 | } |
| 17886 | |
| 17887 | bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, |
| 17888 | SmallVectorImpl< |
| 17889 | PartialDiagnosticAt> &Diags) { |
| 17890 | // FIXME: It would be useful to check constexpr function templates, but at the |
| 17891 | // moment the constant expression evaluator cannot cope with the non-rigorous |
| 17892 | // ASTs which we build for dependent expressions. |
| 17893 | if (FD->isDependentContext()) |
| 17894 | return true; |
| 17895 | |
| 17896 | llvm::TimeTraceScope TimeScope("isPotentialConstantExpr" , [&] { |
| 17897 | std::string Name; |
| 17898 | llvm::raw_string_ostream OS(Name); |
| 17899 | FD->getNameForDiagnostic(OS, Policy: FD->getASTContext().getPrintingPolicy(), |
| 17900 | /*Qualified=*/true); |
| 17901 | return Name; |
| 17902 | }); |
| 17903 | |
| 17904 | Expr::EvalStatus Status; |
| 17905 | Status.Diag = &Diags; |
| 17906 | |
| 17907 | EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); |
| 17908 | Info.InConstantContext = true; |
| 17909 | Info.CheckingPotentialConstantExpression = true; |
| 17910 | |
| 17911 | // The constexpr VM attempts to compile all methods to bytecode here. |
| 17912 | if (Info.EnableNewConstInterp) { |
| 17913 | Info.Ctx.getInterpContext().isPotentialConstantExpr(Parent&: Info, FnDecl: FD); |
| 17914 | return Diags.empty(); |
| 17915 | } |
| 17916 | |
| 17917 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD); |
| 17918 | const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; |
| 17919 | |
| 17920 | // Fabricate an arbitrary expression on the stack and pretend that it |
| 17921 | // is a temporary being used as the 'this' pointer. |
| 17922 | LValue This; |
| 17923 | ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(Decl: RD) : Info.Ctx.IntTy); |
| 17924 | This.set(B: {&VIE, Info.CurrentCall->Index}); |
| 17925 | |
| 17926 | ArrayRef<const Expr*> Args; |
| 17927 | |
| 17928 | APValue Scratch; |
| 17929 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: FD)) { |
| 17930 | // Evaluate the call as a constant initializer, to allow the construction |
| 17931 | // of objects of non-literal types. |
| 17932 | Info.setEvaluatingDecl(Base: This.getLValueBase(), Value&: Scratch); |
| 17933 | HandleConstructorCall(E: &VIE, This, Args, Definition: CD, Info, Result&: Scratch); |
| 17934 | } else { |
| 17935 | SourceLocation Loc = FD->getLocation(); |
| 17936 | HandleFunctionCall( |
| 17937 | CallLoc: Loc, Callee: FD, ObjectArg: (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr, |
| 17938 | E: &VIE, Args, Call: CallRef(), Body: FD->getBody(), Info, Result&: Scratch, |
| 17939 | /*ResultSlot=*/nullptr); |
| 17940 | } |
| 17941 | |
| 17942 | return Diags.empty(); |
| 17943 | } |
| 17944 | |
| 17945 | bool Expr::isPotentialConstantExprUnevaluated(Expr *E, |
| 17946 | const FunctionDecl *FD, |
| 17947 | SmallVectorImpl< |
| 17948 | PartialDiagnosticAt> &Diags) { |
| 17949 | assert(!E->isValueDependent() && |
| 17950 | "Expression evaluator can't be called on a dependent expression." ); |
| 17951 | |
| 17952 | Expr::EvalStatus Status; |
| 17953 | Status.Diag = &Diags; |
| 17954 | |
| 17955 | EvalInfo Info(FD->getASTContext(), Status, |
| 17956 | EvalInfo::EM_ConstantExpressionUnevaluated); |
| 17957 | Info.InConstantContext = true; |
| 17958 | Info.CheckingPotentialConstantExpression = true; |
| 17959 | |
| 17960 | // Fabricate a call stack frame to give the arguments a plausible cover story. |
| 17961 | CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr, |
| 17962 | /*CallExpr=*/nullptr, CallRef()); |
| 17963 | |
| 17964 | APValue ResultScratch; |
| 17965 | Evaluate(Result&: ResultScratch, Info, E); |
| 17966 | return Diags.empty(); |
| 17967 | } |
| 17968 | |
| 17969 | bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, |
| 17970 | unsigned Type) const { |
| 17971 | if (!getType()->isPointerType()) |
| 17972 | return false; |
| 17973 | |
| 17974 | Expr::EvalStatus Status; |
| 17975 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); |
| 17976 | return tryEvaluateBuiltinObjectSize(E: this, Type, Info, Size&: Result); |
| 17977 | } |
| 17978 | |
| 17979 | static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, |
| 17980 | EvalInfo &Info, std::string *StringResult) { |
| 17981 | if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) |
| 17982 | return false; |
| 17983 | |
| 17984 | LValue String; |
| 17985 | |
| 17986 | if (!EvaluatePointer(E, Result&: String, Info)) |
| 17987 | return false; |
| 17988 | |
| 17989 | QualType CharTy = E->getType()->getPointeeType(); |
| 17990 | |
| 17991 | // Fast path: if it's a string literal, search the string value. |
| 17992 | if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( |
| 17993 | Val: String.getLValueBase().dyn_cast<const Expr *>())) { |
| 17994 | StringRef Str = S->getBytes(); |
| 17995 | int64_t Off = String.Offset.getQuantity(); |
| 17996 | if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && |
| 17997 | S->getCharByteWidth() == 1 && |
| 17998 | // FIXME: Add fast-path for wchar_t too. |
| 17999 | Info.Ctx.hasSameUnqualifiedType(T1: CharTy, T2: Info.Ctx.CharTy)) { |
| 18000 | Str = Str.substr(Start: Off); |
| 18001 | |
| 18002 | StringRef::size_type Pos = Str.find(C: 0); |
| 18003 | if (Pos != StringRef::npos) |
| 18004 | Str = Str.substr(Start: 0, N: Pos); |
| 18005 | |
| 18006 | Result = Str.size(); |
| 18007 | if (StringResult) |
| 18008 | *StringResult = Str; |
| 18009 | return true; |
| 18010 | } |
| 18011 | |
| 18012 | // Fall through to slow path. |
| 18013 | } |
| 18014 | |
| 18015 | // Slow path: scan the bytes of the string looking for the terminating 0. |
| 18016 | for (uint64_t Strlen = 0; /**/; ++Strlen) { |
| 18017 | APValue Char; |
| 18018 | if (!handleLValueToRValueConversion(Info, Conv: E, Type: CharTy, LVal: String, RVal&: Char) || |
| 18019 | !Char.isInt()) |
| 18020 | return false; |
| 18021 | if (!Char.getInt()) { |
| 18022 | Result = Strlen; |
| 18023 | return true; |
| 18024 | } else if (StringResult) |
| 18025 | StringResult->push_back(c: Char.getInt().getExtValue()); |
| 18026 | if (!HandleLValueArrayAdjustment(Info, E, LVal&: String, EltTy: CharTy, Adjustment: 1)) |
| 18027 | return false; |
| 18028 | } |
| 18029 | } |
| 18030 | |
| 18031 | std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const { |
| 18032 | Expr::EvalStatus Status; |
| 18033 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); |
| 18034 | uint64_t Result; |
| 18035 | std::string StringResult; |
| 18036 | |
| 18037 | if (EvaluateBuiltinStrLen(E: this, Result, Info, StringResult: &StringResult)) |
| 18038 | return StringResult; |
| 18039 | return {}; |
| 18040 | } |
| 18041 | |
| 18042 | template <typename T> |
| 18043 | static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, |
| 18044 | const Expr *SizeExpression, |
| 18045 | const Expr *PtrExpression, |
| 18046 | ASTContext &Ctx, |
| 18047 | Expr::EvalResult &Status) { |
| 18048 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); |
| 18049 | Info.InConstantContext = true; |
| 18050 | |
| 18051 | if (Info.EnableNewConstInterp) |
| 18052 | return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression, |
| 18053 | PtrExpression, Result); |
| 18054 | |
| 18055 | LValue String; |
| 18056 | FullExpressionRAII Scope(Info); |
| 18057 | APSInt SizeValue; |
| 18058 | if (!::EvaluateInteger(E: SizeExpression, Result&: SizeValue, Info)) |
| 18059 | return false; |
| 18060 | |
| 18061 | uint64_t Size = SizeValue.getZExtValue(); |
| 18062 | |
| 18063 | // FIXME: better protect against invalid or excessive sizes |
| 18064 | if constexpr (std::is_same_v<APValue, T>) |
| 18065 | Result = APValue(APValue::UninitArray{}, Size, Size); |
| 18066 | else { |
| 18067 | if (Size < Result.max_size()) |
| 18068 | Result.reserve(Size); |
| 18069 | } |
| 18070 | if (!::EvaluatePointer(E: PtrExpression, Result&: String, Info)) |
| 18071 | return false; |
| 18072 | |
| 18073 | QualType CharTy = PtrExpression->getType()->getPointeeType(); |
| 18074 | for (uint64_t I = 0; I < Size; ++I) { |
| 18075 | APValue Char; |
| 18076 | if (!handleLValueToRValueConversion(Info, Conv: PtrExpression, Type: CharTy, LVal: String, |
| 18077 | RVal&: Char)) |
| 18078 | return false; |
| 18079 | |
| 18080 | if constexpr (std::is_same_v<APValue, T>) { |
| 18081 | Result.getArrayInitializedElt(I) = std::move(Char); |
| 18082 | } else { |
| 18083 | APSInt C = Char.getInt(); |
| 18084 | |
| 18085 | assert(C.getBitWidth() <= 8 && |
| 18086 | "string element not representable in char" ); |
| 18087 | |
| 18088 | Result.push_back(static_cast<char>(C.getExtValue())); |
| 18089 | } |
| 18090 | |
| 18091 | if (!HandleLValueArrayAdjustment(Info, E: PtrExpression, LVal&: String, EltTy: CharTy, Adjustment: 1)) |
| 18092 | return false; |
| 18093 | } |
| 18094 | |
| 18095 | return Scope.destroy() && CheckMemoryLeaks(Info); |
| 18096 | } |
| 18097 | |
| 18098 | bool Expr::EvaluateCharRangeAsString(std::string &Result, |
| 18099 | const Expr *SizeExpression, |
| 18100 | const Expr *PtrExpression, ASTContext &Ctx, |
| 18101 | EvalResult &Status) const { |
| 18102 | return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression, |
| 18103 | PtrExpression, Ctx, Status); |
| 18104 | } |
| 18105 | |
| 18106 | bool Expr::EvaluateCharRangeAsString(APValue &Result, |
| 18107 | const Expr *SizeExpression, |
| 18108 | const Expr *PtrExpression, ASTContext &Ctx, |
| 18109 | EvalResult &Status) const { |
| 18110 | return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression, |
| 18111 | PtrExpression, Ctx, Status); |
| 18112 | } |
| 18113 | |
| 18114 | bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { |
| 18115 | Expr::EvalStatus Status; |
| 18116 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); |
| 18117 | return EvaluateBuiltinStrLen(E: this, Result, Info); |
| 18118 | } |
| 18119 | |
| 18120 | namespace { |
| 18121 | struct IsWithinLifetimeHandler { |
| 18122 | EvalInfo &Info; |
| 18123 | static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime; |
| 18124 | using result_type = std::optional<bool>; |
| 18125 | std::optional<bool> failed() { return std::nullopt; } |
| 18126 | template <typename T> |
| 18127 | std::optional<bool> found(T &Subobj, QualType SubobjType) { |
| 18128 | return true; |
| 18129 | } |
| 18130 | }; |
| 18131 | |
| 18132 | std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE, |
| 18133 | const CallExpr *E) { |
| 18134 | EvalInfo &Info = IEE.Info; |
| 18135 | // Sometimes this is called during some sorts of constant folding / early |
| 18136 | // evaluation. These are meant for non-constant expressions and are not |
| 18137 | // necessary since this consteval builtin will never be evaluated at runtime. |
| 18138 | // Just fail to evaluate when not in a constant context. |
| 18139 | if (!Info.InConstantContext) |
| 18140 | return std::nullopt; |
| 18141 | assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime); |
| 18142 | const Expr *Arg = E->getArg(Arg: 0); |
| 18143 | if (Arg->isValueDependent()) |
| 18144 | return std::nullopt; |
| 18145 | LValue Val; |
| 18146 | if (!EvaluatePointer(E: Arg, Result&: Val, Info)) |
| 18147 | return std::nullopt; |
| 18148 | |
| 18149 | if (Val.allowConstexprUnknown()) |
| 18150 | return true; |
| 18151 | |
| 18152 | auto Error = [&](int Diag) { |
| 18153 | bool CalledFromStd = false; |
| 18154 | const auto *Callee = Info.CurrentCall->getCallee(); |
| 18155 | if (Callee && Callee->isInStdNamespace()) { |
| 18156 | const IdentifierInfo *Identifier = Callee->getIdentifier(); |
| 18157 | CalledFromStd = Identifier && Identifier->isStr(Str: "is_within_lifetime" ); |
| 18158 | } |
| 18159 | Info.CCEDiag(Loc: CalledFromStd ? Info.CurrentCall->getCallRange().getBegin() |
| 18160 | : E->getExprLoc(), |
| 18161 | DiagId: diag::err_invalid_is_within_lifetime) |
| 18162 | << (CalledFromStd ? "std::is_within_lifetime" |
| 18163 | : "__builtin_is_within_lifetime" ) |
| 18164 | << Diag; |
| 18165 | return std::nullopt; |
| 18166 | }; |
| 18167 | // C++2c [meta.const.eval]p4: |
| 18168 | // During the evaluation of an expression E as a core constant expression, a |
| 18169 | // call to this function is ill-formed unless p points to an object that is |
| 18170 | // usable in constant expressions or whose complete object's lifetime began |
| 18171 | // within E. |
| 18172 | |
| 18173 | // Make sure it points to an object |
| 18174 | // nullptr does not point to an object |
| 18175 | if (Val.isNullPointer() || Val.getLValueBase().isNull()) |
| 18176 | return Error(0); |
| 18177 | QualType T = Val.getLValueBase().getType(); |
| 18178 | assert(!T->isFunctionType() && |
| 18179 | "Pointers to functions should have been typed as function pointers " |
| 18180 | "which would have been rejected earlier" ); |
| 18181 | assert(T->isObjectType()); |
| 18182 | // Hypothetical array element is not an object |
| 18183 | if (Val.getLValueDesignator().isOnePastTheEnd()) |
| 18184 | return Error(1); |
| 18185 | assert(Val.getLValueDesignator().isValidSubobject() && |
| 18186 | "Unchecked case for valid subobject" ); |
| 18187 | // All other ill-formed values should have failed EvaluatePointer, so the |
| 18188 | // object should be a pointer to an object that is usable in a constant |
| 18189 | // expression or whose complete lifetime began within the expression |
| 18190 | CompleteObject CO = |
| 18191 | findCompleteObject(Info, E, AK: AccessKinds::AK_IsWithinLifetime, LVal: Val, LValType: T); |
| 18192 | // The lifetime hasn't begun yet if we are still evaluating the |
| 18193 | // initializer ([basic.life]p(1.2)) |
| 18194 | if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue) |
| 18195 | return Error(2); |
| 18196 | |
| 18197 | if (!CO) |
| 18198 | return false; |
| 18199 | IsWithinLifetimeHandler handler{.Info: Info}; |
| 18200 | return findSubobject(Info, E, Obj: CO, Sub: Val.getLValueDesignator(), handler); |
| 18201 | } |
| 18202 | } // namespace |
| 18203 | |