| File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/AST/ExprConstant.cpp |
| Warning: | line 6028, column 57 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 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 "Interp/Context.h" | |||
| 36 | #include "Interp/Frame.h" | |||
| 37 | #include "Interp/State.h" | |||
| 38 | #include "clang/AST/APValue.h" | |||
| 39 | #include "clang/AST/ASTContext.h" | |||
| 40 | #include "clang/AST/ASTDiagnostic.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/TargetInfo.h" | |||
| 54 | #include "llvm/ADT/APFixedPoint.h" | |||
| 55 | #include "llvm/ADT/Optional.h" | |||
| 56 | #include "llvm/ADT/SmallBitVector.h" | |||
| 57 | #include "llvm/Support/Debug.h" | |||
| 58 | #include "llvm/Support/SaveAndRestore.h" | |||
| 59 | #include "llvm/Support/raw_ostream.h" | |||
| 60 | #include <cstring> | |||
| 61 | #include <functional> | |||
| 62 | ||||
| 63 | #define DEBUG_TYPE"exprconstant" "exprconstant" | |||
| 64 | ||||
| 65 | using namespace clang; | |||
| 66 | using llvm::APFixedPoint; | |||
| 67 | using llvm::APInt; | |||
| 68 | using llvm::APSInt; | |||
| 69 | using llvm::APFloat; | |||
| 70 | using llvm::FixedPointSemantics; | |||
| 71 | using llvm::Optional; | |||
| 72 | ||||
| 73 | namespace { | |||
| 74 | struct LValue; | |||
| 75 | class CallStackFrame; | |||
| 76 | class EvalInfo; | |||
| 77 | ||||
| 78 | using SourceLocExprScopeGuard = | |||
| 79 | CurrentSourceLocExprScope::SourceLocExprScopeGuard; | |||
| 80 | ||||
| 81 | static QualType getType(APValue::LValueBase B) { | |||
| 82 | return B.getType(); | |||
| 83 | } | |||
| 84 | ||||
| 85 | /// Get an LValue path entry, which is known to not be an array index, as a | |||
| 86 | /// field declaration. | |||
| 87 | static const FieldDecl *getAsField(APValue::LValuePathEntry E) { | |||
| 88 | return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); | |||
| 89 | } | |||
| 90 | /// Get an LValue path entry, which is known to not be an array index, as a | |||
| 91 | /// base class declaration. | |||
| 92 | static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { | |||
| 93 | return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); | |||
| 94 | } | |||
| 95 | /// Determine whether this LValue path entry for a base class names a virtual | |||
| 96 | /// base class. | |||
| 97 | static bool isVirtualBaseClass(APValue::LValuePathEntry E) { | |||
| 98 | return E.getAsBaseOrMember().getInt(); | |||
| 99 | } | |||
| 100 | ||||
| 101 | /// Given an expression, determine the type used to store the result of | |||
| 102 | /// evaluating that expression. | |||
| 103 | static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { | |||
| 104 | if (E->isPRValue()) | |||
| 105 | return E->getType(); | |||
| 106 | return Ctx.getLValueReferenceType(E->getType()); | |||
| 107 | } | |||
| 108 | ||||
| 109 | /// Given a CallExpr, try to get the alloc_size attribute. May return null. | |||
| 110 | static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { | |||
| 111 | if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) | |||
| 112 | return DirectCallee->getAttr<AllocSizeAttr>(); | |||
| 113 | if (const Decl *IndirectCallee = CE->getCalleeDecl()) | |||
| 114 | return IndirectCallee->getAttr<AllocSizeAttr>(); | |||
| 115 | return nullptr; | |||
| 116 | } | |||
| 117 | ||||
| 118 | /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. | |||
| 119 | /// This will look through a single cast. | |||
| 120 | /// | |||
| 121 | /// Returns null if we couldn't unwrap a function with alloc_size. | |||
| 122 | static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { | |||
| 123 | if (!E->getType()->isPointerType()) | |||
| 124 | return nullptr; | |||
| 125 | ||||
| 126 | E = E->IgnoreParens(); | |||
| 127 | // If we're doing a variable assignment from e.g. malloc(N), there will | |||
| 128 | // probably be a cast of some kind. In exotic cases, we might also see a | |||
| 129 | // top-level ExprWithCleanups. Ignore them either way. | |||
| 130 | if (const auto *FE = dyn_cast<FullExpr>(E)) | |||
| 131 | E = FE->getSubExpr()->IgnoreParens(); | |||
| 132 | ||||
| 133 | if (const auto *Cast = dyn_cast<CastExpr>(E)) | |||
| 134 | E = Cast->getSubExpr()->IgnoreParens(); | |||
| 135 | ||||
| 136 | if (const auto *CE = dyn_cast<CallExpr>(E)) | |||
| 137 | return getAllocSizeAttr(CE) ? CE : nullptr; | |||
| 138 | return nullptr; | |||
| 139 | } | |||
| 140 | ||||
| 141 | /// Determines whether or not the given Base contains a call to a function | |||
| 142 | /// with the alloc_size attribute. | |||
| 143 | static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { | |||
| 144 | const auto *E = Base.dyn_cast<const Expr *>(); | |||
| 145 | return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); | |||
| 146 | } | |||
| 147 | ||||
| 148 | /// Determines whether the given kind of constant expression is only ever | |||
| 149 | /// used for name mangling. If so, it's permitted to reference things that we | |||
| 150 | /// can't generate code for (in particular, dllimported functions). | |||
| 151 | static bool isForManglingOnly(ConstantExprKind Kind) { | |||
| 152 | switch (Kind) { | |||
| 153 | case ConstantExprKind::Normal: | |||
| 154 | case ConstantExprKind::ClassTemplateArgument: | |||
| 155 | case ConstantExprKind::ImmediateInvocation: | |||
| 156 | // Note that non-type template arguments of class type are emitted as | |||
| 157 | // template parameter objects. | |||
| 158 | return false; | |||
| 159 | ||||
| 160 | case ConstantExprKind::NonClassTemplateArgument: | |||
| 161 | return true; | |||
| 162 | } | |||
| 163 | llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind", "clang/lib/AST/ExprConstant.cpp", 163); | |||
| 164 | } | |||
| 165 | ||||
| 166 | static bool isTemplateArgument(ConstantExprKind Kind) { | |||
| 167 | switch (Kind) { | |||
| 168 | case ConstantExprKind::Normal: | |||
| 169 | case ConstantExprKind::ImmediateInvocation: | |||
| 170 | return false; | |||
| 171 | ||||
| 172 | case ConstantExprKind::ClassTemplateArgument: | |||
| 173 | case ConstantExprKind::NonClassTemplateArgument: | |||
| 174 | return true; | |||
| 175 | } | |||
| 176 | llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind", "clang/lib/AST/ExprConstant.cpp", 176); | |||
| 177 | } | |||
| 178 | ||||
| 179 | /// The bound to claim that an array of unknown bound has. | |||
| 180 | /// The value in MostDerivedArraySize is undefined in this case. So, set it | |||
| 181 | /// to an arbitrary value that's likely to loudly break things if it's used. | |||
| 182 | static const uint64_t AssumedSizeForUnsizedArray = | |||
| 183 | std::numeric_limits<uint64_t>::max() / 2; | |||
| 184 | ||||
| 185 | /// Determines if an LValue with the given LValueBase will have an unsized | |||
| 186 | /// array in its designator. | |||
| 187 | /// Find the path length and type of the most-derived subobject in the given | |||
| 188 | /// path, and find the size of the containing array, if any. | |||
| 189 | static unsigned | |||
| 190 | findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, | |||
| 191 | ArrayRef<APValue::LValuePathEntry> Path, | |||
| 192 | uint64_t &ArraySize, QualType &Type, bool &IsArray, | |||
| 193 | bool &FirstEntryIsUnsizedArray) { | |||
| 194 | // This only accepts LValueBases from APValues, and APValues don't support | |||
| 195 | // arrays that lack size info. | |||
| 196 | assert(!isBaseAnAllocSizeCall(Base) &&(static_cast <bool> (!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here") ? void (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__ )) | |||
| 197 | "Unsized arrays shouldn't appear here")(static_cast <bool> (!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here") ? void (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__ )); | |||
| 198 | unsigned MostDerivedLength = 0; | |||
| 199 | Type = getType(Base); | |||
| 200 | ||||
| 201 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { | |||
| 202 | if (Type->isArrayType()) { | |||
| 203 | const ArrayType *AT = Ctx.getAsArrayType(Type); | |||
| 204 | Type = AT->getElementType(); | |||
| 205 | MostDerivedLength = I + 1; | |||
| 206 | IsArray = true; | |||
| 207 | ||||
| 208 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { | |||
| 209 | ArraySize = CAT->getSize().getZExtValue(); | |||
| 210 | } else { | |||
| 211 | assert(I == 0 && "unexpected unsized array designator")(static_cast <bool> (I == 0 && "unexpected unsized array designator" ) ? void (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\"" , "clang/lib/AST/ExprConstant.cpp", 211, __extension__ __PRETTY_FUNCTION__ )); | |||
| 212 | FirstEntryIsUnsizedArray = true; | |||
| 213 | ArraySize = AssumedSizeForUnsizedArray; | |||
| 214 | } | |||
| 215 | } else if (Type->isAnyComplexType()) { | |||
| 216 | const ComplexType *CT = Type->castAs<ComplexType>(); | |||
| 217 | Type = CT->getElementType(); | |||
| 218 | ArraySize = 2; | |||
| 219 | MostDerivedLength = I + 1; | |||
| 220 | IsArray = true; | |||
| 221 | } else if (const FieldDecl *FD = getAsField(Path[I])) { | |||
| 222 | Type = FD->getType(); | |||
| 223 | ArraySize = 0; | |||
| 224 | MostDerivedLength = I + 1; | |||
| 225 | IsArray = false; | |||
| 226 | } else { | |||
| 227 | // Path[I] describes a base class. | |||
| 228 | ArraySize = 0; | |||
| 229 | IsArray = false; | |||
| 230 | } | |||
| 231 | } | |||
| 232 | return MostDerivedLength; | |||
| 233 | } | |||
| 234 | ||||
| 235 | /// A path from a glvalue to a subobject of that glvalue. | |||
| 236 | struct SubobjectDesignator { | |||
| 237 | /// True if the subobject was named in a manner not supported by C++11. Such | |||
| 238 | /// lvalues can still be folded, but they are not core constant expressions | |||
| 239 | /// and we cannot perform lvalue-to-rvalue conversions on them. | |||
| 240 | unsigned Invalid : 1; | |||
| 241 | ||||
| 242 | /// Is this a pointer one past the end of an object? | |||
| 243 | unsigned IsOnePastTheEnd : 1; | |||
| 244 | ||||
| 245 | /// Indicator of whether the first entry is an unsized array. | |||
| 246 | unsigned FirstEntryIsAnUnsizedArray : 1; | |||
| 247 | ||||
| 248 | /// Indicator of whether the most-derived object is an array element. | |||
| 249 | unsigned MostDerivedIsArrayElement : 1; | |||
| 250 | ||||
| 251 | /// The length of the path to the most-derived object of which this is a | |||
| 252 | /// subobject. | |||
| 253 | unsigned MostDerivedPathLength : 28; | |||
| 254 | ||||
| 255 | /// The size of the array of which the most-derived object is an element. | |||
| 256 | /// This will always be 0 if the most-derived object is not an array | |||
| 257 | /// element. 0 is not an indicator of whether or not the most-derived object | |||
| 258 | /// is an array, however, because 0-length arrays are allowed. | |||
| 259 | /// | |||
| 260 | /// If the current array is an unsized array, the value of this is | |||
| 261 | /// undefined. | |||
| 262 | uint64_t MostDerivedArraySize; | |||
| 263 | ||||
| 264 | /// The type of the most derived object referred to by this address. | |||
| 265 | QualType MostDerivedType; | |||
| 266 | ||||
| 267 | typedef APValue::LValuePathEntry PathEntry; | |||
| 268 | ||||
| 269 | /// The entries on the path from the glvalue to the designated subobject. | |||
| 270 | SmallVector<PathEntry, 8> Entries; | |||
| 271 | ||||
| 272 | SubobjectDesignator() : Invalid(true) {} | |||
| 273 | ||||
| 274 | explicit SubobjectDesignator(QualType T) | |||
| 275 | : Invalid(false), IsOnePastTheEnd(false), | |||
| 276 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | |||
| 277 | MostDerivedPathLength(0), MostDerivedArraySize(0), | |||
| 278 | MostDerivedType(T) {} | |||
| 279 | ||||
| 280 | SubobjectDesignator(ASTContext &Ctx, const APValue &V) | |||
| 281 | : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), | |||
| 282 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | |||
| 283 | MostDerivedPathLength(0), MostDerivedArraySize(0) { | |||
| 284 | assert(V.isLValue() && "Non-LValue used to make an LValue designator?")(static_cast <bool> (V.isLValue() && "Non-LValue used to make an LValue designator?" ) ? void (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\"" , "clang/lib/AST/ExprConstant.cpp", 284, __extension__ __PRETTY_FUNCTION__ )); | |||
| 285 | if (!Invalid) { | |||
| 286 | IsOnePastTheEnd = V.isLValueOnePastTheEnd(); | |||
| 287 | ArrayRef<PathEntry> VEntries = V.getLValuePath(); | |||
| 288 | Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); | |||
| 289 | if (V.getLValueBase()) { | |||
| 290 | bool IsArray = false; | |||
| 291 | bool FirstIsUnsizedArray = false; | |||
| 292 | MostDerivedPathLength = findMostDerivedSubobject( | |||
| 293 | Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, | |||
| 294 | MostDerivedType, IsArray, FirstIsUnsizedArray); | |||
| 295 | MostDerivedIsArrayElement = IsArray; | |||
| 296 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | |||
| 297 | } | |||
| 298 | } | |||
| 299 | } | |||
| 300 | ||||
| 301 | void truncate(ASTContext &Ctx, APValue::LValueBase Base, | |||
| 302 | unsigned NewLength) { | |||
| 303 | if (Invalid) | |||
| 304 | return; | |||
| 305 | ||||
| 306 | assert(Base && "cannot truncate path for null pointer")(static_cast <bool> (Base && "cannot truncate path for null pointer" ) ? void (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\"" , "clang/lib/AST/ExprConstant.cpp", 306, __extension__ __PRETTY_FUNCTION__ )); | |||
| 307 | assert(NewLength <= Entries.size() && "not a truncation")(static_cast <bool> (NewLength <= Entries.size() && "not a truncation") ? void (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\"" , "clang/lib/AST/ExprConstant.cpp", 307, __extension__ __PRETTY_FUNCTION__ )); | |||
| 308 | ||||
| 309 | if (NewLength == Entries.size()) | |||
| 310 | return; | |||
| 311 | Entries.resize(NewLength); | |||
| 312 | ||||
| 313 | bool IsArray = false; | |||
| 314 | bool FirstIsUnsizedArray = false; | |||
| 315 | MostDerivedPathLength = findMostDerivedSubobject( | |||
| 316 | Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, | |||
| 317 | FirstIsUnsizedArray); | |||
| 318 | MostDerivedIsArrayElement = IsArray; | |||
| 319 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | |||
| 320 | } | |||
| 321 | ||||
| 322 | void setInvalid() { | |||
| 323 | Invalid = true; | |||
| 324 | Entries.clear(); | |||
| 325 | } | |||
| 326 | ||||
| 327 | /// Determine whether the most derived subobject is an array without a | |||
| 328 | /// known bound. | |||
| 329 | bool isMostDerivedAnUnsizedArray() const { | |||
| 330 | assert(!Invalid && "Calling this makes no sense on invalid designators")(static_cast <bool> (!Invalid && "Calling this makes no sense on invalid designators" ) ? void (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\"" , "clang/lib/AST/ExprConstant.cpp", 330, __extension__ __PRETTY_FUNCTION__ )); | |||
| 331 | return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; | |||
| 332 | } | |||
| 333 | ||||
| 334 | /// Determine what the most derived array's size is. Results in an assertion | |||
| 335 | /// failure if the most derived array lacks a size. | |||
| 336 | uint64_t getMostDerivedArraySize() const { | |||
| 337 | assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")(static_cast <bool> (!isMostDerivedAnUnsizedArray() && "Unsized array has no size") ? void (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\"" , "clang/lib/AST/ExprConstant.cpp", 337, __extension__ __PRETTY_FUNCTION__ )); | |||
| 338 | return MostDerivedArraySize; | |||
| 339 | } | |||
| 340 | ||||
| 341 | /// Determine whether this is a one-past-the-end pointer. | |||
| 342 | bool isOnePastTheEnd() const { | |||
| 343 | assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail ("!Invalid", "clang/lib/AST/ExprConstant.cpp", 343, __extension__ __PRETTY_FUNCTION__)); | |||
| 344 | if (IsOnePastTheEnd) | |||
| 345 | return true; | |||
| 346 | if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && | |||
| 347 | Entries[MostDerivedPathLength - 1].getAsArrayIndex() == | |||
| 348 | MostDerivedArraySize) | |||
| 349 | return true; | |||
| 350 | return false; | |||
| 351 | } | |||
| 352 | ||||
| 353 | /// Get the range of valid index adjustments in the form | |||
| 354 | /// {maximum value that can be subtracted from this pointer, | |||
| 355 | /// maximum value that can be added to this pointer} | |||
| 356 | std::pair<uint64_t, uint64_t> validIndexAdjustments() { | |||
| 357 | if (Invalid || isMostDerivedAnUnsizedArray()) | |||
| 358 | return {0, 0}; | |||
| 359 | ||||
| 360 | // [expr.add]p4: For the purposes of these operators, a pointer to a | |||
| 361 | // nonarray object behaves the same as a pointer to the first element of | |||
| 362 | // an array of length one with the type of the object as its element type. | |||
| 363 | bool IsArray = MostDerivedPathLength == Entries.size() && | |||
| 364 | MostDerivedIsArrayElement; | |||
| 365 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | |||
| 366 | : (uint64_t)IsOnePastTheEnd; | |||
| 367 | uint64_t ArraySize = | |||
| 368 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | |||
| 369 | return {ArrayIndex, ArraySize - ArrayIndex}; | |||
| 370 | } | |||
| 371 | ||||
| 372 | /// Check that this refers to a valid subobject. | |||
| 373 | bool isValidSubobject() const { | |||
| 374 | if (Invalid) | |||
| 375 | return false; | |||
| 376 | return !isOnePastTheEnd(); | |||
| 377 | } | |||
| 378 | /// Check that this refers to a valid subobject, and if not, produce a | |||
| 379 | /// relevant diagnostic and set the designator as invalid. | |||
| 380 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); | |||
| 381 | ||||
| 382 | /// Get the type of the designated object. | |||
| 383 | QualType getType(ASTContext &Ctx) const { | |||
| 384 | assert(!Invalid && "invalid designator has no subobject type")(static_cast <bool> (!Invalid && "invalid designator has no subobject type" ) ? void (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\"" , "clang/lib/AST/ExprConstant.cpp", 384, __extension__ __PRETTY_FUNCTION__ )); | |||
| 385 | return MostDerivedPathLength == Entries.size() | |||
| 386 | ? MostDerivedType | |||
| 387 | : Ctx.getRecordType(getAsBaseClass(Entries.back())); | |||
| 388 | } | |||
| 389 | ||||
| 390 | /// Update this designator to refer to the first element within this array. | |||
| 391 | void addArrayUnchecked(const ConstantArrayType *CAT) { | |||
| 392 | Entries.push_back(PathEntry::ArrayIndex(0)); | |||
| 393 | ||||
| 394 | // This is a most-derived object. | |||
| 395 | MostDerivedType = CAT->getElementType(); | |||
| 396 | MostDerivedIsArrayElement = true; | |||
| 397 | MostDerivedArraySize = CAT->getSize().getZExtValue(); | |||
| 398 | MostDerivedPathLength = Entries.size(); | |||
| 399 | } | |||
| 400 | /// Update this designator to refer to the first element within the array of | |||
| 401 | /// elements of type T. This is an array of unknown size. | |||
| 402 | void addUnsizedArrayUnchecked(QualType ElemTy) { | |||
| 403 | Entries.push_back(PathEntry::ArrayIndex(0)); | |||
| 404 | ||||
| 405 | MostDerivedType = ElemTy; | |||
| 406 | MostDerivedIsArrayElement = true; | |||
| 407 | // The value in MostDerivedArraySize is undefined in this case. So, set it | |||
| 408 | // to an arbitrary value that's likely to loudly break things if it's | |||
| 409 | // used. | |||
| 410 | MostDerivedArraySize = AssumedSizeForUnsizedArray; | |||
| 411 | MostDerivedPathLength = Entries.size(); | |||
| 412 | } | |||
| 413 | /// Update this designator to refer to the given base or member of this | |||
| 414 | /// object. | |||
| 415 | void addDeclUnchecked(const Decl *D, bool Virtual = false) { | |||
| 416 | Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); | |||
| 417 | ||||
| 418 | // If this isn't a base class, it's a new most-derived object. | |||
| 419 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { | |||
| 420 | MostDerivedType = FD->getType(); | |||
| 421 | MostDerivedIsArrayElement = false; | |||
| 422 | MostDerivedArraySize = 0; | |||
| 423 | MostDerivedPathLength = Entries.size(); | |||
| 424 | } | |||
| 425 | } | |||
| 426 | /// Update this designator to refer to the given complex component. | |||
| 427 | void addComplexUnchecked(QualType EltTy, bool Imag) { | |||
| 428 | Entries.push_back(PathEntry::ArrayIndex(Imag)); | |||
| 429 | ||||
| 430 | // This is technically a most-derived object, though in practice this | |||
| 431 | // is unlikely to matter. | |||
| 432 | MostDerivedType = EltTy; | |||
| 433 | MostDerivedIsArrayElement = true; | |||
| 434 | MostDerivedArraySize = 2; | |||
| 435 | MostDerivedPathLength = Entries.size(); | |||
| 436 | } | |||
| 437 | void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); | |||
| 438 | void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, | |||
| 439 | const APSInt &N); | |||
| 440 | /// Add N to the address of this subobject. | |||
| 441 | void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { | |||
| 442 | if (Invalid || !N) return; | |||
| 443 | uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); | |||
| 444 | if (isMostDerivedAnUnsizedArray()) { | |||
| 445 | diagnoseUnsizedArrayPointerArithmetic(Info, E); | |||
| 446 | // Can't verify -- trust that the user is doing the right thing (or if | |||
| 447 | // not, trust that the caller will catch the bad behavior). | |||
| 448 | // FIXME: Should we reject if this overflows, at least? | |||
| 449 | Entries.back() = PathEntry::ArrayIndex( | |||
| 450 | Entries.back().getAsArrayIndex() + TruncatedN); | |||
| 451 | return; | |||
| 452 | } | |||
| 453 | ||||
| 454 | // [expr.add]p4: For the purposes of these operators, a pointer to a | |||
| 455 | // nonarray object behaves the same as a pointer to the first element of | |||
| 456 | // an array of length one with the type of the object as its element type. | |||
| 457 | bool IsArray = MostDerivedPathLength == Entries.size() && | |||
| 458 | MostDerivedIsArrayElement; | |||
| 459 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | |||
| 460 | : (uint64_t)IsOnePastTheEnd; | |||
| 461 | uint64_t ArraySize = | |||
| 462 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | |||
| 463 | ||||
| 464 | if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { | |||
| 465 | // Calculate the actual index in a wide enough type, so we can include | |||
| 466 | // it in the note. | |||
| 467 | N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); | |||
| 468 | (llvm::APInt&)N += ArrayIndex; | |||
| 469 | assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")(static_cast <bool> (N.ugt(ArraySize) && "bounds check failed for in-bounds index" ) ? void (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\"" , "clang/lib/AST/ExprConstant.cpp", 469, __extension__ __PRETTY_FUNCTION__ )); | |||
| 470 | diagnosePointerArithmetic(Info, E, N); | |||
| 471 | setInvalid(); | |||
| 472 | return; | |||
| 473 | } | |||
| 474 | ||||
| 475 | ArrayIndex += TruncatedN; | |||
| 476 | assert(ArrayIndex <= ArraySize &&(static_cast <bool> (ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index") ? void (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__ )) | |||
| 477 | "bounds check succeeded for out-of-bounds index")(static_cast <bool> (ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index") ? void (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__ )); | |||
| 478 | ||||
| 479 | if (IsArray) | |||
| 480 | Entries.back() = PathEntry::ArrayIndex(ArrayIndex); | |||
| 481 | else | |||
| 482 | IsOnePastTheEnd = (ArrayIndex != 0); | |||
| 483 | } | |||
| 484 | }; | |||
| 485 | ||||
| 486 | /// A scope at the end of which an object can need to be destroyed. | |||
| 487 | enum class ScopeKind { | |||
| 488 | Block, | |||
| 489 | FullExpression, | |||
| 490 | Call | |||
| 491 | }; | |||
| 492 | ||||
| 493 | /// A reference to a particular call and its arguments. | |||
| 494 | struct CallRef { | |||
| 495 | CallRef() : OrigCallee(), CallIndex(0), Version() {} | |||
| 496 | CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) | |||
| 497 | : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} | |||
| 498 | ||||
| 499 | explicit operator bool() const { return OrigCallee; } | |||
| 500 | ||||
| 501 | /// Get the parameter that the caller initialized, corresponding to the | |||
| 502 | /// given parameter in the callee. | |||
| 503 | const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { | |||
| 504 | return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) | |||
| 505 | : PVD; | |||
| 506 | } | |||
| 507 | ||||
| 508 | /// The callee at the point where the arguments were evaluated. This might | |||
| 509 | /// be different from the actual callee (a different redeclaration, or a | |||
| 510 | /// virtual override), but this function's parameters are the ones that | |||
| 511 | /// appear in the parameter map. | |||
| 512 | const FunctionDecl *OrigCallee; | |||
| 513 | /// The call index of the frame that holds the argument values. | |||
| 514 | unsigned CallIndex; | |||
| 515 | /// The version of the parameters corresponding to this call. | |||
| 516 | unsigned Version; | |||
| 517 | }; | |||
| 518 | ||||
| 519 | /// A stack frame in the constexpr call stack. | |||
| 520 | class CallStackFrame : public interp::Frame { | |||
| 521 | public: | |||
| 522 | EvalInfo &Info; | |||
| 523 | ||||
| 524 | /// Parent - The caller of this stack frame. | |||
| 525 | CallStackFrame *Caller; | |||
| 526 | ||||
| 527 | /// Callee - The function which was called. | |||
| 528 | const FunctionDecl *Callee; | |||
| 529 | ||||
| 530 | /// This - The binding for the this pointer in this call, if any. | |||
| 531 | const LValue *This; | |||
| 532 | ||||
| 533 | /// Information on how to find the arguments to this call. Our arguments | |||
| 534 | /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a | |||
| 535 | /// key and this value as the version. | |||
| 536 | CallRef Arguments; | |||
| 537 | ||||
| 538 | /// Source location information about the default argument or default | |||
| 539 | /// initializer expression we're evaluating, if any. | |||
| 540 | CurrentSourceLocExprScope CurSourceLocExprScope; | |||
| 541 | ||||
| 542 | // Note that we intentionally use std::map here so that references to | |||
| 543 | // values are stable. | |||
| 544 | typedef std::pair<const void *, unsigned> MapKeyTy; | |||
| 545 | typedef std::map<MapKeyTy, APValue> MapTy; | |||
| 546 | /// Temporaries - Temporary lvalues materialized within this stack frame. | |||
| 547 | MapTy Temporaries; | |||
| 548 | ||||
| 549 | /// CallLoc - The location of the call expression for this call. | |||
| 550 | SourceLocation CallLoc; | |||
| 551 | ||||
| 552 | /// Index - The call index of this call. | |||
| 553 | unsigned Index; | |||
| 554 | ||||
| 555 | /// The stack of integers for tracking version numbers for temporaries. | |||
| 556 | SmallVector<unsigned, 2> TempVersionStack = {1}; | |||
| 557 | unsigned CurTempVersion = TempVersionStack.back(); | |||
| 558 | ||||
| 559 | unsigned getTempVersion() const { return TempVersionStack.back(); } | |||
| 560 | ||||
| 561 | void pushTempVersion() { | |||
| 562 | TempVersionStack.push_back(++CurTempVersion); | |||
| 563 | } | |||
| 564 | ||||
| 565 | void popTempVersion() { | |||
| 566 | TempVersionStack.pop_back(); | |||
| 567 | } | |||
| 568 | ||||
| 569 | CallRef createCall(const FunctionDecl *Callee) { | |||
| 570 | return {Callee, Index, ++CurTempVersion}; | |||
| 571 | } | |||
| 572 | ||||
| 573 | // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact | |||
| 574 | // on the overall stack usage of deeply-recursing constexpr evaluations. | |||
| 575 | // (We should cache this map rather than recomputing it repeatedly.) | |||
| 576 | // But let's try this and see how it goes; we can look into caching the map | |||
| 577 | // as a later change. | |||
| 578 | ||||
| 579 | /// LambdaCaptureFields - Mapping from captured variables/this to | |||
| 580 | /// corresponding data members in the closure class. | |||
| 581 | llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; | |||
| 582 | FieldDecl *LambdaThisCaptureField; | |||
| 583 | ||||
| 584 | CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | |||
| 585 | const FunctionDecl *Callee, const LValue *This, | |||
| 586 | CallRef Arguments); | |||
| 587 | ~CallStackFrame(); | |||
| 588 | ||||
| 589 | // Return the temporary for Key whose version number is Version. | |||
| 590 | APValue *getTemporary(const void *Key, unsigned Version) { | |||
| 591 | MapKeyTy KV(Key, Version); | |||
| 592 | auto LB = Temporaries.lower_bound(KV); | |||
| 593 | if (LB != Temporaries.end() && LB->first == KV) | |||
| 594 | return &LB->second; | |||
| 595 | // Pair (Key,Version) wasn't found in the map. Check that no elements | |||
| 596 | // in the map have 'Key' as their key. | |||
| 597 | assert((LB == Temporaries.end() || LB->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB-> first.first != Key) && (LB == Temporaries.begin() || std ::prev(LB)->first.first != Key) && "Element with key 'Key' found in map" ) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "clang/lib/AST/ExprConstant.cpp", 599, __extension__ __PRETTY_FUNCTION__ )) | |||
| 598 | (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB-> first.first != Key) && (LB == Temporaries.begin() || std ::prev(LB)->first.first != Key) && "Element with key 'Key' found in map" ) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "clang/lib/AST/ExprConstant.cpp", 599, __extension__ __PRETTY_FUNCTION__ )) | |||
| 599 | "Element with key 'Key' found in map")(static_cast <bool> ((LB == Temporaries.end() || LB-> first.first != Key) && (LB == Temporaries.begin() || std ::prev(LB)->first.first != Key) && "Element with key 'Key' found in map" ) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "clang/lib/AST/ExprConstant.cpp", 599, __extension__ __PRETTY_FUNCTION__ )); | |||
| 600 | return nullptr; | |||
| 601 | } | |||
| 602 | ||||
| 603 | // Return the current temporary for Key in the map. | |||
| 604 | APValue *getCurrentTemporary(const void *Key) { | |||
| 605 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | |||
| 606 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | |||
| 607 | return &std::prev(UB)->second; | |||
| 608 | return nullptr; | |||
| 609 | } | |||
| 610 | ||||
| 611 | // Return the version number of the current temporary for Key. | |||
| 612 | unsigned getCurrentTemporaryVersion(const void *Key) const { | |||
| 613 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | |||
| 614 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | |||
| 615 | return std::prev(UB)->first.second; | |||
| 616 | return 0; | |||
| 617 | } | |||
| 618 | ||||
| 619 | /// Allocate storage for an object of type T in this stack frame. | |||
| 620 | /// Populates LV with a handle to the created object. Key identifies | |||
| 621 | /// the temporary within the stack frame, and must not be reused without | |||
| 622 | /// bumping the temporary version number. | |||
| 623 | template<typename KeyT> | |||
| 624 | APValue &createTemporary(const KeyT *Key, QualType T, | |||
| 625 | ScopeKind Scope, LValue &LV); | |||
| 626 | ||||
| 627 | /// Allocate storage for a parameter of a function call made in this frame. | |||
| 628 | APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); | |||
| 629 | ||||
| 630 | void describe(llvm::raw_ostream &OS) override; | |||
| 631 | ||||
| 632 | Frame *getCaller() const override { return Caller; } | |||
| 633 | SourceLocation getCallLocation() const override { return CallLoc; } | |||
| 634 | const FunctionDecl *getCallee() const override { return Callee; } | |||
| 635 | ||||
| 636 | bool isStdFunction() const { | |||
| 637 | for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) | |||
| 638 | if (DC->isStdNamespace()) | |||
| 639 | return true; | |||
| 640 | return false; | |||
| 641 | } | |||
| 642 | ||||
| 643 | private: | |||
| 644 | APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, | |||
| 645 | ScopeKind Scope); | |||
| 646 | }; | |||
| 647 | ||||
| 648 | /// Temporarily override 'this'. | |||
| 649 | class ThisOverrideRAII { | |||
| 650 | public: | |||
| 651 | ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) | |||
| 652 | : Frame(Frame), OldThis(Frame.This) { | |||
| 653 | if (Enable) | |||
| 654 | Frame.This = NewThis; | |||
| 655 | } | |||
| 656 | ~ThisOverrideRAII() { | |||
| 657 | Frame.This = OldThis; | |||
| 658 | } | |||
| 659 | private: | |||
| 660 | CallStackFrame &Frame; | |||
| 661 | const LValue *OldThis; | |||
| 662 | }; | |||
| 663 | } | |||
| 664 | ||||
| 665 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | |||
| 666 | const LValue &This, QualType ThisType); | |||
| 667 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | |||
| 668 | APValue::LValueBase LVBase, APValue &Value, | |||
| 669 | QualType T); | |||
| 670 | ||||
| 671 | namespace { | |||
| 672 | /// A cleanup, and a flag indicating whether it is lifetime-extended. | |||
| 673 | class Cleanup { | |||
| 674 | llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; | |||
| 675 | APValue::LValueBase Base; | |||
| 676 | QualType T; | |||
| 677 | ||||
| 678 | public: | |||
| 679 | Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, | |||
| 680 | ScopeKind Scope) | |||
| 681 | : Value(Val, Scope), Base(Base), T(T) {} | |||
| 682 | ||||
| 683 | /// Determine whether this cleanup should be performed at the end of the | |||
| 684 | /// given kind of scope. | |||
| 685 | bool isDestroyedAtEndOf(ScopeKind K) const { | |||
| 686 | return (int)Value.getInt() >= (int)K; | |||
| 687 | } | |||
| 688 | bool endLifetime(EvalInfo &Info, bool RunDestructors) { | |||
| 689 | if (RunDestructors) { | |||
| 690 | SourceLocation Loc; | |||
| 691 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) | |||
| 692 | Loc = VD->getLocation(); | |||
| 693 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | |||
| 694 | Loc = E->getExprLoc(); | |||
| 695 | return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); | |||
| 696 | } | |||
| 697 | *Value.getPointer() = APValue(); | |||
| 698 | return true; | |||
| 699 | } | |||
| 700 | ||||
| 701 | bool hasSideEffect() { | |||
| 702 | return T.isDestructedType(); | |||
| 703 | } | |||
| 704 | }; | |||
| 705 | ||||
| 706 | /// A reference to an object whose construction we are currently evaluating. | |||
| 707 | struct ObjectUnderConstruction { | |||
| 708 | APValue::LValueBase Base; | |||
| 709 | ArrayRef<APValue::LValuePathEntry> Path; | |||
| 710 | friend bool operator==(const ObjectUnderConstruction &LHS, | |||
| 711 | const ObjectUnderConstruction &RHS) { | |||
| 712 | return LHS.Base == RHS.Base && LHS.Path == RHS.Path; | |||
| 713 | } | |||
| 714 | friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { | |||
| 715 | return llvm::hash_combine(Obj.Base, Obj.Path); | |||
| 716 | } | |||
| 717 | }; | |||
| 718 | enum class ConstructionPhase { | |||
| 719 | None, | |||
| 720 | Bases, | |||
| 721 | AfterBases, | |||
| 722 | AfterFields, | |||
| 723 | Destroying, | |||
| 724 | DestroyingBases | |||
| 725 | }; | |||
| 726 | } | |||
| 727 | ||||
| 728 | namespace llvm { | |||
| 729 | template<> struct DenseMapInfo<ObjectUnderConstruction> { | |||
| 730 | using Base = DenseMapInfo<APValue::LValueBase>; | |||
| 731 | static ObjectUnderConstruction getEmptyKey() { | |||
| 732 | return {Base::getEmptyKey(), {}}; } | |||
| 733 | static ObjectUnderConstruction getTombstoneKey() { | |||
| 734 | return {Base::getTombstoneKey(), {}}; | |||
| 735 | } | |||
| 736 | static unsigned getHashValue(const ObjectUnderConstruction &Object) { | |||
| 737 | return hash_value(Object); | |||
| 738 | } | |||
| 739 | static bool isEqual(const ObjectUnderConstruction &LHS, | |||
| 740 | const ObjectUnderConstruction &RHS) { | |||
| 741 | return LHS == RHS; | |||
| 742 | } | |||
| 743 | }; | |||
| 744 | } | |||
| 745 | ||||
| 746 | namespace { | |||
| 747 | /// A dynamically-allocated heap object. | |||
| 748 | struct DynAlloc { | |||
| 749 | /// The value of this heap-allocated object. | |||
| 750 | APValue Value; | |||
| 751 | /// The allocating expression; used for diagnostics. Either a CXXNewExpr | |||
| 752 | /// or a CallExpr (the latter is for direct calls to operator new inside | |||
| 753 | /// std::allocator<T>::allocate). | |||
| 754 | const Expr *AllocExpr = nullptr; | |||
| 755 | ||||
| 756 | enum Kind { | |||
| 757 | New, | |||
| 758 | ArrayNew, | |||
| 759 | StdAllocator | |||
| 760 | }; | |||
| 761 | ||||
| 762 | /// Get the kind of the allocation. This must match between allocation | |||
| 763 | /// and deallocation. | |||
| 764 | Kind getKind() const { | |||
| 765 | if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) | |||
| 766 | return NE->isArray() ? ArrayNew : New; | |||
| 767 | assert(isa<CallExpr>(AllocExpr))(static_cast <bool> (isa<CallExpr>(AllocExpr)) ? void (0) : __assert_fail ("isa<CallExpr>(AllocExpr)", "clang/lib/AST/ExprConstant.cpp" , 767, __extension__ __PRETTY_FUNCTION__)); | |||
| 768 | return StdAllocator; | |||
| 769 | } | |||
| 770 | }; | |||
| 771 | ||||
| 772 | struct DynAllocOrder { | |||
| 773 | bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { | |||
| 774 | return L.getIndex() < R.getIndex(); | |||
| 775 | } | |||
| 776 | }; | |||
| 777 | ||||
| 778 | /// EvalInfo - This is a private struct used by the evaluator to capture | |||
| 779 | /// information about a subexpression as it is folded. It retains information | |||
| 780 | /// about the AST context, but also maintains information about the folded | |||
| 781 | /// expression. | |||
| 782 | /// | |||
| 783 | /// If an expression could be evaluated, it is still possible it is not a C | |||
| 784 | /// "integer constant expression" or constant expression. If not, this struct | |||
| 785 | /// captures information about how and why not. | |||
| 786 | /// | |||
| 787 | /// One bit of information passed *into* the request for constant folding | |||
| 788 | /// indicates whether the subexpression is "evaluated" or not according to C | |||
| 789 | /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can | |||
| 790 | /// evaluate the expression regardless of what the RHS is, but C only allows | |||
| 791 | /// certain things in certain situations. | |||
| 792 | class EvalInfo : public interp::State { | |||
| 793 | public: | |||
| 794 | ASTContext &Ctx; | |||
| 795 | ||||
| 796 | /// EvalStatus - Contains information about the evaluation. | |||
| 797 | Expr::EvalStatus &EvalStatus; | |||
| 798 | ||||
| 799 | /// CurrentCall - The top of the constexpr call stack. | |||
| 800 | CallStackFrame *CurrentCall; | |||
| 801 | ||||
| 802 | /// CallStackDepth - The number of calls in the call stack right now. | |||
| 803 | unsigned CallStackDepth; | |||
| 804 | ||||
| 805 | /// NextCallIndex - The next call index to assign. | |||
| 806 | unsigned NextCallIndex; | |||
| 807 | ||||
| 808 | /// StepsLeft - The remaining number of evaluation steps we're permitted | |||
| 809 | /// to perform. This is essentially a limit for the number of statements | |||
| 810 | /// we will evaluate. | |||
| 811 | unsigned StepsLeft; | |||
| 812 | ||||
| 813 | /// Enable the experimental new constant interpreter. If an expression is | |||
| 814 | /// not supported by the interpreter, an error is triggered. | |||
| 815 | bool EnableNewConstInterp; | |||
| 816 | ||||
| 817 | /// BottomFrame - The frame in which evaluation started. This must be | |||
| 818 | /// initialized after CurrentCall and CallStackDepth. | |||
| 819 | CallStackFrame BottomFrame; | |||
| 820 | ||||
| 821 | /// A stack of values whose lifetimes end at the end of some surrounding | |||
| 822 | /// evaluation frame. | |||
| 823 | llvm::SmallVector<Cleanup, 16> CleanupStack; | |||
| 824 | ||||
| 825 | /// EvaluatingDecl - This is the declaration whose initializer is being | |||
| 826 | /// evaluated, if any. | |||
| 827 | APValue::LValueBase EvaluatingDecl; | |||
| 828 | ||||
| 829 | enum class EvaluatingDeclKind { | |||
| 830 | None, | |||
| 831 | /// We're evaluating the construction of EvaluatingDecl. | |||
| 832 | Ctor, | |||
| 833 | /// We're evaluating the destruction of EvaluatingDecl. | |||
| 834 | Dtor, | |||
| 835 | }; | |||
| 836 | EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; | |||
| 837 | ||||
| 838 | /// EvaluatingDeclValue - This is the value being constructed for the | |||
| 839 | /// declaration whose initializer is being evaluated, if any. | |||
| 840 | APValue *EvaluatingDeclValue; | |||
| 841 | ||||
| 842 | /// Set of objects that are currently being constructed. | |||
| 843 | llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> | |||
| 844 | ObjectsUnderConstruction; | |||
| 845 | ||||
| 846 | /// Current heap allocations, along with the location where each was | |||
| 847 | /// allocated. We use std::map here because we need stable addresses | |||
| 848 | /// for the stored APValues. | |||
| 849 | std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; | |||
| 850 | ||||
| 851 | /// The number of heap allocations performed so far in this evaluation. | |||
| 852 | unsigned NumHeapAllocs = 0; | |||
| 853 | ||||
| 854 | struct EvaluatingConstructorRAII { | |||
| 855 | EvalInfo &EI; | |||
| 856 | ObjectUnderConstruction Object; | |||
| 857 | bool DidInsert; | |||
| 858 | EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, | |||
| 859 | bool HasBases) | |||
| 860 | : EI(EI), Object(Object) { | |||
| 861 | DidInsert = | |||
| 862 | EI.ObjectsUnderConstruction | |||
| 863 | .insert({Object, HasBases ? ConstructionPhase::Bases | |||
| 864 | : ConstructionPhase::AfterBases}) | |||
| 865 | .second; | |||
| 866 | } | |||
| 867 | void finishedConstructingBases() { | |||
| 868 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; | |||
| 869 | } | |||
| 870 | void finishedConstructingFields() { | |||
| 871 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; | |||
| 872 | } | |||
| 873 | ~EvaluatingConstructorRAII() { | |||
| 874 | if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); | |||
| 875 | } | |||
| 876 | }; | |||
| 877 | ||||
| 878 | struct EvaluatingDestructorRAII { | |||
| 879 | EvalInfo &EI; | |||
| 880 | ObjectUnderConstruction Object; | |||
| 881 | bool DidInsert; | |||
| 882 | EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) | |||
| 883 | : EI(EI), Object(Object) { | |||
| 884 | DidInsert = EI.ObjectsUnderConstruction | |||
| 885 | .insert({Object, ConstructionPhase::Destroying}) | |||
| 886 | .second; | |||
| 887 | } | |||
| 888 | void startedDestroyingBases() { | |||
| 889 | EI.ObjectsUnderConstruction[Object] = | |||
| 890 | ConstructionPhase::DestroyingBases; | |||
| 891 | } | |||
| 892 | ~EvaluatingDestructorRAII() { | |||
| 893 | if (DidInsert) | |||
| 894 | EI.ObjectsUnderConstruction.erase(Object); | |||
| 895 | } | |||
| 896 | }; | |||
| 897 | ||||
| 898 | ConstructionPhase | |||
| 899 | isEvaluatingCtorDtor(APValue::LValueBase Base, | |||
| 900 | ArrayRef<APValue::LValuePathEntry> Path) { | |||
| 901 | return ObjectsUnderConstruction.lookup({Base, Path}); | |||
| 902 | } | |||
| 903 | ||||
| 904 | /// If we're currently speculatively evaluating, the outermost call stack | |||
| 905 | /// depth at which we can mutate state, otherwise 0. | |||
| 906 | unsigned SpeculativeEvaluationDepth = 0; | |||
| 907 | ||||
| 908 | /// The current array initialization index, if we're performing array | |||
| 909 | /// initialization. | |||
| 910 | uint64_t ArrayInitIndex = -1; | |||
| 911 | ||||
| 912 | /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further | |||
| 913 | /// notes attached to it will also be stored, otherwise they will not be. | |||
| 914 | bool HasActiveDiagnostic; | |||
| 915 | ||||
| 916 | /// Have we emitted a diagnostic explaining why we couldn't constant | |||
| 917 | /// fold (not just why it's not strictly a constant expression)? | |||
| 918 | bool HasFoldFailureDiagnostic; | |||
| 919 | ||||
| 920 | /// Whether or not we're in a context where the front end requires a | |||
| 921 | /// constant value. | |||
| 922 | bool InConstantContext; | |||
| 923 | ||||
| 924 | /// Whether we're checking that an expression is a potential constant | |||
| 925 | /// expression. If so, do not fail on constructs that could become constant | |||
| 926 | /// later on (such as a use of an undefined global). | |||
| 927 | bool CheckingPotentialConstantExpression = false; | |||
| 928 | ||||
| 929 | /// Whether we're checking for an expression that has undefined behavior. | |||
| 930 | /// If so, we will produce warnings if we encounter an operation that is | |||
| 931 | /// always undefined. | |||
| 932 | /// | |||
| 933 | /// Note that we still need to evaluate the expression normally when this | |||
| 934 | /// is set; this is used when evaluating ICEs in C. | |||
| 935 | bool CheckingForUndefinedBehavior = false; | |||
| 936 | ||||
| 937 | enum EvaluationMode { | |||
| 938 | /// Evaluate as a constant expression. Stop if we find that the expression | |||
| 939 | /// is not a constant expression. | |||
| 940 | EM_ConstantExpression, | |||
| 941 | ||||
| 942 | /// Evaluate as a constant expression. Stop if we find that the expression | |||
| 943 | /// is not a constant expression. Some expressions can be retried in the | |||
| 944 | /// optimizer if we don't constant fold them here, but in an unevaluated | |||
| 945 | /// context we try to fold them immediately since the optimizer never | |||
| 946 | /// gets a chance to look at it. | |||
| 947 | EM_ConstantExpressionUnevaluated, | |||
| 948 | ||||
| 949 | /// Fold the expression to a constant. Stop if we hit a side-effect that | |||
| 950 | /// we can't model. | |||
| 951 | EM_ConstantFold, | |||
| 952 | ||||
| 953 | /// Evaluate in any way we know how. Don't worry about side-effects that | |||
| 954 | /// can't be modeled. | |||
| 955 | EM_IgnoreSideEffects, | |||
| 956 | } EvalMode; | |||
| 957 | ||||
| 958 | /// Are we checking whether the expression is a potential constant | |||
| 959 | /// expression? | |||
| 960 | bool checkingPotentialConstantExpression() const override { | |||
| 961 | return CheckingPotentialConstantExpression; | |||
| 962 | } | |||
| 963 | ||||
| 964 | /// Are we checking an expression for overflow? | |||
| 965 | // FIXME: We should check for any kind of undefined or suspicious behavior | |||
| 966 | // in such constructs, not just overflow. | |||
| 967 | bool checkingForUndefinedBehavior() const override { | |||
| 968 | return CheckingForUndefinedBehavior; | |||
| 969 | } | |||
| 970 | ||||
| 971 | EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) | |||
| 972 | : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), | |||
| 973 | CallStackDepth(0), NextCallIndex(1), | |||
| 974 | StepsLeft(C.getLangOpts().ConstexprStepLimit), | |||
| 975 | EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), | |||
| 976 | BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), | |||
| 977 | EvaluatingDecl((const ValueDecl *)nullptr), | |||
| 978 | EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), | |||
| 979 | HasFoldFailureDiagnostic(false), InConstantContext(false), | |||
| 980 | EvalMode(Mode) {} | |||
| 981 | ||||
| 982 | ~EvalInfo() { | |||
| 983 | discardCleanups(); | |||
| 984 | } | |||
| 985 | ||||
| 986 | ASTContext &getCtx() const override { return Ctx; } | |||
| 987 | ||||
| 988 | void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, | |||
| 989 | EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { | |||
| 990 | EvaluatingDecl = Base; | |||
| 991 | IsEvaluatingDecl = EDK; | |||
| 992 | EvaluatingDeclValue = &Value; | |||
| 993 | } | |||
| 994 | ||||
| 995 | bool CheckCallLimit(SourceLocation Loc) { | |||
| 996 | // Don't perform any constexpr calls (other than the call we're checking) | |||
| 997 | // when checking a potential constant expression. | |||
| 998 | if (checkingPotentialConstantExpression() && CallStackDepth > 1) | |||
| 999 | return false; | |||
| 1000 | if (NextCallIndex == 0) { | |||
| 1001 | // NextCallIndex has wrapped around. | |||
| 1002 | FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); | |||
| 1003 | return false; | |||
| 1004 | } | |||
| 1005 | if (CallStackDepth <= getLangOpts().ConstexprCallDepth) | |||
| 1006 | return true; | |||
| 1007 | FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) | |||
| 1008 | << getLangOpts().ConstexprCallDepth; | |||
| 1009 | return false; | |||
| 1010 | } | |||
| 1011 | ||||
| 1012 | std::pair<CallStackFrame *, unsigned> | |||
| 1013 | getCallFrameAndDepth(unsigned CallIndex) { | |||
| 1014 | assert(CallIndex && "no call index in getCallFrameAndDepth")(static_cast <bool> (CallIndex && "no call index in getCallFrameAndDepth" ) ? void (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\"" , "clang/lib/AST/ExprConstant.cpp", 1014, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1015 | // We will eventually hit BottomFrame, which has Index 1, so Frame can't | |||
| 1016 | // be null in this loop. | |||
| 1017 | unsigned Depth = CallStackDepth; | |||
| 1018 | CallStackFrame *Frame = CurrentCall; | |||
| 1019 | while (Frame->Index > CallIndex) { | |||
| 1020 | Frame = Frame->Caller; | |||
| 1021 | --Depth; | |||
| 1022 | } | |||
| 1023 | if (Frame->Index == CallIndex) | |||
| 1024 | return {Frame, Depth}; | |||
| 1025 | return {nullptr, 0}; | |||
| 1026 | } | |||
| 1027 | ||||
| 1028 | bool nextStep(const Stmt *S) { | |||
| 1029 | if (!StepsLeft) { | |||
| 1030 | FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); | |||
| 1031 | return false; | |||
| 1032 | } | |||
| 1033 | --StepsLeft; | |||
| 1034 | return true; | |||
| 1035 | } | |||
| 1036 | ||||
| 1037 | APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); | |||
| 1038 | ||||
| 1039 | Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { | |||
| 1040 | Optional<DynAlloc*> Result; | |||
| 1041 | auto It = HeapAllocs.find(DA); | |||
| 1042 | if (It != HeapAllocs.end()) | |||
| 1043 | Result = &It->second; | |||
| 1044 | return Result; | |||
| 1045 | } | |||
| 1046 | ||||
| 1047 | /// Get the allocated storage for the given parameter of the given call. | |||
| 1048 | APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { | |||
| 1049 | CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; | |||
| 1050 | return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) | |||
| 1051 | : nullptr; | |||
| 1052 | } | |||
| 1053 | ||||
| 1054 | /// Information about a stack frame for std::allocator<T>::[de]allocate. | |||
| 1055 | struct StdAllocatorCaller { | |||
| 1056 | unsigned FrameIndex; | |||
| 1057 | QualType ElemType; | |||
| 1058 | explicit operator bool() const { return FrameIndex != 0; }; | |||
| 1059 | }; | |||
| 1060 | ||||
| 1061 | StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { | |||
| 1062 | for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; | |||
| 1063 | Call = Call->Caller) { | |||
| 1064 | const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); | |||
| 1065 | if (!MD) | |||
| 1066 | continue; | |||
| 1067 | const IdentifierInfo *FnII = MD->getIdentifier(); | |||
| 1068 | if (!FnII || !FnII->isStr(FnName)) | |||
| 1069 | continue; | |||
| 1070 | ||||
| 1071 | const auto *CTSD = | |||
| 1072 | dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); | |||
| 1073 | if (!CTSD) | |||
| 1074 | continue; | |||
| 1075 | ||||
| 1076 | const IdentifierInfo *ClassII = CTSD->getIdentifier(); | |||
| 1077 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); | |||
| 1078 | if (CTSD->isInStdNamespace() && ClassII && | |||
| 1079 | ClassII->isStr("allocator") && TAL.size() >= 1 && | |||
| 1080 | TAL[0].getKind() == TemplateArgument::Type) | |||
| 1081 | return {Call->Index, TAL[0].getAsType()}; | |||
| 1082 | } | |||
| 1083 | ||||
| 1084 | return {}; | |||
| 1085 | } | |||
| 1086 | ||||
| 1087 | void performLifetimeExtension() { | |||
| 1088 | // Disable the cleanups for lifetime-extended temporaries. | |||
| 1089 | llvm::erase_if(CleanupStack, [](Cleanup &C) { | |||
| 1090 | return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); | |||
| 1091 | }); | |||
| 1092 | } | |||
| 1093 | ||||
| 1094 | /// Throw away any remaining cleanups at the end of evaluation. If any | |||
| 1095 | /// cleanups would have had a side-effect, note that as an unmodeled | |||
| 1096 | /// side-effect and return false. Otherwise, return true. | |||
| 1097 | bool discardCleanups() { | |||
| 1098 | for (Cleanup &C : CleanupStack) { | |||
| 1099 | if (C.hasSideEffect() && !noteSideEffect()) { | |||
| 1100 | CleanupStack.clear(); | |||
| 1101 | return false; | |||
| 1102 | } | |||
| 1103 | } | |||
| 1104 | CleanupStack.clear(); | |||
| 1105 | return true; | |||
| 1106 | } | |||
| 1107 | ||||
| 1108 | private: | |||
| 1109 | interp::Frame *getCurrentFrame() override { return CurrentCall; } | |||
| 1110 | const interp::Frame *getBottomFrame() const override { return &BottomFrame; } | |||
| 1111 | ||||
| 1112 | bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } | |||
| 1113 | void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } | |||
| 1114 | ||||
| 1115 | void setFoldFailureDiagnostic(bool Flag) override { | |||
| 1116 | HasFoldFailureDiagnostic = Flag; | |||
| 1117 | } | |||
| 1118 | ||||
| 1119 | Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } | |||
| 1120 | ||||
| 1121 | // If we have a prior diagnostic, it will be noting that the expression | |||
| 1122 | // isn't a constant expression. This diagnostic is more important, | |||
| 1123 | // unless we require this evaluation to produce a constant expression. | |||
| 1124 | // | |||
| 1125 | // FIXME: We might want to show both diagnostics to the user in | |||
| 1126 | // EM_ConstantFold mode. | |||
| 1127 | bool hasPriorDiagnostic() override { | |||
| 1128 | if (!EvalStatus.Diag->empty()) { | |||
| 1129 | switch (EvalMode) { | |||
| 1130 | case EM_ConstantFold: | |||
| 1131 | case EM_IgnoreSideEffects: | |||
| 1132 | if (!HasFoldFailureDiagnostic) | |||
| 1133 | break; | |||
| 1134 | // We've already failed to fold something. Keep that diagnostic. | |||
| 1135 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 1136 | case EM_ConstantExpression: | |||
| 1137 | case EM_ConstantExpressionUnevaluated: | |||
| 1138 | setActiveDiagnostic(false); | |||
| 1139 | return true; | |||
| 1140 | } | |||
| 1141 | } | |||
| 1142 | return false; | |||
| 1143 | } | |||
| 1144 | ||||
| 1145 | unsigned getCallStackDepth() override { return CallStackDepth; } | |||
| 1146 | ||||
| 1147 | public: | |||
| 1148 | /// Should we continue evaluation after encountering a side-effect that we | |||
| 1149 | /// couldn't model? | |||
| 1150 | bool keepEvaluatingAfterSideEffect() { | |||
| 1151 | switch (EvalMode) { | |||
| 1152 | case EM_IgnoreSideEffects: | |||
| 1153 | return true; | |||
| 1154 | ||||
| 1155 | case EM_ConstantExpression: | |||
| 1156 | case EM_ConstantExpressionUnevaluated: | |||
| 1157 | case EM_ConstantFold: | |||
| 1158 | // By default, assume any side effect might be valid in some other | |||
| 1159 | // evaluation of this expression from a different context. | |||
| 1160 | return checkingPotentialConstantExpression() || | |||
| 1161 | checkingForUndefinedBehavior(); | |||
| 1162 | } | |||
| 1163 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp" , 1163); | |||
| 1164 | } | |||
| 1165 | ||||
| 1166 | /// Note that we have had a side-effect, and determine whether we should | |||
| 1167 | /// keep evaluating. | |||
| 1168 | bool noteSideEffect() { | |||
| 1169 | EvalStatus.HasSideEffects = true; | |||
| 1170 | return keepEvaluatingAfterSideEffect(); | |||
| 1171 | } | |||
| 1172 | ||||
| 1173 | /// Should we continue evaluation after encountering undefined behavior? | |||
| 1174 | bool keepEvaluatingAfterUndefinedBehavior() { | |||
| 1175 | switch (EvalMode) { | |||
| 1176 | case EM_IgnoreSideEffects: | |||
| 1177 | case EM_ConstantFold: | |||
| 1178 | return true; | |||
| 1179 | ||||
| 1180 | case EM_ConstantExpression: | |||
| 1181 | case EM_ConstantExpressionUnevaluated: | |||
| 1182 | return checkingForUndefinedBehavior(); | |||
| 1183 | } | |||
| 1184 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp" , 1184); | |||
| 1185 | } | |||
| 1186 | ||||
| 1187 | /// Note that we hit something that was technically undefined behavior, but | |||
| 1188 | /// that we can evaluate past it (such as signed overflow or floating-point | |||
| 1189 | /// division by zero.) | |||
| 1190 | bool noteUndefinedBehavior() override { | |||
| 1191 | EvalStatus.HasUndefinedBehavior = true; | |||
| 1192 | return keepEvaluatingAfterUndefinedBehavior(); | |||
| 1193 | } | |||
| 1194 | ||||
| 1195 | /// Should we continue evaluation as much as possible after encountering a | |||
| 1196 | /// construct which can't be reduced to a value? | |||
| 1197 | bool keepEvaluatingAfterFailure() const override { | |||
| 1198 | if (!StepsLeft) | |||
| 1199 | return false; | |||
| 1200 | ||||
| 1201 | switch (EvalMode) { | |||
| 1202 | case EM_ConstantExpression: | |||
| 1203 | case EM_ConstantExpressionUnevaluated: | |||
| 1204 | case EM_ConstantFold: | |||
| 1205 | case EM_IgnoreSideEffects: | |||
| 1206 | return checkingPotentialConstantExpression() || | |||
| 1207 | checkingForUndefinedBehavior(); | |||
| 1208 | } | |||
| 1209 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp" , 1209); | |||
| 1210 | } | |||
| 1211 | ||||
| 1212 | /// Notes that we failed to evaluate an expression that other expressions | |||
| 1213 | /// directly depend on, and determine if we should keep evaluating. This | |||
| 1214 | /// should only be called if we actually intend to keep evaluating. | |||
| 1215 | /// | |||
| 1216 | /// Call noteSideEffect() instead if we may be able to ignore the value that | |||
| 1217 | /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: | |||
| 1218 | /// | |||
| 1219 | /// (Foo(), 1) // use noteSideEffect | |||
| 1220 | /// (Foo() || true) // use noteSideEffect | |||
| 1221 | /// Foo() + 1 // use noteFailure | |||
| 1222 | LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() { | |||
| 1223 | // Failure when evaluating some expression often means there is some | |||
| 1224 | // subexpression whose evaluation was skipped. Therefore, (because we | |||
| 1225 | // don't track whether we skipped an expression when unwinding after an | |||
| 1226 | // evaluation failure) every evaluation failure that bubbles up from a | |||
| 1227 | // subexpression implies that a side-effect has potentially happened. We | |||
| 1228 | // skip setting the HasSideEffects flag to true until we decide to | |||
| 1229 | // continue evaluating after that point, which happens here. | |||
| 1230 | bool KeepGoing = keepEvaluatingAfterFailure(); | |||
| 1231 | EvalStatus.HasSideEffects |= KeepGoing; | |||
| 1232 | return KeepGoing; | |||
| 1233 | } | |||
| 1234 | ||||
| 1235 | class ArrayInitLoopIndex { | |||
| 1236 | EvalInfo &Info; | |||
| 1237 | uint64_t OuterIndex; | |||
| 1238 | ||||
| 1239 | public: | |||
| 1240 | ArrayInitLoopIndex(EvalInfo &Info) | |||
| 1241 | : Info(Info), OuterIndex(Info.ArrayInitIndex) { | |||
| 1242 | Info.ArrayInitIndex = 0; | |||
| 1243 | } | |||
| 1244 | ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } | |||
| 1245 | ||||
| 1246 | operator uint64_t&() { return Info.ArrayInitIndex; } | |||
| 1247 | }; | |||
| 1248 | }; | |||
| 1249 | ||||
| 1250 | /// Object used to treat all foldable expressions as constant expressions. | |||
| 1251 | struct FoldConstant { | |||
| 1252 | EvalInfo &Info; | |||
| 1253 | bool Enabled; | |||
| 1254 | bool HadNoPriorDiags; | |||
| 1255 | EvalInfo::EvaluationMode OldMode; | |||
| 1256 | ||||
| 1257 | explicit FoldConstant(EvalInfo &Info, bool Enabled) | |||
| 1258 | : Info(Info), | |||
| 1259 | Enabled(Enabled), | |||
| 1260 | HadNoPriorDiags(Info.EvalStatus.Diag && | |||
| 1261 | Info.EvalStatus.Diag->empty() && | |||
| 1262 | !Info.EvalStatus.HasSideEffects), | |||
| 1263 | OldMode(Info.EvalMode) { | |||
| 1264 | if (Enabled) | |||
| 1265 | Info.EvalMode = EvalInfo::EM_ConstantFold; | |||
| 1266 | } | |||
| 1267 | void keepDiagnostics() { Enabled = false; } | |||
| 1268 | ~FoldConstant() { | |||
| 1269 | if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && | |||
| 1270 | !Info.EvalStatus.HasSideEffects) | |||
| 1271 | Info.EvalStatus.Diag->clear(); | |||
| 1272 | Info.EvalMode = OldMode; | |||
| 1273 | } | |||
| 1274 | }; | |||
| 1275 | ||||
| 1276 | /// RAII object used to set the current evaluation mode to ignore | |||
| 1277 | /// side-effects. | |||
| 1278 | struct IgnoreSideEffectsRAII { | |||
| 1279 | EvalInfo &Info; | |||
| 1280 | EvalInfo::EvaluationMode OldMode; | |||
| 1281 | explicit IgnoreSideEffectsRAII(EvalInfo &Info) | |||
| 1282 | : Info(Info), OldMode(Info.EvalMode) { | |||
| 1283 | Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; | |||
| 1284 | } | |||
| 1285 | ||||
| 1286 | ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } | |||
| 1287 | }; | |||
| 1288 | ||||
| 1289 | /// RAII object used to optionally suppress diagnostics and side-effects from | |||
| 1290 | /// a speculative evaluation. | |||
| 1291 | class SpeculativeEvaluationRAII { | |||
| 1292 | EvalInfo *Info = nullptr; | |||
| 1293 | Expr::EvalStatus OldStatus; | |||
| 1294 | unsigned OldSpeculativeEvaluationDepth; | |||
| 1295 | ||||
| 1296 | void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { | |||
| 1297 | Info = Other.Info; | |||
| 1298 | OldStatus = Other.OldStatus; | |||
| 1299 | OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; | |||
| 1300 | Other.Info = nullptr; | |||
| 1301 | } | |||
| 1302 | ||||
| 1303 | void maybeRestoreState() { | |||
| 1304 | if (!Info) | |||
| 1305 | return; | |||
| 1306 | ||||
| 1307 | Info->EvalStatus = OldStatus; | |||
| 1308 | Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; | |||
| 1309 | } | |||
| 1310 | ||||
| 1311 | public: | |||
| 1312 | SpeculativeEvaluationRAII() = default; | |||
| 1313 | ||||
| 1314 | SpeculativeEvaluationRAII( | |||
| 1315 | EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) | |||
| 1316 | : Info(&Info), OldStatus(Info.EvalStatus), | |||
| 1317 | OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { | |||
| 1318 | Info.EvalStatus.Diag = NewDiag; | |||
| 1319 | Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; | |||
| 1320 | } | |||
| 1321 | ||||
| 1322 | SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; | |||
| 1323 | SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { | |||
| 1324 | moveFromAndCancel(std::move(Other)); | |||
| 1325 | } | |||
| 1326 | ||||
| 1327 | SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { | |||
| 1328 | maybeRestoreState(); | |||
| 1329 | moveFromAndCancel(std::move(Other)); | |||
| 1330 | return *this; | |||
| 1331 | } | |||
| 1332 | ||||
| 1333 | ~SpeculativeEvaluationRAII() { maybeRestoreState(); } | |||
| 1334 | }; | |||
| 1335 | ||||
| 1336 | /// RAII object wrapping a full-expression or block scope, and handling | |||
| 1337 | /// the ending of the lifetime of temporaries created within it. | |||
| 1338 | template<ScopeKind Kind> | |||
| 1339 | class ScopeRAII { | |||
| 1340 | EvalInfo &Info; | |||
| 1341 | unsigned OldStackSize; | |||
| 1342 | public: | |||
| 1343 | ScopeRAII(EvalInfo &Info) | |||
| 1344 | : Info(Info), OldStackSize(Info.CleanupStack.size()) { | |||
| 1345 | // Push a new temporary version. This is needed to distinguish between | |||
| 1346 | // temporaries created in different iterations of a loop. | |||
| 1347 | Info.CurrentCall->pushTempVersion(); | |||
| 1348 | } | |||
| 1349 | bool destroy(bool RunDestructors = true) { | |||
| 1350 | bool OK = cleanup(Info, RunDestructors, OldStackSize); | |||
| 1351 | OldStackSize = -1U; | |||
| 1352 | return OK; | |||
| 1353 | } | |||
| 1354 | ~ScopeRAII() { | |||
| 1355 | if (OldStackSize != -1U) | |||
| 1356 | destroy(false); | |||
| 1357 | // Body moved to a static method to encourage the compiler to inline away | |||
| 1358 | // instances of this class. | |||
| 1359 | Info.CurrentCall->popTempVersion(); | |||
| 1360 | } | |||
| 1361 | private: | |||
| 1362 | static bool cleanup(EvalInfo &Info, bool RunDestructors, | |||
| 1363 | unsigned OldStackSize) { | |||
| 1364 | assert(OldStackSize <= Info.CleanupStack.size() &&(static_cast <bool> (OldStackSize <= Info.CleanupStack .size() && "running cleanups out of order?") ? void ( 0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "clang/lib/AST/ExprConstant.cpp", 1365, __extension__ __PRETTY_FUNCTION__ )) | |||
| 1365 | "running cleanups out of order?")(static_cast <bool> (OldStackSize <= Info.CleanupStack .size() && "running cleanups out of order?") ? void ( 0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "clang/lib/AST/ExprConstant.cpp", 1365, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1366 | ||||
| 1367 | // Run all cleanups for a block scope, and non-lifetime-extended cleanups | |||
| 1368 | // for a full-expression scope. | |||
| 1369 | bool Success = true; | |||
| 1370 | for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { | |||
| 1371 | if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { | |||
| 1372 | if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { | |||
| 1373 | Success = false; | |||
| 1374 | break; | |||
| 1375 | } | |||
| 1376 | } | |||
| 1377 | } | |||
| 1378 | ||||
| 1379 | // Compact any retained cleanups. | |||
| 1380 | auto NewEnd = Info.CleanupStack.begin() + OldStackSize; | |||
| 1381 | if (Kind != ScopeKind::Block) | |||
| 1382 | NewEnd = | |||
| 1383 | std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { | |||
| 1384 | return C.isDestroyedAtEndOf(Kind); | |||
| 1385 | }); | |||
| 1386 | Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); | |||
| 1387 | return Success; | |||
| 1388 | } | |||
| 1389 | }; | |||
| 1390 | typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; | |||
| 1391 | typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; | |||
| 1392 | typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; | |||
| 1393 | } | |||
| 1394 | ||||
| 1395 | bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, | |||
| 1396 | CheckSubobjectKind CSK) { | |||
| 1397 | if (Invalid) | |||
| 1398 | return false; | |||
| 1399 | if (isOnePastTheEnd()) { | |||
| 1400 | Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) | |||
| 1401 | << CSK; | |||
| 1402 | setInvalid(); | |||
| 1403 | return false; | |||
| 1404 | } | |||
| 1405 | // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there | |||
| 1406 | // must actually be at least one array element; even a VLA cannot have a | |||
| 1407 | // bound of zero. And if our index is nonzero, we already had a CCEDiag. | |||
| 1408 | return true; | |||
| 1409 | } | |||
| 1410 | ||||
| 1411 | void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, | |||
| 1412 | const Expr *E) { | |||
| 1413 | Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); | |||
| 1414 | // Do not set the designator as invalid: we can represent this situation, | |||
| 1415 | // and correct handling of __builtin_object_size requires us to do so. | |||
| 1416 | } | |||
| 1417 | ||||
| 1418 | void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, | |||
| 1419 | const Expr *E, | |||
| 1420 | const APSInt &N) { | |||
| 1421 | // If we're complaining, we must be able to statically determine the size of | |||
| 1422 | // the most derived array. | |||
| 1423 | if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) | |||
| 1424 | Info.CCEDiag(E, diag::note_constexpr_array_index) | |||
| 1425 | << N << /*array*/ 0 | |||
| 1426 | << static_cast<unsigned>(getMostDerivedArraySize()); | |||
| 1427 | else | |||
| 1428 | Info.CCEDiag(E, diag::note_constexpr_array_index) | |||
| 1429 | << N << /*non-array*/ 1; | |||
| 1430 | setInvalid(); | |||
| 1431 | } | |||
| 1432 | ||||
| 1433 | CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | |||
| 1434 | const FunctionDecl *Callee, const LValue *This, | |||
| 1435 | CallRef Call) | |||
| 1436 | : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), | |||
| 1437 | Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { | |||
| 1438 | Info.CurrentCall = this; | |||
| 1439 | ++Info.CallStackDepth; | |||
| 1440 | } | |||
| 1441 | ||||
| 1442 | CallStackFrame::~CallStackFrame() { | |||
| 1443 | assert(Info.CurrentCall == this && "calls retired out of order")(static_cast <bool> (Info.CurrentCall == this && "calls retired out of order") ? void (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\"" , "clang/lib/AST/ExprConstant.cpp", 1443, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1444 | --Info.CallStackDepth; | |||
| 1445 | Info.CurrentCall = Caller; | |||
| 1446 | } | |||
| 1447 | ||||
| 1448 | static bool isRead(AccessKinds AK) { | |||
| 1449 | return AK == AK_Read || AK == AK_ReadObjectRepresentation; | |||
| 1450 | } | |||
| 1451 | ||||
| 1452 | static bool isModification(AccessKinds AK) { | |||
| 1453 | switch (AK) { | |||
| 1454 | case AK_Read: | |||
| 1455 | case AK_ReadObjectRepresentation: | |||
| 1456 | case AK_MemberCall: | |||
| 1457 | case AK_DynamicCast: | |||
| 1458 | case AK_TypeId: | |||
| 1459 | return false; | |||
| 1460 | case AK_Assign: | |||
| 1461 | case AK_Increment: | |||
| 1462 | case AK_Decrement: | |||
| 1463 | case AK_Construct: | |||
| 1464 | case AK_Destroy: | |||
| 1465 | return true; | |||
| 1466 | } | |||
| 1467 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp" , 1467); | |||
| 1468 | } | |||
| 1469 | ||||
| 1470 | static bool isAnyAccess(AccessKinds AK) { | |||
| 1471 | return isRead(AK) || isModification(AK); | |||
| 1472 | } | |||
| 1473 | ||||
| 1474 | /// Is this an access per the C++ definition? | |||
| 1475 | static bool isFormalAccess(AccessKinds AK) { | |||
| 1476 | return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; | |||
| 1477 | } | |||
| 1478 | ||||
| 1479 | /// Is this kind of axcess valid on an indeterminate object value? | |||
| 1480 | static bool isValidIndeterminateAccess(AccessKinds AK) { | |||
| 1481 | switch (AK) { | |||
| 1482 | case AK_Read: | |||
| 1483 | case AK_Increment: | |||
| 1484 | case AK_Decrement: | |||
| 1485 | // These need the object's value. | |||
| 1486 | return false; | |||
| 1487 | ||||
| 1488 | case AK_ReadObjectRepresentation: | |||
| 1489 | case AK_Assign: | |||
| 1490 | case AK_Construct: | |||
| 1491 | case AK_Destroy: | |||
| 1492 | // Construction and destruction don't need the value. | |||
| 1493 | return true; | |||
| 1494 | ||||
| 1495 | case AK_MemberCall: | |||
| 1496 | case AK_DynamicCast: | |||
| 1497 | case AK_TypeId: | |||
| 1498 | // These aren't really meaningful on scalars. | |||
| 1499 | return true; | |||
| 1500 | } | |||
| 1501 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp" , 1501); | |||
| 1502 | } | |||
| 1503 | ||||
| 1504 | namespace { | |||
| 1505 | struct ComplexValue { | |||
| 1506 | private: | |||
| 1507 | bool IsInt; | |||
| 1508 | ||||
| 1509 | public: | |||
| 1510 | APSInt IntReal, IntImag; | |||
| 1511 | APFloat FloatReal, FloatImag; | |||
| 1512 | ||||
| 1513 | ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} | |||
| 1514 | ||||
| 1515 | void makeComplexFloat() { IsInt = false; } | |||
| 1516 | bool isComplexFloat() const { return !IsInt; } | |||
| 1517 | APFloat &getComplexFloatReal() { return FloatReal; } | |||
| 1518 | APFloat &getComplexFloatImag() { return FloatImag; } | |||
| 1519 | ||||
| 1520 | void makeComplexInt() { IsInt = true; } | |||
| 1521 | bool isComplexInt() const { return IsInt; } | |||
| 1522 | APSInt &getComplexIntReal() { return IntReal; } | |||
| 1523 | APSInt &getComplexIntImag() { return IntImag; } | |||
| 1524 | ||||
| 1525 | void moveInto(APValue &v) const { | |||
| 1526 | if (isComplexFloat()) | |||
| 1527 | v = APValue(FloatReal, FloatImag); | |||
| 1528 | else | |||
| 1529 | v = APValue(IntReal, IntImag); | |||
| 1530 | } | |||
| 1531 | void setFrom(const APValue &v) { | |||
| 1532 | assert(v.isComplexFloat() || v.isComplexInt())(static_cast <bool> (v.isComplexFloat() || v.isComplexInt ()) ? void (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()" , "clang/lib/AST/ExprConstant.cpp", 1532, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1533 | if (v.isComplexFloat()) { | |||
| 1534 | makeComplexFloat(); | |||
| 1535 | FloatReal = v.getComplexFloatReal(); | |||
| 1536 | FloatImag = v.getComplexFloatImag(); | |||
| 1537 | } else { | |||
| 1538 | makeComplexInt(); | |||
| 1539 | IntReal = v.getComplexIntReal(); | |||
| 1540 | IntImag = v.getComplexIntImag(); | |||
| 1541 | } | |||
| 1542 | } | |||
| 1543 | }; | |||
| 1544 | ||||
| 1545 | struct LValue { | |||
| 1546 | APValue::LValueBase Base; | |||
| 1547 | CharUnits Offset; | |||
| 1548 | SubobjectDesignator Designator; | |||
| 1549 | bool IsNullPtr : 1; | |||
| 1550 | bool InvalidBase : 1; | |||
| 1551 | ||||
| 1552 | const APValue::LValueBase getLValueBase() const { return Base; } | |||
| 1553 | CharUnits &getLValueOffset() { return Offset; } | |||
| 1554 | const CharUnits &getLValueOffset() const { return Offset; } | |||
| 1555 | SubobjectDesignator &getLValueDesignator() { return Designator; } | |||
| 1556 | const SubobjectDesignator &getLValueDesignator() const { return Designator;} | |||
| 1557 | bool isNullPointer() const { return IsNullPtr;} | |||
| 1558 | ||||
| 1559 | unsigned getLValueCallIndex() const { return Base.getCallIndex(); } | |||
| 1560 | unsigned getLValueVersion() const { return Base.getVersion(); } | |||
| 1561 | ||||
| 1562 | void moveInto(APValue &V) const { | |||
| 1563 | if (Designator.Invalid) | |||
| 1564 | V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); | |||
| 1565 | else { | |||
| 1566 | assert(!InvalidBase && "APValues can't handle invalid LValue bases")(static_cast <bool> (!InvalidBase && "APValues can't handle invalid LValue bases" ) ? void (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\"" , "clang/lib/AST/ExprConstant.cpp", 1566, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1567 | V = APValue(Base, Offset, Designator.Entries, | |||
| 1568 | Designator.IsOnePastTheEnd, IsNullPtr); | |||
| 1569 | } | |||
| 1570 | } | |||
| 1571 | void setFrom(ASTContext &Ctx, const APValue &V) { | |||
| 1572 | assert(V.isLValue() && "Setting LValue from a non-LValue?")(static_cast <bool> (V.isLValue() && "Setting LValue from a non-LValue?" ) ? void (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\"" , "clang/lib/AST/ExprConstant.cpp", 1572, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1573 | Base = V.getLValueBase(); | |||
| 1574 | Offset = V.getLValueOffset(); | |||
| 1575 | InvalidBase = false; | |||
| 1576 | Designator = SubobjectDesignator(Ctx, V); | |||
| 1577 | IsNullPtr = V.isNullPointer(); | |||
| 1578 | } | |||
| 1579 | ||||
| 1580 | void set(APValue::LValueBase B, bool BInvalid = false) { | |||
| 1581 | #ifndef NDEBUG | |||
| 1582 | // We only allow a few types of invalid bases. Enforce that here. | |||
| 1583 | if (BInvalid) { | |||
| 1584 | const auto *E = B.get<const Expr *>(); | |||
| 1585 | assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall (E)) && "Unexpected type of invalid base") ? void (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "clang/lib/AST/ExprConstant.cpp", 1586, __extension__ __PRETTY_FUNCTION__ )) | |||
| 1586 | "Unexpected type of invalid base")(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall (E)) && "Unexpected type of invalid base") ? void (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "clang/lib/AST/ExprConstant.cpp", 1586, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1587 | } | |||
| 1588 | #endif | |||
| 1589 | ||||
| 1590 | Base = B; | |||
| 1591 | Offset = CharUnits::fromQuantity(0); | |||
| 1592 | InvalidBase = BInvalid; | |||
| 1593 | Designator = SubobjectDesignator(getType(B)); | |||
| 1594 | IsNullPtr = false; | |||
| 1595 | } | |||
| 1596 | ||||
| 1597 | void setNull(ASTContext &Ctx, QualType PointerTy) { | |||
| 1598 | Base = (const ValueDecl *)nullptr; | |||
| 1599 | Offset = | |||
| 1600 | CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); | |||
| 1601 | InvalidBase = false; | |||
| 1602 | Designator = SubobjectDesignator(PointerTy->getPointeeType()); | |||
| 1603 | IsNullPtr = true; | |||
| 1604 | } | |||
| 1605 | ||||
| 1606 | void setInvalid(APValue::LValueBase B, unsigned I = 0) { | |||
| 1607 | set(B, true); | |||
| 1608 | } | |||
| 1609 | ||||
| 1610 | std::string toString(ASTContext &Ctx, QualType T) const { | |||
| 1611 | APValue Printable; | |||
| 1612 | moveInto(Printable); | |||
| 1613 | return Printable.getAsString(Ctx, T); | |||
| 1614 | } | |||
| 1615 | ||||
| 1616 | private: | |||
| 1617 | // Check that this LValue is not based on a null pointer. If it is, produce | |||
| 1618 | // a diagnostic and mark the designator as invalid. | |||
| 1619 | template <typename GenDiagType> | |||
| 1620 | bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { | |||
| 1621 | if (Designator.Invalid) | |||
| 1622 | return false; | |||
| 1623 | if (IsNullPtr) { | |||
| 1624 | GenDiag(); | |||
| 1625 | Designator.setInvalid(); | |||
| 1626 | return false; | |||
| 1627 | } | |||
| 1628 | return true; | |||
| 1629 | } | |||
| 1630 | ||||
| 1631 | public: | |||
| 1632 | bool checkNullPointer(EvalInfo &Info, const Expr *E, | |||
| 1633 | CheckSubobjectKind CSK) { | |||
| 1634 | return checkNullPointerDiagnosingWith([&Info, E, CSK] { | |||
| 1635 | Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; | |||
| 1636 | }); | |||
| 1637 | } | |||
| 1638 | ||||
| 1639 | bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, | |||
| 1640 | AccessKinds AK) { | |||
| 1641 | return checkNullPointerDiagnosingWith([&Info, E, AK] { | |||
| 1642 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | |||
| 1643 | }); | |||
| 1644 | } | |||
| 1645 | ||||
| 1646 | // Check this LValue refers to an object. If not, set the designator to be | |||
| 1647 | // invalid and emit a diagnostic. | |||
| 1648 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { | |||
| 1649 | return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && | |||
| 1650 | Designator.checkSubobject(Info, E, CSK); | |||
| 1651 | } | |||
| 1652 | ||||
| 1653 | void addDecl(EvalInfo &Info, const Expr *E, | |||
| 1654 | const Decl *D, bool Virtual = false) { | |||
| 1655 | if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) | |||
| 1656 | Designator.addDeclUnchecked(D, Virtual); | |||
| 1657 | } | |||
| 1658 | void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { | |||
| 1659 | if (!Designator.Entries.empty()) { | |||
| 1660 | Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); | |||
| 1661 | Designator.setInvalid(); | |||
| 1662 | return; | |||
| 1663 | } | |||
| 1664 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) { | |||
| 1665 | assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())(static_cast <bool> (getType(Base)->isPointerType() || getType(Base)->isArrayType()) ? void (0) : __assert_fail ( "getType(Base)->isPointerType() || getType(Base)->isArrayType()" , "clang/lib/AST/ExprConstant.cpp", 1665, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1666 | Designator.FirstEntryIsAnUnsizedArray = true; | |||
| 1667 | Designator.addUnsizedArrayUnchecked(ElemTy); | |||
| 1668 | } | |||
| 1669 | } | |||
| 1670 | void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { | |||
| 1671 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) | |||
| 1672 | Designator.addArrayUnchecked(CAT); | |||
| 1673 | } | |||
| 1674 | void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { | |||
| 1675 | if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) | |||
| 1676 | Designator.addComplexUnchecked(EltTy, Imag); | |||
| 1677 | } | |||
| 1678 | void clearIsNullPointer() { | |||
| 1679 | IsNullPtr = false; | |||
| 1680 | } | |||
| 1681 | void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, | |||
| 1682 | const APSInt &Index, CharUnits ElementSize) { | |||
| 1683 | // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, | |||
| 1684 | // but we're not required to diagnose it and it's valid in C++.) | |||
| 1685 | if (!Index) | |||
| 1686 | return; | |||
| 1687 | ||||
| 1688 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | |||
| 1689 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | |||
| 1690 | // offsets. | |||
| 1691 | uint64_t Offset64 = Offset.getQuantity(); | |||
| 1692 | uint64_t ElemSize64 = ElementSize.getQuantity(); | |||
| 1693 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | |||
| 1694 | Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); | |||
| 1695 | ||||
| 1696 | if (checkNullPointer(Info, E, CSK_ArrayIndex)) | |||
| 1697 | Designator.adjustIndex(Info, E, Index); | |||
| 1698 | clearIsNullPointer(); | |||
| 1699 | } | |||
| 1700 | void adjustOffset(CharUnits N) { | |||
| 1701 | Offset += N; | |||
| 1702 | if (N.getQuantity()) | |||
| 1703 | clearIsNullPointer(); | |||
| 1704 | } | |||
| 1705 | }; | |||
| 1706 | ||||
| 1707 | struct MemberPtr { | |||
| 1708 | MemberPtr() {} | |||
| 1709 | explicit MemberPtr(const ValueDecl *Decl) | |||
| 1710 | : DeclAndIsDerivedMember(Decl, false) {} | |||
| 1711 | ||||
| 1712 | /// The member or (direct or indirect) field referred to by this member | |||
| 1713 | /// pointer, or 0 if this is a null member pointer. | |||
| 1714 | const ValueDecl *getDecl() const { | |||
| 1715 | return DeclAndIsDerivedMember.getPointer(); | |||
| 1716 | } | |||
| 1717 | /// Is this actually a member of some type derived from the relevant class? | |||
| 1718 | bool isDerivedMember() const { | |||
| 1719 | return DeclAndIsDerivedMember.getInt(); | |||
| 1720 | } | |||
| 1721 | /// Get the class which the declaration actually lives in. | |||
| 1722 | const CXXRecordDecl *getContainingRecord() const { | |||
| 1723 | return cast<CXXRecordDecl>( | |||
| 1724 | DeclAndIsDerivedMember.getPointer()->getDeclContext()); | |||
| 1725 | } | |||
| 1726 | ||||
| 1727 | void moveInto(APValue &V) const { | |||
| 1728 | V = APValue(getDecl(), isDerivedMember(), Path); | |||
| 1729 | } | |||
| 1730 | void setFrom(const APValue &V) { | |||
| 1731 | assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail ("V.isMemberPointer()", "clang/lib/AST/ExprConstant.cpp", 1731 , __extension__ __PRETTY_FUNCTION__)); | |||
| 1732 | DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); | |||
| 1733 | DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); | |||
| 1734 | Path.clear(); | |||
| 1735 | ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); | |||
| 1736 | Path.insert(Path.end(), P.begin(), P.end()); | |||
| 1737 | } | |||
| 1738 | ||||
| 1739 | /// DeclAndIsDerivedMember - The member declaration, and a flag indicating | |||
| 1740 | /// whether the member is a member of some class derived from the class type | |||
| 1741 | /// of the member pointer. | |||
| 1742 | llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; | |||
| 1743 | /// Path - The path of base/derived classes from the member declaration's | |||
| 1744 | /// class (exclusive) to the class type of the member pointer (inclusive). | |||
| 1745 | SmallVector<const CXXRecordDecl*, 4> Path; | |||
| 1746 | ||||
| 1747 | /// Perform a cast towards the class of the Decl (either up or down the | |||
| 1748 | /// hierarchy). | |||
| 1749 | bool castBack(const CXXRecordDecl *Class) { | |||
| 1750 | assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail ("!Path.empty()", "clang/lib/AST/ExprConstant.cpp", 1750, __extension__ __PRETTY_FUNCTION__)); | |||
| 1751 | const CXXRecordDecl *Expected; | |||
| 1752 | if (Path.size() >= 2) | |||
| 1753 | Expected = Path[Path.size() - 2]; | |||
| 1754 | else | |||
| 1755 | Expected = getContainingRecord(); | |||
| 1756 | if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { | |||
| 1757 | // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), | |||
| 1758 | // if B does not contain the original member and is not a base or | |||
| 1759 | // derived class of the class containing the original member, the result | |||
| 1760 | // of the cast is undefined. | |||
| 1761 | // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to | |||
| 1762 | // (D::*). We consider that to be a language defect. | |||
| 1763 | return false; | |||
| 1764 | } | |||
| 1765 | Path.pop_back(); | |||
| 1766 | return true; | |||
| 1767 | } | |||
| 1768 | /// Perform a base-to-derived member pointer cast. | |||
| 1769 | bool castToDerived(const CXXRecordDecl *Derived) { | |||
| 1770 | if (!getDecl()) | |||
| 1771 | return true; | |||
| 1772 | if (!isDerivedMember()) { | |||
| 1773 | Path.push_back(Derived); | |||
| 1774 | return true; | |||
| 1775 | } | |||
| 1776 | if (!castBack(Derived)) | |||
| 1777 | return false; | |||
| 1778 | if (Path.empty()) | |||
| 1779 | DeclAndIsDerivedMember.setInt(false); | |||
| 1780 | return true; | |||
| 1781 | } | |||
| 1782 | /// Perform a derived-to-base member pointer cast. | |||
| 1783 | bool castToBase(const CXXRecordDecl *Base) { | |||
| 1784 | if (!getDecl()) | |||
| 1785 | return true; | |||
| 1786 | if (Path.empty()) | |||
| 1787 | DeclAndIsDerivedMember.setInt(true); | |||
| 1788 | if (isDerivedMember()) { | |||
| 1789 | Path.push_back(Base); | |||
| 1790 | return true; | |||
| 1791 | } | |||
| 1792 | return castBack(Base); | |||
| 1793 | } | |||
| 1794 | }; | |||
| 1795 | ||||
| 1796 | /// Compare two member pointers, which are assumed to be of the same type. | |||
| 1797 | static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { | |||
| 1798 | if (!LHS.getDecl() || !RHS.getDecl()) | |||
| 1799 | return !LHS.getDecl() && !RHS.getDecl(); | |||
| 1800 | if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) | |||
| 1801 | return false; | |||
| 1802 | return LHS.Path == RHS.Path; | |||
| 1803 | } | |||
| 1804 | } | |||
| 1805 | ||||
| 1806 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); | |||
| 1807 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, | |||
| 1808 | const LValue &This, const Expr *E, | |||
| 1809 | bool AllowNonLiteralTypes = false); | |||
| 1810 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | |||
| 1811 | bool InvalidBaseOK = false); | |||
| 1812 | static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, | |||
| 1813 | bool InvalidBaseOK = false); | |||
| 1814 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | |||
| 1815 | EvalInfo &Info); | |||
| 1816 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); | |||
| 1817 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); | |||
| 1818 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | |||
| 1819 | EvalInfo &Info); | |||
| 1820 | static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); | |||
| 1821 | static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); | |||
| 1822 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | |||
| 1823 | EvalInfo &Info); | |||
| 1824 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); | |||
| 1825 | static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, | |||
| 1826 | EvalInfo &Info); | |||
| 1827 | ||||
| 1828 | /// Evaluate an integer or fixed point expression into an APResult. | |||
| 1829 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | |||
| 1830 | EvalInfo &Info); | |||
| 1831 | ||||
| 1832 | /// Evaluate only a fixed point expression into an APResult. | |||
| 1833 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | |||
| 1834 | EvalInfo &Info); | |||
| 1835 | ||||
| 1836 | //===----------------------------------------------------------------------===// | |||
| 1837 | // Misc utilities | |||
| 1838 | //===----------------------------------------------------------------------===// | |||
| 1839 | ||||
| 1840 | /// Negate an APSInt in place, converting it to a signed form if necessary, and | |||
| 1841 | /// preserving its value (by extending by up to one bit as needed). | |||
| 1842 | static void negateAsSigned(APSInt &Int) { | |||
| 1843 | if (Int.isUnsigned() || Int.isMinSignedValue()) { | |||
| 1844 | Int = Int.extend(Int.getBitWidth() + 1); | |||
| 1845 | Int.setIsSigned(true); | |||
| 1846 | } | |||
| 1847 | Int = -Int; | |||
| 1848 | } | |||
| 1849 | ||||
| 1850 | template<typename KeyT> | |||
| 1851 | APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, | |||
| 1852 | ScopeKind Scope, LValue &LV) { | |||
| 1853 | unsigned Version = getTempVersion(); | |||
| 1854 | APValue::LValueBase Base(Key, Index, Version); | |||
| 1855 | LV.set(Base); | |||
| 1856 | return createLocal(Base, Key, T, Scope); | |||
| 1857 | } | |||
| 1858 | ||||
| 1859 | /// Allocate storage for a parameter of a function call made in this frame. | |||
| 1860 | APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, | |||
| 1861 | LValue &LV) { | |||
| 1862 | assert(Args.CallIndex == Index && "creating parameter in wrong frame")(static_cast <bool> (Args.CallIndex == Index && "creating parameter in wrong frame") ? void (0) : __assert_fail ("Args.CallIndex == Index && \"creating parameter in wrong frame\"" , "clang/lib/AST/ExprConstant.cpp", 1862, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1863 | APValue::LValueBase Base(PVD, Index, Args.Version); | |||
| 1864 | LV.set(Base); | |||
| 1865 | // We always destroy parameters at the end of the call, even if we'd allow | |||
| 1866 | // them to live to the end of the full-expression at runtime, in order to | |||
| 1867 | // give portable results and match other compilers. | |||
| 1868 | return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); | |||
| 1869 | } | |||
| 1870 | ||||
| 1871 | APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, | |||
| 1872 | QualType T, ScopeKind Scope) { | |||
| 1873 | assert(Base.getCallIndex() == Index && "lvalue for wrong frame")(static_cast <bool> (Base.getCallIndex() == Index && "lvalue for wrong frame") ? void (0) : __assert_fail ("Base.getCallIndex() == Index && \"lvalue for wrong frame\"" , "clang/lib/AST/ExprConstant.cpp", 1873, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1874 | unsigned Version = Base.getVersion(); | |||
| 1875 | APValue &Result = Temporaries[MapKeyTy(Key, Version)]; | |||
| 1876 | assert(Result.isAbsent() && "local created multiple times")(static_cast <bool> (Result.isAbsent() && "local created multiple times" ) ? void (0) : __assert_fail ("Result.isAbsent() && \"local created multiple times\"" , "clang/lib/AST/ExprConstant.cpp", 1876, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1877 | ||||
| 1878 | // If we're creating a local immediately in the operand of a speculative | |||
| 1879 | // evaluation, don't register a cleanup to be run outside the speculative | |||
| 1880 | // evaluation context, since we won't actually be able to initialize this | |||
| 1881 | // object. | |||
| 1882 | if (Index <= Info.SpeculativeEvaluationDepth) { | |||
| 1883 | if (T.isDestructedType()) | |||
| 1884 | Info.noteSideEffect(); | |||
| 1885 | } else { | |||
| 1886 | Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); | |||
| 1887 | } | |||
| 1888 | return Result; | |||
| 1889 | } | |||
| 1890 | ||||
| 1891 | APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { | |||
| 1892 | if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { | |||
| 1893 | FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); | |||
| 1894 | return nullptr; | |||
| 1895 | } | |||
| 1896 | ||||
| 1897 | DynamicAllocLValue DA(NumHeapAllocs++); | |||
| 1898 | LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); | |||
| 1899 | auto Result = HeapAllocs.emplace(std::piecewise_construct, | |||
| 1900 | std::forward_as_tuple(DA), std::tuple<>()); | |||
| 1901 | assert(Result.second && "reused a heap alloc index?")(static_cast <bool> (Result.second && "reused a heap alloc index?" ) ? void (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\"" , "clang/lib/AST/ExprConstant.cpp", 1901, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1902 | Result.first->second.AllocExpr = E; | |||
| 1903 | return &Result.first->second.Value; | |||
| 1904 | } | |||
| 1905 | ||||
| 1906 | /// Produce a string describing the given constexpr call. | |||
| 1907 | void CallStackFrame::describe(raw_ostream &Out) { | |||
| 1908 | unsigned ArgIndex = 0; | |||
| 1909 | bool IsMemberCall = isa<CXXMethodDecl>(Callee) && | |||
| 1910 | !isa<CXXConstructorDecl>(Callee) && | |||
| 1911 | cast<CXXMethodDecl>(Callee)->isInstance(); | |||
| 1912 | ||||
| 1913 | if (!IsMemberCall) | |||
| 1914 | Out << *Callee << '('; | |||
| 1915 | ||||
| 1916 | if (This && IsMemberCall) { | |||
| 1917 | APValue Val; | |||
| 1918 | This->moveInto(Val); | |||
| 1919 | Val.printPretty(Out, Info.Ctx, | |||
| 1920 | This->Designator.MostDerivedType); | |||
| 1921 | // FIXME: Add parens around Val if needed. | |||
| 1922 | Out << "->" << *Callee << '('; | |||
| 1923 | IsMemberCall = false; | |||
| 1924 | } | |||
| 1925 | ||||
| 1926 | for (FunctionDecl::param_const_iterator I = Callee->param_begin(), | |||
| 1927 | E = Callee->param_end(); I != E; ++I, ++ArgIndex) { | |||
| 1928 | if (ArgIndex > (unsigned)IsMemberCall) | |||
| 1929 | Out << ", "; | |||
| 1930 | ||||
| 1931 | const ParmVarDecl *Param = *I; | |||
| 1932 | APValue *V = Info.getParamSlot(Arguments, Param); | |||
| 1933 | if (V) | |||
| 1934 | V->printPretty(Out, Info.Ctx, Param->getType()); | |||
| 1935 | else | |||
| 1936 | Out << "<...>"; | |||
| 1937 | ||||
| 1938 | if (ArgIndex == 0 && IsMemberCall) | |||
| 1939 | Out << "->" << *Callee << '('; | |||
| 1940 | } | |||
| 1941 | ||||
| 1942 | Out << ')'; | |||
| 1943 | } | |||
| 1944 | ||||
| 1945 | /// Evaluate an expression to see if it had side-effects, and discard its | |||
| 1946 | /// result. | |||
| 1947 | /// \return \c true if the caller should keep evaluating. | |||
| 1948 | static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { | |||
| 1949 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 1949, __extension__ __PRETTY_FUNCTION__)); | |||
| 1950 | APValue Scratch; | |||
| 1951 | if (!Evaluate(Scratch, Info, E)) | |||
| 1952 | // We don't need the value, but we might have skipped a side effect here. | |||
| 1953 | return Info.noteSideEffect(); | |||
| 1954 | return true; | |||
| 1955 | } | |||
| 1956 | ||||
| 1957 | /// Should this call expression be treated as a constant? | |||
| 1958 | static bool IsConstantCall(const CallExpr *E) { | |||
| 1959 | unsigned Builtin = E->getBuiltinCallee(); | |||
| 1960 | return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || | |||
| 1961 | Builtin == Builtin::BI__builtin___NSStringMakeConstantString || | |||
| 1962 | Builtin == Builtin::BI__builtin_function_start); | |||
| 1963 | } | |||
| 1964 | ||||
| 1965 | static bool IsGlobalLValue(APValue::LValueBase B) { | |||
| 1966 | // C++11 [expr.const]p3 An address constant expression is a prvalue core | |||
| 1967 | // constant expression of pointer type that evaluates to... | |||
| 1968 | ||||
| 1969 | // ... a null pointer value, or a prvalue core constant expression of type | |||
| 1970 | // std::nullptr_t. | |||
| 1971 | if (!B) return true; | |||
| 1972 | ||||
| 1973 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | |||
| 1974 | // ... the address of an object with static storage duration, | |||
| 1975 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | |||
| 1976 | return VD->hasGlobalStorage(); | |||
| 1977 | if (isa<TemplateParamObjectDecl>(D)) | |||
| 1978 | return true; | |||
| 1979 | // ... the address of a function, | |||
| 1980 | // ... the address of a GUID [MS extension], | |||
| 1981 | // ... the address of an unnamed global constant | |||
| 1982 | return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D); | |||
| 1983 | } | |||
| 1984 | ||||
| 1985 | if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) | |||
| 1986 | return true; | |||
| 1987 | ||||
| 1988 | const Expr *E = B.get<const Expr*>(); | |||
| 1989 | switch (E->getStmtClass()) { | |||
| 1990 | default: | |||
| 1991 | return false; | |||
| 1992 | case Expr::CompoundLiteralExprClass: { | |||
| 1993 | const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); | |||
| 1994 | return CLE->isFileScope() && CLE->isLValue(); | |||
| 1995 | } | |||
| 1996 | case Expr::MaterializeTemporaryExprClass: | |||
| 1997 | // A materialized temporary might have been lifetime-extended to static | |||
| 1998 | // storage duration. | |||
| 1999 | return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; | |||
| 2000 | // A string literal has static storage duration. | |||
| 2001 | case Expr::StringLiteralClass: | |||
| 2002 | case Expr::PredefinedExprClass: | |||
| 2003 | case Expr::ObjCStringLiteralClass: | |||
| 2004 | case Expr::ObjCEncodeExprClass: | |||
| 2005 | return true; | |||
| 2006 | case Expr::ObjCBoxedExprClass: | |||
| 2007 | return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); | |||
| 2008 | case Expr::CallExprClass: | |||
| 2009 | return IsConstantCall(cast<CallExpr>(E)); | |||
| 2010 | // For GCC compatibility, &&label has static storage duration. | |||
| 2011 | case Expr::AddrLabelExprClass: | |||
| 2012 | return true; | |||
| 2013 | // A Block literal expression may be used as the initialization value for | |||
| 2014 | // Block variables at global or local static scope. | |||
| 2015 | case Expr::BlockExprClass: | |||
| 2016 | return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); | |||
| 2017 | // The APValue generated from a __builtin_source_location will be emitted as a | |||
| 2018 | // literal. | |||
| 2019 | case Expr::SourceLocExprClass: | |||
| 2020 | return true; | |||
| 2021 | case Expr::ImplicitValueInitExprClass: | |||
| 2022 | // FIXME: | |||
| 2023 | // We can never form an lvalue with an implicit value initialization as its | |||
| 2024 | // base through expression evaluation, so these only appear in one case: the | |||
| 2025 | // implicit variable declaration we invent when checking whether a constexpr | |||
| 2026 | // constructor can produce a constant expression. We must assume that such | |||
| 2027 | // an expression might be a global lvalue. | |||
| 2028 | return true; | |||
| 2029 | } | |||
| 2030 | } | |||
| 2031 | ||||
| 2032 | static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { | |||
| 2033 | return LVal.Base.dyn_cast<const ValueDecl*>(); | |||
| 2034 | } | |||
| 2035 | ||||
| 2036 | static bool IsLiteralLValue(const LValue &Value) { | |||
| 2037 | if (Value.getLValueCallIndex()) | |||
| 2038 | return false; | |||
| 2039 | const Expr *E = Value.Base.dyn_cast<const Expr*>(); | |||
| 2040 | return E && !isa<MaterializeTemporaryExpr>(E); | |||
| 2041 | } | |||
| 2042 | ||||
| 2043 | static bool IsWeakLValue(const LValue &Value) { | |||
| 2044 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | |||
| 2045 | return Decl && Decl->isWeak(); | |||
| 2046 | } | |||
| 2047 | ||||
| 2048 | static bool isZeroSized(const LValue &Value) { | |||
| 2049 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | |||
| 2050 | if (Decl && isa<VarDecl>(Decl)) { | |||
| 2051 | QualType Ty = Decl->getType(); | |||
| 2052 | if (Ty->isArrayType()) | |||
| 2053 | return Ty->isIncompleteType() || | |||
| 2054 | Decl->getASTContext().getTypeSize(Ty) == 0; | |||
| 2055 | } | |||
| 2056 | return false; | |||
| 2057 | } | |||
| 2058 | ||||
| 2059 | static bool HasSameBase(const LValue &A, const LValue &B) { | |||
| 2060 | if (!A.getLValueBase()) | |||
| 2061 | return !B.getLValueBase(); | |||
| 2062 | if (!B.getLValueBase()) | |||
| 2063 | return false; | |||
| 2064 | ||||
| 2065 | if (A.getLValueBase().getOpaqueValue() != | |||
| 2066 | B.getLValueBase().getOpaqueValue()) | |||
| 2067 | return false; | |||
| 2068 | ||||
| 2069 | return A.getLValueCallIndex() == B.getLValueCallIndex() && | |||
| 2070 | A.getLValueVersion() == B.getLValueVersion(); | |||
| 2071 | } | |||
| 2072 | ||||
| 2073 | static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { | |||
| 2074 | assert(Base && "no location for a null lvalue")(static_cast <bool> (Base && "no location for a null lvalue" ) ? void (0) : __assert_fail ("Base && \"no location for a null lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2074, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2075 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | |||
| 2076 | ||||
| 2077 | // For a parameter, find the corresponding call stack frame (if it still | |||
| 2078 | // exists), and point at the parameter of the function definition we actually | |||
| 2079 | // invoked. | |||
| 2080 | if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { | |||
| 2081 | unsigned Idx = PVD->getFunctionScopeIndex(); | |||
| 2082 | for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { | |||
| 2083 | if (F->Arguments.CallIndex == Base.getCallIndex() && | |||
| 2084 | F->Arguments.Version == Base.getVersion() && F->Callee && | |||
| 2085 | Idx < F->Callee->getNumParams()) { | |||
| 2086 | VD = F->Callee->getParamDecl(Idx); | |||
| 2087 | break; | |||
| 2088 | } | |||
| 2089 | } | |||
| 2090 | } | |||
| 2091 | ||||
| 2092 | if (VD) | |||
| 2093 | Info.Note(VD->getLocation(), diag::note_declared_at); | |||
| 2094 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | |||
| 2095 | Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); | |||
| 2096 | else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { | |||
| 2097 | // FIXME: Produce a note for dangling pointers too. | |||
| 2098 | if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) | |||
| 2099 | Info.Note((*Alloc)->AllocExpr->getExprLoc(), | |||
| 2100 | diag::note_constexpr_dynamic_alloc_here); | |||
| 2101 | } | |||
| 2102 | // We have no information to show for a typeid(T) object. | |||
| 2103 | } | |||
| 2104 | ||||
| 2105 | enum class CheckEvaluationResultKind { | |||
| 2106 | ConstantExpression, | |||
| 2107 | FullyInitialized, | |||
| 2108 | }; | |||
| 2109 | ||||
| 2110 | /// Materialized temporaries that we've already checked to determine if they're | |||
| 2111 | /// initializsed by a constant expression. | |||
| 2112 | using CheckedTemporaries = | |||
| 2113 | llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; | |||
| 2114 | ||||
| 2115 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | |||
| 2116 | EvalInfo &Info, SourceLocation DiagLoc, | |||
| 2117 | QualType Type, const APValue &Value, | |||
| 2118 | ConstantExprKind Kind, | |||
| 2119 | SourceLocation SubobjectLoc, | |||
| 2120 | CheckedTemporaries &CheckedTemps); | |||
| 2121 | ||||
| 2122 | /// Check that this reference or pointer core constant expression is a valid | |||
| 2123 | /// value for an address or reference constant expression. Return true if we | |||
| 2124 | /// can fold this expression, whether or not it's a constant expression. | |||
| 2125 | static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, | |||
| 2126 | QualType Type, const LValue &LVal, | |||
| 2127 | ConstantExprKind Kind, | |||
| 2128 | CheckedTemporaries &CheckedTemps) { | |||
| 2129 | bool IsReferenceType = Type->isReferenceType(); | |||
| 2130 | ||||
| 2131 | APValue::LValueBase Base = LVal.getLValueBase(); | |||
| 2132 | const SubobjectDesignator &Designator = LVal.getLValueDesignator(); | |||
| 2133 | ||||
| 2134 | const Expr *BaseE = Base.dyn_cast<const Expr *>(); | |||
| 2135 | const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); | |||
| 2136 | ||||
| 2137 | // Additional restrictions apply in a template argument. We only enforce the | |||
| 2138 | // C++20 restrictions here; additional syntactic and semantic restrictions | |||
| 2139 | // are applied elsewhere. | |||
| 2140 | if (isTemplateArgument(Kind)) { | |||
| 2141 | int InvalidBaseKind = -1; | |||
| 2142 | StringRef Ident; | |||
| 2143 | if (Base.is<TypeInfoLValue>()) | |||
| 2144 | InvalidBaseKind = 0; | |||
| 2145 | else if (isa_and_nonnull<StringLiteral>(BaseE)) | |||
| 2146 | InvalidBaseKind = 1; | |||
| 2147 | else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || | |||
| 2148 | isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) | |||
| 2149 | InvalidBaseKind = 2; | |||
| 2150 | else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { | |||
| 2151 | InvalidBaseKind = 3; | |||
| 2152 | Ident = PE->getIdentKindName(); | |||
| 2153 | } | |||
| 2154 | ||||
| 2155 | if (InvalidBaseKind != -1) { | |||
| 2156 | Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) | |||
| 2157 | << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind | |||
| 2158 | << Ident; | |||
| 2159 | return false; | |||
| 2160 | } | |||
| 2161 | } | |||
| 2162 | ||||
| 2163 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { | |||
| 2164 | if (FD->isConsteval()) { | |||
| 2165 | Info.FFDiag(Loc, diag::note_consteval_address_accessible) | |||
| 2166 | << !Type->isAnyPointerType(); | |||
| 2167 | Info.Note(FD->getLocation(), diag::note_declared_at); | |||
| 2168 | return false; | |||
| 2169 | } | |||
| 2170 | } | |||
| 2171 | ||||
| 2172 | // Check that the object is a global. Note that the fake 'this' object we | |||
| 2173 | // manufacture when checking potential constant expressions is conservatively | |||
| 2174 | // assumed to be global here. | |||
| 2175 | if (!IsGlobalLValue(Base)) { | |||
| 2176 | if (Info.getLangOpts().CPlusPlus11) { | |||
| 2177 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | |||
| 2178 | Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) | |||
| 2179 | << IsReferenceType << !Designator.Entries.empty() | |||
| 2180 | << !!VD << VD; | |||
| 2181 | ||||
| 2182 | auto *VarD = dyn_cast_or_null<VarDecl>(VD); | |||
| 2183 | if (VarD && VarD->isConstexpr()) { | |||
| 2184 | // Non-static local constexpr variables have unintuitive semantics: | |||
| 2185 | // constexpr int a = 1; | |||
| 2186 | // constexpr const int *p = &a; | |||
| 2187 | // ... is invalid because the address of 'a' is not constant. Suggest | |||
| 2188 | // adding a 'static' in this case. | |||
| 2189 | Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) | |||
| 2190 | << VarD | |||
| 2191 | << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); | |||
| 2192 | } else { | |||
| 2193 | NoteLValueLocation(Info, Base); | |||
| 2194 | } | |||
| 2195 | } else { | |||
| 2196 | Info.FFDiag(Loc); | |||
| 2197 | } | |||
| 2198 | // Don't allow references to temporaries to escape. | |||
| 2199 | return false; | |||
| 2200 | } | |||
| 2201 | assert((Info.checkingPotentialConstantExpression() ||(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2203, __extension__ __PRETTY_FUNCTION__ )) | |||
| 2202 | LVal.getLValueCallIndex() == 0) &&(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2203, __extension__ __PRETTY_FUNCTION__ )) | |||
| 2203 | "have call index for global lvalue")(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2203, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2204 | ||||
| 2205 | if (Base.is<DynamicAllocLValue>()) { | |||
| 2206 | Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) | |||
| 2207 | << IsReferenceType << !Designator.Entries.empty(); | |||
| 2208 | NoteLValueLocation(Info, Base); | |||
| 2209 | return false; | |||
| 2210 | } | |||
| 2211 | ||||
| 2212 | if (BaseVD) { | |||
| 2213 | if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { | |||
| 2214 | // Check if this is a thread-local variable. | |||
| 2215 | if (Var->getTLSKind()) | |||
| 2216 | // FIXME: Diagnostic! | |||
| 2217 | return false; | |||
| 2218 | ||||
| 2219 | // A dllimport variable never acts like a constant, unless we're | |||
| 2220 | // evaluating a value for use only in name mangling. | |||
| 2221 | if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) | |||
| 2222 | // FIXME: Diagnostic! | |||
| 2223 | return false; | |||
| 2224 | ||||
| 2225 | // In CUDA/HIP device compilation, only device side variables have | |||
| 2226 | // constant addresses. | |||
| 2227 | if (Info.getCtx().getLangOpts().CUDA && | |||
| 2228 | Info.getCtx().getLangOpts().CUDAIsDevice && | |||
| 2229 | Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { | |||
| 2230 | if ((!Var->hasAttr<CUDADeviceAttr>() && | |||
| 2231 | !Var->hasAttr<CUDAConstantAttr>() && | |||
| 2232 | !Var->getType()->isCUDADeviceBuiltinSurfaceType() && | |||
| 2233 | !Var->getType()->isCUDADeviceBuiltinTextureType()) || | |||
| 2234 | Var->hasAttr<HIPManagedAttr>()) | |||
| 2235 | return false; | |||
| 2236 | } | |||
| 2237 | } | |||
| 2238 | if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { | |||
| 2239 | // __declspec(dllimport) must be handled very carefully: | |||
| 2240 | // We must never initialize an expression with the thunk in C++. | |||
| 2241 | // Doing otherwise would allow the same id-expression to yield | |||
| 2242 | // different addresses for the same function in different translation | |||
| 2243 | // units. However, this means that we must dynamically initialize the | |||
| 2244 | // expression with the contents of the import address table at runtime. | |||
| 2245 | // | |||
| 2246 | // The C language has no notion of ODR; furthermore, it has no notion of | |||
| 2247 | // dynamic initialization. This means that we are permitted to | |||
| 2248 | // perform initialization with the address of the thunk. | |||
| 2249 | if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && | |||
| 2250 | FD->hasAttr<DLLImportAttr>()) | |||
| 2251 | // FIXME: Diagnostic! | |||
| 2252 | return false; | |||
| 2253 | } | |||
| 2254 | } else if (const auto *MTE = | |||
| 2255 | dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { | |||
| 2256 | if (CheckedTemps.insert(MTE).second) { | |||
| 2257 | QualType TempType = getType(Base); | |||
| 2258 | if (TempType.isDestructedType()) { | |||
| 2259 | Info.FFDiag(MTE->getExprLoc(), | |||
| 2260 | diag::note_constexpr_unsupported_temporary_nontrivial_dtor) | |||
| 2261 | << TempType; | |||
| 2262 | return false; | |||
| 2263 | } | |||
| 2264 | ||||
| 2265 | APValue *V = MTE->getOrCreateValue(false); | |||
| 2266 | assert(V && "evasluation result refers to uninitialised temporary")(static_cast <bool> (V && "evasluation result refers to uninitialised temporary" ) ? void (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\"" , "clang/lib/AST/ExprConstant.cpp", 2266, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2267 | if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | |||
| 2268 | Info, MTE->getExprLoc(), TempType, *V, | |||
| 2269 | Kind, SourceLocation(), CheckedTemps)) | |||
| 2270 | return false; | |||
| 2271 | } | |||
| 2272 | } | |||
| 2273 | ||||
| 2274 | // Allow address constant expressions to be past-the-end pointers. This is | |||
| 2275 | // an extension: the standard requires them to point to an object. | |||
| 2276 | if (!IsReferenceType) | |||
| 2277 | return true; | |||
| 2278 | ||||
| 2279 | // A reference constant expression must refer to an object. | |||
| 2280 | if (!Base) { | |||
| 2281 | // FIXME: diagnostic | |||
| 2282 | Info.CCEDiag(Loc); | |||
| 2283 | return true; | |||
| 2284 | } | |||
| 2285 | ||||
| 2286 | // Does this refer one past the end of some object? | |||
| 2287 | if (!Designator.Invalid && Designator.isOnePastTheEnd()) { | |||
| 2288 | Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) | |||
| 2289 | << !Designator.Entries.empty() << !!BaseVD << BaseVD; | |||
| 2290 | NoteLValueLocation(Info, Base); | |||
| 2291 | } | |||
| 2292 | ||||
| 2293 | return true; | |||
| 2294 | } | |||
| 2295 | ||||
| 2296 | /// Member pointers are constant expressions unless they point to a | |||
| 2297 | /// non-virtual dllimport member function. | |||
| 2298 | static bool CheckMemberPointerConstantExpression(EvalInfo &Info, | |||
| 2299 | SourceLocation Loc, | |||
| 2300 | QualType Type, | |||
| 2301 | const APValue &Value, | |||
| 2302 | ConstantExprKind Kind) { | |||
| 2303 | const ValueDecl *Member = Value.getMemberPointerDecl(); | |||
| 2304 | const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); | |||
| 2305 | if (!FD) | |||
| 2306 | return true; | |||
| 2307 | if (FD->isConsteval()) { | |||
| 2308 | Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; | |||
| 2309 | Info.Note(FD->getLocation(), diag::note_declared_at); | |||
| 2310 | return false; | |||
| 2311 | } | |||
| 2312 | return isForManglingOnly(Kind) || FD->isVirtual() || | |||
| 2313 | !FD->hasAttr<DLLImportAttr>(); | |||
| 2314 | } | |||
| 2315 | ||||
| 2316 | /// Check that this core constant expression is of literal type, and if not, | |||
| 2317 | /// produce an appropriate diagnostic. | |||
| 2318 | static bool CheckLiteralType(EvalInfo &Info, const Expr *E, | |||
| 2319 | const LValue *This = nullptr) { | |||
| 2320 | if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) | |||
| 2321 | return true; | |||
| 2322 | ||||
| 2323 | // C++1y: A constant initializer for an object o [...] may also invoke | |||
| 2324 | // constexpr constructors for o and its subobjects even if those objects | |||
| 2325 | // are of non-literal class types. | |||
| 2326 | // | |||
| 2327 | // C++11 missed this detail for aggregates, so classes like this: | |||
| 2328 | // struct foo_t { union { int i; volatile int j; } u; }; | |||
| 2329 | // are not (obviously) initializable like so: | |||
| 2330 | // __attribute__((__require_constant_initialization__)) | |||
| 2331 | // static const foo_t x = {{0}}; | |||
| 2332 | // because "i" is a subobject with non-literal initialization (due to the | |||
| 2333 | // volatile member of the union). See: | |||
| 2334 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 | |||
| 2335 | // Therefore, we use the C++1y behavior. | |||
| 2336 | if (This && Info.EvaluatingDecl == This->getLValueBase()) | |||
| 2337 | return true; | |||
| 2338 | ||||
| 2339 | // Prvalue constant expressions must be of literal types. | |||
| 2340 | if (Info.getLangOpts().CPlusPlus11) | |||
| 2341 | Info.FFDiag(E, diag::note_constexpr_nonliteral) | |||
| 2342 | << E->getType(); | |||
| 2343 | else | |||
| 2344 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 2345 | return false; | |||
| 2346 | } | |||
| 2347 | ||||
| 2348 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | |||
| 2349 | EvalInfo &Info, SourceLocation DiagLoc, | |||
| 2350 | QualType Type, const APValue &Value, | |||
| 2351 | ConstantExprKind Kind, | |||
| 2352 | SourceLocation SubobjectLoc, | |||
| 2353 | CheckedTemporaries &CheckedTemps) { | |||
| 2354 | if (!Value.hasValue()) { | |||
| 2355 | Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) | |||
| 2356 | << true << Type; | |||
| 2357 | if (SubobjectLoc.isValid()) | |||
| 2358 | Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); | |||
| 2359 | return false; | |||
| 2360 | } | |||
| 2361 | ||||
| 2362 | // We allow _Atomic(T) to be initialized from anything that T can be | |||
| 2363 | // initialized from. | |||
| 2364 | if (const AtomicType *AT = Type->getAs<AtomicType>()) | |||
| 2365 | Type = AT->getValueType(); | |||
| 2366 | ||||
| 2367 | // Core issue 1454: For a literal constant expression of array or class type, | |||
| 2368 | // each subobject of its value shall have been initialized by a constant | |||
| 2369 | // expression. | |||
| 2370 | if (Value.isArray()) { | |||
| 2371 | QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); | |||
| 2372 | for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { | |||
| 2373 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | |||
| 2374 | Value.getArrayInitializedElt(I), Kind, | |||
| 2375 | SubobjectLoc, CheckedTemps)) | |||
| 2376 | return false; | |||
| 2377 | } | |||
| 2378 | if (!Value.hasArrayFiller()) | |||
| 2379 | return true; | |||
| 2380 | return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | |||
| 2381 | Value.getArrayFiller(), Kind, SubobjectLoc, | |||
| 2382 | CheckedTemps); | |||
| 2383 | } | |||
| 2384 | if (Value.isUnion() && Value.getUnionField()) { | |||
| 2385 | return CheckEvaluationResult( | |||
| 2386 | CERK, Info, DiagLoc, Value.getUnionField()->getType(), | |||
| 2387 | Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), | |||
| 2388 | CheckedTemps); | |||
| 2389 | } | |||
| 2390 | if (Value.isStruct()) { | |||
| 2391 | RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); | |||
| 2392 | if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { | |||
| 2393 | unsigned BaseIndex = 0; | |||
| 2394 | for (const CXXBaseSpecifier &BS : CD->bases()) { | |||
| 2395 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), | |||
| 2396 | Value.getStructBase(BaseIndex), Kind, | |||
| 2397 | BS.getBeginLoc(), CheckedTemps)) | |||
| 2398 | return false; | |||
| 2399 | ++BaseIndex; | |||
| 2400 | } | |||
| 2401 | } | |||
| 2402 | for (const auto *I : RD->fields()) { | |||
| 2403 | if (I->isUnnamedBitfield()) | |||
| 2404 | continue; | |||
| 2405 | ||||
| 2406 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), | |||
| 2407 | Value.getStructField(I->getFieldIndex()), | |||
| 2408 | Kind, I->getLocation(), CheckedTemps)) | |||
| 2409 | return false; | |||
| 2410 | } | |||
| 2411 | } | |||
| 2412 | ||||
| 2413 | if (Value.isLValue() && | |||
| 2414 | CERK == CheckEvaluationResultKind::ConstantExpression) { | |||
| 2415 | LValue LVal; | |||
| 2416 | LVal.setFrom(Info.Ctx, Value); | |||
| 2417 | return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, | |||
| 2418 | CheckedTemps); | |||
| 2419 | } | |||
| 2420 | ||||
| 2421 | if (Value.isMemberPointer() && | |||
| 2422 | CERK == CheckEvaluationResultKind::ConstantExpression) | |||
| 2423 | return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); | |||
| 2424 | ||||
| 2425 | // Everything else is fine. | |||
| 2426 | return true; | |||
| 2427 | } | |||
| 2428 | ||||
| 2429 | /// Check that this core constant expression value is a valid value for a | |||
| 2430 | /// constant expression. If not, report an appropriate diagnostic. Does not | |||
| 2431 | /// check that the expression is of literal type. | |||
| 2432 | static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, | |||
| 2433 | QualType Type, const APValue &Value, | |||
| 2434 | ConstantExprKind Kind) { | |||
| 2435 | // Nothing to check for a constant expression of type 'cv void'. | |||
| 2436 | if (Type->isVoidType()) | |||
| 2437 | return true; | |||
| 2438 | ||||
| 2439 | CheckedTemporaries CheckedTemps; | |||
| 2440 | return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | |||
| 2441 | Info, DiagLoc, Type, Value, Kind, | |||
| 2442 | SourceLocation(), CheckedTemps); | |||
| 2443 | } | |||
| 2444 | ||||
| 2445 | /// Check that this evaluated value is fully-initialized and can be loaded by | |||
| 2446 | /// an lvalue-to-rvalue conversion. | |||
| 2447 | static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, | |||
| 2448 | QualType Type, const APValue &Value) { | |||
| 2449 | CheckedTemporaries CheckedTemps; | |||
| 2450 | return CheckEvaluationResult( | |||
| 2451 | CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, | |||
| 2452 | ConstantExprKind::Normal, SourceLocation(), CheckedTemps); | |||
| 2453 | } | |||
| 2454 | ||||
| 2455 | /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless | |||
| 2456 | /// "the allocated storage is deallocated within the evaluation". | |||
| 2457 | static bool CheckMemoryLeaks(EvalInfo &Info) { | |||
| 2458 | if (!Info.HeapAllocs.empty()) { | |||
| 2459 | // We can still fold to a constant despite a compile-time memory leak, | |||
| 2460 | // so long as the heap allocation isn't referenced in the result (we check | |||
| 2461 | // that in CheckConstantExpression). | |||
| 2462 | Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, | |||
| 2463 | diag::note_constexpr_memory_leak) | |||
| 2464 | << unsigned(Info.HeapAllocs.size() - 1); | |||
| 2465 | } | |||
| 2466 | return true; | |||
| 2467 | } | |||
| 2468 | ||||
| 2469 | static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { | |||
| 2470 | // A null base expression indicates a null pointer. These are always | |||
| 2471 | // evaluatable, and they are false unless the offset is zero. | |||
| 2472 | if (!Value.getLValueBase()) { | |||
| 2473 | Result = !Value.getLValueOffset().isZero(); | |||
| 2474 | return true; | |||
| 2475 | } | |||
| 2476 | ||||
| 2477 | // We have a non-null base. These are generally known to be true, but if it's | |||
| 2478 | // a weak declaration it can be null at runtime. | |||
| 2479 | Result = true; | |||
| 2480 | const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); | |||
| 2481 | return !Decl || !Decl->isWeak(); | |||
| 2482 | } | |||
| 2483 | ||||
| 2484 | static bool HandleConversionToBool(const APValue &Val, bool &Result) { | |||
| 2485 | switch (Val.getKind()) { | |||
| 2486 | case APValue::None: | |||
| 2487 | case APValue::Indeterminate: | |||
| 2488 | return false; | |||
| 2489 | case APValue::Int: | |||
| 2490 | Result = Val.getInt().getBoolValue(); | |||
| 2491 | return true; | |||
| 2492 | case APValue::FixedPoint: | |||
| 2493 | Result = Val.getFixedPoint().getBoolValue(); | |||
| 2494 | return true; | |||
| 2495 | case APValue::Float: | |||
| 2496 | Result = !Val.getFloat().isZero(); | |||
| 2497 | return true; | |||
| 2498 | case APValue::ComplexInt: | |||
| 2499 | Result = Val.getComplexIntReal().getBoolValue() || | |||
| 2500 | Val.getComplexIntImag().getBoolValue(); | |||
| 2501 | return true; | |||
| 2502 | case APValue::ComplexFloat: | |||
| 2503 | Result = !Val.getComplexFloatReal().isZero() || | |||
| 2504 | !Val.getComplexFloatImag().isZero(); | |||
| 2505 | return true; | |||
| 2506 | case APValue::LValue: | |||
| 2507 | return EvalPointerValueAsBool(Val, Result); | |||
| 2508 | case APValue::MemberPointer: | |||
| 2509 | Result = Val.getMemberPointerDecl(); | |||
| 2510 | return true; | |||
| 2511 | case APValue::Vector: | |||
| 2512 | case APValue::Array: | |||
| 2513 | case APValue::Struct: | |||
| 2514 | case APValue::Union: | |||
| 2515 | case APValue::AddrLabelDiff: | |||
| 2516 | return false; | |||
| 2517 | } | |||
| 2518 | ||||
| 2519 | llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "clang/lib/AST/ExprConstant.cpp" , 2519); | |||
| 2520 | } | |||
| 2521 | ||||
| 2522 | static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, | |||
| 2523 | EvalInfo &Info) { | |||
| 2524 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 2524, __extension__ __PRETTY_FUNCTION__)); | |||
| 2525 | assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition")(static_cast <bool> (E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition" ) ? void (0) : __assert_fail ("E->isPRValue() && \"missing lvalue-to-rvalue conv in bool condition\"" , "clang/lib/AST/ExprConstant.cpp", 2525, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2526 | APValue Val; | |||
| 2527 | if (!Evaluate(Val, Info, E)) | |||
| 2528 | return false; | |||
| 2529 | return HandleConversionToBool(Val, Result); | |||
| 2530 | } | |||
| 2531 | ||||
| 2532 | template<typename T> | |||
| 2533 | static bool HandleOverflow(EvalInfo &Info, const Expr *E, | |||
| 2534 | const T &SrcValue, QualType DestType) { | |||
| 2535 | Info.CCEDiag(E, diag::note_constexpr_overflow) | |||
| 2536 | << SrcValue << DestType; | |||
| 2537 | return Info.noteUndefinedBehavior(); | |||
| 2538 | } | |||
| 2539 | ||||
| 2540 | static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, | |||
| 2541 | QualType SrcType, const APFloat &Value, | |||
| 2542 | QualType DestType, APSInt &Result) { | |||
| 2543 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | |||
| 2544 | // Determine whether we are converting to unsigned or signed. | |||
| 2545 | bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); | |||
| 2546 | ||||
| 2547 | Result = APSInt(DestWidth, !DestSigned); | |||
| 2548 | bool ignored; | |||
| 2549 | if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) | |||
| 2550 | & APFloat::opInvalidOp) | |||
| 2551 | return HandleOverflow(Info, E, Value, DestType); | |||
| 2552 | return true; | |||
| 2553 | } | |||
| 2554 | ||||
| 2555 | /// Get rounding mode used for evaluation of the specified expression. | |||
| 2556 | /// \param[out] DynamicRM Is set to true is the requested rounding mode is | |||
| 2557 | /// dynamic. | |||
| 2558 | /// If rounding mode is unknown at compile time, still try to evaluate the | |||
| 2559 | /// expression. If the result is exact, it does not depend on rounding mode. | |||
| 2560 | /// So return "tonearest" mode instead of "dynamic". | |||
| 2561 | static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, | |||
| 2562 | bool &DynamicRM) { | |||
| 2563 | llvm::RoundingMode RM = | |||
| 2564 | E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); | |||
| 2565 | DynamicRM = (RM == llvm::RoundingMode::Dynamic); | |||
| 2566 | if (DynamicRM) | |||
| 2567 | RM = llvm::RoundingMode::NearestTiesToEven; | |||
| 2568 | return RM; | |||
| 2569 | } | |||
| 2570 | ||||
| 2571 | /// Check if the given evaluation result is allowed for constant evaluation. | |||
| 2572 | static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, | |||
| 2573 | APFloat::opStatus St) { | |||
| 2574 | // In a constant context, assume that any dynamic rounding mode or FP | |||
| 2575 | // exception state matches the default floating-point environment. | |||
| 2576 | if (Info.InConstantContext) | |||
| 2577 | return true; | |||
| 2578 | ||||
| 2579 | FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); | |||
| 2580 | if ((St & APFloat::opInexact) && | |||
| 2581 | FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { | |||
| 2582 | // Inexact result means that it depends on rounding mode. If the requested | |||
| 2583 | // mode is dynamic, the evaluation cannot be made in compile time. | |||
| 2584 | Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); | |||
| 2585 | return false; | |||
| 2586 | } | |||
| 2587 | ||||
| 2588 | if ((St != APFloat::opOK) && | |||
| 2589 | (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || | |||
| 2590 | FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || | |||
| 2591 | FPO.getAllowFEnvAccess())) { | |||
| 2592 | Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); | |||
| 2593 | return false; | |||
| 2594 | } | |||
| 2595 | ||||
| 2596 | if ((St & APFloat::opStatus::opInvalidOp) && | |||
| 2597 | FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { | |||
| 2598 | // There is no usefully definable result. | |||
| 2599 | Info.FFDiag(E); | |||
| 2600 | return false; | |||
| 2601 | } | |||
| 2602 | ||||
| 2603 | // FIXME: if: | |||
| 2604 | // - evaluation triggered other FP exception, and | |||
| 2605 | // - exception mode is not "ignore", and | |||
| 2606 | // - the expression being evaluated is not a part of global variable | |||
| 2607 | // initializer, | |||
| 2608 | // the evaluation probably need to be rejected. | |||
| 2609 | return true; | |||
| 2610 | } | |||
| 2611 | ||||
| 2612 | static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, | |||
| 2613 | QualType SrcType, QualType DestType, | |||
| 2614 | APFloat &Result) { | |||
| 2615 | assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E))(static_cast <bool> (isa<CastExpr>(E) || isa<CompoundAssignOperator >(E)) ? void (0) : __assert_fail ("isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)" , "clang/lib/AST/ExprConstant.cpp", 2615, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2616 | bool DynamicRM; | |||
| 2617 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); | |||
| 2618 | APFloat::opStatus St; | |||
| 2619 | APFloat Value = Result; | |||
| 2620 | bool ignored; | |||
| 2621 | St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); | |||
| 2622 | return checkFloatingPointResult(Info, E, St); | |||
| 2623 | } | |||
| 2624 | ||||
| 2625 | static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, | |||
| 2626 | QualType DestType, QualType SrcType, | |||
| 2627 | const APSInt &Value) { | |||
| 2628 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | |||
| 2629 | // Figure out if this is a truncate, extend or noop cast. | |||
| 2630 | // If the input is signed, do a sign extend, noop, or truncate. | |||
| 2631 | APSInt Result = Value.extOrTrunc(DestWidth); | |||
| 2632 | Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); | |||
| 2633 | if (DestType->isBooleanType()) | |||
| 2634 | Result = Value.getBoolValue(); | |||
| 2635 | return Result; | |||
| 2636 | } | |||
| 2637 | ||||
| 2638 | static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, | |||
| 2639 | const FPOptions FPO, | |||
| 2640 | QualType SrcType, const APSInt &Value, | |||
| 2641 | QualType DestType, APFloat &Result) { | |||
| 2642 | Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); | |||
| 2643 | APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), | |||
| 2644 | APFloat::rmNearestTiesToEven); | |||
| 2645 | if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && | |||
| 2646 | FPO.isFPConstrained()) { | |||
| 2647 | Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); | |||
| 2648 | return false; | |||
| 2649 | } | |||
| 2650 | return true; | |||
| 2651 | } | |||
| 2652 | ||||
| 2653 | static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, | |||
| 2654 | APValue &Value, const FieldDecl *FD) { | |||
| 2655 | assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")(static_cast <bool> (FD->isBitField() && "truncateBitfieldValue on non-bitfield" ) ? void (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\"" , "clang/lib/AST/ExprConstant.cpp", 2655, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2656 | ||||
| 2657 | if (!Value.isInt()) { | |||
| 2658 | // Trying to store a pointer-cast-to-integer into a bitfield. | |||
| 2659 | // FIXME: In this case, we should provide the diagnostic for casting | |||
| 2660 | // a pointer to an integer. | |||
| 2661 | assert(Value.isLValue() && "integral value neither int nor lvalue?")(static_cast <bool> (Value.isLValue() && "integral value neither int nor lvalue?" ) ? void (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\"" , "clang/lib/AST/ExprConstant.cpp", 2661, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2662 | Info.FFDiag(E); | |||
| 2663 | return false; | |||
| 2664 | } | |||
| 2665 | ||||
| 2666 | APSInt &Int = Value.getInt(); | |||
| 2667 | unsigned OldBitWidth = Int.getBitWidth(); | |||
| 2668 | unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); | |||
| 2669 | if (NewBitWidth < OldBitWidth) | |||
| 2670 | Int = Int.trunc(NewBitWidth).extend(OldBitWidth); | |||
| 2671 | return true; | |||
| 2672 | } | |||
| 2673 | ||||
| 2674 | static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, | |||
| 2675 | llvm::APInt &Res) { | |||
| 2676 | APValue SVal; | |||
| 2677 | if (!Evaluate(SVal, Info, E)) | |||
| 2678 | return false; | |||
| 2679 | if (SVal.isInt()) { | |||
| 2680 | Res = SVal.getInt(); | |||
| 2681 | return true; | |||
| 2682 | } | |||
| 2683 | if (SVal.isFloat()) { | |||
| 2684 | Res = SVal.getFloat().bitcastToAPInt(); | |||
| 2685 | return true; | |||
| 2686 | } | |||
| 2687 | if (SVal.isVector()) { | |||
| 2688 | QualType VecTy = E->getType(); | |||
| 2689 | unsigned VecSize = Info.Ctx.getTypeSize(VecTy); | |||
| 2690 | QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); | |||
| 2691 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | |||
| 2692 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | |||
| 2693 | Res = llvm::APInt::getZero(VecSize); | |||
| 2694 | for (unsigned i = 0; i < SVal.getVectorLength(); i++) { | |||
| 2695 | APValue &Elt = SVal.getVectorElt(i); | |||
| 2696 | llvm::APInt EltAsInt; | |||
| 2697 | if (Elt.isInt()) { | |||
| 2698 | EltAsInt = Elt.getInt(); | |||
| 2699 | } else if (Elt.isFloat()) { | |||
| 2700 | EltAsInt = Elt.getFloat().bitcastToAPInt(); | |||
| 2701 | } else { | |||
| 2702 | // Don't try to handle vectors of anything other than int or float | |||
| 2703 | // (not sure if it's possible to hit this case). | |||
| 2704 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 2705 | return false; | |||
| 2706 | } | |||
| 2707 | unsigned BaseEltSize = EltAsInt.getBitWidth(); | |||
| 2708 | if (BigEndian) | |||
| 2709 | Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); | |||
| 2710 | else | |||
| 2711 | Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); | |||
| 2712 | } | |||
| 2713 | return true; | |||
| 2714 | } | |||
| 2715 | // Give up if the input isn't an int, float, or vector. For example, we | |||
| 2716 | // reject "(v4i16)(intptr_t)&a". | |||
| 2717 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 2718 | return false; | |||
| 2719 | } | |||
| 2720 | ||||
| 2721 | /// Perform the given integer operation, which is known to need at most BitWidth | |||
| 2722 | /// bits, and check for overflow in the original type (if that type was not an | |||
| 2723 | /// unsigned type). | |||
| 2724 | template<typename Operation> | |||
| 2725 | static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, | |||
| 2726 | const APSInt &LHS, const APSInt &RHS, | |||
| 2727 | unsigned BitWidth, Operation Op, | |||
| 2728 | APSInt &Result) { | |||
| 2729 | if (LHS.isUnsigned()) { | |||
| 2730 | Result = Op(LHS, RHS); | |||
| 2731 | return true; | |||
| 2732 | } | |||
| 2733 | ||||
| 2734 | APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); | |||
| 2735 | Result = Value.trunc(LHS.getBitWidth()); | |||
| 2736 | if (Result.extend(BitWidth) != Value) { | |||
| 2737 | if (Info.checkingForUndefinedBehavior()) | |||
| 2738 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | |||
| 2739 | diag::warn_integer_constant_overflow) | |||
| 2740 | << toString(Result, 10) << E->getType(); | |||
| 2741 | return HandleOverflow(Info, E, Value, E->getType()); | |||
| 2742 | } | |||
| 2743 | return true; | |||
| 2744 | } | |||
| 2745 | ||||
| 2746 | /// Perform the given binary integer operation. | |||
| 2747 | static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, | |||
| 2748 | BinaryOperatorKind Opcode, APSInt RHS, | |||
| 2749 | APSInt &Result) { | |||
| 2750 | switch (Opcode) { | |||
| 2751 | default: | |||
| 2752 | Info.FFDiag(E); | |||
| 2753 | return false; | |||
| 2754 | case BO_Mul: | |||
| 2755 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, | |||
| 2756 | std::multiplies<APSInt>(), Result); | |||
| 2757 | case BO_Add: | |||
| 2758 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | |||
| 2759 | std::plus<APSInt>(), Result); | |||
| 2760 | case BO_Sub: | |||
| 2761 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | |||
| 2762 | std::minus<APSInt>(), Result); | |||
| 2763 | case BO_And: Result = LHS & RHS; return true; | |||
| 2764 | case BO_Xor: Result = LHS ^ RHS; return true; | |||
| 2765 | case BO_Or: Result = LHS | RHS; return true; | |||
| 2766 | case BO_Div: | |||
| 2767 | case BO_Rem: | |||
| 2768 | if (RHS == 0) { | |||
| 2769 | Info.FFDiag(E, diag::note_expr_divide_by_zero); | |||
| 2770 | return false; | |||
| 2771 | } | |||
| 2772 | Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); | |||
| 2773 | // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports | |||
| 2774 | // this operation and gives the two's complement result. | |||
| 2775 | if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && | |||
| 2776 | LHS.isMinSignedValue()) | |||
| 2777 | return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), | |||
| 2778 | E->getType()); | |||
| 2779 | return true; | |||
| 2780 | case BO_Shl: { | |||
| 2781 | if (Info.getLangOpts().OpenCL) | |||
| 2782 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | |||
| 2783 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | |||
| 2784 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | |||
| 2785 | RHS.isUnsigned()); | |||
| 2786 | else if (RHS.isSigned() && RHS.isNegative()) { | |||
| 2787 | // During constant-folding, a negative shift is an opposite shift. Such | |||
| 2788 | // a shift is not a constant expression. | |||
| 2789 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | |||
| 2790 | RHS = -RHS; | |||
| 2791 | goto shift_right; | |||
| 2792 | } | |||
| 2793 | shift_left: | |||
| 2794 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of | |||
| 2795 | // the shifted type. | |||
| 2796 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | |||
| 2797 | if (SA != RHS) { | |||
| 2798 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | |||
| 2799 | << RHS << E->getType() << LHS.getBitWidth(); | |||
| 2800 | } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { | |||
| 2801 | // C++11 [expr.shift]p2: A signed left shift must have a non-negative | |||
| 2802 | // operand, and must not overflow the corresponding unsigned type. | |||
| 2803 | // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to | |||
| 2804 | // E1 x 2^E2 module 2^N. | |||
| 2805 | if (LHS.isNegative()) | |||
| 2806 | Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; | |||
| 2807 | else if (LHS.countLeadingZeros() < SA) | |||
| 2808 | Info.CCEDiag(E, diag::note_constexpr_lshift_discards); | |||
| 2809 | } | |||
| 2810 | Result = LHS << SA; | |||
| 2811 | return true; | |||
| 2812 | } | |||
| 2813 | case BO_Shr: { | |||
| 2814 | if (Info.getLangOpts().OpenCL) | |||
| 2815 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | |||
| 2816 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | |||
| 2817 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | |||
| 2818 | RHS.isUnsigned()); | |||
| 2819 | else if (RHS.isSigned() && RHS.isNegative()) { | |||
| 2820 | // During constant-folding, a negative shift is an opposite shift. Such a | |||
| 2821 | // shift is not a constant expression. | |||
| 2822 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | |||
| 2823 | RHS = -RHS; | |||
| 2824 | goto shift_left; | |||
| 2825 | } | |||
| 2826 | shift_right: | |||
| 2827 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of the | |||
| 2828 | // shifted type. | |||
| 2829 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | |||
| 2830 | if (SA != RHS) | |||
| 2831 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | |||
| 2832 | << RHS << E->getType() << LHS.getBitWidth(); | |||
| 2833 | Result = LHS >> SA; | |||
| 2834 | return true; | |||
| 2835 | } | |||
| 2836 | ||||
| 2837 | case BO_LT: Result = LHS < RHS; return true; | |||
| 2838 | case BO_GT: Result = LHS > RHS; return true; | |||
| 2839 | case BO_LE: Result = LHS <= RHS; return true; | |||
| 2840 | case BO_GE: Result = LHS >= RHS; return true; | |||
| 2841 | case BO_EQ: Result = LHS == RHS; return true; | |||
| 2842 | case BO_NE: Result = LHS != RHS; return true; | |||
| 2843 | case BO_Cmp: | |||
| 2844 | llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere" , "clang/lib/AST/ExprConstant.cpp", 2844); | |||
| 2845 | } | |||
| 2846 | } | |||
| 2847 | ||||
| 2848 | /// Perform the given binary floating-point operation, in-place, on LHS. | |||
| 2849 | static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, | |||
| 2850 | APFloat &LHS, BinaryOperatorKind Opcode, | |||
| 2851 | const APFloat &RHS) { | |||
| 2852 | bool DynamicRM; | |||
| 2853 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); | |||
| 2854 | APFloat::opStatus St; | |||
| 2855 | switch (Opcode) { | |||
| 2856 | default: | |||
| 2857 | Info.FFDiag(E); | |||
| 2858 | return false; | |||
| 2859 | case BO_Mul: | |||
| 2860 | St = LHS.multiply(RHS, RM); | |||
| 2861 | break; | |||
| 2862 | case BO_Add: | |||
| 2863 | St = LHS.add(RHS, RM); | |||
| 2864 | break; | |||
| 2865 | case BO_Sub: | |||
| 2866 | St = LHS.subtract(RHS, RM); | |||
| 2867 | break; | |||
| 2868 | case BO_Div: | |||
| 2869 | // [expr.mul]p4: | |||
| 2870 | // If the second operand of / or % is zero the behavior is undefined. | |||
| 2871 | if (RHS.isZero()) | |||
| 2872 | Info.CCEDiag(E, diag::note_expr_divide_by_zero); | |||
| 2873 | St = LHS.divide(RHS, RM); | |||
| 2874 | break; | |||
| 2875 | } | |||
| 2876 | ||||
| 2877 | // [expr.pre]p4: | |||
| 2878 | // If during the evaluation of an expression, the result is not | |||
| 2879 | // mathematically defined [...], the behavior is undefined. | |||
| 2880 | // FIXME: C++ rules require us to not conform to IEEE 754 here. | |||
| 2881 | if (LHS.isNaN()) { | |||
| 2882 | Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); | |||
| 2883 | return Info.noteUndefinedBehavior(); | |||
| 2884 | } | |||
| 2885 | ||||
| 2886 | return checkFloatingPointResult(Info, E, St); | |||
| 2887 | } | |||
| 2888 | ||||
| 2889 | static bool handleLogicalOpForVector(const APInt &LHSValue, | |||
| 2890 | BinaryOperatorKind Opcode, | |||
| 2891 | const APInt &RHSValue, APInt &Result) { | |||
| 2892 | bool LHS = (LHSValue != 0); | |||
| 2893 | bool RHS = (RHSValue != 0); | |||
| 2894 | ||||
| 2895 | if (Opcode == BO_LAnd) | |||
| 2896 | Result = LHS && RHS; | |||
| 2897 | else | |||
| 2898 | Result = LHS || RHS; | |||
| 2899 | return true; | |||
| 2900 | } | |||
| 2901 | static bool handleLogicalOpForVector(const APFloat &LHSValue, | |||
| 2902 | BinaryOperatorKind Opcode, | |||
| 2903 | const APFloat &RHSValue, APInt &Result) { | |||
| 2904 | bool LHS = !LHSValue.isZero(); | |||
| 2905 | bool RHS = !RHSValue.isZero(); | |||
| 2906 | ||||
| 2907 | if (Opcode == BO_LAnd) | |||
| 2908 | Result = LHS && RHS; | |||
| 2909 | else | |||
| 2910 | Result = LHS || RHS; | |||
| 2911 | return true; | |||
| 2912 | } | |||
| 2913 | ||||
| 2914 | static bool handleLogicalOpForVector(const APValue &LHSValue, | |||
| 2915 | BinaryOperatorKind Opcode, | |||
| 2916 | const APValue &RHSValue, APInt &Result) { | |||
| 2917 | // The result is always an int type, however operands match the first. | |||
| 2918 | if (LHSValue.getKind() == APValue::Int) | |||
| 2919 | return handleLogicalOpForVector(LHSValue.getInt(), Opcode, | |||
| 2920 | RHSValue.getInt(), Result); | |||
| 2921 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float && "Should be no other options") ? void (0) : __assert_fail ("LHSValue.getKind() == APValue::Float && \"Should be no other options\"" , "clang/lib/AST/ExprConstant.cpp", 2921, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2922 | return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, | |||
| 2923 | RHSValue.getFloat(), Result); | |||
| 2924 | } | |||
| 2925 | ||||
| 2926 | template <typename APTy> | |||
| 2927 | static bool | |||
| 2928 | handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, | |||
| 2929 | const APTy &RHSValue, APInt &Result) { | |||
| 2930 | switch (Opcode) { | |||
| 2931 | default: | |||
| 2932 | llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator" , "clang/lib/AST/ExprConstant.cpp", 2932); | |||
| 2933 | case BO_EQ: | |||
| 2934 | Result = (LHSValue == RHSValue); | |||
| 2935 | break; | |||
| 2936 | case BO_NE: | |||
| 2937 | Result = (LHSValue != RHSValue); | |||
| 2938 | break; | |||
| 2939 | case BO_LT: | |||
| 2940 | Result = (LHSValue < RHSValue); | |||
| 2941 | break; | |||
| 2942 | case BO_GT: | |||
| 2943 | Result = (LHSValue > RHSValue); | |||
| 2944 | break; | |||
| 2945 | case BO_LE: | |||
| 2946 | Result = (LHSValue <= RHSValue); | |||
| 2947 | break; | |||
| 2948 | case BO_GE: | |||
| 2949 | Result = (LHSValue >= RHSValue); | |||
| 2950 | break; | |||
| 2951 | } | |||
| 2952 | ||||
| 2953 | // The boolean operations on these vector types use an instruction that | |||
| 2954 | // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 | |||
| 2955 | // to -1 to make sure that we produce the correct value. | |||
| 2956 | Result.negate(); | |||
| 2957 | ||||
| 2958 | return true; | |||
| 2959 | } | |||
| 2960 | ||||
| 2961 | static bool handleCompareOpForVector(const APValue &LHSValue, | |||
| 2962 | BinaryOperatorKind Opcode, | |||
| 2963 | const APValue &RHSValue, APInt &Result) { | |||
| 2964 | // The result is always an int type, however operands match the first. | |||
| 2965 | if (LHSValue.getKind() == APValue::Int) | |||
| 2966 | return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, | |||
| 2967 | RHSValue.getInt(), Result); | |||
| 2968 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float && "Should be no other options") ? void (0) : __assert_fail ("LHSValue.getKind() == APValue::Float && \"Should be no other options\"" , "clang/lib/AST/ExprConstant.cpp", 2968, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2969 | return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, | |||
| 2970 | RHSValue.getFloat(), Result); | |||
| 2971 | } | |||
| 2972 | ||||
| 2973 | // Perform binary operations for vector types, in place on the LHS. | |||
| 2974 | static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, | |||
| 2975 | BinaryOperatorKind Opcode, | |||
| 2976 | APValue &LHSValue, | |||
| 2977 | const APValue &RHSValue) { | |||
| 2978 | assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&(static_cast <bool> (Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\"" , "clang/lib/AST/ExprConstant.cpp", 2979, __extension__ __PRETTY_FUNCTION__ )) | |||
| 2979 | "Operation not supported on vector types")(static_cast <bool> (Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\"" , "clang/lib/AST/ExprConstant.cpp", 2979, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2980 | ||||
| 2981 | const auto *VT = E->getType()->castAs<VectorType>(); | |||
| 2982 | unsigned NumElements = VT->getNumElements(); | |||
| 2983 | QualType EltTy = VT->getElementType(); | |||
| 2984 | ||||
| 2985 | // In the cases (typically C as I've observed) where we aren't evaluating | |||
| 2986 | // constexpr but are checking for cases where the LHS isn't yet evaluatable, | |||
| 2987 | // just give up. | |||
| 2988 | if (!LHSValue.isVector()) { | |||
| 2989 | assert(LHSValue.isLValue() &&(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue" ) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\"" , "clang/lib/AST/ExprConstant.cpp", 2990, __extension__ __PRETTY_FUNCTION__ )) | |||
| 2990 | "A vector result that isn't a vector OR uncalculated LValue")(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue" ) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\"" , "clang/lib/AST/ExprConstant.cpp", 2990, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2991 | Info.FFDiag(E); | |||
| 2992 | return false; | |||
| 2993 | } | |||
| 2994 | ||||
| 2995 | assert(LHSValue.getVectorLength() == NumElements &&(static_cast <bool> (LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && "Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\"" , "clang/lib/AST/ExprConstant.cpp", 2996, __extension__ __PRETTY_FUNCTION__ )) | |||
| 2996 | RHSValue.getVectorLength() == NumElements && "Different vector sizes")(static_cast <bool> (LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && "Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\"" , "clang/lib/AST/ExprConstant.cpp", 2996, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2997 | ||||
| 2998 | SmallVector<APValue, 4> ResultElements; | |||
| 2999 | ||||
| 3000 | for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { | |||
| 3001 | APValue LHSElt = LHSValue.getVectorElt(EltNum); | |||
| 3002 | APValue RHSElt = RHSValue.getVectorElt(EltNum); | |||
| 3003 | ||||
| 3004 | if (EltTy->isIntegerType()) { | |||
| 3005 | APSInt EltResult{Info.Ctx.getIntWidth(EltTy), | |||
| 3006 | EltTy->isUnsignedIntegerType()}; | |||
| 3007 | bool Success = true; | |||
| 3008 | ||||
| 3009 | if (BinaryOperator::isLogicalOp(Opcode)) | |||
| 3010 | Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); | |||
| 3011 | else if (BinaryOperator::isComparisonOp(Opcode)) | |||
| 3012 | Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); | |||
| 3013 | else | |||
| 3014 | Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, | |||
| 3015 | RHSElt.getInt(), EltResult); | |||
| 3016 | ||||
| 3017 | if (!Success) { | |||
| 3018 | Info.FFDiag(E); | |||
| 3019 | return false; | |||
| 3020 | } | |||
| 3021 | ResultElements.emplace_back(EltResult); | |||
| 3022 | ||||
| 3023 | } else if (EltTy->isFloatingType()) { | |||
| 3024 | assert(LHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "clang/lib/AST/ExprConstant.cpp", 3026, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3025 | RHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "clang/lib/AST/ExprConstant.cpp", 3026, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3026 | "Mismatched LHS/RHS/Result Type")(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "clang/lib/AST/ExprConstant.cpp", 3026, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3027 | APFloat LHSFloat = LHSElt.getFloat(); | |||
| 3028 | ||||
| 3029 | if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, | |||
| 3030 | RHSElt.getFloat())) { | |||
| 3031 | Info.FFDiag(E); | |||
| 3032 | return false; | |||
| 3033 | } | |||
| 3034 | ||||
| 3035 | ResultElements.emplace_back(LHSFloat); | |||
| 3036 | } | |||
| 3037 | } | |||
| 3038 | ||||
| 3039 | LHSValue = APValue(ResultElements.data(), ResultElements.size()); | |||
| 3040 | return true; | |||
| 3041 | } | |||
| 3042 | ||||
| 3043 | /// Cast an lvalue referring to a base subobject to a derived class, by | |||
| 3044 | /// truncating the lvalue's path to the given length. | |||
| 3045 | static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, | |||
| 3046 | const RecordDecl *TruncatedType, | |||
| 3047 | unsigned TruncatedElements) { | |||
| 3048 | SubobjectDesignator &D = Result.Designator; | |||
| 3049 | ||||
| 3050 | // Check we actually point to a derived class object. | |||
| 3051 | if (TruncatedElements == D.Entries.size()) | |||
| 3052 | return true; | |||
| 3053 | assert(TruncatedElements >= D.MostDerivedPathLength &&(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class") ? void (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "clang/lib/AST/ExprConstant.cpp", 3054, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3054 | "not casting to a derived class")(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class") ? void (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "clang/lib/AST/ExprConstant.cpp", 3054, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3055 | if (!Result.checkSubobject(Info, E, CSK_Derived)) | |||
| 3056 | return false; | |||
| 3057 | ||||
| 3058 | // Truncate the path to the subobject, and remove any derived-to-base offsets. | |||
| 3059 | const RecordDecl *RD = TruncatedType; | |||
| 3060 | for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { | |||
| 3061 | if (RD->isInvalidDecl()) return false; | |||
| 3062 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | |||
| 3063 | const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); | |||
| 3064 | if (isVirtualBaseClass(D.Entries[I])) | |||
| 3065 | Result.Offset -= Layout.getVBaseClassOffset(Base); | |||
| 3066 | else | |||
| 3067 | Result.Offset -= Layout.getBaseClassOffset(Base); | |||
| 3068 | RD = Base; | |||
| 3069 | } | |||
| 3070 | D.Entries.resize(TruncatedElements); | |||
| 3071 | return true; | |||
| 3072 | } | |||
| 3073 | ||||
| 3074 | static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, | |||
| 3075 | const CXXRecordDecl *Derived, | |||
| 3076 | const CXXRecordDecl *Base, | |||
| 3077 | const ASTRecordLayout *RL = nullptr) { | |||
| 3078 | if (!RL) { | |||
| 3079 | if (Derived->isInvalidDecl()) return false; | |||
| 3080 | RL = &Info.Ctx.getASTRecordLayout(Derived); | |||
| 3081 | } | |||
| 3082 | ||||
| 3083 | Obj.getLValueOffset() += RL->getBaseClassOffset(Base); | |||
| 3084 | Obj.addDecl(Info, E, Base, /*Virtual*/ false); | |||
| 3085 | return true; | |||
| 3086 | } | |||
| 3087 | ||||
| 3088 | static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, | |||
| 3089 | const CXXRecordDecl *DerivedDecl, | |||
| 3090 | const CXXBaseSpecifier *Base) { | |||
| 3091 | const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); | |||
| 3092 | ||||
| 3093 | if (!Base->isVirtual()) | |||
| 3094 | return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); | |||
| 3095 | ||||
| 3096 | SubobjectDesignator &D = Obj.Designator; | |||
| 3097 | if (D.Invalid) | |||
| 3098 | return false; | |||
| 3099 | ||||
| 3100 | // Extract most-derived object and corresponding type. | |||
| 3101 | DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); | |||
| 3102 | if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) | |||
| 3103 | return false; | |||
| 3104 | ||||
| 3105 | // Find the virtual base class. | |||
| 3106 | if (DerivedDecl->isInvalidDecl()) return false; | |||
| 3107 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); | |||
| 3108 | Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); | |||
| 3109 | Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); | |||
| 3110 | return true; | |||
| 3111 | } | |||
| 3112 | ||||
| 3113 | static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, | |||
| 3114 | QualType Type, LValue &Result) { | |||
| 3115 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | |||
| 3116 | PathE = E->path_end(); | |||
| 3117 | PathI != PathE; ++PathI) { | |||
| 3118 | if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), | |||
| 3119 | *PathI)) | |||
| 3120 | return false; | |||
| 3121 | Type = (*PathI)->getType(); | |||
| 3122 | } | |||
| 3123 | return true; | |||
| 3124 | } | |||
| 3125 | ||||
| 3126 | /// Cast an lvalue referring to a derived class to a known base subobject. | |||
| 3127 | static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, | |||
| 3128 | const CXXRecordDecl *DerivedRD, | |||
| 3129 | const CXXRecordDecl *BaseRD) { | |||
| 3130 | CXXBasePaths Paths(/*FindAmbiguities=*/false, | |||
| 3131 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | |||
| 3132 | if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) | |||
| 3133 | llvm_unreachable("Class must be derived from the passed in base class!")::llvm::llvm_unreachable_internal("Class must be derived from the passed in base class!" , "clang/lib/AST/ExprConstant.cpp", 3133); | |||
| 3134 | ||||
| 3135 | for (CXXBasePathElement &Elem : Paths.front()) | |||
| 3136 | if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) | |||
| 3137 | return false; | |||
| 3138 | return true; | |||
| 3139 | } | |||
| 3140 | ||||
| 3141 | /// Update LVal to refer to the given field, which must be a member of the type | |||
| 3142 | /// currently described by LVal. | |||
| 3143 | static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, | |||
| 3144 | const FieldDecl *FD, | |||
| 3145 | const ASTRecordLayout *RL = nullptr) { | |||
| 3146 | if (!RL) { | |||
| 3147 | if (FD->getParent()->isInvalidDecl()) return false; | |||
| 3148 | RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); | |||
| 3149 | } | |||
| 3150 | ||||
| 3151 | unsigned I = FD->getFieldIndex(); | |||
| 3152 | LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); | |||
| 3153 | LVal.addDecl(Info, E, FD); | |||
| 3154 | return true; | |||
| 3155 | } | |||
| 3156 | ||||
| 3157 | /// Update LVal to refer to the given indirect field. | |||
| 3158 | static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, | |||
| 3159 | LValue &LVal, | |||
| 3160 | const IndirectFieldDecl *IFD) { | |||
| 3161 | for (const auto *C : IFD->chain()) | |||
| 3162 | if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) | |||
| 3163 | return false; | |||
| 3164 | return true; | |||
| 3165 | } | |||
| 3166 | ||||
| 3167 | /// Get the size of the given type in char units. | |||
| 3168 | static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, | |||
| 3169 | QualType Type, CharUnits &Size) { | |||
| 3170 | // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc | |||
| 3171 | // extension. | |||
| 3172 | if (Type->isVoidType() || Type->isFunctionType()) { | |||
| 3173 | Size = CharUnits::One(); | |||
| 3174 | return true; | |||
| 3175 | } | |||
| 3176 | ||||
| 3177 | if (Type->isDependentType()) { | |||
| 3178 | Info.FFDiag(Loc); | |||
| 3179 | return false; | |||
| 3180 | } | |||
| 3181 | ||||
| 3182 | if (!Type->isConstantSizeType()) { | |||
| 3183 | // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. | |||
| 3184 | // FIXME: Better diagnostic. | |||
| 3185 | Info.FFDiag(Loc); | |||
| 3186 | return false; | |||
| 3187 | } | |||
| 3188 | ||||
| 3189 | Size = Info.Ctx.getTypeSizeInChars(Type); | |||
| 3190 | return true; | |||
| 3191 | } | |||
| 3192 | ||||
| 3193 | /// Update a pointer value to model pointer arithmetic. | |||
| 3194 | /// \param Info - Information about the ongoing evaluation. | |||
| 3195 | /// \param E - The expression being evaluated, for diagnostic purposes. | |||
| 3196 | /// \param LVal - The pointer value to be updated. | |||
| 3197 | /// \param EltTy - The pointee type represented by LVal. | |||
| 3198 | /// \param Adjustment - The adjustment, in objects of type EltTy, to add. | |||
| 3199 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | |||
| 3200 | LValue &LVal, QualType EltTy, | |||
| 3201 | APSInt Adjustment) { | |||
| 3202 | CharUnits SizeOfPointee; | |||
| 3203 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) | |||
| 3204 | return false; | |||
| 3205 | ||||
| 3206 | LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); | |||
| 3207 | return true; | |||
| 3208 | } | |||
| 3209 | ||||
| 3210 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | |||
| 3211 | LValue &LVal, QualType EltTy, | |||
| 3212 | int64_t Adjustment) { | |||
| 3213 | return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, | |||
| 3214 | APSInt::get(Adjustment)); | |||
| 3215 | } | |||
| 3216 | ||||
| 3217 | /// Update an lvalue to refer to a component of a complex number. | |||
| 3218 | /// \param Info - Information about the ongoing evaluation. | |||
| 3219 | /// \param LVal - The lvalue to be updated. | |||
| 3220 | /// \param EltTy - The complex number's component type. | |||
| 3221 | /// \param Imag - False for the real component, true for the imaginary. | |||
| 3222 | static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, | |||
| 3223 | LValue &LVal, QualType EltTy, | |||
| 3224 | bool Imag) { | |||
| 3225 | if (Imag) { | |||
| 3226 | CharUnits SizeOfComponent; | |||
| 3227 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) | |||
| 3228 | return false; | |||
| 3229 | LVal.Offset += SizeOfComponent; | |||
| 3230 | } | |||
| 3231 | LVal.addComplex(Info, E, EltTy, Imag); | |||
| 3232 | return true; | |||
| 3233 | } | |||
| 3234 | ||||
| 3235 | /// Try to evaluate the initializer for a variable declaration. | |||
| 3236 | /// | |||
| 3237 | /// \param Info Information about the ongoing evaluation. | |||
| 3238 | /// \param E An expression to be used when printing diagnostics. | |||
| 3239 | /// \param VD The variable whose initializer should be obtained. | |||
| 3240 | /// \param Version The version of the variable within the frame. | |||
| 3241 | /// \param Frame The frame in which the variable was created. Must be null | |||
| 3242 | /// if this variable is not local to the evaluation. | |||
| 3243 | /// \param Result Filled in with a pointer to the value of the variable. | |||
| 3244 | static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, | |||
| 3245 | const VarDecl *VD, CallStackFrame *Frame, | |||
| 3246 | unsigned Version, APValue *&Result) { | |||
| 3247 | APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); | |||
| 3248 | ||||
| 3249 | // If this is a local variable, dig out its value. | |||
| 3250 | if (Frame) { | |||
| 3251 | Result = Frame->getTemporary(VD, Version); | |||
| 3252 | if (Result) | |||
| 3253 | return true; | |||
| 3254 | ||||
| 3255 | if (!isa<ParmVarDecl>(VD)) { | |||
| 3256 | // Assume variables referenced within a lambda's call operator that were | |||
| 3257 | // not declared within the call operator are captures and during checking | |||
| 3258 | // of a potential constant expression, assume they are unknown constant | |||
| 3259 | // expressions. | |||
| 3260 | assert(isLambdaCallOperator(Frame->Callee) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "clang/lib/AST/ExprConstant.cpp", 3262, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3261 | (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "clang/lib/AST/ExprConstant.cpp", 3262, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3262 | "missing value for local variable")(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "clang/lib/AST/ExprConstant.cpp", 3262, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3263 | if (Info.checkingPotentialConstantExpression()) | |||
| 3264 | return false; | |||
| 3265 | // FIXME: This diagnostic is bogus; we do support captures. Is this code | |||
| 3266 | // still reachable at all? | |||
| 3267 | Info.FFDiag(E->getBeginLoc(), | |||
| 3268 | diag::note_unimplemented_constexpr_lambda_feature_ast) | |||
| 3269 | << "captures not currently allowed"; | |||
| 3270 | return false; | |||
| 3271 | } | |||
| 3272 | } | |||
| 3273 | ||||
| 3274 | // If we're currently evaluating the initializer of this declaration, use that | |||
| 3275 | // in-flight value. | |||
| 3276 | if (Info.EvaluatingDecl == Base) { | |||
| 3277 | Result = Info.EvaluatingDeclValue; | |||
| 3278 | return true; | |||
| 3279 | } | |||
| 3280 | ||||
| 3281 | if (isa<ParmVarDecl>(VD)) { | |||
| 3282 | // Assume parameters of a potential constant expression are usable in | |||
| 3283 | // constant expressions. | |||
| 3284 | if (!Info.checkingPotentialConstantExpression() || | |||
| 3285 | !Info.CurrentCall->Callee || | |||
| 3286 | !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { | |||
| 3287 | if (Info.getLangOpts().CPlusPlus11) { | |||
| 3288 | Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) | |||
| 3289 | << VD; | |||
| 3290 | NoteLValueLocation(Info, Base); | |||
| 3291 | } else { | |||
| 3292 | Info.FFDiag(E); | |||
| 3293 | } | |||
| 3294 | } | |||
| 3295 | return false; | |||
| 3296 | } | |||
| 3297 | ||||
| 3298 | // Dig out the initializer, and use the declaration which it's attached to. | |||
| 3299 | // FIXME: We should eventually check whether the variable has a reachable | |||
| 3300 | // initializing declaration. | |||
| 3301 | const Expr *Init = VD->getAnyInitializer(VD); | |||
| 3302 | if (!Init) { | |||
| 3303 | // Don't diagnose during potential constant expression checking; an | |||
| 3304 | // initializer might be added later. | |||
| 3305 | if (!Info.checkingPotentialConstantExpression()) { | |||
| 3306 | Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) | |||
| 3307 | << VD; | |||
| 3308 | NoteLValueLocation(Info, Base); | |||
| 3309 | } | |||
| 3310 | return false; | |||
| 3311 | } | |||
| 3312 | ||||
| 3313 | if (Init->isValueDependent()) { | |||
| 3314 | // The DeclRefExpr is not value-dependent, but the variable it refers to | |||
| 3315 | // has a value-dependent initializer. This should only happen in | |||
| 3316 | // constant-folding cases, where the variable is not actually of a suitable | |||
| 3317 | // type for use in a constant expression (otherwise the DeclRefExpr would | |||
| 3318 | // have been value-dependent too), so diagnose that. | |||
| 3319 | assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx))(static_cast <bool> (!VD->mightBeUsableInConstantExpressions (Info.Ctx)) ? void (0) : __assert_fail ("!VD->mightBeUsableInConstantExpressions(Info.Ctx)" , "clang/lib/AST/ExprConstant.cpp", 3319, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3320 | if (!Info.checkingPotentialConstantExpression()) { | |||
| 3321 | Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 | |||
| 3322 | ? diag::note_constexpr_ltor_non_constexpr | |||
| 3323 | : diag::note_constexpr_ltor_non_integral, 1) | |||
| 3324 | << VD << VD->getType(); | |||
| 3325 | NoteLValueLocation(Info, Base); | |||
| 3326 | } | |||
| 3327 | return false; | |||
| 3328 | } | |||
| 3329 | ||||
| 3330 | // Check that we can fold the initializer. In C++, we will have already done | |||
| 3331 | // this in the cases where it matters for conformance. | |||
| 3332 | if (!VD->evaluateValue()) { | |||
| 3333 | Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; | |||
| 3334 | NoteLValueLocation(Info, Base); | |||
| 3335 | return false; | |||
| 3336 | } | |||
| 3337 | ||||
| 3338 | // Check that the variable is actually usable in constant expressions. For a | |||
| 3339 | // const integral variable or a reference, we might have a non-constant | |||
| 3340 | // initializer that we can nonetheless evaluate the initializer for. Such | |||
| 3341 | // variables are not usable in constant expressions. In C++98, the | |||
| 3342 | // initializer also syntactically needs to be an ICE. | |||
| 3343 | // | |||
| 3344 | // FIXME: We don't diagnose cases that aren't potentially usable in constant | |||
| 3345 | // expressions here; doing so would regress diagnostics for things like | |||
| 3346 | // reading from a volatile constexpr variable. | |||
| 3347 | if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && | |||
| 3348 | VD->mightBeUsableInConstantExpressions(Info.Ctx)) || | |||
| 3349 | ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && | |||
| 3350 | !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { | |||
| 3351 | Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; | |||
| 3352 | NoteLValueLocation(Info, Base); | |||
| 3353 | } | |||
| 3354 | ||||
| 3355 | // Never use the initializer of a weak variable, not even for constant | |||
| 3356 | // folding. We can't be sure that this is the definition that will be used. | |||
| 3357 | if (VD->isWeak()) { | |||
| 3358 | Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; | |||
| 3359 | NoteLValueLocation(Info, Base); | |||
| 3360 | return false; | |||
| 3361 | } | |||
| 3362 | ||||
| 3363 | Result = VD->getEvaluatedValue(); | |||
| 3364 | return true; | |||
| 3365 | } | |||
| 3366 | ||||
| 3367 | /// Get the base index of the given base class within an APValue representing | |||
| 3368 | /// the given derived class. | |||
| 3369 | static unsigned getBaseIndex(const CXXRecordDecl *Derived, | |||
| 3370 | const CXXRecordDecl *Base) { | |||
| 3371 | Base = Base->getCanonicalDecl(); | |||
| 3372 | unsigned Index = 0; | |||
| 3373 | for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), | |||
| 3374 | E = Derived->bases_end(); I != E; ++I, ++Index) { | |||
| 3375 | if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) | |||
| 3376 | return Index; | |||
| 3377 | } | |||
| 3378 | ||||
| 3379 | llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list" , "clang/lib/AST/ExprConstant.cpp", 3379); | |||
| 3380 | } | |||
| 3381 | ||||
| 3382 | /// Extract the value of a character from a string literal. | |||
| 3383 | static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, | |||
| 3384 | uint64_t Index) { | |||
| 3385 | assert(!isa<SourceLocExpr>(Lit) &&(static_cast <bool> (!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "clang/lib/AST/ExprConstant.cpp", 3386, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3386 | "SourceLocExpr should have already been converted to a StringLiteral")(static_cast <bool> (!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "clang/lib/AST/ExprConstant.cpp", 3386, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3387 | ||||
| 3388 | // FIXME: Support MakeStringConstant | |||
| 3389 | if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { | |||
| 3390 | std::string Str; | |||
| 3391 | Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); | |||
| 3392 | assert(Index <= Str.size() && "Index too large")(static_cast <bool> (Index <= Str.size() && "Index too large" ) ? void (0) : __assert_fail ("Index <= Str.size() && \"Index too large\"" , "clang/lib/AST/ExprConstant.cpp", 3392, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3393 | return APSInt::getUnsigned(Str.c_str()[Index]); | |||
| 3394 | } | |||
| 3395 | ||||
| 3396 | if (auto PE = dyn_cast<PredefinedExpr>(Lit)) | |||
| 3397 | Lit = PE->getFunctionName(); | |||
| 3398 | const StringLiteral *S = cast<StringLiteral>(Lit); | |||
| 3399 | const ConstantArrayType *CAT = | |||
| 3400 | Info.Ctx.getAsConstantArrayType(S->getType()); | |||
| 3401 | assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array" ) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "clang/lib/AST/ExprConstant.cpp", 3401, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3402 | QualType CharType = CAT->getElementType(); | |||
| 3403 | assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() && "unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "clang/lib/AST/ExprConstant.cpp", 3403, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3404 | ||||
| 3405 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | |||
| 3406 | CharType->isUnsignedIntegerType()); | |||
| 3407 | if (Index < S->getLength()) | |||
| 3408 | Value = S->getCodeUnit(Index); | |||
| 3409 | return Value; | |||
| 3410 | } | |||
| 3411 | ||||
| 3412 | // Expand a string literal into an array of characters. | |||
| 3413 | // | |||
| 3414 | // FIXME: This is inefficient; we should probably introduce something similar | |||
| 3415 | // to the LLVM ConstantDataArray to make this cheaper. | |||
| 3416 | static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, | |||
| 3417 | APValue &Result, | |||
| 3418 | QualType AllocType = QualType()) { | |||
| 3419 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | |||
| 3420 | AllocType.isNull() ? S->getType() : AllocType); | |||
| 3421 | assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array" ) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "clang/lib/AST/ExprConstant.cpp", 3421, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3422 | QualType CharType = CAT->getElementType(); | |||
| 3423 | assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() && "unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "clang/lib/AST/ExprConstant.cpp", 3423, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3424 | ||||
| 3425 | unsigned Elts = CAT->getSize().getZExtValue(); | |||
| 3426 | Result = APValue(APValue::UninitArray(), | |||
| 3427 | std::min(S->getLength(), Elts), Elts); | |||
| 3428 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | |||
| 3429 | CharType->isUnsignedIntegerType()); | |||
| 3430 | if (Result.hasArrayFiller()) | |||
| 3431 | Result.getArrayFiller() = APValue(Value); | |||
| 3432 | for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { | |||
| 3433 | Value = S->getCodeUnit(I); | |||
| 3434 | Result.getArrayInitializedElt(I) = APValue(Value); | |||
| 3435 | } | |||
| 3436 | } | |||
| 3437 | ||||
| 3438 | // Expand an array so that it has more than Index filled elements. | |||
| 3439 | static void expandArray(APValue &Array, unsigned Index) { | |||
| 3440 | unsigned Size = Array.getArraySize(); | |||
| 3441 | assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail ("Index < Size", "clang/lib/AST/ExprConstant.cpp", 3441, __extension__ __PRETTY_FUNCTION__)); | |||
| 3442 | ||||
| 3443 | // Always at least double the number of elements for which we store a value. | |||
| 3444 | unsigned OldElts = Array.getArrayInitializedElts(); | |||
| 3445 | unsigned NewElts = std::max(Index+1, OldElts * 2); | |||
| 3446 | NewElts = std::min(Size, std::max(NewElts, 8u)); | |||
| 3447 | ||||
| 3448 | // Copy the data across. | |||
| 3449 | APValue NewValue(APValue::UninitArray(), NewElts, Size); | |||
| 3450 | for (unsigned I = 0; I != OldElts; ++I) | |||
| 3451 | NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); | |||
| 3452 | for (unsigned I = OldElts; I != NewElts; ++I) | |||
| 3453 | NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); | |||
| 3454 | if (NewValue.hasArrayFiller()) | |||
| 3455 | NewValue.getArrayFiller() = Array.getArrayFiller(); | |||
| 3456 | Array.swap(NewValue); | |||
| 3457 | } | |||
| 3458 | ||||
| 3459 | /// Determine whether a type would actually be read by an lvalue-to-rvalue | |||
| 3460 | /// conversion. If it's of class type, we may assume that the copy operation | |||
| 3461 | /// is trivial. Note that this is never true for a union type with fields | |||
| 3462 | /// (because the copy always "reads" the active member) and always true for | |||
| 3463 | /// a non-class type. | |||
| 3464 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); | |||
| 3465 | static bool isReadByLvalueToRvalueConversion(QualType T) { | |||
| 3466 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
| 3467 | return !RD || isReadByLvalueToRvalueConversion(RD); | |||
| 3468 | } | |||
| 3469 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { | |||
| 3470 | // FIXME: A trivial copy of a union copies the object representation, even if | |||
| 3471 | // the union is empty. | |||
| 3472 | if (RD->isUnion()) | |||
| 3473 | return !RD->field_empty(); | |||
| 3474 | if (RD->isEmpty()) | |||
| 3475 | return false; | |||
| 3476 | ||||
| 3477 | for (auto *Field : RD->fields()) | |||
| 3478 | if (!Field->isUnnamedBitfield() && | |||
| 3479 | isReadByLvalueToRvalueConversion(Field->getType())) | |||
| 3480 | return true; | |||
| 3481 | ||||
| 3482 | for (auto &BaseSpec : RD->bases()) | |||
| 3483 | if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) | |||
| 3484 | return true; | |||
| 3485 | ||||
| 3486 | return false; | |||
| 3487 | } | |||
| 3488 | ||||
| 3489 | /// Diagnose an attempt to read from any unreadable field within the specified | |||
| 3490 | /// type, which might be a class type. | |||
| 3491 | static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, | |||
| 3492 | QualType T) { | |||
| 3493 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
| 3494 | if (!RD) | |||
| 3495 | return false; | |||
| 3496 | ||||
| 3497 | if (!RD->hasMutableFields()) | |||
| 3498 | return false; | |||
| 3499 | ||||
| 3500 | for (auto *Field : RD->fields()) { | |||
| 3501 | // If we're actually going to read this field in some way, then it can't | |||
| 3502 | // be mutable. If we're in a union, then assigning to a mutable field | |||
| 3503 | // (even an empty one) can change the active member, so that's not OK. | |||
| 3504 | // FIXME: Add core issue number for the union case. | |||
| 3505 | if (Field->isMutable() && | |||
| 3506 | (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { | |||
| 3507 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; | |||
| 3508 | Info.Note(Field->getLocation(), diag::note_declared_at); | |||
| 3509 | return true; | |||
| 3510 | } | |||
| 3511 | ||||
| 3512 | if (diagnoseMutableFields(Info, E, AK, Field->getType())) | |||
| 3513 | return true; | |||
| 3514 | } | |||
| 3515 | ||||
| 3516 | for (auto &BaseSpec : RD->bases()) | |||
| 3517 | if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) | |||
| 3518 | return true; | |||
| 3519 | ||||
| 3520 | // All mutable fields were empty, and thus not actually read. | |||
| 3521 | return false; | |||
| 3522 | } | |||
| 3523 | ||||
| 3524 | static bool lifetimeStartedInEvaluation(EvalInfo &Info, | |||
| 3525 | APValue::LValueBase Base, | |||
| 3526 | bool MutableSubobject = false) { | |||
| 3527 | // A temporary or transient heap allocation we created. | |||
| 3528 | if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) | |||
| 3529 | return true; | |||
| 3530 | ||||
| 3531 | switch (Info.IsEvaluatingDecl) { | |||
| 3532 | case EvalInfo::EvaluatingDeclKind::None: | |||
| 3533 | return false; | |||
| 3534 | ||||
| 3535 | case EvalInfo::EvaluatingDeclKind::Ctor: | |||
| 3536 | // The variable whose initializer we're evaluating. | |||
| 3537 | if (Info.EvaluatingDecl == Base) | |||
| 3538 | return true; | |||
| 3539 | ||||
| 3540 | // A temporary lifetime-extended by the variable whose initializer we're | |||
| 3541 | // evaluating. | |||
| 3542 | if (auto *BaseE = Base.dyn_cast<const Expr *>()) | |||
| 3543 | if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) | |||
| 3544 | return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); | |||
| 3545 | return false; | |||
| 3546 | ||||
| 3547 | case EvalInfo::EvaluatingDeclKind::Dtor: | |||
| 3548 | // C++2a [expr.const]p6: | |||
| 3549 | // [during constant destruction] the lifetime of a and its non-mutable | |||
| 3550 | // subobjects (but not its mutable subobjects) [are] considered to start | |||
| 3551 | // within e. | |||
| 3552 | if (MutableSubobject || Base != Info.EvaluatingDecl) | |||
| 3553 | return false; | |||
| 3554 | // FIXME: We can meaningfully extend this to cover non-const objects, but | |||
| 3555 | // we will need special handling: we should be able to access only | |||
| 3556 | // subobjects of such objects that are themselves declared const. | |||
| 3557 | QualType T = getType(Base); | |||
| 3558 | return T.isConstQualified() || T->isReferenceType(); | |||
| 3559 | } | |||
| 3560 | ||||
| 3561 | llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind" , "clang/lib/AST/ExprConstant.cpp", 3561); | |||
| 3562 | } | |||
| 3563 | ||||
| 3564 | namespace { | |||
| 3565 | /// A handle to a complete object (an object that is not a subobject of | |||
| 3566 | /// another object). | |||
| 3567 | struct CompleteObject { | |||
| 3568 | /// The identity of the object. | |||
| 3569 | APValue::LValueBase Base; | |||
| 3570 | /// The value of the complete object. | |||
| 3571 | APValue *Value; | |||
| 3572 | /// The type of the complete object. | |||
| 3573 | QualType Type; | |||
| 3574 | ||||
| 3575 | CompleteObject() : Value(nullptr) {} | |||
| 3576 | CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) | |||
| 3577 | : Base(Base), Value(Value), Type(Type) {} | |||
| 3578 | ||||
| 3579 | bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { | |||
| 3580 | // If this isn't a "real" access (eg, if it's just accessing the type | |||
| 3581 | // info), allow it. We assume the type doesn't change dynamically for | |||
| 3582 | // subobjects of constexpr objects (even though we'd hit UB here if it | |||
| 3583 | // did). FIXME: Is this right? | |||
| 3584 | if (!isAnyAccess(AK)) | |||
| 3585 | return true; | |||
| 3586 | ||||
| 3587 | // In C++14 onwards, it is permitted to read a mutable member whose | |||
| 3588 | // lifetime began within the evaluation. | |||
| 3589 | // FIXME: Should we also allow this in C++11? | |||
| 3590 | if (!Info.getLangOpts().CPlusPlus14) | |||
| 3591 | return false; | |||
| 3592 | return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); | |||
| 3593 | } | |||
| 3594 | ||||
| 3595 | explicit operator bool() const { return !Type.isNull(); } | |||
| 3596 | }; | |||
| 3597 | } // end anonymous namespace | |||
| 3598 | ||||
| 3599 | static QualType getSubobjectType(QualType ObjType, QualType SubobjType, | |||
| 3600 | bool IsMutable = false) { | |||
| 3601 | // C++ [basic.type.qualifier]p1: | |||
| 3602 | // - A const object is an object of type const T or a non-mutable subobject | |||
| 3603 | // of a const object. | |||
| 3604 | if (ObjType.isConstQualified() && !IsMutable) | |||
| 3605 | SubobjType.addConst(); | |||
| 3606 | // - A volatile object is an object of type const T or a subobject of a | |||
| 3607 | // volatile object. | |||
| 3608 | if (ObjType.isVolatileQualified()) | |||
| 3609 | SubobjType.addVolatile(); | |||
| 3610 | return SubobjType; | |||
| 3611 | } | |||
| 3612 | ||||
| 3613 | /// Find the designated sub-object of an rvalue. | |||
| 3614 | template<typename SubobjectHandler> | |||
| 3615 | typename SubobjectHandler::result_type | |||
| 3616 | findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, | |||
| 3617 | const SubobjectDesignator &Sub, SubobjectHandler &handler) { | |||
| 3618 | if (Sub.Invalid) | |||
| 3619 | // A diagnostic will have already been produced. | |||
| 3620 | return handler.failed(); | |||
| 3621 | if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { | |||
| 3622 | if (Info.getLangOpts().CPlusPlus11) | |||
| 3623 | Info.FFDiag(E, Sub.isOnePastTheEnd() | |||
| 3624 | ? diag::note_constexpr_access_past_end | |||
| 3625 | : diag::note_constexpr_access_unsized_array) | |||
| 3626 | << handler.AccessKind; | |||
| 3627 | else | |||
| 3628 | Info.FFDiag(E); | |||
| 3629 | return handler.failed(); | |||
| 3630 | } | |||
| 3631 | ||||
| 3632 | APValue *O = Obj.Value; | |||
| 3633 | QualType ObjType = Obj.Type; | |||
| 3634 | const FieldDecl *LastField = nullptr; | |||
| 3635 | const FieldDecl *VolatileField = nullptr; | |||
| 3636 | ||||
| 3637 | // Walk the designator's path to find the subobject. | |||
| 3638 | for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { | |||
| 3639 | // Reading an indeterminate value is undefined, but assigning over one is OK. | |||
| 3640 | if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || | |||
| 3641 | (O->isIndeterminate() && | |||
| 3642 | !isValidIndeterminateAccess(handler.AccessKind))) { | |||
| 3643 | if (!Info.checkingPotentialConstantExpression()) | |||
| 3644 | Info.FFDiag(E, diag::note_constexpr_access_uninit) | |||
| 3645 | << handler.AccessKind << O->isIndeterminate(); | |||
| 3646 | return handler.failed(); | |||
| 3647 | } | |||
| 3648 | ||||
| 3649 | // C++ [class.ctor]p5, C++ [class.dtor]p5: | |||
| 3650 | // const and volatile semantics are not applied on an object under | |||
| 3651 | // {con,de}struction. | |||
| 3652 | if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && | |||
| 3653 | ObjType->isRecordType() && | |||
| 3654 | Info.isEvaluatingCtorDtor( | |||
| 3655 | Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), | |||
| 3656 | Sub.Entries.begin() + I)) != | |||
| 3657 | ConstructionPhase::None) { | |||
| 3658 | ObjType = Info.Ctx.getCanonicalType(ObjType); | |||
| 3659 | ObjType.removeLocalConst(); | |||
| 3660 | ObjType.removeLocalVolatile(); | |||
| 3661 | } | |||
| 3662 | ||||
| 3663 | // If this is our last pass, check that the final object type is OK. | |||
| 3664 | if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { | |||
| 3665 | // Accesses to volatile objects are prohibited. | |||
| 3666 | if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { | |||
| 3667 | if (Info.getLangOpts().CPlusPlus) { | |||
| 3668 | int DiagKind; | |||
| 3669 | SourceLocation Loc; | |||
| 3670 | const NamedDecl *Decl = nullptr; | |||
| 3671 | if (VolatileField) { | |||
| 3672 | DiagKind = 2; | |||
| 3673 | Loc = VolatileField->getLocation(); | |||
| 3674 | Decl = VolatileField; | |||
| 3675 | } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { | |||
| 3676 | DiagKind = 1; | |||
| 3677 | Loc = VD->getLocation(); | |||
| 3678 | Decl = VD; | |||
| 3679 | } else { | |||
| 3680 | DiagKind = 0; | |||
| 3681 | if (auto *E = Obj.Base.dyn_cast<const Expr *>()) | |||
| 3682 | Loc = E->getExprLoc(); | |||
| 3683 | } | |||
| 3684 | Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) | |||
| 3685 | << handler.AccessKind << DiagKind << Decl; | |||
| 3686 | Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; | |||
| 3687 | } else { | |||
| 3688 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 3689 | } | |||
| 3690 | return handler.failed(); | |||
| 3691 | } | |||
| 3692 | ||||
| 3693 | // If we are reading an object of class type, there may still be more | |||
| 3694 | // things we need to check: if there are any mutable subobjects, we | |||
| 3695 | // cannot perform this read. (This only happens when performing a trivial | |||
| 3696 | // copy or assignment.) | |||
| 3697 | if (ObjType->isRecordType() && | |||
| 3698 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && | |||
| 3699 | diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) | |||
| 3700 | return handler.failed(); | |||
| 3701 | } | |||
| 3702 | ||||
| 3703 | if (I == N) { | |||
| 3704 | if (!handler.found(*O, ObjType)) | |||
| 3705 | return false; | |||
| 3706 | ||||
| 3707 | // If we modified a bit-field, truncate it to the right width. | |||
| 3708 | if (isModification(handler.AccessKind) && | |||
| 3709 | LastField && LastField->isBitField() && | |||
| 3710 | !truncateBitfieldValue(Info, E, *O, LastField)) | |||
| 3711 | return false; | |||
| 3712 | ||||
| 3713 | return true; | |||
| 3714 | } | |||
| 3715 | ||||
| 3716 | LastField = nullptr; | |||
| 3717 | if (ObjType->isArrayType()) { | |||
| 3718 | // Next subobject is an array element. | |||
| 3719 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); | |||
| 3720 | assert(CAT && "vla in literal type?")(static_cast <bool> (CAT && "vla in literal type?" ) ? void (0) : __assert_fail ("CAT && \"vla in literal type?\"" , "clang/lib/AST/ExprConstant.cpp", 3720, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3721 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | |||
| 3722 | if (CAT->getSize().ule(Index)) { | |||
| 3723 | // Note, it should not be possible to form a pointer with a valid | |||
| 3724 | // designator which points more than one past the end of the array. | |||
| 3725 | if (Info.getLangOpts().CPlusPlus11) | |||
| 3726 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | |||
| 3727 | << handler.AccessKind; | |||
| 3728 | else | |||
| 3729 | Info.FFDiag(E); | |||
| 3730 | return handler.failed(); | |||
| 3731 | } | |||
| 3732 | ||||
| 3733 | ObjType = CAT->getElementType(); | |||
| 3734 | ||||
| 3735 | if (O->getArrayInitializedElts() > Index) | |||
| 3736 | O = &O->getArrayInitializedElt(Index); | |||
| 3737 | else if (!isRead(handler.AccessKind)) { | |||
| 3738 | expandArray(*O, Index); | |||
| 3739 | O = &O->getArrayInitializedElt(Index); | |||
| 3740 | } else | |||
| 3741 | O = &O->getArrayFiller(); | |||
| 3742 | } else if (ObjType->isAnyComplexType()) { | |||
| 3743 | // Next subobject is a complex number. | |||
| 3744 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | |||
| 3745 | if (Index > 1) { | |||
| 3746 | if (Info.getLangOpts().CPlusPlus11) | |||
| 3747 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | |||
| 3748 | << handler.AccessKind; | |||
| 3749 | else | |||
| 3750 | Info.FFDiag(E); | |||
| 3751 | return handler.failed(); | |||
| 3752 | } | |||
| 3753 | ||||
| 3754 | ObjType = getSubobjectType( | |||
| 3755 | ObjType, ObjType->castAs<ComplexType>()->getElementType()); | |||
| 3756 | ||||
| 3757 | assert(I == N - 1 && "extracting subobject of scalar?")(static_cast <bool> (I == N - 1 && "extracting subobject of scalar?" ) ? void (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\"" , "clang/lib/AST/ExprConstant.cpp", 3757, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3758 | if (O->isComplexInt()) { | |||
| 3759 | return handler.found(Index ? O->getComplexIntImag() | |||
| 3760 | : O->getComplexIntReal(), ObjType); | |||
| 3761 | } else { | |||
| 3762 | assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0) : __assert_fail ("O->isComplexFloat()", "clang/lib/AST/ExprConstant.cpp" , 3762, __extension__ __PRETTY_FUNCTION__)); | |||
| 3763 | return handler.found(Index ? O->getComplexFloatImag() | |||
| 3764 | : O->getComplexFloatReal(), ObjType); | |||
| 3765 | } | |||
| 3766 | } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { | |||
| 3767 | if (Field->isMutable() && | |||
| 3768 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { | |||
| 3769 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) | |||
| 3770 | << handler.AccessKind << Field; | |||
| 3771 | Info.Note(Field->getLocation(), diag::note_declared_at); | |||
| 3772 | return handler.failed(); | |||
| 3773 | } | |||
| 3774 | ||||
| 3775 | // Next subobject is a class, struct or union field. | |||
| 3776 | RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); | |||
| 3777 | if (RD->isUnion()) { | |||
| 3778 | const FieldDecl *UnionField = O->getUnionField(); | |||
| 3779 | if (!UnionField || | |||
| 3780 | UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { | |||
| 3781 | if (I == N - 1 && handler.AccessKind == AK_Construct) { | |||
| 3782 | // Placement new onto an inactive union member makes it active. | |||
| 3783 | O->setUnion(Field, APValue()); | |||
| 3784 | } else { | |||
| 3785 | // FIXME: If O->getUnionValue() is absent, report that there's no | |||
| 3786 | // active union member rather than reporting the prior active union | |||
| 3787 | // member. We'll need to fix nullptr_t to not use APValue() as its | |||
| 3788 | // representation first. | |||
| 3789 | Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) | |||
| 3790 | << handler.AccessKind << Field << !UnionField << UnionField; | |||
| 3791 | return handler.failed(); | |||
| 3792 | } | |||
| 3793 | } | |||
| 3794 | O = &O->getUnionValue(); | |||
| 3795 | } else | |||
| 3796 | O = &O->getStructField(Field->getFieldIndex()); | |||
| 3797 | ||||
| 3798 | ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); | |||
| 3799 | LastField = Field; | |||
| 3800 | if (Field->getType().isVolatileQualified()) | |||
| 3801 | VolatileField = Field; | |||
| 3802 | } else { | |||
| 3803 | // Next subobject is a base class. | |||
| 3804 | const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); | |||
| 3805 | const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); | |||
| 3806 | O = &O->getStructBase(getBaseIndex(Derived, Base)); | |||
| 3807 | ||||
| 3808 | ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); | |||
| 3809 | } | |||
| 3810 | } | |||
| 3811 | } | |||
| 3812 | ||||
| 3813 | namespace { | |||
| 3814 | struct ExtractSubobjectHandler { | |||
| 3815 | EvalInfo &Info; | |||
| 3816 | const Expr *E; | |||
| 3817 | APValue &Result; | |||
| 3818 | const AccessKinds AccessKind; | |||
| 3819 | ||||
| 3820 | typedef bool result_type; | |||
| 3821 | bool failed() { return false; } | |||
| 3822 | bool found(APValue &Subobj, QualType SubobjType) { | |||
| 3823 | Result = Subobj; | |||
| 3824 | if (AccessKind == AK_ReadObjectRepresentation) | |||
| 3825 | return true; | |||
| 3826 | return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); | |||
| 3827 | } | |||
| 3828 | bool found(APSInt &Value, QualType SubobjType) { | |||
| 3829 | Result = APValue(Value); | |||
| 3830 | return true; | |||
| 3831 | } | |||
| 3832 | bool found(APFloat &Value, QualType SubobjType) { | |||
| 3833 | Result = APValue(Value); | |||
| 3834 | return true; | |||
| 3835 | } | |||
| 3836 | }; | |||
| 3837 | } // end anonymous namespace | |||
| 3838 | ||||
| 3839 | /// Extract the designated sub-object of an rvalue. | |||
| 3840 | static bool extractSubobject(EvalInfo &Info, const Expr *E, | |||
| 3841 | const CompleteObject &Obj, | |||
| 3842 | const SubobjectDesignator &Sub, APValue &Result, | |||
| 3843 | AccessKinds AK = AK_Read) { | |||
| 3844 | assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)(static_cast <bool> (AK == AK_Read || AK == AK_ReadObjectRepresentation ) ? void (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation" , "clang/lib/AST/ExprConstant.cpp", 3844, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3845 | ExtractSubobjectHandler Handler = {Info, E, Result, AK}; | |||
| 3846 | return findSubobject(Info, E, Obj, Sub, Handler); | |||
| 3847 | } | |||
| 3848 | ||||
| 3849 | namespace { | |||
| 3850 | struct ModifySubobjectHandler { | |||
| 3851 | EvalInfo &Info; | |||
| 3852 | APValue &NewVal; | |||
| 3853 | const Expr *E; | |||
| 3854 | ||||
| 3855 | typedef bool result_type; | |||
| 3856 | static const AccessKinds AccessKind = AK_Assign; | |||
| 3857 | ||||
| 3858 | bool checkConst(QualType QT) { | |||
| 3859 | // Assigning to a const object has undefined behavior. | |||
| 3860 | if (QT.isConstQualified()) { | |||
| 3861 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | |||
| 3862 | return false; | |||
| 3863 | } | |||
| 3864 | return true; | |||
| 3865 | } | |||
| 3866 | ||||
| 3867 | bool failed() { return false; } | |||
| 3868 | bool found(APValue &Subobj, QualType SubobjType) { | |||
| 3869 | if (!checkConst(SubobjType)) | |||
| 3870 | return false; | |||
| 3871 | // We've been given ownership of NewVal, so just swap it in. | |||
| 3872 | Subobj.swap(NewVal); | |||
| 3873 | return true; | |||
| 3874 | } | |||
| 3875 | bool found(APSInt &Value, QualType SubobjType) { | |||
| 3876 | if (!checkConst(SubobjType)) | |||
| 3877 | return false; | |||
| 3878 | if (!NewVal.isInt()) { | |||
| 3879 | // Maybe trying to write a cast pointer value into a complex? | |||
| 3880 | Info.FFDiag(E); | |||
| 3881 | return false; | |||
| 3882 | } | |||
| 3883 | Value = NewVal.getInt(); | |||
| 3884 | return true; | |||
| 3885 | } | |||
| 3886 | bool found(APFloat &Value, QualType SubobjType) { | |||
| 3887 | if (!checkConst(SubobjType)) | |||
| 3888 | return false; | |||
| 3889 | Value = NewVal.getFloat(); | |||
| 3890 | return true; | |||
| 3891 | } | |||
| 3892 | }; | |||
| 3893 | } // end anonymous namespace | |||
| 3894 | ||||
| 3895 | const AccessKinds ModifySubobjectHandler::AccessKind; | |||
| 3896 | ||||
| 3897 | /// Update the designated sub-object of an rvalue to the given value. | |||
| 3898 | static bool modifySubobject(EvalInfo &Info, const Expr *E, | |||
| 3899 | const CompleteObject &Obj, | |||
| 3900 | const SubobjectDesignator &Sub, | |||
| 3901 | APValue &NewVal) { | |||
| 3902 | ModifySubobjectHandler Handler = { Info, NewVal, E }; | |||
| 3903 | return findSubobject(Info, E, Obj, Sub, Handler); | |||
| 3904 | } | |||
| 3905 | ||||
| 3906 | /// Find the position where two subobject designators diverge, or equivalently | |||
| 3907 | /// the length of the common initial subsequence. | |||
| 3908 | static unsigned FindDesignatorMismatch(QualType ObjType, | |||
| 3909 | const SubobjectDesignator &A, | |||
| 3910 | const SubobjectDesignator &B, | |||
| 3911 | bool &WasArrayIndex) { | |||
| 3912 | unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); | |||
| 3913 | for (/**/; I != N; ++I) { | |||
| 3914 | if (!ObjType.isNull() && | |||
| 3915 | (ObjType->isArrayType() || ObjType->isAnyComplexType())) { | |||
| 3916 | // Next subobject is an array element. | |||
| 3917 | if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { | |||
| 3918 | WasArrayIndex = true; | |||
| 3919 | return I; | |||
| 3920 | } | |||
| 3921 | if (ObjType->isAnyComplexType()) | |||
| 3922 | ObjType = ObjType->castAs<ComplexType>()->getElementType(); | |||
| 3923 | else | |||
| 3924 | ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); | |||
| 3925 | } else { | |||
| 3926 | if (A.Entries[I].getAsBaseOrMember() != | |||
| 3927 | B.Entries[I].getAsBaseOrMember()) { | |||
| 3928 | WasArrayIndex = false; | |||
| 3929 | return I; | |||
| 3930 | } | |||
| 3931 | if (const FieldDecl *FD = getAsField(A.Entries[I])) | |||
| 3932 | // Next subobject is a field. | |||
| 3933 | ObjType = FD->getType(); | |||
| 3934 | else | |||
| 3935 | // Next subobject is a base class. | |||
| 3936 | ObjType = QualType(); | |||
| 3937 | } | |||
| 3938 | } | |||
| 3939 | WasArrayIndex = false; | |||
| 3940 | return I; | |||
| 3941 | } | |||
| 3942 | ||||
| 3943 | /// Determine whether the given subobject designators refer to elements of the | |||
| 3944 | /// same array object. | |||
| 3945 | static bool AreElementsOfSameArray(QualType ObjType, | |||
| 3946 | const SubobjectDesignator &A, | |||
| 3947 | const SubobjectDesignator &B) { | |||
| 3948 | if (A.Entries.size() != B.Entries.size()) | |||
| 3949 | return false; | |||
| 3950 | ||||
| 3951 | bool IsArray = A.MostDerivedIsArrayElement; | |||
| 3952 | if (IsArray && A.MostDerivedPathLength != A.Entries.size()) | |||
| 3953 | // A is a subobject of the array element. | |||
| 3954 | return false; | |||
| 3955 | ||||
| 3956 | // If A (and B) designates an array element, the last entry will be the array | |||
| 3957 | // index. That doesn't have to match. Otherwise, we're in the 'implicit array | |||
| 3958 | // of length 1' case, and the entire path must match. | |||
| 3959 | bool WasArrayIndex; | |||
| 3960 | unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); | |||
| 3961 | return CommonLength >= A.Entries.size() - IsArray; | |||
| 3962 | } | |||
| 3963 | ||||
| 3964 | /// Find the complete object to which an LValue refers. | |||
| 3965 | static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, | |||
| 3966 | AccessKinds AK, const LValue &LVal, | |||
| 3967 | QualType LValType) { | |||
| 3968 | if (LVal.InvalidBase) { | |||
| 3969 | Info.FFDiag(E); | |||
| 3970 | return CompleteObject(); | |||
| 3971 | } | |||
| 3972 | ||||
| 3973 | if (!LVal.Base) { | |||
| 3974 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | |||
| 3975 | return CompleteObject(); | |||
| 3976 | } | |||
| 3977 | ||||
| 3978 | CallStackFrame *Frame = nullptr; | |||
| 3979 | unsigned Depth = 0; | |||
| 3980 | if (LVal.getLValueCallIndex()) { | |||
| 3981 | std::tie(Frame, Depth) = | |||
| 3982 | Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); | |||
| 3983 | if (!Frame) { | |||
| 3984 | Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) | |||
| 3985 | << AK << LVal.Base.is<const ValueDecl*>(); | |||
| 3986 | NoteLValueLocation(Info, LVal.Base); | |||
| 3987 | return CompleteObject(); | |||
| 3988 | } | |||
| 3989 | } | |||
| 3990 | ||||
| 3991 | bool IsAccess = isAnyAccess(AK); | |||
| 3992 | ||||
| 3993 | // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type | |||
| 3994 | // is not a constant expression (even if the object is non-volatile). We also | |||
| 3995 | // apply this rule to C++98, in order to conform to the expected 'volatile' | |||
| 3996 | // semantics. | |||
| 3997 | if (isFormalAccess(AK) && LValType.isVolatileQualified()) { | |||
| 3998 | if (Info.getLangOpts().CPlusPlus) | |||
| 3999 | Info.FFDiag(E, diag::note_constexpr_access_volatile_type) | |||
| 4000 | << AK << LValType; | |||
| 4001 | else | |||
| 4002 | Info.FFDiag(E); | |||
| 4003 | return CompleteObject(); | |||
| 4004 | } | |||
| 4005 | ||||
| 4006 | // Compute value storage location and type of base object. | |||
| 4007 | APValue *BaseVal = nullptr; | |||
| 4008 | QualType BaseType = getType(LVal.Base); | |||
| 4009 | ||||
| 4010 | if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && | |||
| 4011 | lifetimeStartedInEvaluation(Info, LVal.Base)) { | |||
| 4012 | // This is the object whose initializer we're evaluating, so its lifetime | |||
| 4013 | // started in the current evaluation. | |||
| 4014 | BaseVal = Info.EvaluatingDeclValue; | |||
| 4015 | } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { | |||
| 4016 | // Allow reading from a GUID declaration. | |||
| 4017 | if (auto *GD = dyn_cast<MSGuidDecl>(D)) { | |||
| 4018 | if (isModification(AK)) { | |||
| 4019 | // All the remaining cases do not permit modification of the object. | |||
| 4020 | Info.FFDiag(E, diag::note_constexpr_modify_global); | |||
| 4021 | return CompleteObject(); | |||
| 4022 | } | |||
| 4023 | APValue &V = GD->getAsAPValue(); | |||
| 4024 | if (V.isAbsent()) { | |||
| 4025 | Info.FFDiag(E, diag::note_constexpr_unsupported_layout) | |||
| 4026 | << GD->getType(); | |||
| 4027 | return CompleteObject(); | |||
| 4028 | } | |||
| 4029 | return CompleteObject(LVal.Base, &V, GD->getType()); | |||
| 4030 | } | |||
| 4031 | ||||
| 4032 | // Allow reading the APValue from an UnnamedGlobalConstantDecl. | |||
| 4033 | if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) { | |||
| 4034 | if (isModification(AK)) { | |||
| 4035 | Info.FFDiag(E, diag::note_constexpr_modify_global); | |||
| 4036 | return CompleteObject(); | |||
| 4037 | } | |||
| 4038 | return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), | |||
| 4039 | GCD->getType()); | |||
| 4040 | } | |||
| 4041 | ||||
| 4042 | // Allow reading from template parameter objects. | |||
| 4043 | if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { | |||
| 4044 | if (isModification(AK)) { | |||
| 4045 | Info.FFDiag(E, diag::note_constexpr_modify_global); | |||
| 4046 | return CompleteObject(); | |||
| 4047 | } | |||
| 4048 | return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), | |||
| 4049 | TPO->getType()); | |||
| 4050 | } | |||
| 4051 | ||||
| 4052 | // In C++98, const, non-volatile integers initialized with ICEs are ICEs. | |||
| 4053 | // In C++11, constexpr, non-volatile variables initialized with constant | |||
| 4054 | // expressions are constant expressions too. Inside constexpr functions, | |||
| 4055 | // parameters are constant expressions even if they're non-const. | |||
| 4056 | // In C++1y, objects local to a constant expression (those with a Frame) are | |||
| 4057 | // both readable and writable inside constant expressions. | |||
| 4058 | // In C, such things can also be folded, although they are not ICEs. | |||
| 4059 | const VarDecl *VD = dyn_cast<VarDecl>(D); | |||
| 4060 | if (VD) { | |||
| 4061 | if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) | |||
| 4062 | VD = VDef; | |||
| 4063 | } | |||
| 4064 | if (!VD || VD->isInvalidDecl()) { | |||
| 4065 | Info.FFDiag(E); | |||
| 4066 | return CompleteObject(); | |||
| 4067 | } | |||
| 4068 | ||||
| 4069 | bool IsConstant = BaseType.isConstant(Info.Ctx); | |||
| 4070 | ||||
| 4071 | // Unless we're looking at a local variable or argument in a constexpr call, | |||
| 4072 | // the variable we're reading must be const. | |||
| 4073 | if (!Frame) { | |||
| 4074 | if (IsAccess && isa<ParmVarDecl>(VD)) { | |||
| 4075 | // Access of a parameter that's not associated with a frame isn't going | |||
| 4076 | // to work out, but we can leave it to evaluateVarDeclInit to provide a | |||
| 4077 | // suitable diagnostic. | |||
| 4078 | } else if (Info.getLangOpts().CPlusPlus14 && | |||
| 4079 | lifetimeStartedInEvaluation(Info, LVal.Base)) { | |||
| 4080 | // OK, we can read and modify an object if we're in the process of | |||
| 4081 | // evaluating its initializer, because its lifetime began in this | |||
| 4082 | // evaluation. | |||
| 4083 | } else if (isModification(AK)) { | |||
| 4084 | // All the remaining cases do not permit modification of the object. | |||
| 4085 | Info.FFDiag(E, diag::note_constexpr_modify_global); | |||
| 4086 | return CompleteObject(); | |||
| 4087 | } else if (VD->isConstexpr()) { | |||
| 4088 | // OK, we can read this variable. | |||
| 4089 | } else if (BaseType->isIntegralOrEnumerationType()) { | |||
| 4090 | if (!IsConstant) { | |||
| 4091 | if (!IsAccess) | |||
| 4092 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | |||
| 4093 | if (Info.getLangOpts().CPlusPlus) { | |||
| 4094 | Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; | |||
| 4095 | Info.Note(VD->getLocation(), diag::note_declared_at); | |||
| 4096 | } else { | |||
| 4097 | Info.FFDiag(E); | |||
| 4098 | } | |||
| 4099 | return CompleteObject(); | |||
| 4100 | } | |||
| 4101 | } else if (!IsAccess) { | |||
| 4102 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | |||
| 4103 | } else if (IsConstant && Info.checkingPotentialConstantExpression() && | |||
| 4104 | BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { | |||
| 4105 | // This variable might end up being constexpr. Don't diagnose it yet. | |||
| 4106 | } else if (IsConstant) { | |||
| 4107 | // Keep evaluating to see what we can do. In particular, we support | |||
| 4108 | // folding of const floating-point types, in order to make static const | |||
| 4109 | // data members of such types (supported as an extension) more useful. | |||
| 4110 | if (Info.getLangOpts().CPlusPlus) { | |||
| 4111 | Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 | |||
| 4112 | ? diag::note_constexpr_ltor_non_constexpr | |||
| 4113 | : diag::note_constexpr_ltor_non_integral, 1) | |||
| 4114 | << VD << BaseType; | |||
| 4115 | Info.Note(VD->getLocation(), diag::note_declared_at); | |||
| 4116 | } else { | |||
| 4117 | Info.CCEDiag(E); | |||
| 4118 | } | |||
| 4119 | } else { | |||
| 4120 | // Never allow reading a non-const value. | |||
| 4121 | if (Info.getLangOpts().CPlusPlus) { | |||
| 4122 | Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 | |||
| 4123 | ? diag::note_constexpr_ltor_non_constexpr | |||
| 4124 | : diag::note_constexpr_ltor_non_integral, 1) | |||
| 4125 | << VD << BaseType; | |||
| 4126 | Info.Note(VD->getLocation(), diag::note_declared_at); | |||
| 4127 | } else { | |||
| 4128 | Info.FFDiag(E); | |||
| 4129 | } | |||
| 4130 | return CompleteObject(); | |||
| 4131 | } | |||
| 4132 | } | |||
| 4133 | ||||
| 4134 | if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) | |||
| 4135 | return CompleteObject(); | |||
| 4136 | } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { | |||
| 4137 | Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); | |||
| 4138 | if (!Alloc) { | |||
| 4139 | Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; | |||
| 4140 | return CompleteObject(); | |||
| 4141 | } | |||
| 4142 | return CompleteObject(LVal.Base, &(*Alloc)->Value, | |||
| 4143 | LVal.Base.getDynamicAllocType()); | |||
| 4144 | } else { | |||
| 4145 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | |||
| 4146 | ||||
| 4147 | if (!Frame) { | |||
| 4148 | if (const MaterializeTemporaryExpr *MTE = | |||
| 4149 | dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { | |||
| 4150 | assert(MTE->getStorageDuration() == SD_Static &&(static_cast <bool> (MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4151, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4151 | "should have a frame for a non-global materialized temporary")(static_cast <bool> (MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4151, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4152 | ||||
| 4153 | // C++20 [expr.const]p4: [DR2126] | |||
| 4154 | // An object or reference is usable in constant expressions if it is | |||
| 4155 | // - a temporary object of non-volatile const-qualified literal type | |||
| 4156 | // whose lifetime is extended to that of a variable that is usable | |||
| 4157 | // in constant expressions | |||
| 4158 | // | |||
| 4159 | // C++20 [expr.const]p5: | |||
| 4160 | // an lvalue-to-rvalue conversion [is not allowed unless it applies to] | |||
| 4161 | // - a non-volatile glvalue that refers to an object that is usable | |||
| 4162 | // in constant expressions, or | |||
| 4163 | // - a non-volatile glvalue of literal type that refers to a | |||
| 4164 | // non-volatile object whose lifetime began within the evaluation | |||
| 4165 | // of E; | |||
| 4166 | // | |||
| 4167 | // C++11 misses the 'began within the evaluation of e' check and | |||
| 4168 | // instead allows all temporaries, including things like: | |||
| 4169 | // int &&r = 1; | |||
| 4170 | // int x = ++r; | |||
| 4171 | // constexpr int k = r; | |||
| 4172 | // Therefore we use the C++14-onwards rules in C++11 too. | |||
| 4173 | // | |||
| 4174 | // Note that temporaries whose lifetimes began while evaluating a | |||
| 4175 | // variable's constructor are not usable while evaluating the | |||
| 4176 | // corresponding destructor, not even if they're of const-qualified | |||
| 4177 | // types. | |||
| 4178 | if (!MTE->isUsableInConstantExpressions(Info.Ctx) && | |||
| 4179 | !lifetimeStartedInEvaluation(Info, LVal.Base)) { | |||
| 4180 | if (!IsAccess) | |||
| 4181 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | |||
| 4182 | Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; | |||
| 4183 | Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); | |||
| 4184 | return CompleteObject(); | |||
| 4185 | } | |||
| 4186 | ||||
| 4187 | BaseVal = MTE->getOrCreateValue(false); | |||
| 4188 | assert(BaseVal && "got reference to unevaluated temporary")(static_cast <bool> (BaseVal && "got reference to unevaluated temporary" ) ? void (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4188, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4189 | } else { | |||
| 4190 | if (!IsAccess) | |||
| 4191 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | |||
| 4192 | APValue Val; | |||
| 4193 | LVal.moveInto(Val); | |||
| 4194 | Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) | |||
| 4195 | << AK | |||
| 4196 | << Val.getAsString(Info.Ctx, | |||
| 4197 | Info.Ctx.getLValueReferenceType(LValType)); | |||
| 4198 | NoteLValueLocation(Info, LVal.Base); | |||
| 4199 | return CompleteObject(); | |||
| 4200 | } | |||
| 4201 | } else { | |||
| 4202 | BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); | |||
| 4203 | assert(BaseVal && "missing value for temporary")(static_cast <bool> (BaseVal && "missing value for temporary" ) ? void (0) : __assert_fail ("BaseVal && \"missing value for temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4203, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4204 | } | |||
| 4205 | } | |||
| 4206 | ||||
| 4207 | // In C++14, we can't safely access any mutable state when we might be | |||
| 4208 | // evaluating after an unmodeled side effect. Parameters are modeled as state | |||
| 4209 | // in the caller, but aren't visible once the call returns, so they can be | |||
| 4210 | // modified in a speculatively-evaluated call. | |||
| 4211 | // | |||
| 4212 | // FIXME: Not all local state is mutable. Allow local constant subobjects | |||
| 4213 | // to be read here (but take care with 'mutable' fields). | |||
| 4214 | unsigned VisibleDepth = Depth; | |||
| 4215 | if (llvm::isa_and_nonnull<ParmVarDecl>( | |||
| 4216 | LVal.Base.dyn_cast<const ValueDecl *>())) | |||
| 4217 | ++VisibleDepth; | |||
| 4218 | if ((Frame && Info.getLangOpts().CPlusPlus14 && | |||
| 4219 | Info.EvalStatus.HasSideEffects) || | |||
| 4220 | (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) | |||
| 4221 | return CompleteObject(); | |||
| 4222 | ||||
| 4223 | return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); | |||
| 4224 | } | |||
| 4225 | ||||
| 4226 | /// Perform an lvalue-to-rvalue conversion on the given glvalue. This | |||
| 4227 | /// can also be used for 'lvalue-to-lvalue' conversions for looking up the | |||
| 4228 | /// glvalue referred to by an entity of reference type. | |||
| 4229 | /// | |||
| 4230 | /// \param Info - Information about the ongoing evaluation. | |||
| 4231 | /// \param Conv - The expression for which we are performing the conversion. | |||
| 4232 | /// Used for diagnostics. | |||
| 4233 | /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the | |||
| 4234 | /// case of a non-class type). | |||
| 4235 | /// \param LVal - The glvalue on which we are attempting to perform this action. | |||
| 4236 | /// \param RVal - The produced value will be placed here. | |||
| 4237 | /// \param WantObjectRepresentation - If true, we're looking for the object | |||
| 4238 | /// representation rather than the value, and in particular, | |||
| 4239 | /// there is no requirement that the result be fully initialized. | |||
| 4240 | static bool | |||
| 4241 | handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, | |||
| 4242 | const LValue &LVal, APValue &RVal, | |||
| 4243 | bool WantObjectRepresentation = false) { | |||
| 4244 | if (LVal.Designator.Invalid) | |||
| 4245 | return false; | |||
| 4246 | ||||
| 4247 | // Check for special cases where there is no existing APValue to look at. | |||
| 4248 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | |||
| 4249 | ||||
| 4250 | AccessKinds AK = | |||
| 4251 | WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; | |||
| 4252 | ||||
| 4253 | if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { | |||
| 4254 | if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { | |||
| 4255 | // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the | |||
| 4256 | // initializer until now for such expressions. Such an expression can't be | |||
| 4257 | // an ICE in C, so this only matters for fold. | |||
| 4258 | if (Type.isVolatileQualified()) { | |||
| 4259 | Info.FFDiag(Conv); | |||
| 4260 | return false; | |||
| 4261 | } | |||
| 4262 | APValue Lit; | |||
| 4263 | if (!Evaluate(Lit, Info, CLE->getInitializer())) | |||
| 4264 | return false; | |||
| 4265 | CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); | |||
| 4266 | return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); | |||
| 4267 | } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { | |||
| 4268 | // Special-case character extraction so we don't have to construct an | |||
| 4269 | // APValue for the whole string. | |||
| 4270 | assert(LVal.Designator.Entries.size() <= 1 &&(static_cast <bool> (LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "clang/lib/AST/ExprConstant.cpp", 4271, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4271 | "Can only read characters from string literals")(static_cast <bool> (LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "clang/lib/AST/ExprConstant.cpp", 4271, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4272 | if (LVal.Designator.Entries.empty()) { | |||
| 4273 | // Fail for now for LValue to RValue conversion of an array. | |||
| 4274 | // (This shouldn't show up in C/C++, but it could be triggered by a | |||
| 4275 | // weird EvaluateAsRValue call from a tool.) | |||
| 4276 | Info.FFDiag(Conv); | |||
| 4277 | return false; | |||
| 4278 | } | |||
| 4279 | if (LVal.Designator.isOnePastTheEnd()) { | |||
| 4280 | if (Info.getLangOpts().CPlusPlus11) | |||
| 4281 | Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; | |||
| 4282 | else | |||
| 4283 | Info.FFDiag(Conv); | |||
| 4284 | return false; | |||
| 4285 | } | |||
| 4286 | uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); | |||
| 4287 | RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); | |||
| 4288 | return true; | |||
| 4289 | } | |||
| 4290 | } | |||
| 4291 | ||||
| 4292 | CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); | |||
| 4293 | return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); | |||
| 4294 | } | |||
| 4295 | ||||
| 4296 | /// Perform an assignment of Val to LVal. Takes ownership of Val. | |||
| 4297 | static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, | |||
| 4298 | QualType LValType, APValue &Val) { | |||
| 4299 | if (LVal.Designator.Invalid) | |||
| 4300 | return false; | |||
| 4301 | ||||
| 4302 | if (!Info.getLangOpts().CPlusPlus14) { | |||
| 4303 | Info.FFDiag(E); | |||
| 4304 | return false; | |||
| 4305 | } | |||
| 4306 | ||||
| 4307 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | |||
| 4308 | return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); | |||
| 4309 | } | |||
| 4310 | ||||
| 4311 | namespace { | |||
| 4312 | struct CompoundAssignSubobjectHandler { | |||
| 4313 | EvalInfo &Info; | |||
| 4314 | const CompoundAssignOperator *E; | |||
| 4315 | QualType PromotedLHSType; | |||
| 4316 | BinaryOperatorKind Opcode; | |||
| 4317 | const APValue &RHS; | |||
| 4318 | ||||
| 4319 | static const AccessKinds AccessKind = AK_Assign; | |||
| 4320 | ||||
| 4321 | typedef bool result_type; | |||
| 4322 | ||||
| 4323 | bool checkConst(QualType QT) { | |||
| 4324 | // Assigning to a const object has undefined behavior. | |||
| 4325 | if (QT.isConstQualified()) { | |||
| 4326 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | |||
| 4327 | return false; | |||
| 4328 | } | |||
| 4329 | return true; | |||
| 4330 | } | |||
| 4331 | ||||
| 4332 | bool failed() { return false; } | |||
| 4333 | bool found(APValue &Subobj, QualType SubobjType) { | |||
| 4334 | switch (Subobj.getKind()) { | |||
| 4335 | case APValue::Int: | |||
| 4336 | return found(Subobj.getInt(), SubobjType); | |||
| 4337 | case APValue::Float: | |||
| 4338 | return found(Subobj.getFloat(), SubobjType); | |||
| 4339 | case APValue::ComplexInt: | |||
| 4340 | case APValue::ComplexFloat: | |||
| 4341 | // FIXME: Implement complex compound assignment. | |||
| 4342 | Info.FFDiag(E); | |||
| 4343 | return false; | |||
| 4344 | case APValue::LValue: | |||
| 4345 | return foundPointer(Subobj, SubobjType); | |||
| 4346 | case APValue::Vector: | |||
| 4347 | return foundVector(Subobj, SubobjType); | |||
| 4348 | default: | |||
| 4349 | // FIXME: can this happen? | |||
| 4350 | Info.FFDiag(E); | |||
| 4351 | return false; | |||
| 4352 | } | |||
| 4353 | } | |||
| 4354 | ||||
| 4355 | bool foundVector(APValue &Value, QualType SubobjType) { | |||
| 4356 | if (!checkConst(SubobjType)) | |||
| 4357 | return false; | |||
| 4358 | ||||
| 4359 | if (!SubobjType->isVectorType()) { | |||
| 4360 | Info.FFDiag(E); | |||
| 4361 | return false; | |||
| 4362 | } | |||
| 4363 | return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); | |||
| 4364 | } | |||
| 4365 | ||||
| 4366 | bool found(APSInt &Value, QualType SubobjType) { | |||
| 4367 | if (!checkConst(SubobjType)) | |||
| 4368 | return false; | |||
| 4369 | ||||
| 4370 | if (!SubobjType->isIntegerType()) { | |||
| 4371 | // We don't support compound assignment on integer-cast-to-pointer | |||
| 4372 | // values. | |||
| 4373 | Info.FFDiag(E); | |||
| 4374 | return false; | |||
| 4375 | } | |||
| 4376 | ||||
| 4377 | if (RHS.isInt()) { | |||
| 4378 | APSInt LHS = | |||
| 4379 | HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); | |||
| 4380 | if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) | |||
| 4381 | return false; | |||
| 4382 | Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); | |||
| 4383 | return true; | |||
| 4384 | } else if (RHS.isFloat()) { | |||
| 4385 | const FPOptions FPO = E->getFPFeaturesInEffect( | |||
| 4386 | Info.Ctx.getLangOpts()); | |||
| 4387 | APFloat FValue(0.0); | |||
| 4388 | return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, | |||
| 4389 | PromotedLHSType, FValue) && | |||
| 4390 | handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && | |||
| 4391 | HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, | |||
| 4392 | Value); | |||
| 4393 | } | |||
| 4394 | ||||
| 4395 | Info.FFDiag(E); | |||
| 4396 | return false; | |||
| 4397 | } | |||
| 4398 | bool found(APFloat &Value, QualType SubobjType) { | |||
| 4399 | return checkConst(SubobjType) && | |||
| 4400 | HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, | |||
| 4401 | Value) && | |||
| 4402 | handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && | |||
| 4403 | HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); | |||
| 4404 | } | |||
| 4405 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | |||
| 4406 | if (!checkConst(SubobjType)) | |||
| 4407 | return false; | |||
| 4408 | ||||
| 4409 | QualType PointeeType; | |||
| 4410 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | |||
| 4411 | PointeeType = PT->getPointeeType(); | |||
| 4412 | ||||
| 4413 | if (PointeeType.isNull() || !RHS.isInt() || | |||
| 4414 | (Opcode != BO_Add && Opcode != BO_Sub)) { | |||
| 4415 | Info.FFDiag(E); | |||
| 4416 | return false; | |||
| 4417 | } | |||
| 4418 | ||||
| 4419 | APSInt Offset = RHS.getInt(); | |||
| 4420 | if (Opcode == BO_Sub) | |||
| 4421 | negateAsSigned(Offset); | |||
| 4422 | ||||
| 4423 | LValue LVal; | |||
| 4424 | LVal.setFrom(Info.Ctx, Subobj); | |||
| 4425 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) | |||
| 4426 | return false; | |||
| 4427 | LVal.moveInto(Subobj); | |||
| 4428 | return true; | |||
| 4429 | } | |||
| 4430 | }; | |||
| 4431 | } // end anonymous namespace | |||
| 4432 | ||||
| 4433 | const AccessKinds CompoundAssignSubobjectHandler::AccessKind; | |||
| 4434 | ||||
| 4435 | /// Perform a compound assignment of LVal <op>= RVal. | |||
| 4436 | static bool handleCompoundAssignment(EvalInfo &Info, | |||
| 4437 | const CompoundAssignOperator *E, | |||
| 4438 | const LValue &LVal, QualType LValType, | |||
| 4439 | QualType PromotedLValType, | |||
| 4440 | BinaryOperatorKind Opcode, | |||
| 4441 | const APValue &RVal) { | |||
| 4442 | if (LVal.Designator.Invalid) | |||
| 4443 | return false; | |||
| 4444 | ||||
| 4445 | if (!Info.getLangOpts().CPlusPlus14) { | |||
| 4446 | Info.FFDiag(E); | |||
| 4447 | return false; | |||
| 4448 | } | |||
| 4449 | ||||
| 4450 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | |||
| 4451 | CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, | |||
| 4452 | RVal }; | |||
| 4453 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | |||
| 4454 | } | |||
| 4455 | ||||
| 4456 | namespace { | |||
| 4457 | struct IncDecSubobjectHandler { | |||
| 4458 | EvalInfo &Info; | |||
| 4459 | const UnaryOperator *E; | |||
| 4460 | AccessKinds AccessKind; | |||
| 4461 | APValue *Old; | |||
| 4462 | ||||
| 4463 | typedef bool result_type; | |||
| 4464 | ||||
| 4465 | bool checkConst(QualType QT) { | |||
| 4466 | // Assigning to a const object has undefined behavior. | |||
| 4467 | if (QT.isConstQualified()) { | |||
| 4468 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | |||
| 4469 | return false; | |||
| 4470 | } | |||
| 4471 | return true; | |||
| 4472 | } | |||
| 4473 | ||||
| 4474 | bool failed() { return false; } | |||
| 4475 | bool found(APValue &Subobj, QualType SubobjType) { | |||
| 4476 | // Stash the old value. Also clear Old, so we don't clobber it later | |||
| 4477 | // if we're post-incrementing a complex. | |||
| 4478 | if (Old) { | |||
| 4479 | *Old = Subobj; | |||
| 4480 | Old = nullptr; | |||
| 4481 | } | |||
| 4482 | ||||
| 4483 | switch (Subobj.getKind()) { | |||
| 4484 | case APValue::Int: | |||
| 4485 | return found(Subobj.getInt(), SubobjType); | |||
| 4486 | case APValue::Float: | |||
| 4487 | return found(Subobj.getFloat(), SubobjType); | |||
| 4488 | case APValue::ComplexInt: | |||
| 4489 | return found(Subobj.getComplexIntReal(), | |||
| 4490 | SubobjType->castAs<ComplexType>()->getElementType() | |||
| 4491 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | |||
| 4492 | case APValue::ComplexFloat: | |||
| 4493 | return found(Subobj.getComplexFloatReal(), | |||
| 4494 | SubobjType->castAs<ComplexType>()->getElementType() | |||
| 4495 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | |||
| 4496 | case APValue::LValue: | |||
| 4497 | return foundPointer(Subobj, SubobjType); | |||
| 4498 | default: | |||
| 4499 | // FIXME: can this happen? | |||
| 4500 | Info.FFDiag(E); | |||
| 4501 | return false; | |||
| 4502 | } | |||
| 4503 | } | |||
| 4504 | bool found(APSInt &Value, QualType SubobjType) { | |||
| 4505 | if (!checkConst(SubobjType)) | |||
| 4506 | return false; | |||
| 4507 | ||||
| 4508 | if (!SubobjType->isIntegerType()) { | |||
| 4509 | // We don't support increment / decrement on integer-cast-to-pointer | |||
| 4510 | // values. | |||
| 4511 | Info.FFDiag(E); | |||
| 4512 | return false; | |||
| 4513 | } | |||
| 4514 | ||||
| 4515 | if (Old) *Old = APValue(Value); | |||
| 4516 | ||||
| 4517 | // bool arithmetic promotes to int, and the conversion back to bool | |||
| 4518 | // doesn't reduce mod 2^n, so special-case it. | |||
| 4519 | if (SubobjType->isBooleanType()) { | |||
| 4520 | if (AccessKind == AK_Increment) | |||
| 4521 | Value = 1; | |||
| 4522 | else | |||
| 4523 | Value = !Value; | |||
| 4524 | return true; | |||
| 4525 | } | |||
| 4526 | ||||
| 4527 | bool WasNegative = Value.isNegative(); | |||
| 4528 | if (AccessKind == AK_Increment) { | |||
| 4529 | ++Value; | |||
| 4530 | ||||
| 4531 | if (!WasNegative && Value.isNegative() && E->canOverflow()) { | |||
| 4532 | APSInt ActualValue(Value, /*IsUnsigned*/true); | |||
| 4533 | return HandleOverflow(Info, E, ActualValue, SubobjType); | |||
| 4534 | } | |||
| 4535 | } else { | |||
| 4536 | --Value; | |||
| 4537 | ||||
| 4538 | if (WasNegative && !Value.isNegative() && E->canOverflow()) { | |||
| 4539 | unsigned BitWidth = Value.getBitWidth(); | |||
| 4540 | APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); | |||
| 4541 | ActualValue.setBit(BitWidth); | |||
| 4542 | return HandleOverflow(Info, E, ActualValue, SubobjType); | |||
| 4543 | } | |||
| 4544 | } | |||
| 4545 | return true; | |||
| 4546 | } | |||
| 4547 | bool found(APFloat &Value, QualType SubobjType) { | |||
| 4548 | if (!checkConst(SubobjType)) | |||
| 4549 | return false; | |||
| 4550 | ||||
| 4551 | if (Old) *Old = APValue(Value); | |||
| 4552 | ||||
| 4553 | APFloat One(Value.getSemantics(), 1); | |||
| 4554 | if (AccessKind == AK_Increment) | |||
| 4555 | Value.add(One, APFloat::rmNearestTiesToEven); | |||
| 4556 | else | |||
| 4557 | Value.subtract(One, APFloat::rmNearestTiesToEven); | |||
| 4558 | return true; | |||
| 4559 | } | |||
| 4560 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | |||
| 4561 | if (!checkConst(SubobjType)) | |||
| 4562 | return false; | |||
| 4563 | ||||
| 4564 | QualType PointeeType; | |||
| 4565 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | |||
| 4566 | PointeeType = PT->getPointeeType(); | |||
| 4567 | else { | |||
| 4568 | Info.FFDiag(E); | |||
| 4569 | return false; | |||
| 4570 | } | |||
| 4571 | ||||
| 4572 | LValue LVal; | |||
| 4573 | LVal.setFrom(Info.Ctx, Subobj); | |||
| 4574 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, | |||
| 4575 | AccessKind == AK_Increment ? 1 : -1)) | |||
| 4576 | return false; | |||
| 4577 | LVal.moveInto(Subobj); | |||
| 4578 | return true; | |||
| 4579 | } | |||
| 4580 | }; | |||
| 4581 | } // end anonymous namespace | |||
| 4582 | ||||
| 4583 | /// Perform an increment or decrement on LVal. | |||
| 4584 | static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, | |||
| 4585 | QualType LValType, bool IsIncrement, APValue *Old) { | |||
| 4586 | if (LVal.Designator.Invalid) | |||
| 4587 | return false; | |||
| 4588 | ||||
| 4589 | if (!Info.getLangOpts().CPlusPlus14) { | |||
| 4590 | Info.FFDiag(E); | |||
| 4591 | return false; | |||
| 4592 | } | |||
| 4593 | ||||
| 4594 | AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; | |||
| 4595 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); | |||
| 4596 | IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; | |||
| 4597 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | |||
| 4598 | } | |||
| 4599 | ||||
| 4600 | /// Build an lvalue for the object argument of a member function call. | |||
| 4601 | static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, | |||
| 4602 | LValue &This) { | |||
| 4603 | if (Object->getType()->isPointerType() && Object->isPRValue()) | |||
| 4604 | return EvaluatePointer(Object, This, Info); | |||
| 4605 | ||||
| 4606 | if (Object->isGLValue()) | |||
| 4607 | return EvaluateLValue(Object, This, Info); | |||
| 4608 | ||||
| 4609 | if (Object->getType()->isLiteralType(Info.Ctx)) | |||
| 4610 | return EvaluateTemporary(Object, This, Info); | |||
| 4611 | ||||
| 4612 | Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); | |||
| 4613 | return false; | |||
| 4614 | } | |||
| 4615 | ||||
| 4616 | /// HandleMemberPointerAccess - Evaluate a member access operation and build an | |||
| 4617 | /// lvalue referring to the result. | |||
| 4618 | /// | |||
| 4619 | /// \param Info - Information about the ongoing evaluation. | |||
| 4620 | /// \param LV - An lvalue referring to the base of the member pointer. | |||
| 4621 | /// \param RHS - The member pointer expression. | |||
| 4622 | /// \param IncludeMember - Specifies whether the member itself is included in | |||
| 4623 | /// the resulting LValue subobject designator. This is not possible when | |||
| 4624 | /// creating a bound member function. | |||
| 4625 | /// \return The field or method declaration to which the member pointer refers, | |||
| 4626 | /// or 0 if evaluation fails. | |||
| 4627 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | |||
| 4628 | QualType LVType, | |||
| 4629 | LValue &LV, | |||
| 4630 | const Expr *RHS, | |||
| 4631 | bool IncludeMember = true) { | |||
| 4632 | MemberPtr MemPtr; | |||
| 4633 | if (!EvaluateMemberPointer(RHS, MemPtr, Info)) | |||
| 4634 | return nullptr; | |||
| 4635 | ||||
| 4636 | // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to | |||
| 4637 | // member value, the behavior is undefined. | |||
| 4638 | if (!MemPtr.getDecl()) { | |||
| 4639 | // FIXME: Specific diagnostic. | |||
| 4640 | Info.FFDiag(RHS); | |||
| 4641 | return nullptr; | |||
| 4642 | } | |||
| 4643 | ||||
| 4644 | if (MemPtr.isDerivedMember()) { | |||
| 4645 | // This is a member of some derived class. Truncate LV appropriately. | |||
| 4646 | // The end of the derived-to-base path for the base object must match the | |||
| 4647 | // derived-to-base path for the member pointer. | |||
| 4648 | if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > | |||
| 4649 | LV.Designator.Entries.size()) { | |||
| 4650 | Info.FFDiag(RHS); | |||
| 4651 | return nullptr; | |||
| 4652 | } | |||
| 4653 | unsigned PathLengthToMember = | |||
| 4654 | LV.Designator.Entries.size() - MemPtr.Path.size(); | |||
| 4655 | for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { | |||
| 4656 | const CXXRecordDecl *LVDecl = getAsBaseClass( | |||
| 4657 | LV.Designator.Entries[PathLengthToMember + I]); | |||
| 4658 | const CXXRecordDecl *MPDecl = MemPtr.Path[I]; | |||
| 4659 | if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { | |||
| 4660 | Info.FFDiag(RHS); | |||
| 4661 | return nullptr; | |||
| 4662 | } | |||
| 4663 | } | |||
| 4664 | ||||
| 4665 | // Truncate the lvalue to the appropriate derived class. | |||
| 4666 | if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), | |||
| 4667 | PathLengthToMember)) | |||
| 4668 | return nullptr; | |||
| 4669 | } else if (!MemPtr.Path.empty()) { | |||
| 4670 | // Extend the LValue path with the member pointer's path. | |||
| 4671 | LV.Designator.Entries.reserve(LV.Designator.Entries.size() + | |||
| 4672 | MemPtr.Path.size() + IncludeMember); | |||
| 4673 | ||||
| 4674 | // Walk down to the appropriate base class. | |||
| 4675 | if (const PointerType *PT = LVType->getAs<PointerType>()) | |||
| 4676 | LVType = PT->getPointeeType(); | |||
| 4677 | const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); | |||
| 4678 | assert(RD && "member pointer access on non-class-type expression")(static_cast <bool> (RD && "member pointer access on non-class-type expression" ) ? void (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\"" , "clang/lib/AST/ExprConstant.cpp", 4678, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4679 | // The first class in the path is that of the lvalue. | |||
| 4680 | for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { | |||
| 4681 | const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; | |||
| 4682 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) | |||
| 4683 | return nullptr; | |||
| 4684 | RD = Base; | |||
| 4685 | } | |||
| 4686 | // Finally cast to the class containing the member. | |||
| 4687 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, | |||
| 4688 | MemPtr.getContainingRecord())) | |||
| 4689 | return nullptr; | |||
| 4690 | } | |||
| 4691 | ||||
| 4692 | // Add the member. Note that we cannot build bound member functions here. | |||
| 4693 | if (IncludeMember) { | |||
| 4694 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { | |||
| 4695 | if (!HandleLValueMember(Info, RHS, LV, FD)) | |||
| 4696 | return nullptr; | |||
| 4697 | } else if (const IndirectFieldDecl *IFD = | |||
| 4698 | dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { | |||
| 4699 | if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) | |||
| 4700 | return nullptr; | |||
| 4701 | } else { | |||
| 4702 | llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function" , "clang/lib/AST/ExprConstant.cpp", 4702); | |||
| 4703 | } | |||
| 4704 | } | |||
| 4705 | ||||
| 4706 | return MemPtr.getDecl(); | |||
| 4707 | } | |||
| 4708 | ||||
| 4709 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | |||
| 4710 | const BinaryOperator *BO, | |||
| 4711 | LValue &LV, | |||
| 4712 | bool IncludeMember = true) { | |||
| 4713 | assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)(static_cast <bool> (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail ("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI" , "clang/lib/AST/ExprConstant.cpp", 4713, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4714 | ||||
| 4715 | if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { | |||
| 4716 | if (Info.noteFailure()) { | |||
| 4717 | MemberPtr MemPtr; | |||
| 4718 | EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); | |||
| 4719 | } | |||
| 4720 | return nullptr; | |||
| 4721 | } | |||
| 4722 | ||||
| 4723 | return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, | |||
| 4724 | BO->getRHS(), IncludeMember); | |||
| 4725 | } | |||
| 4726 | ||||
| 4727 | /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on | |||
| 4728 | /// the provided lvalue, which currently refers to the base object. | |||
| 4729 | static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, | |||
| 4730 | LValue &Result) { | |||
| 4731 | SubobjectDesignator &D = Result.Designator; | |||
| 4732 | if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) | |||
| 4733 | return false; | |||
| 4734 | ||||
| 4735 | QualType TargetQT = E->getType(); | |||
| 4736 | if (const PointerType *PT = TargetQT->getAs<PointerType>()) | |||
| 4737 | TargetQT = PT->getPointeeType(); | |||
| 4738 | ||||
| 4739 | // Check this cast lands within the final derived-to-base subobject path. | |||
| 4740 | if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { | |||
| 4741 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | |||
| 4742 | << D.MostDerivedType << TargetQT; | |||
| 4743 | return false; | |||
| 4744 | } | |||
| 4745 | ||||
| 4746 | // Check the type of the final cast. We don't need to check the path, | |||
| 4747 | // since a cast can only be formed if the path is unique. | |||
| 4748 | unsigned NewEntriesSize = D.Entries.size() - E->path_size(); | |||
| 4749 | const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); | |||
| 4750 | const CXXRecordDecl *FinalType; | |||
| 4751 | if (NewEntriesSize == D.MostDerivedPathLength) | |||
| 4752 | FinalType = D.MostDerivedType->getAsCXXRecordDecl(); | |||
| 4753 | else | |||
| 4754 | FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); | |||
| 4755 | if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { | |||
| 4756 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | |||
| 4757 | << D.MostDerivedType << TargetQT; | |||
| 4758 | return false; | |||
| 4759 | } | |||
| 4760 | ||||
| 4761 | // Truncate the lvalue to the appropriate derived class. | |||
| 4762 | return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); | |||
| 4763 | } | |||
| 4764 | ||||
| 4765 | /// Get the value to use for a default-initialized object of type T. | |||
| 4766 | /// Return false if it encounters something invalid. | |||
| 4767 | static bool getDefaultInitValue(QualType T, APValue &Result) { | |||
| 4768 | bool Success = true; | |||
| 4769 | if (auto *RD = T->getAsCXXRecordDecl()) { | |||
| 4770 | if (RD->isInvalidDecl()) { | |||
| 4771 | Result = APValue(); | |||
| 4772 | return false; | |||
| 4773 | } | |||
| 4774 | if (RD->isUnion()) { | |||
| 4775 | Result = APValue((const FieldDecl *)nullptr); | |||
| 4776 | return true; | |||
| 4777 | } | |||
| 4778 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), | |||
| 4779 | std::distance(RD->field_begin(), RD->field_end())); | |||
| 4780 | ||||
| 4781 | unsigned Index = 0; | |||
| 4782 | for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), | |||
| 4783 | End = RD->bases_end(); | |||
| 4784 | I != End; ++I, ++Index) | |||
| 4785 | Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); | |||
| 4786 | ||||
| 4787 | for (const auto *I : RD->fields()) { | |||
| 4788 | if (I->isUnnamedBitfield()) | |||
| 4789 | continue; | |||
| 4790 | Success &= getDefaultInitValue(I->getType(), | |||
| 4791 | Result.getStructField(I->getFieldIndex())); | |||
| 4792 | } | |||
| 4793 | return Success; | |||
| 4794 | } | |||
| 4795 | ||||
| 4796 | if (auto *AT = | |||
| 4797 | dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { | |||
| 4798 | Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); | |||
| 4799 | if (Result.hasArrayFiller()) | |||
| 4800 | Success &= | |||
| 4801 | getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); | |||
| 4802 | ||||
| 4803 | return Success; | |||
| 4804 | } | |||
| 4805 | ||||
| 4806 | Result = APValue::IndeterminateValue(); | |||
| 4807 | return true; | |||
| 4808 | } | |||
| 4809 | ||||
| 4810 | namespace { | |||
| 4811 | enum EvalStmtResult { | |||
| 4812 | /// Evaluation failed. | |||
| 4813 | ESR_Failed, | |||
| 4814 | /// Hit a 'return' statement. | |||
| 4815 | ESR_Returned, | |||
| 4816 | /// Evaluation succeeded. | |||
| 4817 | ESR_Succeeded, | |||
| 4818 | /// Hit a 'continue' statement. | |||
| 4819 | ESR_Continue, | |||
| 4820 | /// Hit a 'break' statement. | |||
| 4821 | ESR_Break, | |||
| 4822 | /// Still scanning for 'case' or 'default' statement. | |||
| 4823 | ESR_CaseNotFound | |||
| 4824 | }; | |||
| 4825 | } | |||
| 4826 | ||||
| 4827 | static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { | |||
| 4828 | // We don't need to evaluate the initializer for a static local. | |||
| 4829 | if (!VD->hasLocalStorage()) | |||
| 4830 | return true; | |||
| 4831 | ||||
| 4832 | LValue Result; | |||
| 4833 | APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), | |||
| 4834 | ScopeKind::Block, Result); | |||
| 4835 | ||||
| 4836 | const Expr *InitE = VD->getInit(); | |||
| 4837 | if (!InitE) { | |||
| 4838 | if (VD->getType()->isDependentType()) | |||
| 4839 | return Info.noteSideEffect(); | |||
| 4840 | return getDefaultInitValue(VD->getType(), Val); | |||
| 4841 | } | |||
| 4842 | if (InitE->isValueDependent()) | |||
| 4843 | return false; | |||
| 4844 | ||||
| 4845 | if (!EvaluateInPlace(Val, Info, Result, InitE)) { | |||
| 4846 | // Wipe out any partially-computed value, to allow tracking that this | |||
| 4847 | // evaluation failed. | |||
| 4848 | Val = APValue(); | |||
| 4849 | return false; | |||
| 4850 | } | |||
| 4851 | ||||
| 4852 | return true; | |||
| 4853 | } | |||
| 4854 | ||||
| 4855 | static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { | |||
| 4856 | bool OK = true; | |||
| 4857 | ||||
| 4858 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | |||
| 4859 | OK &= EvaluateVarDecl(Info, VD); | |||
| 4860 | ||||
| 4861 | if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) | |||
| 4862 | for (auto *BD : DD->bindings()) | |||
| 4863 | if (auto *VD = BD->getHoldingVar()) | |||
| 4864 | OK &= EvaluateDecl(Info, VD); | |||
| 4865 | ||||
| 4866 | return OK; | |||
| 4867 | } | |||
| 4868 | ||||
| 4869 | static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { | |||
| 4870 | assert(E->isValueDependent())(static_cast <bool> (E->isValueDependent()) ? void ( 0) : __assert_fail ("E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 4870, __extension__ __PRETTY_FUNCTION__)); | |||
| 4871 | if (Info.noteSideEffect()) | |||
| 4872 | return true; | |||
| 4873 | assert(E->containsErrors() && "valid value-dependent expression should never "(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never " "reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\"" , "clang/lib/AST/ExprConstant.cpp", 4874, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4874 | "reach invalid code path.")(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never " "reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\"" , "clang/lib/AST/ExprConstant.cpp", 4874, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4875 | return false; | |||
| 4876 | } | |||
| 4877 | ||||
| 4878 | /// Evaluate a condition (either a variable declaration or an expression). | |||
| 4879 | static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, | |||
| 4880 | const Expr *Cond, bool &Result) { | |||
| 4881 | if (Cond->isValueDependent()) | |||
| 4882 | return false; | |||
| 4883 | FullExpressionRAII Scope(Info); | |||
| 4884 | if (CondDecl && !EvaluateDecl(Info, CondDecl)) | |||
| 4885 | return false; | |||
| 4886 | if (!EvaluateAsBooleanCondition(Cond, Result, Info)) | |||
| 4887 | return false; | |||
| 4888 | return Scope.destroy(); | |||
| 4889 | } | |||
| 4890 | ||||
| 4891 | namespace { | |||
| 4892 | /// A location where the result (returned value) of evaluating a | |||
| 4893 | /// statement should be stored. | |||
| 4894 | struct StmtResult { | |||
| 4895 | /// The APValue that should be filled in with the returned value. | |||
| 4896 | APValue &Value; | |||
| 4897 | /// The location containing the result, if any (used to support RVO). | |||
| 4898 | const LValue *Slot; | |||
| 4899 | }; | |||
| 4900 | ||||
| 4901 | struct TempVersionRAII { | |||
| 4902 | CallStackFrame &Frame; | |||
| 4903 | ||||
| 4904 | TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { | |||
| 4905 | Frame.pushTempVersion(); | |||
| 4906 | } | |||
| 4907 | ||||
| 4908 | ~TempVersionRAII() { | |||
| 4909 | Frame.popTempVersion(); | |||
| 4910 | } | |||
| 4911 | }; | |||
| 4912 | ||||
| 4913 | } | |||
| 4914 | ||||
| 4915 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | |||
| 4916 | const Stmt *S, | |||
| 4917 | const SwitchCase *SC = nullptr); | |||
| 4918 | ||||
| 4919 | /// Evaluate the body of a loop, and translate the result as appropriate. | |||
| 4920 | static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, | |||
| 4921 | const Stmt *Body, | |||
| 4922 | const SwitchCase *Case = nullptr) { | |||
| 4923 | BlockScopeRAII Scope(Info); | |||
| 4924 | ||||
| 4925 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); | |||
| 4926 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | |||
| 4927 | ESR = ESR_Failed; | |||
| 4928 | ||||
| 4929 | switch (ESR) { | |||
| 4930 | case ESR_Break: | |||
| 4931 | return ESR_Succeeded; | |||
| 4932 | case ESR_Succeeded: | |||
| 4933 | case ESR_Continue: | |||
| 4934 | return ESR_Continue; | |||
| 4935 | case ESR_Failed: | |||
| 4936 | case ESR_Returned: | |||
| 4937 | case ESR_CaseNotFound: | |||
| 4938 | return ESR; | |||
| 4939 | } | |||
| 4940 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp" , 4940); | |||
| 4941 | } | |||
| 4942 | ||||
| 4943 | /// Evaluate a switch statement. | |||
| 4944 | static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, | |||
| 4945 | const SwitchStmt *SS) { | |||
| 4946 | BlockScopeRAII Scope(Info); | |||
| 4947 | ||||
| 4948 | // Evaluate the switch condition. | |||
| 4949 | APSInt Value; | |||
| 4950 | { | |||
| 4951 | if (const Stmt *Init = SS->getInit()) { | |||
| 4952 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | |||
| 4953 | if (ESR != ESR_Succeeded) { | |||
| 4954 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 4955 | ESR = ESR_Failed; | |||
| 4956 | return ESR; | |||
| 4957 | } | |||
| 4958 | } | |||
| 4959 | ||||
| 4960 | FullExpressionRAII CondScope(Info); | |||
| 4961 | if (SS->getConditionVariable() && | |||
| 4962 | !EvaluateDecl(Info, SS->getConditionVariable())) | |||
| 4963 | return ESR_Failed; | |||
| 4964 | if (SS->getCond()->isValueDependent()) { | |||
| 4965 | if (!EvaluateDependentExpr(SS->getCond(), Info)) | |||
| 4966 | return ESR_Failed; | |||
| 4967 | } else { | |||
| 4968 | if (!EvaluateInteger(SS->getCond(), Value, Info)) | |||
| 4969 | return ESR_Failed; | |||
| 4970 | } | |||
| 4971 | if (!CondScope.destroy()) | |||
| 4972 | return ESR_Failed; | |||
| 4973 | } | |||
| 4974 | ||||
| 4975 | // Find the switch case corresponding to the value of the condition. | |||
| 4976 | // FIXME: Cache this lookup. | |||
| 4977 | const SwitchCase *Found = nullptr; | |||
| 4978 | for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; | |||
| 4979 | SC = SC->getNextSwitchCase()) { | |||
| 4980 | if (isa<DefaultStmt>(SC)) { | |||
| 4981 | Found = SC; | |||
| 4982 | continue; | |||
| 4983 | } | |||
| 4984 | ||||
| 4985 | const CaseStmt *CS = cast<CaseStmt>(SC); | |||
| 4986 | APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); | |||
| 4987 | APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) | |||
| 4988 | : LHS; | |||
| 4989 | if (LHS <= Value && Value <= RHS) { | |||
| 4990 | Found = SC; | |||
| 4991 | break; | |||
| 4992 | } | |||
| 4993 | } | |||
| 4994 | ||||
| 4995 | if (!Found) | |||
| 4996 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | |||
| 4997 | ||||
| 4998 | // Search the switch body for the switch case and evaluate it from there. | |||
| 4999 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); | |||
| 5000 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | |||
| 5001 | return ESR_Failed; | |||
| 5002 | ||||
| 5003 | switch (ESR) { | |||
| 5004 | case ESR_Break: | |||
| 5005 | return ESR_Succeeded; | |||
| 5006 | case ESR_Succeeded: | |||
| 5007 | case ESR_Continue: | |||
| 5008 | case ESR_Failed: | |||
| 5009 | case ESR_Returned: | |||
| 5010 | return ESR; | |||
| 5011 | case ESR_CaseNotFound: | |||
| 5012 | // This can only happen if the switch case is nested within a statement | |||
| 5013 | // expression. We have no intention of supporting that. | |||
| 5014 | Info.FFDiag(Found->getBeginLoc(), | |||
| 5015 | diag::note_constexpr_stmt_expr_unsupported); | |||
| 5016 | return ESR_Failed; | |||
| 5017 | } | |||
| 5018 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp" , 5018); | |||
| 5019 | } | |||
| 5020 | ||||
| 5021 | static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { | |||
| 5022 | // An expression E is a core constant expression unless the evaluation of E | |||
| 5023 | // would evaluate one of the following: [C++2b] - a control flow that passes | |||
| 5024 | // through a declaration of a variable with static or thread storage duration. | |||
| 5025 | if (VD->isLocalVarDecl() && VD->isStaticLocal()) { | |||
| 5026 | Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) | |||
| 5027 | << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; | |||
| 5028 | return false; | |||
| 5029 | } | |||
| 5030 | return true; | |||
| 5031 | } | |||
| 5032 | ||||
| 5033 | // Evaluate a statement. | |||
| 5034 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | |||
| 5035 | const Stmt *S, const SwitchCase *Case) { | |||
| 5036 | if (!Info.nextStep(S)) | |||
| 5037 | return ESR_Failed; | |||
| 5038 | ||||
| 5039 | // If we're hunting down a 'case' or 'default' label, recurse through | |||
| 5040 | // substatements until we hit the label. | |||
| 5041 | if (Case) { | |||
| 5042 | switch (S->getStmtClass()) { | |||
| 5043 | case Stmt::CompoundStmtClass: | |||
| 5044 | // FIXME: Precompute which substatement of a compound statement we | |||
| 5045 | // would jump to, and go straight there rather than performing a | |||
| 5046 | // linear scan each time. | |||
| 5047 | case Stmt::LabelStmtClass: | |||
| 5048 | case Stmt::AttributedStmtClass: | |||
| 5049 | case Stmt::DoStmtClass: | |||
| 5050 | break; | |||
| 5051 | ||||
| 5052 | case Stmt::CaseStmtClass: | |||
| 5053 | case Stmt::DefaultStmtClass: | |||
| 5054 | if (Case == S) | |||
| 5055 | Case = nullptr; | |||
| 5056 | break; | |||
| 5057 | ||||
| 5058 | case Stmt::IfStmtClass: { | |||
| 5059 | // FIXME: Precompute which side of an 'if' we would jump to, and go | |||
| 5060 | // straight there rather than scanning both sides. | |||
| 5061 | const IfStmt *IS = cast<IfStmt>(S); | |||
| 5062 | ||||
| 5063 | // Wrap the evaluation in a block scope, in case it's a DeclStmt | |||
| 5064 | // preceded by our switch label. | |||
| 5065 | BlockScopeRAII Scope(Info); | |||
| 5066 | ||||
| 5067 | // Step into the init statement in case it brings an (uninitialized) | |||
| 5068 | // variable into scope. | |||
| 5069 | if (const Stmt *Init = IS->getInit()) { | |||
| 5070 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | |||
| 5071 | if (ESR != ESR_CaseNotFound) { | |||
| 5072 | assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) : __assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp" , 5072, __extension__ __PRETTY_FUNCTION__)); | |||
| 5073 | return ESR; | |||
| 5074 | } | |||
| 5075 | } | |||
| 5076 | ||||
| 5077 | // Condition variable must be initialized if it exists. | |||
| 5078 | // FIXME: We can skip evaluating the body if there's a condition | |||
| 5079 | // variable, as there can't be any case labels within it. | |||
| 5080 | // (The same is true for 'for' statements.) | |||
| 5081 | ||||
| 5082 | EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); | |||
| 5083 | if (ESR == ESR_Failed) | |||
| 5084 | return ESR; | |||
| 5085 | if (ESR != ESR_CaseNotFound) | |||
| 5086 | return Scope.destroy() ? ESR : ESR_Failed; | |||
| 5087 | if (!IS->getElse()) | |||
| 5088 | return ESR_CaseNotFound; | |||
| 5089 | ||||
| 5090 | ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); | |||
| 5091 | if (ESR == ESR_Failed) | |||
| 5092 | return ESR; | |||
| 5093 | if (ESR != ESR_CaseNotFound) | |||
| 5094 | return Scope.destroy() ? ESR : ESR_Failed; | |||
| 5095 | return ESR_CaseNotFound; | |||
| 5096 | } | |||
| 5097 | ||||
| 5098 | case Stmt::WhileStmtClass: { | |||
| 5099 | EvalStmtResult ESR = | |||
| 5100 | EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); | |||
| 5101 | if (ESR != ESR_Continue) | |||
| 5102 | return ESR; | |||
| 5103 | break; | |||
| 5104 | } | |||
| 5105 | ||||
| 5106 | case Stmt::ForStmtClass: { | |||
| 5107 | const ForStmt *FS = cast<ForStmt>(S); | |||
| 5108 | BlockScopeRAII Scope(Info); | |||
| 5109 | ||||
| 5110 | // Step into the init statement in case it brings an (uninitialized) | |||
| 5111 | // variable into scope. | |||
| 5112 | if (const Stmt *Init = FS->getInit()) { | |||
| 5113 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | |||
| 5114 | if (ESR != ESR_CaseNotFound) { | |||
| 5115 | assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) : __assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp" , 5115, __extension__ __PRETTY_FUNCTION__)); | |||
| 5116 | return ESR; | |||
| 5117 | } | |||
| 5118 | } | |||
| 5119 | ||||
| 5120 | EvalStmtResult ESR = | |||
| 5121 | EvaluateLoopBody(Result, Info, FS->getBody(), Case); | |||
| 5122 | if (ESR != ESR_Continue) | |||
| 5123 | return ESR; | |||
| 5124 | if (const auto *Inc = FS->getInc()) { | |||
| 5125 | if (Inc->isValueDependent()) { | |||
| 5126 | if (!EvaluateDependentExpr(Inc, Info)) | |||
| 5127 | return ESR_Failed; | |||
| 5128 | } else { | |||
| 5129 | FullExpressionRAII IncScope(Info); | |||
| 5130 | if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) | |||
| 5131 | return ESR_Failed; | |||
| 5132 | } | |||
| 5133 | } | |||
| 5134 | break; | |||
| 5135 | } | |||
| 5136 | ||||
| 5137 | case Stmt::DeclStmtClass: { | |||
| 5138 | // Start the lifetime of any uninitialized variables we encounter. They | |||
| 5139 | // might be used by the selected branch of the switch. | |||
| 5140 | const DeclStmt *DS = cast<DeclStmt>(S); | |||
| 5141 | for (const auto *D : DS->decls()) { | |||
| 5142 | if (const auto *VD = dyn_cast<VarDecl>(D)) { | |||
| 5143 | if (!CheckLocalVariableDeclaration(Info, VD)) | |||
| 5144 | return ESR_Failed; | |||
| 5145 | if (VD->hasLocalStorage() && !VD->getInit()) | |||
| 5146 | if (!EvaluateVarDecl(Info, VD)) | |||
| 5147 | return ESR_Failed; | |||
| 5148 | // FIXME: If the variable has initialization that can't be jumped | |||
| 5149 | // over, bail out of any immediately-surrounding compound-statement | |||
| 5150 | // too. There can't be any case labels here. | |||
| 5151 | } | |||
| 5152 | } | |||
| 5153 | return ESR_CaseNotFound; | |||
| 5154 | } | |||
| 5155 | ||||
| 5156 | default: | |||
| 5157 | return ESR_CaseNotFound; | |||
| 5158 | } | |||
| 5159 | } | |||
| 5160 | ||||
| 5161 | switch (S->getStmtClass()) { | |||
| 5162 | default: | |||
| 5163 | if (const Expr *E = dyn_cast<Expr>(S)) { | |||
| 5164 | if (E->isValueDependent()) { | |||
| 5165 | if (!EvaluateDependentExpr(E, Info)) | |||
| 5166 | return ESR_Failed; | |||
| 5167 | } else { | |||
| 5168 | // Don't bother evaluating beyond an expression-statement which couldn't | |||
| 5169 | // be evaluated. | |||
| 5170 | // FIXME: Do we need the FullExpressionRAII object here? | |||
| 5171 | // VisitExprWithCleanups should create one when necessary. | |||
| 5172 | FullExpressionRAII Scope(Info); | |||
| 5173 | if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) | |||
| 5174 | return ESR_Failed; | |||
| 5175 | } | |||
| 5176 | return ESR_Succeeded; | |||
| 5177 | } | |||
| 5178 | ||||
| 5179 | Info.FFDiag(S->getBeginLoc()); | |||
| 5180 | return ESR_Failed; | |||
| 5181 | ||||
| 5182 | case Stmt::NullStmtClass: | |||
| 5183 | return ESR_Succeeded; | |||
| 5184 | ||||
| 5185 | case Stmt::DeclStmtClass: { | |||
| 5186 | const DeclStmt *DS = cast<DeclStmt>(S); | |||
| 5187 | for (const auto *D : DS->decls()) { | |||
| 5188 | const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); | |||
| 5189 | if (VD && !CheckLocalVariableDeclaration(Info, VD)) | |||
| 5190 | return ESR_Failed; | |||
| 5191 | // Each declaration initialization is its own full-expression. | |||
| 5192 | FullExpressionRAII Scope(Info); | |||
| 5193 | if (!EvaluateDecl(Info, D) && !Info.noteFailure()) | |||
| 5194 | return ESR_Failed; | |||
| 5195 | if (!Scope.destroy()) | |||
| 5196 | return ESR_Failed; | |||
| 5197 | } | |||
| 5198 | return ESR_Succeeded; | |||
| 5199 | } | |||
| 5200 | ||||
| 5201 | case Stmt::ReturnStmtClass: { | |||
| 5202 | const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); | |||
| 5203 | FullExpressionRAII Scope(Info); | |||
| 5204 | if (RetExpr && RetExpr->isValueDependent()) { | |||
| 5205 | EvaluateDependentExpr(RetExpr, Info); | |||
| 5206 | // We know we returned, but we don't know what the value is. | |||
| 5207 | return ESR_Failed; | |||
| 5208 | } | |||
| 5209 | if (RetExpr && | |||
| 5210 | !(Result.Slot | |||
| 5211 | ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) | |||
| 5212 | : Evaluate(Result.Value, Info, RetExpr))) | |||
| 5213 | return ESR_Failed; | |||
| 5214 | return Scope.destroy() ? ESR_Returned : ESR_Failed; | |||
| 5215 | } | |||
| 5216 | ||||
| 5217 | case Stmt::CompoundStmtClass: { | |||
| 5218 | BlockScopeRAII Scope(Info); | |||
| 5219 | ||||
| 5220 | const CompoundStmt *CS = cast<CompoundStmt>(S); | |||
| 5221 | for (const auto *BI : CS->body()) { | |||
| 5222 | EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); | |||
| 5223 | if (ESR == ESR_Succeeded) | |||
| 5224 | Case = nullptr; | |||
| 5225 | else if (ESR != ESR_CaseNotFound) { | |||
| 5226 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5227 | return ESR_Failed; | |||
| 5228 | return ESR; | |||
| 5229 | } | |||
| 5230 | } | |||
| 5231 | if (Case) | |||
| 5232 | return ESR_CaseNotFound; | |||
| 5233 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | |||
| 5234 | } | |||
| 5235 | ||||
| 5236 | case Stmt::IfStmtClass: { | |||
| 5237 | const IfStmt *IS = cast<IfStmt>(S); | |||
| 5238 | ||||
| 5239 | // Evaluate the condition, as either a var decl or as an expression. | |||
| 5240 | BlockScopeRAII Scope(Info); | |||
| 5241 | if (const Stmt *Init = IS->getInit()) { | |||
| 5242 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | |||
| 5243 | if (ESR != ESR_Succeeded) { | |||
| 5244 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5245 | return ESR_Failed; | |||
| 5246 | return ESR; | |||
| 5247 | } | |||
| 5248 | } | |||
| 5249 | bool Cond; | |||
| 5250 | if (IS->isConsteval()) | |||
| 5251 | Cond = IS->isNonNegatedConsteval(); | |||
| 5252 | else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), | |||
| 5253 | Cond)) | |||
| 5254 | return ESR_Failed; | |||
| 5255 | ||||
| 5256 | if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { | |||
| 5257 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); | |||
| 5258 | if (ESR != ESR_Succeeded) { | |||
| 5259 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5260 | return ESR_Failed; | |||
| 5261 | return ESR; | |||
| 5262 | } | |||
| 5263 | } | |||
| 5264 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | |||
| 5265 | } | |||
| 5266 | ||||
| 5267 | case Stmt::WhileStmtClass: { | |||
| 5268 | const WhileStmt *WS = cast<WhileStmt>(S); | |||
| 5269 | while (true) { | |||
| 5270 | BlockScopeRAII Scope(Info); | |||
| 5271 | bool Continue; | |||
| 5272 | if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), | |||
| 5273 | Continue)) | |||
| 5274 | return ESR_Failed; | |||
| 5275 | if (!Continue) | |||
| 5276 | break; | |||
| 5277 | ||||
| 5278 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); | |||
| 5279 | if (ESR != ESR_Continue) { | |||
| 5280 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5281 | return ESR_Failed; | |||
| 5282 | return ESR; | |||
| 5283 | } | |||
| 5284 | if (!Scope.destroy()) | |||
| 5285 | return ESR_Failed; | |||
| 5286 | } | |||
| 5287 | return ESR_Succeeded; | |||
| 5288 | } | |||
| 5289 | ||||
| 5290 | case Stmt::DoStmtClass: { | |||
| 5291 | const DoStmt *DS = cast<DoStmt>(S); | |||
| 5292 | bool Continue; | |||
| 5293 | do { | |||
| 5294 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); | |||
| 5295 | if (ESR != ESR_Continue) | |||
| 5296 | return ESR; | |||
| 5297 | Case = nullptr; | |||
| 5298 | ||||
| 5299 | if (DS->getCond()->isValueDependent()) { | |||
| 5300 | EvaluateDependentExpr(DS->getCond(), Info); | |||
| 5301 | // Bailout as we don't know whether to keep going or terminate the loop. | |||
| 5302 | return ESR_Failed; | |||
| 5303 | } | |||
| 5304 | FullExpressionRAII CondScope(Info); | |||
| 5305 | if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || | |||
| 5306 | !CondScope.destroy()) | |||
| 5307 | return ESR_Failed; | |||
| 5308 | } while (Continue); | |||
| 5309 | return ESR_Succeeded; | |||
| 5310 | } | |||
| 5311 | ||||
| 5312 | case Stmt::ForStmtClass: { | |||
| 5313 | const ForStmt *FS = cast<ForStmt>(S); | |||
| 5314 | BlockScopeRAII ForScope(Info); | |||
| 5315 | if (FS->getInit()) { | |||
| 5316 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | |||
| 5317 | if (ESR != ESR_Succeeded) { | |||
| 5318 | if (ESR != ESR_Failed && !ForScope.destroy()) | |||
| 5319 | return ESR_Failed; | |||
| 5320 | return ESR; | |||
| 5321 | } | |||
| 5322 | } | |||
| 5323 | while (true) { | |||
| 5324 | BlockScopeRAII IterScope(Info); | |||
| 5325 | bool Continue = true; | |||
| 5326 | if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), | |||
| 5327 | FS->getCond(), Continue)) | |||
| 5328 | return ESR_Failed; | |||
| 5329 | if (!Continue) | |||
| 5330 | break; | |||
| 5331 | ||||
| 5332 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | |||
| 5333 | if (ESR != ESR_Continue) { | |||
| 5334 | if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) | |||
| 5335 | return ESR_Failed; | |||
| 5336 | return ESR; | |||
| 5337 | } | |||
| 5338 | ||||
| 5339 | if (const auto *Inc = FS->getInc()) { | |||
| 5340 | if (Inc->isValueDependent()) { | |||
| 5341 | if (!EvaluateDependentExpr(Inc, Info)) | |||
| 5342 | return ESR_Failed; | |||
| 5343 | } else { | |||
| 5344 | FullExpressionRAII IncScope(Info); | |||
| 5345 | if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) | |||
| 5346 | return ESR_Failed; | |||
| 5347 | } | |||
| 5348 | } | |||
| 5349 | ||||
| 5350 | if (!IterScope.destroy()) | |||
| 5351 | return ESR_Failed; | |||
| 5352 | } | |||
| 5353 | return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; | |||
| 5354 | } | |||
| 5355 | ||||
| 5356 | case Stmt::CXXForRangeStmtClass: { | |||
| 5357 | const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); | |||
| 5358 | BlockScopeRAII Scope(Info); | |||
| 5359 | ||||
| 5360 | // Evaluate the init-statement if present. | |||
| 5361 | if (FS->getInit()) { | |||
| 5362 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | |||
| 5363 | if (ESR != ESR_Succeeded) { | |||
| 5364 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5365 | return ESR_Failed; | |||
| 5366 | return ESR; | |||
| 5367 | } | |||
| 5368 | } | |||
| 5369 | ||||
| 5370 | // Initialize the __range variable. | |||
| 5371 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); | |||
| 5372 | if (ESR != ESR_Succeeded) { | |||
| 5373 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5374 | return ESR_Failed; | |||
| 5375 | return ESR; | |||
| 5376 | } | |||
| 5377 | ||||
| 5378 | // In error-recovery cases it's possible to get here even if we failed to | |||
| 5379 | // synthesize the __begin and __end variables. | |||
| 5380 | if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) | |||
| 5381 | return ESR_Failed; | |||
| 5382 | ||||
| 5383 | // Create the __begin and __end iterators. | |||
| 5384 | ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); | |||
| 5385 | if (ESR != ESR_Succeeded) { | |||
| 5386 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5387 | return ESR_Failed; | |||
| 5388 | return ESR; | |||
| 5389 | } | |||
| 5390 | ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); | |||
| 5391 | if (ESR != ESR_Succeeded) { | |||
| 5392 | if (ESR != ESR_Failed && !Scope.destroy()) | |||
| 5393 | return ESR_Failed; | |||
| 5394 | return ESR; | |||
| 5395 | } | |||
| 5396 | ||||
| 5397 | while (true) { | |||
| 5398 | // Condition: __begin != __end. | |||
| 5399 | { | |||
| 5400 | if (FS->getCond()->isValueDependent()) { | |||
| 5401 | EvaluateDependentExpr(FS->getCond(), Info); | |||
| 5402 | // We don't know whether to keep going or terminate the loop. | |||
| 5403 | return ESR_Failed; | |||
| 5404 | } | |||
| 5405 | bool Continue = true; | |||
| 5406 | FullExpressionRAII CondExpr(Info); | |||
| 5407 | if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) | |||
| 5408 | return ESR_Failed; | |||
| 5409 | if (!Continue) | |||
| 5410 | break; | |||
| 5411 | } | |||
| 5412 | ||||
| 5413 | // User's variable declaration, initialized by *__begin. | |||
| 5414 | BlockScopeRAII InnerScope(Info); | |||
| 5415 | ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); | |||
| 5416 | if (ESR != ESR_Succeeded) { | |||
| 5417 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | |||
| 5418 | return ESR_Failed; | |||
| 5419 | return ESR; | |||
| 5420 | } | |||
| 5421 | ||||
| 5422 | // Loop body. | |||
| 5423 | ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | |||
| 5424 | if (ESR != ESR_Continue) { | |||
| 5425 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | |||
| 5426 | return ESR_Failed; | |||
| 5427 | return ESR; | |||
| 5428 | } | |||
| 5429 | if (FS->getInc()->isValueDependent()) { | |||
| 5430 | if (!EvaluateDependentExpr(FS->getInc(), Info)) | |||
| 5431 | return ESR_Failed; | |||
| 5432 | } else { | |||
| 5433 | // Increment: ++__begin | |||
| 5434 | if (!EvaluateIgnoredValue(Info, FS->getInc())) | |||
| 5435 | return ESR_Failed; | |||
| 5436 | } | |||
| 5437 | ||||
| 5438 | if (!InnerScope.destroy()) | |||
| 5439 | return ESR_Failed; | |||
| 5440 | } | |||
| 5441 | ||||
| 5442 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | |||
| 5443 | } | |||
| 5444 | ||||
| 5445 | case Stmt::SwitchStmtClass: | |||
| 5446 | return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); | |||
| 5447 | ||||
| 5448 | case Stmt::ContinueStmtClass: | |||
| 5449 | return ESR_Continue; | |||
| 5450 | ||||
| 5451 | case Stmt::BreakStmtClass: | |||
| 5452 | return ESR_Break; | |||
| 5453 | ||||
| 5454 | case Stmt::LabelStmtClass: | |||
| 5455 | return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); | |||
| 5456 | ||||
| 5457 | case Stmt::AttributedStmtClass: | |||
| 5458 | // As a general principle, C++11 attributes can be ignored without | |||
| 5459 | // any semantic impact. | |||
| 5460 | return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), | |||
| 5461 | Case); | |||
| 5462 | ||||
| 5463 | case Stmt::CaseStmtClass: | |||
| 5464 | case Stmt::DefaultStmtClass: | |||
| 5465 | return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); | |||
| 5466 | case Stmt::CXXTryStmtClass: | |||
| 5467 | // Evaluate try blocks by evaluating all sub statements. | |||
| 5468 | return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); | |||
| 5469 | } | |||
| 5470 | } | |||
| 5471 | ||||
| 5472 | /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial | |||
| 5473 | /// default constructor. If so, we'll fold it whether or not it's marked as | |||
| 5474 | /// constexpr. If it is marked as constexpr, we will never implicitly define it, | |||
| 5475 | /// so we need special handling. | |||
| 5476 | static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, | |||
| 5477 | const CXXConstructorDecl *CD, | |||
| 5478 | bool IsValueInitialization) { | |||
| 5479 | if (!CD->isTrivial() || !CD->isDefaultConstructor()) | |||
| 5480 | return false; | |||
| 5481 | ||||
| 5482 | // Value-initialization does not call a trivial default constructor, so such a | |||
| 5483 | // call is a core constant expression whether or not the constructor is | |||
| 5484 | // constexpr. | |||
| 5485 | if (!CD->isConstexpr() && !IsValueInitialization) { | |||
| 5486 | if (Info.getLangOpts().CPlusPlus11) { | |||
| 5487 | // FIXME: If DiagDecl is an implicitly-declared special member function, | |||
| 5488 | // we should be much more explicit about why it's not constexpr. | |||
| 5489 | Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) | |||
| 5490 | << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; | |||
| 5491 | Info.Note(CD->getLocation(), diag::note_declared_at); | |||
| 5492 | } else { | |||
| 5493 | Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); | |||
| 5494 | } | |||
| 5495 | } | |||
| 5496 | return true; | |||
| 5497 | } | |||
| 5498 | ||||
| 5499 | /// CheckConstexprFunction - Check that a function can be called in a constant | |||
| 5500 | /// expression. | |||
| 5501 | static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, | |||
| 5502 | const FunctionDecl *Declaration, | |||
| 5503 | const FunctionDecl *Definition, | |||
| 5504 | const Stmt *Body) { | |||
| 5505 | // Potential constant expressions can contain calls to declared, but not yet | |||
| 5506 | // defined, constexpr functions. | |||
| 5507 | if (Info.checkingPotentialConstantExpression() && !Definition && | |||
| 5508 | Declaration->isConstexpr()) | |||
| 5509 | return false; | |||
| 5510 | ||||
| 5511 | // Bail out if the function declaration itself is invalid. We will | |||
| 5512 | // have produced a relevant diagnostic while parsing it, so just | |||
| 5513 | // note the problematic sub-expression. | |||
| 5514 | if (Declaration->isInvalidDecl()) { | |||
| 5515 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | |||
| 5516 | return false; | |||
| 5517 | } | |||
| 5518 | ||||
| 5519 | // DR1872: An instantiated virtual constexpr function can't be called in a | |||
| 5520 | // constant expression (prior to C++20). We can still constant-fold such a | |||
| 5521 | // call. | |||
| 5522 | if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && | |||
| 5523 | cast<CXXMethodDecl>(Declaration)->isVirtual()) | |||
| 5524 | Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); | |||
| 5525 | ||||
| 5526 | if (Definition && Definition->isInvalidDecl()) { | |||
| 5527 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | |||
| 5528 | return false; | |||
| 5529 | } | |||
| 5530 | ||||
| 5531 | // Can we evaluate this function call? | |||
| 5532 | if (Definition && Definition->isConstexpr() && Body) | |||
| 5533 | return true; | |||
| 5534 | ||||
| 5535 | if (Info.getLangOpts().CPlusPlus11) { | |||
| 5536 | const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; | |||
| 5537 | ||||
| 5538 | // If this function is not constexpr because it is an inherited | |||
| 5539 | // non-constexpr constructor, diagnose that directly. | |||
| 5540 | auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); | |||
| 5541 | if (CD && CD->isInheritingConstructor()) { | |||
| 5542 | auto *Inherited = CD->getInheritedConstructor().getConstructor(); | |||
| 5543 | if (!Inherited->isConstexpr()) | |||
| 5544 | DiagDecl = CD = Inherited; | |||
| 5545 | } | |||
| 5546 | ||||
| 5547 | // FIXME: If DiagDecl is an implicitly-declared special member function | |||
| 5548 | // or an inheriting constructor, we should be much more explicit about why | |||
| 5549 | // it's not constexpr. | |||
| 5550 | if (CD && CD->isInheritingConstructor()) | |||
| 5551 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) | |||
| 5552 | << CD->getInheritedConstructor().getConstructor()->getParent(); | |||
| 5553 | else | |||
| 5554 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) | |||
| 5555 | << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; | |||
| 5556 | Info.Note(DiagDecl->getLocation(), diag::note_declared_at); | |||
| 5557 | } else { | |||
| 5558 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | |||
| 5559 | } | |||
| 5560 | return false; | |||
| 5561 | } | |||
| 5562 | ||||
| 5563 | namespace { | |||
| 5564 | struct CheckDynamicTypeHandler { | |||
| 5565 | AccessKinds AccessKind; | |||
| 5566 | typedef bool result_type; | |||
| 5567 | bool failed() { return false; } | |||
| 5568 | bool found(APValue &Subobj, QualType SubobjType) { return true; } | |||
| 5569 | bool found(APSInt &Value, QualType SubobjType) { return true; } | |||
| 5570 | bool found(APFloat &Value, QualType SubobjType) { return true; } | |||
| 5571 | }; | |||
| 5572 | } // end anonymous namespace | |||
| 5573 | ||||
| 5574 | /// Check that we can access the notional vptr of an object / determine its | |||
| 5575 | /// dynamic type. | |||
| 5576 | static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, | |||
| 5577 | AccessKinds AK, bool Polymorphic) { | |||
| 5578 | if (This.Designator.Invalid) | |||
| 5579 | return false; | |||
| 5580 | ||||
| 5581 | CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); | |||
| 5582 | ||||
| 5583 | if (!Obj) | |||
| 5584 | return false; | |||
| 5585 | ||||
| 5586 | if (!Obj.Value) { | |||
| 5587 | // The object is not usable in constant expressions, so we can't inspect | |||
| 5588 | // its value to see if it's in-lifetime or what the active union members | |||
| 5589 | // are. We can still check for a one-past-the-end lvalue. | |||
| 5590 | if (This.Designator.isOnePastTheEnd() || | |||
| 5591 | This.Designator.isMostDerivedAnUnsizedArray()) { | |||
| 5592 | Info.FFDiag(E, This.Designator.isOnePastTheEnd() | |||
| 5593 | ? diag::note_constexpr_access_past_end | |||
| 5594 | : diag::note_constexpr_access_unsized_array) | |||
| 5595 | << AK; | |||
| 5596 | return false; | |||
| 5597 | } else if (Polymorphic) { | |||
| 5598 | // Conservatively refuse to perform a polymorphic operation if we would | |||
| 5599 | // not be able to read a notional 'vptr' value. | |||
| 5600 | APValue Val; | |||
| 5601 | This.moveInto(Val); | |||
| 5602 | QualType StarThisType = | |||
| 5603 | Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); | |||
| 5604 | Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) | |||
| 5605 | << AK << Val.getAsString(Info.Ctx, StarThisType); | |||
| 5606 | return false; | |||
| 5607 | } | |||
| 5608 | return true; | |||
| 5609 | } | |||
| 5610 | ||||
| 5611 | CheckDynamicTypeHandler Handler{AK}; | |||
| 5612 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | |||
| 5613 | } | |||
| 5614 | ||||
| 5615 | /// Check that the pointee of the 'this' pointer in a member function call is | |||
| 5616 | /// either within its lifetime or in its period of construction or destruction. | |||
| 5617 | static bool | |||
| 5618 | checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, | |||
| 5619 | const LValue &This, | |||
| 5620 | const CXXMethodDecl *NamedMember) { | |||
| 5621 | return checkDynamicType( | |||
| 5622 | Info, E, This, | |||
| 5623 | isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); | |||
| 5624 | } | |||
| 5625 | ||||
| 5626 | struct DynamicType { | |||
| 5627 | /// The dynamic class type of the object. | |||
| 5628 | const CXXRecordDecl *Type; | |||
| 5629 | /// The corresponding path length in the lvalue. | |||
| 5630 | unsigned PathLength; | |||
| 5631 | }; | |||
| 5632 | ||||
| 5633 | static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, | |||
| 5634 | unsigned PathLength) { | |||
| 5635 | assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "clang/lib/AST/ExprConstant.cpp", 5636, __extension__ __PRETTY_FUNCTION__ )) | |||
| 5636 | Designator.Entries.size() && "invalid path length")(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "clang/lib/AST/ExprConstant.cpp", 5636, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5637 | return (PathLength == Designator.MostDerivedPathLength) | |||
| 5638 | ? Designator.MostDerivedType->getAsCXXRecordDecl() | |||
| 5639 | : getAsBaseClass(Designator.Entries[PathLength - 1]); | |||
| 5640 | } | |||
| 5641 | ||||
| 5642 | /// Determine the dynamic type of an object. | |||
| 5643 | static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, | |||
| 5644 | LValue &This, AccessKinds AK) { | |||
| 5645 | // If we don't have an lvalue denoting an object of class type, there is no | |||
| 5646 | // meaningful dynamic type. (We consider objects of non-class type to have no | |||
| 5647 | // dynamic type.) | |||
| 5648 | if (!checkDynamicType(Info, E, This, AK, true)) | |||
| 5649 | return None; | |||
| 5650 | ||||
| 5651 | // Refuse to compute a dynamic type in the presence of virtual bases. This | |||
| 5652 | // shouldn't happen other than in constant-folding situations, since literal | |||
| 5653 | // types can't have virtual bases. | |||
| 5654 | // | |||
| 5655 | // Note that consumers of DynamicType assume that the type has no virtual | |||
| 5656 | // bases, and will need modifications if this restriction is relaxed. | |||
| 5657 | const CXXRecordDecl *Class = | |||
| 5658 | This.Designator.MostDerivedType->getAsCXXRecordDecl(); | |||
| 5659 | if (!Class || Class->getNumVBases()) { | |||
| 5660 | Info.FFDiag(E); | |||
| 5661 | return None; | |||
| 5662 | } | |||
| 5663 | ||||
| 5664 | // FIXME: For very deep class hierarchies, it might be beneficial to use a | |||
| 5665 | // binary search here instead. But the overwhelmingly common case is that | |||
| 5666 | // we're not in the middle of a constructor, so it probably doesn't matter | |||
| 5667 | // in practice. | |||
| 5668 | ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; | |||
| 5669 | for (unsigned PathLength = This.Designator.MostDerivedPathLength; | |||
| 5670 | PathLength <= Path.size(); ++PathLength) { | |||
| 5671 | switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), | |||
| 5672 | Path.slice(0, PathLength))) { | |||
| 5673 | case ConstructionPhase::Bases: | |||
| 5674 | case ConstructionPhase::DestroyingBases: | |||
| 5675 | // We're constructing or destroying a base class. This is not the dynamic | |||
| 5676 | // type. | |||
| 5677 | break; | |||
| 5678 | ||||
| 5679 | case ConstructionPhase::None: | |||
| 5680 | case ConstructionPhase::AfterBases: | |||
| 5681 | case ConstructionPhase::AfterFields: | |||
| 5682 | case ConstructionPhase::Destroying: | |||
| 5683 | // We've finished constructing the base classes and not yet started | |||
| 5684 | // destroying them again, so this is the dynamic type. | |||
| 5685 | return DynamicType{getBaseClassType(This.Designator, PathLength), | |||
| 5686 | PathLength}; | |||
| 5687 | } | |||
| 5688 | } | |||
| 5689 | ||||
| 5690 | // CWG issue 1517: we're constructing a base class of the object described by | |||
| 5691 | // 'This', so that object has not yet begun its period of construction and | |||
| 5692 | // any polymorphic operation on it results in undefined behavior. | |||
| 5693 | Info.FFDiag(E); | |||
| 5694 | return None; | |||
| 5695 | } | |||
| 5696 | ||||
| 5697 | /// Perform virtual dispatch. | |||
| 5698 | static const CXXMethodDecl *HandleVirtualDispatch( | |||
| 5699 | EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, | |||
| 5700 | llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { | |||
| 5701 | Optional<DynamicType> DynType = ComputeDynamicType( | |||
| 5702 | Info, E, This, | |||
| 5703 | isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); | |||
| 5704 | if (!DynType) | |||
| 5705 | return nullptr; | |||
| 5706 | ||||
| 5707 | // Find the final overrider. It must be declared in one of the classes on the | |||
| 5708 | // path from the dynamic type to the static type. | |||
| 5709 | // FIXME: If we ever allow literal types to have virtual base classes, that | |||
| 5710 | // won't be true. | |||
| 5711 | const CXXMethodDecl *Callee = Found; | |||
| 5712 | unsigned PathLength = DynType->PathLength; | |||
| 5713 | for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { | |||
| 5714 | const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); | |||
| 5715 | const CXXMethodDecl *Overrider = | |||
| 5716 | Found->getCorrespondingMethodDeclaredInClass(Class, false); | |||
| 5717 | if (Overrider) { | |||
| 5718 | Callee = Overrider; | |||
| 5719 | break; | |||
| 5720 | } | |||
| 5721 | } | |||
| 5722 | ||||
| 5723 | // C++2a [class.abstract]p6: | |||
| 5724 | // the effect of making a virtual call to a pure virtual function [...] is | |||
| 5725 | // undefined | |||
| 5726 | if (Callee->isPure()) { | |||
| 5727 | Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; | |||
| 5728 | Info.Note(Callee->getLocation(), diag::note_declared_at); | |||
| 5729 | return nullptr; | |||
| 5730 | } | |||
| 5731 | ||||
| 5732 | // If necessary, walk the rest of the path to determine the sequence of | |||
| 5733 | // covariant adjustment steps to apply. | |||
| 5734 | if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), | |||
| 5735 | Found->getReturnType())) { | |||
| 5736 | CovariantAdjustmentPath.push_back(Callee->getReturnType()); | |||
| 5737 | for (unsigned CovariantPathLength = PathLength + 1; | |||
| 5738 | CovariantPathLength != This.Designator.Entries.size(); | |||
| 5739 | ++CovariantPathLength) { | |||
| 5740 | const CXXRecordDecl *NextClass = | |||
| 5741 | getBaseClassType(This.Designator, CovariantPathLength); | |||
| 5742 | const CXXMethodDecl *Next = | |||
| 5743 | Found->getCorrespondingMethodDeclaredInClass(NextClass, false); | |||
| 5744 | if (Next && !Info.Ctx.hasSameUnqualifiedType( | |||
| 5745 | Next->getReturnType(), CovariantAdjustmentPath.back())) | |||
| 5746 | CovariantAdjustmentPath.push_back(Next->getReturnType()); | |||
| 5747 | } | |||
| 5748 | if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), | |||
| 5749 | CovariantAdjustmentPath.back())) | |||
| 5750 | CovariantAdjustmentPath.push_back(Found->getReturnType()); | |||
| 5751 | } | |||
| 5752 | ||||
| 5753 | // Perform 'this' adjustment. | |||
| 5754 | if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) | |||
| 5755 | return nullptr; | |||
| 5756 | ||||
| 5757 | return Callee; | |||
| 5758 | } | |||
| 5759 | ||||
| 5760 | /// Perform the adjustment from a value returned by a virtual function to | |||
| 5761 | /// a value of the statically expected type, which may be a pointer or | |||
| 5762 | /// reference to a base class of the returned type. | |||
| 5763 | static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, | |||
| 5764 | APValue &Result, | |||
| 5765 | ArrayRef<QualType> Path) { | |||
| 5766 | assert(Result.isLValue() &&(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "clang/lib/AST/ExprConstant.cpp", 5767, __extension__ __PRETTY_FUNCTION__ )) | |||
| 5767 | "unexpected kind of APValue for covariant return")(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "clang/lib/AST/ExprConstant.cpp", 5767, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5768 | if (Result.isNullPointer()) | |||
| 5769 | return true; | |||
| 5770 | ||||
| 5771 | LValue LVal; | |||
| 5772 | LVal.setFrom(Info.Ctx, Result); | |||
| 5773 | ||||
| 5774 | const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); | |||
| 5775 | for (unsigned I = 1; I != Path.size(); ++I) { | |||
| 5776 | const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); | |||
| 5777 | assert(OldClass && NewClass && "unexpected kind of covariant return")(static_cast <bool> (OldClass && NewClass && "unexpected kind of covariant return") ? void (0) : __assert_fail ("OldClass && NewClass && \"unexpected kind of covariant return\"" , "clang/lib/AST/ExprConstant.cpp", 5777, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5778 | if (OldClass != NewClass && | |||
| 5779 | !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) | |||
| 5780 | return false; | |||
| 5781 | OldClass = NewClass; | |||
| 5782 | } | |||
| 5783 | ||||
| 5784 | LVal.moveInto(Result); | |||
| 5785 | return true; | |||
| 5786 | } | |||
| 5787 | ||||
| 5788 | /// Determine whether \p Base, which is known to be a direct base class of | |||
| 5789 | /// \p Derived, is a public base class. | |||
| 5790 | static bool isBaseClassPublic(const CXXRecordDecl *Derived, | |||
| 5791 | const CXXRecordDecl *Base) { | |||
| 5792 | for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { | |||
| 5793 | auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); | |||
| 5794 | if (BaseClass && declaresSameEntity(BaseClass, Base)) | |||
| 5795 | return BaseSpec.getAccessSpecifier() == AS_public; | |||
| 5796 | } | |||
| 5797 | llvm_unreachable("Base is not a direct base of Derived")::llvm::llvm_unreachable_internal("Base is not a direct base of Derived" , "clang/lib/AST/ExprConstant.cpp", 5797); | |||
| 5798 | } | |||
| 5799 | ||||
| 5800 | /// Apply the given dynamic cast operation on the provided lvalue. | |||
| 5801 | /// | |||
| 5802 | /// This implements the hard case of dynamic_cast, requiring a "runtime check" | |||
| 5803 | /// to find a suitable target subobject. | |||
| 5804 | static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, | |||
| 5805 | LValue &Ptr) { | |||
| 5806 | // We can't do anything with a non-symbolic pointer value. | |||
| 5807 | SubobjectDesignator &D = Ptr.Designator; | |||
| 5808 | if (D.Invalid) | |||
| 5809 | return false; | |||
| 5810 | ||||
| 5811 | // C++ [expr.dynamic.cast]p6: | |||
| 5812 | // If v is a null pointer value, the result is a null pointer value. | |||
| 5813 | if (Ptr.isNullPointer() && !E->isGLValue()) | |||
| 5814 | return true; | |||
| 5815 | ||||
| 5816 | // For all the other cases, we need the pointer to point to an object within | |||
| 5817 | // its lifetime / period of construction / destruction, and we need to know | |||
| 5818 | // its dynamic type. | |||
| 5819 | Optional<DynamicType> DynType = | |||
| 5820 | ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); | |||
| 5821 | if (!DynType) | |||
| 5822 | return false; | |||
| 5823 | ||||
| 5824 | // C++ [expr.dynamic.cast]p7: | |||
| 5825 | // If T is "pointer to cv void", then the result is a pointer to the most | |||
| 5826 | // derived object | |||
| 5827 | if (E->getType()->isVoidPointerType()) | |||
| 5828 | return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); | |||
| 5829 | ||||
| 5830 | const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); | |||
| 5831 | assert(C && "dynamic_cast target is not void pointer nor class")(static_cast <bool> (C && "dynamic_cast target is not void pointer nor class" ) ? void (0) : __assert_fail ("C && \"dynamic_cast target is not void pointer nor class\"" , "clang/lib/AST/ExprConstant.cpp", 5831, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5832 | CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); | |||
| 5833 | ||||
| 5834 | auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { | |||
| 5835 | // C++ [expr.dynamic.cast]p9: | |||
| 5836 | if (!E->isGLValue()) { | |||
| 5837 | // The value of a failed cast to pointer type is the null pointer value | |||
| 5838 | // of the required result type. | |||
| 5839 | Ptr.setNull(Info.Ctx, E->getType()); | |||
| 5840 | return true; | |||
| 5841 | } | |||
| 5842 | ||||
| 5843 | // A failed cast to reference type throws [...] std::bad_cast. | |||
| 5844 | unsigned DiagKind; | |||
| 5845 | if (!Paths && (declaresSameEntity(DynType->Type, C) || | |||
| 5846 | DynType->Type->isDerivedFrom(C))) | |||
| 5847 | DiagKind = 0; | |||
| 5848 | else if (!Paths || Paths->begin() == Paths->end()) | |||
| 5849 | DiagKind = 1; | |||
| 5850 | else if (Paths->isAmbiguous(CQT)) | |||
| 5851 | DiagKind = 2; | |||
| 5852 | else { | |||
| 5853 | assert(Paths->front().Access != AS_public && "why did the cast fail?")(static_cast <bool> (Paths->front().Access != AS_public && "why did the cast fail?") ? void (0) : __assert_fail ("Paths->front().Access != AS_public && \"why did the cast fail?\"" , "clang/lib/AST/ExprConstant.cpp", 5853, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5854 | DiagKind = 3; | |||
| 5855 | } | |||
| 5856 | Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) | |||
| 5857 | << DiagKind << Ptr.Designator.getType(Info.Ctx) | |||
| 5858 | << Info.Ctx.getRecordType(DynType->Type) | |||
| 5859 | << E->getType().getUnqualifiedType(); | |||
| 5860 | return false; | |||
| 5861 | }; | |||
| 5862 | ||||
| 5863 | // Runtime check, phase 1: | |||
| 5864 | // Walk from the base subobject towards the derived object looking for the | |||
| 5865 | // target type. | |||
| 5866 | for (int PathLength = Ptr.Designator.Entries.size(); | |||
| 5867 | PathLength >= (int)DynType->PathLength; --PathLength) { | |||
| 5868 | const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); | |||
| 5869 | if (declaresSameEntity(Class, C)) | |||
| 5870 | return CastToDerivedClass(Info, E, Ptr, Class, PathLength); | |||
| 5871 | // We can only walk across public inheritance edges. | |||
| 5872 | if (PathLength > (int)DynType->PathLength && | |||
| 5873 | !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), | |||
| 5874 | Class)) | |||
| 5875 | return RuntimeCheckFailed(nullptr); | |||
| 5876 | } | |||
| 5877 | ||||
| 5878 | // Runtime check, phase 2: | |||
| 5879 | // Search the dynamic type for an unambiguous public base of type C. | |||
| 5880 | CXXBasePaths Paths(/*FindAmbiguities=*/true, | |||
| 5881 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | |||
| 5882 | if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && | |||
| 5883 | Paths.front().Access == AS_public) { | |||
| 5884 | // Downcast to the dynamic type... | |||
| 5885 | if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) | |||
| 5886 | return false; | |||
| 5887 | // ... then upcast to the chosen base class subobject. | |||
| 5888 | for (CXXBasePathElement &Elem : Paths.front()) | |||
| 5889 | if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) | |||
| 5890 | return false; | |||
| 5891 | return true; | |||
| 5892 | } | |||
| 5893 | ||||
| 5894 | // Otherwise, the runtime check fails. | |||
| 5895 | return RuntimeCheckFailed(&Paths); | |||
| 5896 | } | |||
| 5897 | ||||
| 5898 | namespace { | |||
| 5899 | struct StartLifetimeOfUnionMemberHandler { | |||
| 5900 | EvalInfo &Info; | |||
| 5901 | const Expr *LHSExpr; | |||
| 5902 | const FieldDecl *Field; | |||
| 5903 | bool DuringInit; | |||
| 5904 | bool Failed = false; | |||
| 5905 | static const AccessKinds AccessKind = AK_Assign; | |||
| 5906 | ||||
| 5907 | typedef bool result_type; | |||
| 5908 | bool failed() { return Failed; } | |||
| 5909 | bool found(APValue &Subobj, QualType SubobjType) { | |||
| 5910 | // We are supposed to perform no initialization but begin the lifetime of | |||
| 5911 | // the object. We interpret that as meaning to do what default | |||
| 5912 | // initialization of the object would do if all constructors involved were | |||
| 5913 | // trivial: | |||
| 5914 | // * All base, non-variant member, and array element subobjects' lifetimes | |||
| 5915 | // begin | |||
| 5916 | // * No variant members' lifetimes begin | |||
| 5917 | // * All scalar subobjects whose lifetimes begin have indeterminate values | |||
| 5918 | assert(SubobjType->isUnionType())(static_cast <bool> (SubobjType->isUnionType()) ? void (0) : __assert_fail ("SubobjType->isUnionType()", "clang/lib/AST/ExprConstant.cpp" , 5918, __extension__ __PRETTY_FUNCTION__)); | |||
| 5919 | if (declaresSameEntity(Subobj.getUnionField(), Field)) { | |||
| 5920 | // This union member is already active. If it's also in-lifetime, there's | |||
| 5921 | // nothing to do. | |||
| 5922 | if (Subobj.getUnionValue().hasValue()) | |||
| 5923 | return true; | |||
| 5924 | } else if (DuringInit) { | |||
| 5925 | // We're currently in the process of initializing a different union | |||
| 5926 | // member. If we carried on, that initialization would attempt to | |||
| 5927 | // store to an inactive union member, resulting in undefined behavior. | |||
| 5928 | Info.FFDiag(LHSExpr, | |||
| 5929 | diag::note_constexpr_union_member_change_during_init); | |||
| 5930 | return false; | |||
| 5931 | } | |||
| 5932 | APValue Result; | |||
| 5933 | Failed = !getDefaultInitValue(Field->getType(), Result); | |||
| 5934 | Subobj.setUnion(Field, Result); | |||
| 5935 | return true; | |||
| 5936 | } | |||
| 5937 | bool found(APSInt &Value, QualType SubobjType) { | |||
| 5938 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "clang/lib/AST/ExprConstant.cpp", 5938); | |||
| 5939 | } | |||
| 5940 | bool found(APFloat &Value, QualType SubobjType) { | |||
| 5941 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "clang/lib/AST/ExprConstant.cpp", 5941); | |||
| 5942 | } | |||
| 5943 | }; | |||
| 5944 | } // end anonymous namespace | |||
| 5945 | ||||
| 5946 | const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; | |||
| 5947 | ||||
| 5948 | /// Handle a builtin simple-assignment or a call to a trivial assignment | |||
| 5949 | /// operator whose left-hand side might involve a union member access. If it | |||
| 5950 | /// does, implicitly start the lifetime of any accessed union elements per | |||
| 5951 | /// C++20 [class.union]5. | |||
| 5952 | static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, | |||
| 5953 | const LValue &LHS) { | |||
| 5954 | if (LHS.InvalidBase || LHS.Designator.Invalid) | |||
| 5955 | return false; | |||
| 5956 | ||||
| 5957 | llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; | |||
| 5958 | // C++ [class.union]p5: | |||
| 5959 | // define the set S(E) of subexpressions of E as follows: | |||
| 5960 | unsigned PathLength = LHS.Designator.Entries.size(); | |||
| 5961 | for (const Expr *E = LHSExpr; E != nullptr;) { | |||
| 5962 | // -- If E is of the form A.B, S(E) contains the elements of S(A)... | |||
| 5963 | if (auto *ME = dyn_cast<MemberExpr>(E)) { | |||
| 5964 | auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
| 5965 | // Note that we can't implicitly start the lifetime of a reference, | |||
| 5966 | // so we don't need to proceed any further if we reach one. | |||
| 5967 | if (!FD || FD->getType()->isReferenceType()) | |||
| 5968 | break; | |||
| 5969 | ||||
| 5970 | // ... and also contains A.B if B names a union member ... | |||
| 5971 | if (FD->getParent()->isUnion()) { | |||
| 5972 | // ... of a non-class, non-array type, or of a class type with a | |||
| 5973 | // trivial default constructor that is not deleted, or an array of | |||
| 5974 | // such types. | |||
| 5975 | auto *RD = | |||
| 5976 | FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
| 5977 | if (!RD || RD->hasTrivialDefaultConstructor()) | |||
| 5978 | UnionPathLengths.push_back({PathLength - 1, FD}); | |||
| 5979 | } | |||
| 5980 | ||||
| 5981 | E = ME->getBase(); | |||
| 5982 | --PathLength; | |||
| 5983 | assert(declaresSameEntity(FD,(static_cast <bool> (declaresSameEntity(FD, LHS.Designator .Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "clang/lib/AST/ExprConstant.cpp", 5985, __extension__ __PRETTY_FUNCTION__ )) | |||
| 5984 | LHS.Designator.Entries[PathLength](static_cast <bool> (declaresSameEntity(FD, LHS.Designator .Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "clang/lib/AST/ExprConstant.cpp", 5985, __extension__ __PRETTY_FUNCTION__ )) | |||
| 5985 | .getAsBaseOrMember().getPointer()))(static_cast <bool> (declaresSameEntity(FD, LHS.Designator .Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "clang/lib/AST/ExprConstant.cpp", 5985, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5986 | ||||
| 5987 | // -- If E is of the form A[B] and is interpreted as a built-in array | |||
| 5988 | // subscripting operator, S(E) is [S(the array operand, if any)]. | |||
| 5989 | } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { | |||
| 5990 | // Step over an ArrayToPointerDecay implicit cast. | |||
| 5991 | auto *Base = ASE->getBase()->IgnoreImplicit(); | |||
| 5992 | if (!Base->getType()->isArrayType()) | |||
| 5993 | break; | |||
| 5994 | ||||
| 5995 | E = Base; | |||
| 5996 | --PathLength; | |||
| 5997 | ||||
| 5998 | } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { | |||
| 5999 | // Step over a derived-to-base conversion. | |||
| 6000 | E = ICE->getSubExpr(); | |||
| 6001 | if (ICE->getCastKind() == CK_NoOp) | |||
| 6002 | continue; | |||
| 6003 | if (ICE->getCastKind() != CK_DerivedToBase && | |||
| 6004 | ICE->getCastKind() != CK_UncheckedDerivedToBase) | |||
| 6005 | break; | |||
| 6006 | // Walk path backwards as we walk up from the base to the derived class. | |||
| 6007 | for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { | |||
| 6008 | --PathLength; | |||
| 6009 | (void)Elt; | |||
| 6010 | assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),(static_cast <bool> (declaresSameEntity(Elt->getType ()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength ] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "clang/lib/AST/ExprConstant.cpp", 6012, __extension__ __PRETTY_FUNCTION__ )) | |||
| 6011 | LHS.Designator.Entries[PathLength](static_cast <bool> (declaresSameEntity(Elt->getType ()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength ] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "clang/lib/AST/ExprConstant.cpp", 6012, __extension__ __PRETTY_FUNCTION__ )) | |||
| 6012 | .getAsBaseOrMember().getPointer()))(static_cast <bool> (declaresSameEntity(Elt->getType ()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength ] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "clang/lib/AST/ExprConstant.cpp", 6012, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6013 | } | |||
| 6014 | ||||
| 6015 | // -- Otherwise, S(E) is empty. | |||
| 6016 | } else { | |||
| 6017 | break; | |||
| 6018 | } | |||
| 6019 | } | |||
| 6020 | ||||
| 6021 | // Common case: no unions' lifetimes are started. | |||
| 6022 | if (UnionPathLengths.empty()) | |||
| 6023 | return true; | |||
| 6024 | ||||
| 6025 | // if modification of X [would access an inactive union member], an object | |||
| 6026 | // of the type of X is implicitly created | |||
| 6027 | CompleteObject Obj = | |||
| 6028 | findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); | |||
| ||||
| 6029 | if (!Obj) | |||
| 6030 | return false; | |||
| 6031 | for (std::pair<unsigned, const FieldDecl *> LengthAndField : | |||
| 6032 | llvm::reverse(UnionPathLengths)) { | |||
| 6033 | // Form a designator for the union object. | |||
| 6034 | SubobjectDesignator D = LHS.Designator; | |||
| 6035 | D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); | |||
| 6036 | ||||
| 6037 | bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == | |||
| 6038 | ConstructionPhase::AfterBases; | |||
| 6039 | StartLifetimeOfUnionMemberHandler StartLifetime{ | |||
| 6040 | Info, LHSExpr, LengthAndField.second, DuringInit}; | |||
| 6041 | if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) | |||
| 6042 | return false; | |||
| 6043 | } | |||
| 6044 | ||||
| 6045 | return true; | |||
| 6046 | } | |||
| 6047 | ||||
| 6048 | static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, | |||
| 6049 | CallRef Call, EvalInfo &Info, | |||
| 6050 | bool NonNull = false) { | |||
| 6051 | LValue LV; | |||
| 6052 | // Create the parameter slot and register its destruction. For a vararg | |||
| 6053 | // argument, create a temporary. | |||
| 6054 | // FIXME: For calling conventions that destroy parameters in the callee, | |||
| 6055 | // should we consider performing destruction when the function returns | |||
| 6056 | // instead? | |||
| 6057 | APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) | |||
| 6058 | : Info.CurrentCall->createTemporary(Arg, Arg->getType(), | |||
| 6059 | ScopeKind::Call, LV); | |||
| 6060 | if (!EvaluateInPlace(V, Info, LV, Arg)) | |||
| 6061 | return false; | |||
| 6062 | ||||
| 6063 | // Passing a null pointer to an __attribute__((nonnull)) parameter results in | |||
| 6064 | // undefined behavior, so is non-constant. | |||
| 6065 | if (NonNull && V.isLValue() && V.isNullPointer()) { | |||
| 6066 | Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); | |||
| 6067 | return false; | |||
| 6068 | } | |||
| 6069 | ||||
| 6070 | return true; | |||
| 6071 | } | |||
| 6072 | ||||
| 6073 | /// Evaluate the arguments to a function call. | |||
| 6074 | static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, | |||
| 6075 | EvalInfo &Info, const FunctionDecl *Callee, | |||
| 6076 | bool RightToLeft = false) { | |||
| 6077 | bool Success = true; | |||
| 6078 | llvm::SmallBitVector ForbiddenNullArgs; | |||
| 6079 | if (Callee->hasAttr<NonNullAttr>()) { | |||
| 6080 | ForbiddenNullArgs.resize(Args.size()); | |||
| 6081 | for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { | |||
| 6082 | if (!Attr->args_size()) { | |||
| 6083 | ForbiddenNullArgs.set(); | |||
| 6084 | break; | |||
| 6085 | } else | |||
| 6086 | for (auto Idx : Attr->args()) { | |||
| 6087 | unsigned ASTIdx = Idx.getASTIndex(); | |||
| 6088 | if (ASTIdx >= Args.size()) | |||
| 6089 | continue; | |||
| 6090 | ForbiddenNullArgs[ASTIdx] = true; | |||
| 6091 | } | |||
| 6092 | } | |||
| 6093 | } | |||
| 6094 | for (unsigned I = 0; I < Args.size(); I++) { | |||
| 6095 | unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; | |||
| 6096 | const ParmVarDecl *PVD = | |||
| 6097 | Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; | |||
| 6098 | bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; | |||
| 6099 | if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { | |||
| 6100 | // If we're checking for a potential constant expression, evaluate all | |||
| 6101 | // initializers even if some of them fail. | |||
| 6102 | if (!Info.noteFailure()) | |||
| 6103 | return false; | |||
| 6104 | Success = false; | |||
| 6105 | } | |||
| 6106 | } | |||
| 6107 | return Success; | |||
| 6108 | } | |||
| 6109 | ||||
| 6110 | /// Perform a trivial copy from Param, which is the parameter of a copy or move | |||
| 6111 | /// constructor or assignment operator. | |||
| 6112 | static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, | |||
| 6113 | const Expr *E, APValue &Result, | |||
| 6114 | bool CopyObjectRepresentation) { | |||
| 6115 | // Find the reference argument. | |||
| 6116 | CallStackFrame *Frame = Info.CurrentCall; | |||
| 6117 | APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); | |||
| 6118 | if (!RefValue) { | |||
| 6119 | Info.FFDiag(E); | |||
| 6120 | return false; | |||
| 6121 | } | |||
| 6122 | ||||
| 6123 | // Copy out the contents of the RHS object. | |||
| 6124 | LValue RefLValue; | |||
| 6125 | RefLValue.setFrom(Info.Ctx, *RefValue); | |||
| 6126 | return handleLValueToRValueConversion( | |||
| 6127 | Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, | |||
| 6128 | CopyObjectRepresentation); | |||
| 6129 | } | |||
| 6130 | ||||
| 6131 | /// Evaluate a function call. | |||
| 6132 | static bool HandleFunctionCall(SourceLocation CallLoc, | |||
| 6133 | const FunctionDecl *Callee, const LValue *This, | |||
| 6134 | ArrayRef<const Expr *> Args, CallRef Call, | |||
| 6135 | const Stmt *Body, EvalInfo &Info, | |||
| 6136 | APValue &Result, const LValue *ResultSlot) { | |||
| 6137 | if (!Info.CheckCallLimit(CallLoc)) | |||
| 6138 | return false; | |||
| 6139 | ||||
| 6140 | CallStackFrame Frame(Info, CallLoc, Callee, This, Call); | |||
| 6141 | ||||
| 6142 | // For a trivial copy or move assignment, perform an APValue copy. This is | |||
| 6143 | // essential for unions, where the operations performed by the assignment | |||
| 6144 | // operator cannot be represented as statements. | |||
| 6145 | // | |||
| 6146 | // Skip this for non-union classes with no fields; in that case, the defaulted | |||
| 6147 | // copy/move does not actually read the object. | |||
| 6148 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); | |||
| 6149 | if (MD && MD->isDefaulted() && | |||
| 6150 | (MD->getParent()->isUnion() || | |||
| 6151 | (MD->isTrivial() && | |||
| 6152 | isReadByLvalueToRvalueConversion(MD->getParent())))) { | |||
| 6153 | assert(This &&(static_cast <bool> (This && (MD->isCopyAssignmentOperator () || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "clang/lib/AST/ExprConstant.cpp", 6154, __extension__ __PRETTY_FUNCTION__ )) | |||
| 6154 | (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))(static_cast <bool> (This && (MD->isCopyAssignmentOperator () || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "clang/lib/AST/ExprConstant.cpp", 6154, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6155 | APValue RHSValue; | |||
| 6156 | if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, | |||
| 6157 | MD->getParent()->isUnion())) | |||
| 6158 | return false; | |||
| 6159 | if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), | |||
| 6160 | RHSValue)) | |||
| 6161 | return false; | |||
| 6162 | This->moveInto(Result); | |||
| 6163 | return true; | |||
| 6164 | } else if (MD && isLambdaCallOperator(MD)) { | |||
| 6165 | // We're in a lambda; determine the lambda capture field maps unless we're | |||
| 6166 | // just constexpr checking a lambda's call operator. constexpr checking is | |||
| 6167 | // done before the captures have been added to the closure object (unless | |||
| 6168 | // we're inferring constexpr-ness), so we don't have access to them in this | |||
| 6169 | // case. But since we don't need the captures to constexpr check, we can | |||
| 6170 | // just ignore them. | |||
| 6171 | if (!Info.checkingPotentialConstantExpression()) | |||
| 6172 | MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, | |||
| 6173 | Frame.LambdaThisCaptureField); | |||
| 6174 | } | |||
| 6175 | ||||
| 6176 | StmtResult Ret = {Result, ResultSlot}; | |||
| 6177 | EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); | |||
| 6178 | if (ESR == ESR_Succeeded) { | |||
| 6179 | if (Callee->getReturnType()->isVoidType()) | |||
| 6180 | return true; | |||
| 6181 | Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); | |||
| 6182 | } | |||
| 6183 | return ESR == ESR_Returned; | |||
| 6184 | } | |||
| 6185 | ||||
| 6186 | /// Evaluate a constructor call. | |||
| 6187 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | |||
| 6188 | CallRef Call, | |||
| 6189 | const CXXConstructorDecl *Definition, | |||
| 6190 | EvalInfo &Info, APValue &Result) { | |||
| 6191 | SourceLocation CallLoc = E->getExprLoc(); | |||
| 6192 | if (!Info.CheckCallLimit(CallLoc)) | |||
| 6193 | return false; | |||
| 6194 | ||||
| 6195 | const CXXRecordDecl *RD = Definition->getParent(); | |||
| 6196 | if (RD->getNumVBases()) { | |||
| 6197 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | |||
| 6198 | return false; | |||
| 6199 | } | |||
| 6200 | ||||
| 6201 | EvalInfo::EvaluatingConstructorRAII EvalObj( | |||
| 6202 | Info, | |||
| 6203 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | |||
| 6204 | RD->getNumBases()); | |||
| 6205 | CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); | |||
| 6206 | ||||
| 6207 | // FIXME: Creating an APValue just to hold a nonexistent return value is | |||
| 6208 | // wasteful. | |||
| 6209 | APValue RetVal; | |||
| 6210 | StmtResult Ret = {RetVal, nullptr}; | |||
| 6211 | ||||
| 6212 | // If it's a delegating constructor, delegate. | |||
| 6213 | if (Definition->isDelegatingConstructor()) { | |||
| 6214 | CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); | |||
| 6215 | if ((*I)->getInit()->isValueDependent()) { | |||
| 6216 | if (!EvaluateDependentExpr((*I)->getInit(), Info)) | |||
| 6217 | return false; | |||
| 6218 | } else { | |||
| 6219 | FullExpressionRAII InitScope(Info); | |||
| 6220 | if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || | |||
| 6221 | !InitScope.destroy()) | |||
| 6222 | return false; | |||
| 6223 | } | |||
| 6224 | return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; | |||
| 6225 | } | |||
| 6226 | ||||
| 6227 | // For a trivial copy or move constructor, perform an APValue copy. This is | |||
| 6228 | // essential for unions (or classes with anonymous union members), where the | |||
| 6229 | // operations performed by the constructor cannot be represented by | |||
| 6230 | // ctor-initializers. | |||
| 6231 | // | |||
| 6232 | // Skip this for empty non-union classes; we should not perform an | |||
| 6233 | // lvalue-to-rvalue conversion on them because their copy constructor does not | |||
| 6234 | // actually read them. | |||
| 6235 | if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && | |||
| 6236 | (Definition->getParent()->isUnion() || | |||
| 6237 | (Definition->isTrivial() && | |||
| 6238 | isReadByLvalueToRvalueConversion(Definition->getParent())))) { | |||
| 6239 | return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, | |||
| 6240 | Definition->getParent()->isUnion()); | |||
| 6241 | } | |||
| 6242 | ||||
| 6243 | // Reserve space for the struct members. | |||
| 6244 | if (!Result.hasValue()) { | |||
| 6245 | if (!RD->isUnion()) | |||
| 6246 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), | |||
| 6247 | std::distance(RD->field_begin(), RD->field_end())); | |||
| 6248 | else | |||
| 6249 | // A union starts with no active member. | |||
| 6250 | Result = APValue((const FieldDecl*)nullptr); | |||
| 6251 | } | |||
| 6252 | ||||
| 6253 | if (RD->isInvalidDecl()) return false; | |||
| 6254 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | |||
| 6255 | ||||
| 6256 | // A scope for temporaries lifetime-extended by reference members. | |||
| 6257 | BlockScopeRAII LifetimeExtendedScope(Info); | |||
| 6258 | ||||
| 6259 | bool Success = true; | |||
| 6260 | unsigned BasesSeen = 0; | |||
| 6261 | #ifndef NDEBUG | |||
| 6262 | CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); | |||
| 6263 | #endif | |||
| 6264 | CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); | |||
| 6265 | auto SkipToField = [&](FieldDecl *FD, bool Indirect) { | |||
| 6266 | // We might be initializing the same field again if this is an indirect | |||
| 6267 | // field initialization. | |||
| 6268 | if (FieldIt == RD->field_end() || | |||
| 6269 | FieldIt->getFieldIndex() > FD->getFieldIndex()) { | |||
| 6270 | assert(Indirect && "fields out of order?")(static_cast <bool> (Indirect && "fields out of order?" ) ? void (0) : __assert_fail ("Indirect && \"fields out of order?\"" , "clang/lib/AST/ExprConstant.cpp", 6270, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6271 | return; | |||
| 6272 | } | |||
| 6273 | ||||
| 6274 | // Default-initialize any fields with no explicit initializer. | |||
| 6275 | for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { | |||
| 6276 | assert(FieldIt != RD->field_end() && "missing field?")(static_cast <bool> (FieldIt != RD->field_end() && "missing field?") ? void (0) : __assert_fail ("FieldIt != RD->field_end() && \"missing field?\"" , "clang/lib/AST/ExprConstant.cpp", 6276, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6277 | if (!FieldIt->isUnnamedBitfield()) | |||
| 6278 | Success &= getDefaultInitValue( | |||
| 6279 | FieldIt->getType(), | |||
| 6280 | Result.getStructField(FieldIt->getFieldIndex())); | |||
| 6281 | } | |||
| 6282 | ++FieldIt; | |||
| 6283 | }; | |||
| 6284 | for (const auto *I : Definition->inits()) { | |||
| 6285 | LValue Subobject = This; | |||
| 6286 | LValue SubobjectParent = This; | |||
| 6287 | APValue *Value = &Result; | |||
| 6288 | ||||
| 6289 | // Determine the subobject to initialize. | |||
| 6290 | FieldDecl *FD = nullptr; | |||
| 6291 | if (I->isBaseInitializer()) { | |||
| 6292 | QualType BaseType(I->getBaseClass(), 0); | |||
| 6293 | #ifndef NDEBUG | |||
| 6294 | // Non-virtual base classes are initialized in the order in the class | |||
| 6295 | // definition. We have already checked for virtual base classes. | |||
| 6296 | assert(!BaseIt->isVirtual() && "virtual base for literal type")(static_cast <bool> (!BaseIt->isVirtual() && "virtual base for literal type") ? void (0) : __assert_fail ( "!BaseIt->isVirtual() && \"virtual base for literal type\"" , "clang/lib/AST/ExprConstant.cpp", 6296, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6297 | assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType (), BaseType) && "base class initializers not in expected order" ) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "clang/lib/AST/ExprConstant.cpp", 6298, __extension__ __PRETTY_FUNCTION__ )) | |||
| 6298 | "base class initializers not in expected order")(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType (), BaseType) && "base class initializers not in expected order" ) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "clang/lib/AST/ExprConstant.cpp", 6298, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6299 | ++BaseIt; | |||
| 6300 | #endif | |||
| 6301 | if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, | |||
| 6302 | BaseType->getAsCXXRecordDecl(), &Layout)) | |||
| 6303 | return false; | |||
| 6304 | Value = &Result.getStructBase(BasesSeen++); | |||
| 6305 | } else if ((FD = I->getMember())) { | |||
| 6306 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) | |||
| 6307 | return false; | |||
| 6308 | if (RD->isUnion()) { | |||
| 6309 | Result = APValue(FD); | |||
| 6310 | Value = &Result.getUnionValue(); | |||
| 6311 | } else { | |||
| 6312 | SkipToField(FD, false); | |||
| 6313 | Value = &Result.getStructField(FD->getFieldIndex()); | |||
| 6314 | } | |||
| 6315 | } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { | |||
| 6316 | // Walk the indirect field decl's chain to find the object to initialize, | |||
| 6317 | // and make sure we've initialized every step along it. | |||
| 6318 | auto IndirectFieldChain = IFD->chain(); | |||
| 6319 | for (auto *C : IndirectFieldChain) { | |||
| 6320 | FD = cast<FieldDecl>(C); | |||
| 6321 | CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); | |||
| 6322 | // Switch the union field if it differs. This happens if we had | |||
| 6323 | // preceding zero-initialization, and we're now initializing a union | |||
| 6324 | // subobject other than the first. | |||
| 6325 | // FIXME: In this case, the values of the other subobjects are | |||
| 6326 | // specified, since zero-initialization sets all padding bits to zero. | |||
| 6327 | if (!Value->hasValue() || | |||
| 6328 | (Value->isUnion() && Value->getUnionField() != FD)) { | |||
| 6329 | if (CD->isUnion()) | |||
| 6330 | *Value = APValue(FD); | |||
| 6331 | else | |||
| 6332 | // FIXME: This immediately starts the lifetime of all members of | |||
| 6333 | // an anonymous struct. It would be preferable to strictly start | |||
| 6334 | // member lifetime in initialization order. | |||
| 6335 | Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); | |||
| 6336 | } | |||
| 6337 | // Store Subobject as its parent before updating it for the last element | |||
| 6338 | // in the chain. | |||
| 6339 | if (C == IndirectFieldChain.back()) | |||
| 6340 | SubobjectParent = Subobject; | |||
| 6341 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) | |||
| 6342 | return false; | |||
| 6343 | if (CD->isUnion()) | |||
| 6344 | Value = &Value->getUnionValue(); | |||
| 6345 | else { | |||
| 6346 | if (C == IndirectFieldChain.front() && !RD->isUnion()) | |||
| 6347 | SkipToField(FD, true); | |||
| 6348 | Value = &Value->getStructField(FD->getFieldIndex()); | |||
| 6349 | } | |||
| 6350 | } | |||
| 6351 | } else { | |||
| 6352 | llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind" , "clang/lib/AST/ExprConstant.cpp", 6352); | |||
| 6353 | } | |||
| 6354 | ||||
| 6355 | // Need to override This for implicit field initializers as in this case | |||
| 6356 | // This refers to innermost anonymous struct/union containing initializer, | |||
| 6357 | // not to currently constructed class. | |||
| 6358 | const Expr *Init = I->getInit(); | |||
| 6359 | if (Init->isValueDependent()) { | |||
| 6360 | if (!EvaluateDependentExpr(Init, Info)) | |||
| 6361 | return false; | |||
| 6362 | } else { | |||
| 6363 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, | |||
| 6364 | isa<CXXDefaultInitExpr>(Init)); | |||
| 6365 | FullExpressionRAII InitScope(Info); | |||
| 6366 | if (!EvaluateInPlace(*Value, Info, Subobject, Init) || | |||
| 6367 | (FD && FD->isBitField() && | |||
| 6368 | !truncateBitfieldValue(Info, Init, *Value, FD))) { | |||
| 6369 | // If we're checking for a potential constant expression, evaluate all | |||
| 6370 | // initializers even if some of them fail. | |||
| 6371 | if (!Info.noteFailure()) | |||
| 6372 | return false; | |||
| 6373 | Success = false; | |||
| 6374 | } | |||
| 6375 | } | |||
| 6376 | ||||
| 6377 | // This is the point at which the dynamic type of the object becomes this | |||
| 6378 | // class type. | |||
| 6379 | if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) | |||
| 6380 | EvalObj.finishedConstructingBases(); | |||
| 6381 | } | |||
| 6382 | ||||
| 6383 | // Default-initialize any remaining fields. | |||
| 6384 | if (!RD->isUnion()) { | |||
| 6385 | for (; FieldIt != RD->field_end(); ++FieldIt) { | |||
| 6386 | if (!FieldIt->isUnnamedBitfield()) | |||
| 6387 | Success &= getDefaultInitValue( | |||
| 6388 | FieldIt->getType(), | |||
| 6389 | Result.getStructField(FieldIt->getFieldIndex())); | |||
| 6390 | } | |||
| 6391 | } | |||
| 6392 | ||||
| 6393 | EvalObj.finishedConstructingFields(); | |||
| 6394 | ||||
| 6395 | return Success && | |||
| 6396 | EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && | |||
| 6397 | LifetimeExtendedScope.destroy(); | |||
| 6398 | } | |||
| 6399 | ||||
| 6400 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | |||
| 6401 | ArrayRef<const Expr*> Args, | |||
| 6402 | const CXXConstructorDecl *Definition, | |||
| 6403 | EvalInfo &Info, APValue &Result) { | |||
| 6404 | CallScopeRAII CallScope(Info); | |||
| 6405 | CallRef Call = Info.CurrentCall->createCall(Definition); | |||
| 6406 | if (!EvaluateArgs(Args, Call, Info, Definition)) | |||
| 6407 | return false; | |||
| 6408 | ||||
| 6409 | return HandleConstructorCall(E, This, Call, Definition, Info, Result) && | |||
| 6410 | CallScope.destroy(); | |||
| 6411 | } | |||
| 6412 | ||||
| 6413 | static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, | |||
| 6414 | const LValue &This, APValue &Value, | |||
| 6415 | QualType T) { | |||
| 6416 | // Objects can only be destroyed while they're within their lifetimes. | |||
| 6417 | // FIXME: We have no representation for whether an object of type nullptr_t | |||
| 6418 | // is in its lifetime; it usually doesn't matter. Perhaps we should model it | |||
| 6419 | // as indeterminate instead? | |||
| 6420 | if (Value.isAbsent() && !T->isNullPtrType()) { | |||
| 6421 | APValue Printable; | |||
| 6422 | This.moveInto(Printable); | |||
| 6423 | Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) | |||
| 6424 | << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); | |||
| 6425 | return false; | |||
| 6426 | } | |||
| 6427 | ||||
| 6428 | // Invent an expression for location purposes. | |||
| 6429 | // FIXME: We shouldn't need to do this. | |||
| 6430 | OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); | |||
| 6431 | ||||
| 6432 | // For arrays, destroy elements right-to-left. | |||
| 6433 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { | |||
| 6434 | uint64_t Size = CAT->getSize().getZExtValue(); | |||
| 6435 | QualType ElemT = CAT->getElementType(); | |||
| 6436 | ||||
| 6437 | LValue ElemLV = This; | |||
| 6438 | ElemLV.addArray(Info, &LocE, CAT); | |||
| 6439 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) | |||
| 6440 | return false; | |||
| 6441 | ||||
| 6442 | // Ensure that we have actual array elements available to destroy; the | |||
| 6443 | // destructors might mutate the value, so we can't run them on the array | |||
| 6444 | // filler. | |||
| 6445 | if (Size && Size > Value.getArrayInitializedElts()) | |||
| 6446 | expandArray(Value, Value.getArraySize() - 1); | |||
| 6447 | ||||
| 6448 | for (; Size != 0; --Size) { | |||
| 6449 | APValue &Elem = Value.getArrayInitializedElt(Size - 1); | |||
| 6450 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || | |||
| 6451 | !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) | |||
| 6452 | return false; | |||
| 6453 | } | |||
| 6454 | ||||
| 6455 | // End the lifetime of this array now. | |||
| 6456 | Value = APValue(); | |||
| 6457 | return true; | |||
| 6458 | } | |||
| 6459 | ||||
| 6460 | const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); | |||
| 6461 | if (!RD) { | |||
| 6462 | if (T.isDestructedType()) { | |||
| 6463 | Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; | |||
| 6464 | return false; | |||
| 6465 | } | |||
| 6466 | ||||
| 6467 | Value = APValue(); | |||
| 6468 | return true; | |||
| 6469 | } | |||
| 6470 | ||||
| 6471 | if (RD->getNumVBases()) { | |||
| 6472 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | |||
| 6473 | return false; | |||
| 6474 | } | |||
| 6475 | ||||
| 6476 | const CXXDestructorDecl *DD = RD->getDestructor(); | |||
| 6477 | if (!DD && !RD->hasTrivialDestructor()) { | |||
| 6478 | Info.FFDiag(CallLoc); | |||
| 6479 | return false; | |||
| 6480 | } | |||
| 6481 | ||||
| 6482 | if (!DD || DD->isTrivial() || | |||
| 6483 | (RD->isAnonymousStructOrUnion() && RD->isUnion())) { | |||
| 6484 | // A trivial destructor just ends the lifetime of the object. Check for | |||
| 6485 | // this case before checking for a body, because we might not bother | |||
| 6486 | // building a body for a trivial destructor. Note that it doesn't matter | |||
| 6487 | // whether the destructor is constexpr in this case; all trivial | |||
| 6488 | // destructors are constexpr. | |||
| 6489 | // | |||
| 6490 | // If an anonymous union would be destroyed, some enclosing destructor must | |||
| 6491 | // have been explicitly defined, and the anonymous union destruction should | |||
| 6492 | // have no effect. | |||
| 6493 | Value = APValue(); | |||
| 6494 | return true; | |||
| 6495 | } | |||
| 6496 | ||||
| 6497 | if (!Info.CheckCallLimit(CallLoc)) | |||
| 6498 | return false; | |||
| 6499 | ||||
| 6500 | const FunctionDecl *Definition = nullptr; | |||
| 6501 | const Stmt *Body = DD->getBody(Definition); | |||
| 6502 | ||||
| 6503 | if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) | |||
| 6504 | return false; | |||
| 6505 | ||||
| 6506 | CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); | |||
| 6507 | ||||
| 6508 | // We're now in the period of destruction of this object. | |||
| 6509 | unsigned BasesLeft = RD->getNumBases(); | |||
| 6510 | EvalInfo::EvaluatingDestructorRAII EvalObj( | |||
| 6511 | Info, | |||
| 6512 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); | |||
| 6513 | if (!EvalObj.DidInsert) { | |||
| 6514 | // C++2a [class.dtor]p19: | |||
| 6515 | // the behavior is undefined if the destructor is invoked for an object | |||
| 6516 | // whose lifetime has ended | |||
| 6517 | // (Note that formally the lifetime ends when the period of destruction | |||
| 6518 | // begins, even though certain uses of the object remain valid until the | |||
| 6519 | // period of destruction ends.) | |||
| 6520 | Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); | |||
| 6521 | return false; | |||
| 6522 | } | |||
| 6523 | ||||
| 6524 | // FIXME: Creating an APValue just to hold a nonexistent return value is | |||
| 6525 | // wasteful. | |||
| 6526 | APValue RetVal; | |||
| 6527 | StmtResult Ret = {RetVal, nullptr}; | |||
| 6528 | if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) | |||
| 6529 | return false; | |||
| 6530 | ||||
| 6531 | // A union destructor does not implicitly destroy its members. | |||
| 6532 | if (RD->isUnion()) | |||
| 6533 | return true; | |||
| 6534 | ||||
| 6535 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | |||
| 6536 | ||||
| 6537 | // We don't have a good way to iterate fields in reverse, so collect all the | |||
| 6538 | // fields first and then walk them backwards. | |||
| 6539 | SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); | |||
| 6540 | for (const FieldDecl *FD : llvm::reverse(Fields)) { | |||
| 6541 | if (FD->isUnnamedBitfield()) | |||
| 6542 | continue; | |||
| 6543 | ||||
| 6544 | LValue Subobject = This; | |||
| 6545 | if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) | |||
| 6546 | return false; | |||
| 6547 | ||||
| 6548 | APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); | |||
| 6549 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | |||
| 6550 | FD->getType())) | |||
| 6551 | return false; | |||
| 6552 | } | |||
| 6553 | ||||
| 6554 | if (BasesLeft != 0) | |||
| 6555 | EvalObj.startedDestroyingBases(); | |||
| 6556 | ||||
| 6557 | // Destroy base classes in reverse order. | |||
| 6558 | for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { | |||
| 6559 | --BasesLeft; | |||
| 6560 | ||||
| 6561 | QualType BaseType = Base.getType(); | |||
| 6562 | LValue Subobject = This; | |||
| 6563 | if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, | |||
| 6564 | BaseType->getAsCXXRecordDecl(), &Layout)) | |||
| 6565 | return false; | |||
| 6566 | ||||
| 6567 | APValue *SubobjectValue = &Value.getStructBase(BasesLeft); | |||
| 6568 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | |||
| 6569 | BaseType)) | |||
| 6570 | return false; | |||
| 6571 | } | |||
| 6572 | assert(BasesLeft == 0 && "NumBases was wrong?")(static_cast <bool> (BasesLeft == 0 && "NumBases was wrong?" ) ? void (0) : __assert_fail ("BasesLeft == 0 && \"NumBases was wrong?\"" , "clang/lib/AST/ExprConstant.cpp", 6572, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6573 | ||||
| 6574 | // The period of destruction ends now. The object is gone. | |||
| 6575 | Value = APValue(); | |||
| 6576 | return true; | |||
| 6577 | } | |||
| 6578 | ||||
| 6579 | namespace { | |||
| 6580 | struct DestroyObjectHandler { | |||
| 6581 | EvalInfo &Info; | |||
| 6582 | const Expr *E; | |||
| 6583 | const LValue &This; | |||
| 6584 | const AccessKinds AccessKind; | |||
| 6585 | ||||
| 6586 | typedef bool result_type; | |||
| 6587 | bool failed() { return false; } | |||
| 6588 | bool found(APValue &Subobj, QualType SubobjType) { | |||
| 6589 | return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, | |||
| 6590 | SubobjType); | |||
| 6591 | } | |||
| 6592 | bool found(APSInt &Value, QualType SubobjType) { | |||
| 6593 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | |||
| 6594 | return false; | |||
| 6595 | } | |||
| 6596 | bool found(APFloat &Value, QualType SubobjType) { | |||
| 6597 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | |||
| 6598 | return false; | |||
| 6599 | } | |||
| 6600 | }; | |||
| 6601 | } | |||
| 6602 | ||||
| 6603 | /// Perform a destructor or pseudo-destructor call on the given object, which | |||
| 6604 | /// might in general not be a complete object. | |||
| 6605 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | |||
| 6606 | const LValue &This, QualType ThisType) { | |||
| 6607 | CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); | |||
| 6608 | DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; | |||
| 6609 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | |||
| 6610 | } | |||
| 6611 | ||||
| 6612 | /// Destroy and end the lifetime of the given complete object. | |||
| 6613 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | |||
| 6614 | APValue::LValueBase LVBase, APValue &Value, | |||
| 6615 | QualType T) { | |||
| 6616 | // If we've had an unmodeled side-effect, we can't rely on mutable state | |||
| 6617 | // (such as the object we're about to destroy) being correct. | |||
| 6618 | if (Info.EvalStatus.HasSideEffects) | |||
| 6619 | return false; | |||
| 6620 | ||||
| 6621 | LValue LV; | |||
| 6622 | LV.set({LVBase}); | |||
| 6623 | return HandleDestructionImpl(Info, Loc, LV, Value, T); | |||
| 6624 | } | |||
| 6625 | ||||
| 6626 | /// Perform a call to 'perator new' or to `__builtin_operator_new'. | |||
| 6627 | static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, | |||
| 6628 | LValue &Result) { | |||
| 6629 | if (Info.checkingPotentialConstantExpression() || | |||
| 6630 | Info.SpeculativeEvaluationDepth) | |||
| 6631 | return false; | |||
| 6632 | ||||
| 6633 | // This is permitted only within a call to std::allocator<T>::allocate. | |||
| 6634 | auto Caller = Info.getStdAllocatorCaller("allocate"); | |||
| 6635 | if (!Caller) { | |||
| 6636 | Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 | |||
| 6637 | ? diag::note_constexpr_new_untyped | |||
| 6638 | : diag::note_constexpr_new); | |||
| 6639 | return false; | |||
| 6640 | } | |||
| 6641 | ||||
| 6642 | QualType ElemType = Caller.ElemType; | |||
| 6643 | if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { | |||
| 6644 | Info.FFDiag(E->getExprLoc(), | |||
| 6645 | diag::note_constexpr_new_not_complete_object_type) | |||
| 6646 | << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; | |||
| 6647 | return false; | |||
| 6648 | } | |||
| 6649 | ||||
| 6650 | APSInt ByteSize; | |||
| 6651 | if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) | |||
| 6652 | return false; | |||
| 6653 | bool IsNothrow = false; | |||
| 6654 | for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { | |||
| 6655 | EvaluateIgnoredValue(Info, E->getArg(I)); | |||
| 6656 | IsNothrow |= E->getType()->isNothrowT(); | |||
| 6657 | } | |||
| 6658 | ||||
| 6659 | CharUnits ElemSize; | |||
| 6660 | if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) | |||
| 6661 | return false; | |||
| 6662 | APInt Size, Remainder; | |||
| 6663 | APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); | |||
| 6664 | APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); | |||
| 6665 | if (Remainder != 0) { | |||
| 6666 | // This likely indicates a bug in the implementation of 'std::allocator'. | |||
| 6667 | Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) | |||
| 6668 | << ByteSize << APSInt(ElemSizeAP, true) << ElemType; | |||
| 6669 | return false; | |||
| 6670 | } | |||
| 6671 | ||||
| 6672 | if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { | |||
| 6673 | if (IsNothrow) { | |||
| 6674 | Result.setNull(Info.Ctx, E->getType()); | |||
| 6675 | return true; | |||
| 6676 | } | |||
| 6677 | ||||
| 6678 | Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); | |||
| 6679 | return false; | |||
| 6680 | } | |||
| 6681 | ||||
| 6682 | QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, | |||
| 6683 | ArrayType::Normal, 0); | |||
| 6684 | APValue *Val = Info.createHeapAlloc(E, AllocType, Result); | |||
| 6685 | *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); | |||
| 6686 | Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); | |||
| 6687 | return true; | |||
| 6688 | } | |||
| 6689 | ||||
| 6690 | static bool hasVirtualDestructor(QualType T) { | |||
| 6691 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
| 6692 | if (CXXDestructorDecl *DD = RD->getDestructor()) | |||
| 6693 | return DD->isVirtual(); | |||
| 6694 | return false; | |||
| 6695 | } | |||
| 6696 | ||||
| 6697 | static const FunctionDecl *getVirtualOperatorDelete(QualType T) { | |||
| 6698 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
| 6699 | if (CXXDestructorDecl *DD = RD->getDestructor()) | |||
| 6700 | return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; | |||
| 6701 | return nullptr; | |||
| 6702 | } | |||
| 6703 | ||||
| 6704 | /// Check that the given object is a suitable pointer to a heap allocation that | |||
| 6705 | /// still exists and is of the right kind for the purpose of a deletion. | |||
| 6706 | /// | |||
| 6707 | /// On success, returns the heap allocation to deallocate. On failure, produces | |||
| 6708 | /// a diagnostic and returns None. | |||
| 6709 | static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, | |||
| 6710 | const LValue &Pointer, | |||
| 6711 | DynAlloc::Kind DeallocKind) { | |||
| 6712 | auto PointerAsString = [&] { | |||
| 6713 | return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); | |||
| 6714 | }; | |||
| 6715 | ||||
| 6716 | DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); | |||
| 6717 | if (!DA) { | |||
| 6718 | Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) | |||
| 6719 | << PointerAsString(); | |||
| 6720 | if (Pointer.Base) | |||
| 6721 | NoteLValueLocation(Info, Pointer.Base); | |||
| 6722 | return None; | |||
| 6723 | } | |||
| 6724 | ||||
| 6725 | Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); | |||
| 6726 | if (!Alloc) { | |||
| 6727 | Info.FFDiag(E, diag::note_constexpr_double_delete); | |||
| 6728 | return None; | |||
| 6729 | } | |||
| 6730 | ||||
| 6731 | QualType AllocType = Pointer.Base.getDynamicAllocType(); | |||
| 6732 | if (DeallocKind != (*Alloc)->getKind()) { | |||
| 6733 | Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) | |||
| 6734 | << DeallocKind << (*Alloc)->getKind() << AllocType; | |||
| 6735 | NoteLValueLocation(Info, Pointer.Base); | |||
| 6736 | return None; | |||
| 6737 | } | |||
| 6738 | ||||
| 6739 | bool Subobject = false; | |||
| 6740 | if (DeallocKind == DynAlloc::New) { | |||
| 6741 | Subobject = Pointer.Designator.MostDerivedPathLength != 0 || | |||
| 6742 | Pointer.Designator.isOnePastTheEnd(); | |||
| 6743 | } else { | |||
| 6744 | Subobject = Pointer.Designator.Entries.size() != 1 || | |||
| 6745 | Pointer.Designator.Entries[0].getAsArrayIndex() != 0; | |||
| 6746 | } | |||
| 6747 | if (Subobject) { | |||
| 6748 | Info.FFDiag(E, diag::note_constexpr_delete_subobject) | |||
| 6749 | << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); | |||
| 6750 | return None; | |||
| 6751 | } | |||
| 6752 | ||||
| 6753 | return Alloc; | |||
| 6754 | } | |||
| 6755 | ||||
| 6756 | // Perform a call to 'operator delete' or '__builtin_operator_delete'. | |||
| 6757 | bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { | |||
| 6758 | if (Info.checkingPotentialConstantExpression() || | |||
| 6759 | Info.SpeculativeEvaluationDepth) | |||
| 6760 | return false; | |||
| 6761 | ||||
| 6762 | // This is permitted only within a call to std::allocator<T>::deallocate. | |||
| 6763 | if (!Info.getStdAllocatorCaller("deallocate")) { | |||
| 6764 | Info.FFDiag(E->getExprLoc()); | |||
| 6765 | return true; | |||
| 6766 | } | |||
| 6767 | ||||
| 6768 | LValue Pointer; | |||
| 6769 | if (!EvaluatePointer(E->getArg(0), Pointer, Info)) | |||
| 6770 | return false; | |||
| 6771 | for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) | |||
| 6772 | EvaluateIgnoredValue(Info, E->getArg(I)); | |||
| 6773 | ||||
| 6774 | if (Pointer.Designator.Invalid) | |||
| 6775 | return false; | |||
| 6776 | ||||
| 6777 | // Deleting a null pointer would have no effect, but it's not permitted by | |||
| 6778 | // std::allocator<T>::deallocate's contract. | |||
| 6779 | if (Pointer.isNullPointer()) { | |||
| 6780 | Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); | |||
| 6781 | return true; | |||
| 6782 | } | |||
| 6783 | ||||
| 6784 | if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) | |||
| 6785 | return false; | |||
| 6786 | ||||
| 6787 | Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); | |||
| 6788 | return true; | |||
| 6789 | } | |||
| 6790 | ||||
| 6791 | //===----------------------------------------------------------------------===// | |||
| 6792 | // Generic Evaluation | |||
| 6793 | //===----------------------------------------------------------------------===// | |||
| 6794 | namespace { | |||
| 6795 | ||||
| 6796 | class BitCastBuffer { | |||
| 6797 | // FIXME: We're going to need bit-level granularity when we support | |||
| 6798 | // bit-fields. | |||
| 6799 | // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but | |||
| 6800 | // we don't support a host or target where that is the case. Still, we should | |||
| 6801 | // use a more generic type in case we ever do. | |||
| 6802 | SmallVector<Optional<unsigned char>, 32> Bytes; | |||
| 6803 | ||||
| 6804 | static_assert(std::numeric_limits<unsigned char>::digits >= 8, | |||
| 6805 | "Need at least 8 bit unsigned char"); | |||
| 6806 | ||||
| 6807 | bool TargetIsLittleEndian; | |||
| 6808 | ||||
| 6809 | public: | |||
| 6810 | BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) | |||
| 6811 | : Bytes(Width.getQuantity()), | |||
| 6812 | TargetIsLittleEndian(TargetIsLittleEndian) {} | |||
| 6813 | ||||
| 6814 | LLVM_NODISCARD[[clang::warn_unused_result]] | |||
| 6815 | bool readObject(CharUnits Offset, CharUnits Width, | |||
| 6816 | SmallVectorImpl<unsigned char> &Output) const { | |||
| 6817 | for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { | |||
| 6818 | // If a byte of an integer is uninitialized, then the whole integer is | |||
| 6819 | // uninitialized. | |||
| 6820 | if (!Bytes[I.getQuantity()]) | |||
| 6821 | return false; | |||
| 6822 | Output.push_back(*Bytes[I.getQuantity()]); | |||
| 6823 | } | |||
| 6824 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | |||
| 6825 | std::reverse(Output.begin(), Output.end()); | |||
| 6826 | return true; | |||
| 6827 | } | |||
| 6828 | ||||
| 6829 | void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { | |||
| 6830 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | |||
| 6831 | std::reverse(Input.begin(), Input.end()); | |||
| 6832 | ||||
| 6833 | size_t Index = 0; | |||
| 6834 | for (unsigned char Byte : Input) { | |||
| 6835 | assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?")(static_cast <bool> (!Bytes[Offset.getQuantity() + Index ] && "overwriting a byte?") ? void (0) : __assert_fail ("!Bytes[Offset.getQuantity() + Index] && \"overwriting a byte?\"" , "clang/lib/AST/ExprConstant.cpp", 6835, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6836 | Bytes[Offset.getQuantity() + Index] = Byte; | |||
| 6837 | ++Index; | |||
| 6838 | } | |||
| 6839 | } | |||
| 6840 | ||||
| 6841 | size_t size() { return Bytes.size(); } | |||
| 6842 | }; | |||
| 6843 | ||||
| 6844 | /// Traverse an APValue to produce an BitCastBuffer, emulating how the current | |||
| 6845 | /// target would represent the value at runtime. | |||
| 6846 | class APValueToBufferConverter { | |||
| 6847 | EvalInfo &Info; | |||
| 6848 | BitCastBuffer Buffer; | |||
| 6849 | const CastExpr *BCE; | |||
| 6850 | ||||
| 6851 | APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, | |||
| 6852 | const CastExpr *BCE) | |||
| 6853 | : Info(Info), | |||
| 6854 | Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), | |||
| 6855 | BCE(BCE) {} | |||
| 6856 | ||||
| 6857 | bool visit(const APValue &Val, QualType Ty) { | |||
| 6858 | return visit(Val, Ty, CharUnits::fromQuantity(0)); | |||
| 6859 | } | |||
| 6860 | ||||
| 6861 | // Write out Val with type Ty into Buffer starting at Offset. | |||
| 6862 | bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { | |||
| 6863 | assert((size_t)Offset.getQuantity() <= Buffer.size())(static_cast <bool> ((size_t)Offset.getQuantity() <= Buffer.size()) ? void (0) : __assert_fail ("(size_t)Offset.getQuantity() <= Buffer.size()" , "clang/lib/AST/ExprConstant.cpp", 6863, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6864 | ||||
| 6865 | // As a special case, nullptr_t has an indeterminate value. | |||
| 6866 | if (Ty->isNullPtrType()) | |||
| 6867 | return true; | |||
| 6868 | ||||
| 6869 | // Dig through Src to find the byte at SrcOffset. | |||
| 6870 | switch (Val.getKind()) { | |||
| 6871 | case APValue::Indeterminate: | |||
| 6872 | case APValue::None: | |||
| 6873 | return true; | |||
| 6874 | ||||
| 6875 | case APValue::Int: | |||
| 6876 | return visitInt(Val.getInt(), Ty, Offset); | |||
| 6877 | case APValue::Float: | |||
| 6878 | return visitFloat(Val.getFloat(), Ty, Offset); | |||
| 6879 | case APValue::Array: | |||
| 6880 | return visitArray(Val, Ty, Offset); | |||
| 6881 | case APValue::Struct: | |||
| 6882 | return visitRecord(Val, Ty, Offset); | |||
| 6883 | ||||
| 6884 | case APValue::ComplexInt: | |||
| 6885 | case APValue::ComplexFloat: | |||
| 6886 | case APValue::Vector: | |||
| 6887 | case APValue::FixedPoint: | |||
| 6888 | // FIXME: We should support these. | |||
| 6889 | ||||
| 6890 | case APValue::Union: | |||
| 6891 | case APValue::MemberPointer: | |||
| 6892 | case APValue::AddrLabelDiff: { | |||
| 6893 | Info.FFDiag(BCE->getBeginLoc(), | |||
| 6894 | diag::note_constexpr_bit_cast_unsupported_type) | |||
| 6895 | << Ty; | |||
| 6896 | return false; | |||
| 6897 | } | |||
| 6898 | ||||
| 6899 | case APValue::LValue: | |||
| 6900 | llvm_unreachable("LValue subobject in bit_cast?")::llvm::llvm_unreachable_internal("LValue subobject in bit_cast?" , "clang/lib/AST/ExprConstant.cpp", 6900); | |||
| 6901 | } | |||
| 6902 | llvm_unreachable("Unhandled APValue::ValueKind")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind" , "clang/lib/AST/ExprConstant.cpp", 6902); | |||
| 6903 | } | |||
| 6904 | ||||
| 6905 | bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { | |||
| 6906 | const RecordDecl *RD = Ty->getAsRecordDecl(); | |||
| 6907 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | |||
| 6908 | ||||
| 6909 | // Visit the base classes. | |||
| 6910 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | |||
| 6911 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | |||
| 6912 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | |||
| 6913 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | |||
| 6914 | ||||
| 6915 | if (!visitRecord(Val.getStructBase(I), BS.getType(), | |||
| 6916 | Layout.getBaseClassOffset(BaseDecl) + Offset)) | |||
| 6917 | return false; | |||
| 6918 | } | |||
| 6919 | } | |||
| 6920 | ||||
| 6921 | // Visit the fields. | |||
| 6922 | unsigned FieldIdx = 0; | |||
| 6923 | for (FieldDecl *FD : RD->fields()) { | |||
| 6924 | if (FD->isBitField()) { | |||
| 6925 | Info.FFDiag(BCE->getBeginLoc(), | |||
| 6926 | diag::note_constexpr_bit_cast_unsupported_bitfield); | |||
| 6927 | return false; | |||
| 6928 | } | |||
| 6929 | ||||
| 6930 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | |||
| 6931 | ||||
| 6932 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth () == 0 && "only bit-fields can have sub-char alignment" ) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "clang/lib/AST/ExprConstant.cpp", 6933, __extension__ __PRETTY_FUNCTION__ )) | |||
| 6933 | "only bit-fields can have sub-char alignment")(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth () == 0 && "only bit-fields can have sub-char alignment" ) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "clang/lib/AST/ExprConstant.cpp", 6933, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6934 | CharUnits FieldOffset = | |||
| 6935 | Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; | |||
| 6936 | QualType FieldTy = FD->getType(); | |||
| 6937 | if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) | |||
| 6938 | return false; | |||
| 6939 | ++FieldIdx; | |||
| 6940 | } | |||
| 6941 | ||||
| 6942 | return true; | |||
| 6943 | } | |||
| 6944 | ||||
| 6945 | bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { | |||
| 6946 | const auto *CAT = | |||
| 6947 | dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); | |||
| 6948 | if (!CAT) | |||
| 6949 | return false; | |||
| 6950 | ||||
| 6951 | CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); | |||
| 6952 | unsigned NumInitializedElts = Val.getArrayInitializedElts(); | |||
| 6953 | unsigned ArraySize = Val.getArraySize(); | |||
| 6954 | // First, initialize the initialized elements. | |||
| 6955 | for (unsigned I = 0; I != NumInitializedElts; ++I) { | |||
| 6956 | const APValue &SubObj = Val.getArrayInitializedElt(I); | |||
| 6957 | if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) | |||
| 6958 | return false; | |||
| 6959 | } | |||
| 6960 | ||||
| 6961 | // Next, initialize the rest of the array using the filler. | |||
| 6962 | if (Val.hasArrayFiller()) { | |||
| 6963 | const APValue &Filler = Val.getArrayFiller(); | |||
| 6964 | for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { | |||
| 6965 | if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) | |||
| 6966 | return false; | |||
| 6967 | } | |||
| 6968 | } | |||
| 6969 | ||||
| 6970 | return true; | |||
| 6971 | } | |||
| 6972 | ||||
| 6973 | bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { | |||
| 6974 | APSInt AdjustedVal = Val; | |||
| 6975 | unsigned Width = AdjustedVal.getBitWidth(); | |||
| 6976 | if (Ty->isBooleanType()) { | |||
| 6977 | Width = Info.Ctx.getTypeSize(Ty); | |||
| 6978 | AdjustedVal = AdjustedVal.extend(Width); | |||
| 6979 | } | |||
| 6980 | ||||
| 6981 | SmallVector<unsigned char, 8> Bytes(Width / 8); | |||
| 6982 | llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); | |||
| 6983 | Buffer.writeObject(Offset, Bytes); | |||
| 6984 | return true; | |||
| 6985 | } | |||
| 6986 | ||||
| 6987 | bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { | |||
| 6988 | APSInt AsInt(Val.bitcastToAPInt()); | |||
| 6989 | return visitInt(AsInt, Ty, Offset); | |||
| 6990 | } | |||
| 6991 | ||||
| 6992 | public: | |||
| 6993 | static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, | |||
| 6994 | const CastExpr *BCE) { | |||
| 6995 | CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); | |||
| 6996 | APValueToBufferConverter Converter(Info, DstSize, BCE); | |||
| 6997 | if (!Converter.visit(Src, BCE->getSubExpr()->getType())) | |||
| 6998 | return None; | |||
| 6999 | return Converter.Buffer; | |||
| 7000 | } | |||
| 7001 | }; | |||
| 7002 | ||||
| 7003 | /// Write an BitCastBuffer into an APValue. | |||
| 7004 | class BufferToAPValueConverter { | |||
| 7005 | EvalInfo &Info; | |||
| 7006 | const BitCastBuffer &Buffer; | |||
| 7007 | const CastExpr *BCE; | |||
| 7008 | ||||
| 7009 | BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, | |||
| 7010 | const CastExpr *BCE) | |||
| 7011 | : Info(Info), Buffer(Buffer), BCE(BCE) {} | |||
| 7012 | ||||
| 7013 | // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast | |||
| 7014 | // with an invalid type, so anything left is a deficiency on our part (FIXME). | |||
| 7015 | // Ideally this will be unreachable. | |||
| 7016 | llvm::NoneType unsupportedType(QualType Ty) { | |||
| 7017 | Info.FFDiag(BCE->getBeginLoc(), | |||
| 7018 | diag::note_constexpr_bit_cast_unsupported_type) | |||
| 7019 | << Ty; | |||
| 7020 | return None; | |||
| 7021 | } | |||
| 7022 | ||||
| 7023 | llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { | |||
| 7024 | Info.FFDiag(BCE->getBeginLoc(), | |||
| 7025 | diag::note_constexpr_bit_cast_unrepresentable_value) | |||
| 7026 | << Ty << toString(Val, /*Radix=*/10); | |||
| 7027 | return None; | |||
| 7028 | } | |||
| 7029 | ||||
| 7030 | Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, | |||
| 7031 | const EnumType *EnumSugar = nullptr) { | |||
| 7032 | if (T->isNullPtrType()) { | |||
| 7033 | uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); | |||
| 7034 | return APValue((Expr *)nullptr, | |||
| 7035 | /*Offset=*/CharUnits::fromQuantity(NullValue), | |||
| 7036 | APValue::NoLValuePath{}, /*IsNullPtr=*/true); | |||
| 7037 | } | |||
| 7038 | ||||
| 7039 | CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); | |||
| 7040 | ||||
| 7041 | // Work around floating point types that contain unused padding bytes. This | |||
| 7042 | // is really just `long double` on x86, which is the only fundamental type | |||
| 7043 | // with padding bytes. | |||
| 7044 | if (T->isRealFloatingType()) { | |||
| 7045 | const llvm::fltSemantics &Semantics = | |||
| 7046 | Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); | |||
| 7047 | unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); | |||
| 7048 | assert(NumBits % 8 == 0)(static_cast <bool> (NumBits % 8 == 0) ? void (0) : __assert_fail ("NumBits % 8 == 0", "clang/lib/AST/ExprConstant.cpp", 7048, __extension__ __PRETTY_FUNCTION__)); | |||
| 7049 | CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); | |||
| 7050 | if (NumBytes != SizeOf) | |||
| 7051 | SizeOf = NumBytes; | |||
| 7052 | } | |||
| 7053 | ||||
| 7054 | SmallVector<uint8_t, 8> Bytes; | |||
| 7055 | if (!Buffer.readObject(Offset, SizeOf, Bytes)) { | |||
| 7056 | // If this is std::byte or unsigned char, then its okay to store an | |||
| 7057 | // indeterminate value. | |||
| 7058 | bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); | |||
| 7059 | bool IsUChar = | |||
| 7060 | !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || | |||
| 7061 | T->isSpecificBuiltinType(BuiltinType::Char_U)); | |||
| 7062 | if (!IsStdByte && !IsUChar) { | |||
| 7063 | QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); | |||
| 7064 | Info.FFDiag(BCE->getExprLoc(), | |||
| 7065 | diag::note_constexpr_bit_cast_indet_dest) | |||
| 7066 | << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; | |||
| 7067 | return None; | |||
| 7068 | } | |||
| 7069 | ||||
| 7070 | return APValue::IndeterminateValue(); | |||
| 7071 | } | |||
| 7072 | ||||
| 7073 | APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); | |||
| 7074 | llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); | |||
| 7075 | ||||
| 7076 | if (T->isIntegralOrEnumerationType()) { | |||
| 7077 | Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); | |||
| 7078 | ||||
| 7079 | unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); | |||
| 7080 | if (IntWidth != Val.getBitWidth()) { | |||
| 7081 | APSInt Truncated = Val.trunc(IntWidth); | |||
| 7082 | if (Truncated.extend(Val.getBitWidth()) != Val) | |||
| 7083 | return unrepresentableValue(QualType(T, 0), Val); | |||
| 7084 | Val = Truncated; | |||
| 7085 | } | |||
| 7086 | ||||
| 7087 | return APValue(Val); | |||
| 7088 | } | |||
| 7089 | ||||
| 7090 | if (T->isRealFloatingType()) { | |||
| 7091 | const llvm::fltSemantics &Semantics = | |||
| 7092 | Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); | |||
| 7093 | return APValue(APFloat(Semantics, Val)); | |||
| 7094 | } | |||
| 7095 | ||||
| 7096 | return unsupportedType(QualType(T, 0)); | |||
| 7097 | } | |||
| 7098 | ||||
| 7099 | Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { | |||
| 7100 | const RecordDecl *RD = RTy->getAsRecordDecl(); | |||
| 7101 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | |||
| 7102 | ||||
| 7103 | unsigned NumBases = 0; | |||
| 7104 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | |||
| 7105 | NumBases = CXXRD->getNumBases(); | |||
| 7106 | ||||
| 7107 | APValue ResultVal(APValue::UninitStruct(), NumBases, | |||
| 7108 | std::distance(RD->field_begin(), RD->field_end())); | |||
| 7109 | ||||
| 7110 | // Visit the base classes. | |||
| 7111 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | |||
| 7112 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | |||
| 7113 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | |||
| 7114 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | |||
| 7115 | if (BaseDecl->isEmpty() || | |||
| 7116 | Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) | |||
| 7117 | continue; | |||
| 7118 | ||||
| 7119 | Optional<APValue> SubObj = visitType( | |||
| 7120 | BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); | |||
| 7121 | if (!SubObj) | |||
| 7122 | return None; | |||
| 7123 | ResultVal.getStructBase(I) = *SubObj; | |||
| 7124 | } | |||
| 7125 | } | |||
| 7126 | ||||
| 7127 | // Visit the fields. | |||
| 7128 | unsigned FieldIdx = 0; | |||
| 7129 | for (FieldDecl *FD : RD->fields()) { | |||
| 7130 | // FIXME: We don't currently support bit-fields. A lot of the logic for | |||
| 7131 | // this is in CodeGen, so we need to factor it around. | |||
| 7132 | if (FD->isBitField()) { | |||
| 7133 | Info.FFDiag(BCE->getBeginLoc(), | |||
| 7134 | diag::note_constexpr_bit_cast_unsupported_bitfield); | |||
| 7135 | return None; | |||
| 7136 | } | |||
| 7137 | ||||
| 7138 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | |||
| 7139 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0)(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth () == 0) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0" , "clang/lib/AST/ExprConstant.cpp", 7139, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7140 | ||||
| 7141 | CharUnits FieldOffset = | |||
| 7142 | CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + | |||
| 7143 | Offset; | |||
| 7144 | QualType FieldTy = FD->getType(); | |||
| 7145 | Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); | |||
| 7146 | if (!SubObj) | |||
| 7147 | return None; | |||
| 7148 | ResultVal.getStructField(FieldIdx) = *SubObj; | |||
| 7149 | ++FieldIdx; | |||
| 7150 | } | |||
| 7151 | ||||
| 7152 | return ResultVal; | |||
| 7153 | } | |||
| 7154 | ||||
| 7155 | Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { | |||
| 7156 | QualType RepresentationType = Ty->getDecl()->getIntegerType(); | |||
| 7157 | assert(!RepresentationType.isNull() &&(static_cast <bool> (!RepresentationType.isNull() && "enum forward decl should be caught by Sema") ? void (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "clang/lib/AST/ExprConstant.cpp", 7158, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7158 | "enum forward decl should be caught by Sema")(static_cast <bool> (!RepresentationType.isNull() && "enum forward decl should be caught by Sema") ? void (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "clang/lib/AST/ExprConstant.cpp", 7158, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7159 | const auto *AsBuiltin = | |||
| 7160 | RepresentationType.getCanonicalType()->castAs<BuiltinType>(); | |||
| 7161 | // Recurse into the underlying type. Treat std::byte transparently as | |||
| 7162 | // unsigned char. | |||
| 7163 | return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); | |||
| 7164 | } | |||
| 7165 | ||||
| 7166 | Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { | |||
| 7167 | size_t Size = Ty->getSize().getLimitedValue(); | |||
| 7168 | CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); | |||
| 7169 | ||||
| 7170 | APValue ArrayValue(APValue::UninitArray(), Size, Size); | |||
| 7171 | for (size_t I = 0; I != Size; ++I) { | |||
| 7172 | Optional<APValue> ElementValue = | |||
| 7173 | visitType(Ty->getElementType(), Offset + I * ElementWidth); | |||
| 7174 | if (!ElementValue) | |||
| 7175 | return None; | |||
| 7176 | ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); | |||
| 7177 | } | |||
| 7178 | ||||
| 7179 | return ArrayValue; | |||
| 7180 | } | |||
| 7181 | ||||
| 7182 | Optional<APValue> visit(const Type *Ty, CharUnits Offset) { | |||
| 7183 | return unsupportedType(QualType(Ty, 0)); | |||
| 7184 | } | |||
| 7185 | ||||
| 7186 | Optional<APValue> visitType(QualType Ty, CharUnits Offset) { | |||
| 7187 | QualType Can = Ty.getCanonicalType(); | |||
| 7188 | ||||
| 7189 | switch (Can->getTypeClass()) { | |||
| 7190 | #define TYPE(Class, Base) \ | |||
| 7191 | case Type::Class: \ | |||
| 7192 | return visit(cast<Class##Type>(Can.getTypePtr()), Offset); | |||
| 7193 | #define ABSTRACT_TYPE(Class, Base) | |||
| 7194 | #define NON_CANONICAL_TYPE(Class, Base) \ | |||
| 7195 | case Type::Class: \ | |||
| 7196 | llvm_unreachable("non-canonical type should be impossible!")::llvm::llvm_unreachable_internal("non-canonical type should be impossible!" , "clang/lib/AST/ExprConstant.cpp", 7196); | |||
| 7197 | #define DEPENDENT_TYPE(Class, Base) \ | |||
| 7198 | case Type::Class: \ | |||
| 7199 | llvm_unreachable( \::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!" , "clang/lib/AST/ExprConstant.cpp", 7200) | |||
| 7200 | "dependent types aren't supported in the constant evaluator!")::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!" , "clang/lib/AST/ExprConstant.cpp", 7200); | |||
| 7201 | #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)case Type::Class: ::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "clang/lib/AST/ExprConstant.cpp", 7201); \ | |||
| 7202 | case Type::Class: \ | |||
| 7203 | llvm_unreachable("either dependent or not canonical!")::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "clang/lib/AST/ExprConstant.cpp", 7203); | |||
| 7204 | #include "clang/AST/TypeNodes.inc" | |||
| 7205 | } | |||
| 7206 | llvm_unreachable("Unhandled Type::TypeClass")::llvm::llvm_unreachable_internal("Unhandled Type::TypeClass" , "clang/lib/AST/ExprConstant.cpp", 7206); | |||
| 7207 | } | |||
| 7208 | ||||
| 7209 | public: | |||
| 7210 | // Pull out a full value of type DstType. | |||
| 7211 | static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, | |||
| 7212 | const CastExpr *BCE) { | |||
| 7213 | BufferToAPValueConverter Converter(Info, Buffer, BCE); | |||
| 7214 | return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); | |||
| 7215 | } | |||
| 7216 | }; | |||
| 7217 | ||||
| 7218 | static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, | |||
| 7219 | QualType Ty, EvalInfo *Info, | |||
| 7220 | const ASTContext &Ctx, | |||
| 7221 | bool CheckingDest) { | |||
| 7222 | Ty = Ty.getCanonicalType(); | |||
| 7223 | ||||
| 7224 | auto diag = [&](int Reason) { | |||
| 7225 | if (Info) | |||
| 7226 | Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) | |||
| 7227 | << CheckingDest << (Reason == 4) << Reason; | |||
| 7228 | return false; | |||
| 7229 | }; | |||
| 7230 | auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { | |||
| 7231 | if (Info) | |||
| 7232 | Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) | |||
| 7233 | << NoteTy << Construct << Ty; | |||
| 7234 | return false; | |||
| 7235 | }; | |||
| 7236 | ||||
| 7237 | if (Ty->isUnionType()) | |||
| 7238 | return diag(0); | |||
| 7239 | if (Ty->isPointerType()) | |||
| 7240 | return diag(1); | |||
| 7241 | if (Ty->isMemberPointerType()) | |||
| 7242 | return diag(2); | |||
| 7243 | if (Ty.isVolatileQualified()) | |||
| 7244 | return diag(3); | |||
| 7245 | ||||
| 7246 | if (RecordDecl *Record = Ty->getAsRecordDecl()) { | |||
| 7247 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { | |||
| 7248 | for (CXXBaseSpecifier &BS : CXXRD->bases()) | |||
| 7249 | if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, | |||
| 7250 | CheckingDest)) | |||
| 7251 | return note(1, BS.getType(), BS.getBeginLoc()); | |||
| 7252 | } | |||
| 7253 | for (FieldDecl *FD : Record->fields()) { | |||
| 7254 | if (FD->getType()->isReferenceType()) | |||
| 7255 | return diag(4); | |||
| 7256 | if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, | |||
| 7257 | CheckingDest)) | |||
| 7258 | return note(0, FD->getType(), FD->getBeginLoc()); | |||
| 7259 | } | |||
| 7260 | } | |||
| 7261 | ||||
| 7262 | if (Ty->isArrayType() && | |||
| 7263 | !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), | |||
| 7264 | Info, Ctx, CheckingDest)) | |||
| 7265 | return false; | |||
| 7266 | ||||
| 7267 | return true; | |||
| 7268 | } | |||
| 7269 | ||||
| 7270 | static bool checkBitCastConstexprEligibility(EvalInfo *Info, | |||
| 7271 | const ASTContext &Ctx, | |||
| 7272 | const CastExpr *BCE) { | |||
| 7273 | bool DestOK = checkBitCastConstexprEligibilityType( | |||
| 7274 | BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); | |||
| 7275 | bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( | |||
| 7276 | BCE->getBeginLoc(), | |||
| 7277 | BCE->getSubExpr()->getType(), Info, Ctx, false); | |||
| 7278 | return SourceOK; | |||
| 7279 | } | |||
| 7280 | ||||
| 7281 | static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, | |||
| 7282 | APValue &SourceValue, | |||
| 7283 | const CastExpr *BCE) { | |||
| 7284 | assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&(static_cast <bool> (8 == 8 && Info.Ctx.getTargetInfo ().getCharWidth() == 8 && "no host or target supports non 8-bit chars" ) ? void (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\"" , "clang/lib/AST/ExprConstant.cpp", 7285, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7285 | "no host or target supports non 8-bit chars")(static_cast <bool> (8 == 8 && Info.Ctx.getTargetInfo ().getCharWidth() == 8 && "no host or target supports non 8-bit chars" ) ? void (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\"" , "clang/lib/AST/ExprConstant.cpp", 7285, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7286 | assert(SourceValue.isLValue() &&(static_cast <bool> (SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? void (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "clang/lib/AST/ExprConstant.cpp", 7287, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7287 | "LValueToRValueBitcast requires an lvalue operand!")(static_cast <bool> (SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? void (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "clang/lib/AST/ExprConstant.cpp", 7287, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7288 | ||||
| 7289 | if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) | |||
| 7290 | return false; | |||
| 7291 | ||||
| 7292 | LValue SourceLValue; | |||
| 7293 | APValue SourceRValue; | |||
| 7294 | SourceLValue.setFrom(Info.Ctx, SourceValue); | |||
| 7295 | if (!handleLValueToRValueConversion( | |||
| 7296 | Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, | |||
| 7297 | SourceRValue, /*WantObjectRepresentation=*/true)) | |||
| 7298 | return false; | |||
| 7299 | ||||
| 7300 | // Read out SourceValue into a char buffer. | |||
| 7301 | Optional<BitCastBuffer> Buffer = | |||
| 7302 | APValueToBufferConverter::convert(Info, SourceRValue, BCE); | |||
| 7303 | if (!Buffer) | |||
| 7304 | return false; | |||
| 7305 | ||||
| 7306 | // Write out the buffer into a new APValue. | |||
| 7307 | Optional<APValue> MaybeDestValue = | |||
| 7308 | BufferToAPValueConverter::convert(Info, *Buffer, BCE); | |||
| 7309 | if (!MaybeDestValue) | |||
| 7310 | return false; | |||
| 7311 | ||||
| 7312 | DestValue = std::move(*MaybeDestValue); | |||
| 7313 | return true; | |||
| 7314 | } | |||
| 7315 | ||||
| 7316 | template <class Derived> | |||
| 7317 | class ExprEvaluatorBase | |||
| 7318 | : public ConstStmtVisitor<Derived, bool> { | |||
| 7319 | private: | |||
| 7320 | Derived &getDerived() { return static_cast<Derived&>(*this); } | |||
| 7321 | bool DerivedSuccess(const APValue &V, const Expr *E) { | |||
| 7322 | return getDerived().Success(V, E); | |||
| 7323 | } | |||
| 7324 | bool DerivedZeroInitialization(const Expr *E) { | |||
| 7325 | return getDerived().ZeroInitialization(E); | |||
| 7326 | } | |||
| 7327 | ||||
| 7328 | // Check whether a conditional operator with a non-constant condition is a | |||
| 7329 | // potential constant expression. If neither arm is a potential constant | |||
| 7330 | // expression, then the conditional operator is not either. | |||
| 7331 | template<typename ConditionalOperator> | |||
| 7332 | void CheckPotentialConstantConditional(const ConditionalOperator *E) { | |||
| 7333 | assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression ()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "clang/lib/AST/ExprConstant.cpp", 7333, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7334 | ||||
| 7335 | // Speculatively evaluate both arms. | |||
| 7336 | SmallVector<PartialDiagnosticAt, 8> Diag; | |||
| 7337 | { | |||
| 7338 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | |||
| 7339 | StmtVisitorTy::Visit(E->getFalseExpr()); | |||
| 7340 | if (Diag.empty()) | |||
| 7341 | return; | |||
| 7342 | } | |||
| 7343 | ||||
| 7344 | { | |||
| 7345 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | |||
| 7346 | Diag.clear(); | |||
| 7347 | StmtVisitorTy::Visit(E->getTrueExpr()); | |||
| 7348 | if (Diag.empty()) | |||
| 7349 | return; | |||
| 7350 | } | |||
| 7351 | ||||
| 7352 | Error(E, diag::note_constexpr_conditional_never_const); | |||
| 7353 | } | |||
| 7354 | ||||
| 7355 | ||||
| 7356 | template<typename ConditionalOperator> | |||
| 7357 | bool HandleConditionalOperator(const ConditionalOperator *E) { | |||
| 7358 | bool BoolResult; | |||
| 7359 | if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { | |||
| 7360 | if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { | |||
| 7361 | CheckPotentialConstantConditional(E); | |||
| 7362 | return false; | |||
| 7363 | } | |||
| 7364 | if (Info.noteFailure()) { | |||
| 7365 | StmtVisitorTy::Visit(E->getTrueExpr()); | |||
| 7366 | StmtVisitorTy::Visit(E->getFalseExpr()); | |||
| 7367 | } | |||
| 7368 | return false; | |||
| 7369 | } | |||
| 7370 | ||||
| 7371 | Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); | |||
| 7372 | return StmtVisitorTy::Visit(EvalExpr); | |||
| 7373 | } | |||
| 7374 | ||||
| 7375 | protected: | |||
| 7376 | EvalInfo &Info; | |||
| 7377 | typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; | |||
| 7378 | typedef ExprEvaluatorBase ExprEvaluatorBaseTy; | |||
| 7379 | ||||
| 7380 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | |||
| 7381 | return Info.CCEDiag(E, D); | |||
| 7382 | } | |||
| 7383 | ||||
| 7384 | bool ZeroInitialization(const Expr *E) { return Error(E); } | |||
| 7385 | ||||
| 7386 | public: | |||
| 7387 | ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} | |||
| 7388 | ||||
| 7389 | EvalInfo &getEvalInfo() { return Info; } | |||
| 7390 | ||||
| 7391 | /// Report an evaluation error. This should only be called when an error is | |||
| 7392 | /// first discovered. When propagating an error, just return false. | |||
| 7393 | bool Error(const Expr *E, diag::kind D) { | |||
| 7394 | Info.FFDiag(E, D); | |||
| 7395 | return false; | |||
| 7396 | } | |||
| 7397 | bool Error(const Expr *E) { | |||
| 7398 | return Error(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 7399 | } | |||
| 7400 | ||||
| 7401 | bool VisitStmt(const Stmt *) { | |||
| 7402 | llvm_unreachable("Expression evaluator should not be called on stmts")::llvm::llvm_unreachable_internal("Expression evaluator should not be called on stmts" , "clang/lib/AST/ExprConstant.cpp", 7402); | |||
| 7403 | } | |||
| 7404 | bool VisitExpr(const Expr *E) { | |||
| 7405 | return Error(E); | |||
| 7406 | } | |||
| 7407 | ||||
| 7408 | bool VisitConstantExpr(const ConstantExpr *E) { | |||
| 7409 | if (E->hasAPValueResult()) | |||
| 7410 | return DerivedSuccess(E->getAPValueResult(), E); | |||
| 7411 | ||||
| 7412 | return StmtVisitorTy::Visit(E->getSubExpr()); | |||
| 7413 | } | |||
| 7414 | ||||
| 7415 | bool VisitParenExpr(const ParenExpr *E) | |||
| 7416 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | |||
| 7417 | bool VisitUnaryExtension(const UnaryOperator *E) | |||
| 7418 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | |||
| 7419 | bool VisitUnaryPlus(const UnaryOperator *E) | |||
| 7420 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | |||
| 7421 | bool VisitChooseExpr(const ChooseExpr *E) | |||
| 7422 | { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } | |||
| 7423 | bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) | |||
| 7424 | { return StmtVisitorTy::Visit(E->getResultExpr()); } | |||
| 7425 | bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) | |||
| 7426 | { return StmtVisitorTy::Visit(E->getReplacement()); } | |||
| 7427 | bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { | |||
| 7428 | TempVersionRAII RAII(*Info.CurrentCall); | |||
| 7429 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | |||
| 7430 | return StmtVisitorTy::Visit(E->getExpr()); | |||
| 7431 | } | |||
| 7432 | bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { | |||
| 7433 | TempVersionRAII RAII(*Info.CurrentCall); | |||
| 7434 | // The initializer may not have been parsed yet, or might be erroneous. | |||
| 7435 | if (!E->getExpr()) | |||
| 7436 | return Error(E); | |||
| 7437 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | |||
| 7438 | return StmtVisitorTy::Visit(E->getExpr()); | |||
| 7439 | } | |||
| 7440 | ||||
| 7441 | bool VisitExprWithCleanups(const ExprWithCleanups *E) { | |||
| 7442 | FullExpressionRAII Scope(Info); | |||
| 7443 | return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); | |||
| 7444 | } | |||
| 7445 | ||||
| 7446 | // Temporaries are registered when created, so we don't care about | |||
| 7447 | // CXXBindTemporaryExpr. | |||
| 7448 | bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { | |||
| 7449 | return StmtVisitorTy::Visit(E->getSubExpr()); | |||
| 7450 | } | |||
| 7451 | ||||
| 7452 | bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { | |||
| 7453 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; | |||
| 7454 | return static_cast<Derived*>(this)->VisitCastExpr(E); | |||
| 7455 | } | |||
| 7456 | bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { | |||
| 7457 | if (!Info.Ctx.getLangOpts().CPlusPlus20) | |||
| 7458 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; | |||
| 7459 | return static_cast<Derived*>(this)->VisitCastExpr(E); | |||
| 7460 | } | |||
| 7461 | bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { | |||
| 7462 | return static_cast<Derived*>(this)->VisitCastExpr(E); | |||
| 7463 | } | |||
| 7464 | ||||
| 7465 | bool VisitBinaryOperator(const BinaryOperator *E) { | |||
| 7466 | switch (E->getOpcode()) { | |||
| 7467 | default: | |||
| 7468 | return Error(E); | |||
| 7469 | ||||
| 7470 | case BO_Comma: | |||
| 7471 | VisitIgnoredValue(E->getLHS()); | |||
| 7472 | return StmtVisitorTy::Visit(E->getRHS()); | |||
| 7473 | ||||
| 7474 | case BO_PtrMemD: | |||
| 7475 | case BO_PtrMemI: { | |||
| 7476 | LValue Obj; | |||
| 7477 | if (!HandleMemberPointerAccess(Info, E, Obj)) | |||
| 7478 | return false; | |||
| 7479 | APValue Result; | |||
| 7480 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) | |||
| 7481 | return false; | |||
| 7482 | return DerivedSuccess(Result, E); | |||
| 7483 | } | |||
| 7484 | } | |||
| 7485 | } | |||
| 7486 | ||||
| 7487 | bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { | |||
| 7488 | return StmtVisitorTy::Visit(E->getSemanticForm()); | |||
| 7489 | } | |||
| 7490 | ||||
| 7491 | bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { | |||
| 7492 | // Evaluate and cache the common expression. We treat it as a temporary, | |||
| 7493 | // even though it's not quite the same thing. | |||
| 7494 | LValue CommonLV; | |||
| 7495 | if (!Evaluate(Info.CurrentCall->createTemporary( | |||
| 7496 | E->getOpaqueValue(), | |||
| 7497 | getStorageType(Info.Ctx, E->getOpaqueValue()), | |||
| 7498 | ScopeKind::FullExpression, CommonLV), | |||
| 7499 | Info, E->getCommon())) | |||
| 7500 | return false; | |||
| 7501 | ||||
| 7502 | return HandleConditionalOperator(E); | |||
| 7503 | } | |||
| 7504 | ||||
| 7505 | bool VisitConditionalOperator(const ConditionalOperator *E) { | |||
| 7506 | bool IsBcpCall = false; | |||
| 7507 | // If the condition (ignoring parens) is a __builtin_constant_p call, | |||
| 7508 | // the result is a constant expression if it can be folded without | |||
| 7509 | // side-effects. This is an important GNU extension. See GCC PR38377 | |||
| 7510 | // for discussion. | |||
| 7511 | if (const CallExpr *CallCE = | |||
| 7512 | dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) | |||
| 7513 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | |||
| 7514 | IsBcpCall = true; | |||
| 7515 | ||||
| 7516 | // Always assume __builtin_constant_p(...) ? ... : ... is a potential | |||
| 7517 | // constant expression; we can't check whether it's potentially foldable. | |||
| 7518 | // FIXME: We should instead treat __builtin_constant_p as non-constant if | |||
| 7519 | // it would return 'false' in this mode. | |||
| 7520 | if (Info.checkingPotentialConstantExpression() && IsBcpCall) | |||
| 7521 | return false; | |||
| 7522 | ||||
| 7523 | FoldConstant Fold(Info, IsBcpCall); | |||
| 7524 | if (!HandleConditionalOperator(E)) { | |||
| 7525 | Fold.keepDiagnostics(); | |||
| 7526 | return false; | |||
| 7527 | } | |||
| 7528 | ||||
| 7529 | return true; | |||
| 7530 | } | |||
| 7531 | ||||
| 7532 | bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { | |||
| 7533 | if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) | |||
| 7534 | return DerivedSuccess(*Value, E); | |||
| 7535 | ||||
| 7536 | const Expr *Source = E->getSourceExpr(); | |||
| 7537 | if (!Source) | |||
| 7538 | return Error(E); | |||
| 7539 | if (Source == E) { | |||
| 7540 | assert(0 && "OpaqueValueExpr recursively refers to itself")(static_cast <bool> (0 && "OpaqueValueExpr recursively refers to itself" ) ? void (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\"" , "clang/lib/AST/ExprConstant.cpp", 7540, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7541 | return Error(E); | |||
| 7542 | } | |||
| 7543 | return StmtVisitorTy::Visit(Source); | |||
| 7544 | } | |||
| 7545 | ||||
| 7546 | bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { | |||
| 7547 | for (const Expr *SemE : E->semantics()) { | |||
| 7548 | if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { | |||
| 7549 | // FIXME: We can't handle the case where an OpaqueValueExpr is also the | |||
| 7550 | // result expression: there could be two different LValues that would | |||
| 7551 | // refer to the same object in that case, and we can't model that. | |||
| 7552 | if (SemE == E->getResultExpr()) | |||
| 7553 | return Error(E); | |||
| 7554 | ||||
| 7555 | // Unique OVEs get evaluated if and when we encounter them when | |||
| 7556 | // emitting the rest of the semantic form, rather than eagerly. | |||
| 7557 | if (OVE->isUnique()) | |||
| 7558 | continue; | |||
| 7559 | ||||
| 7560 | LValue LV; | |||
| 7561 | if (!Evaluate(Info.CurrentCall->createTemporary( | |||
| 7562 | OVE, getStorageType(Info.Ctx, OVE), | |||
| 7563 | ScopeKind::FullExpression, LV), | |||
| 7564 | Info, OVE->getSourceExpr())) | |||
| 7565 | return false; | |||
| 7566 | } else if (SemE == E->getResultExpr()) { | |||
| 7567 | if (!StmtVisitorTy::Visit(SemE)) | |||
| 7568 | return false; | |||
| 7569 | } else { | |||
| 7570 | if (!EvaluateIgnoredValue(Info, SemE)) | |||
| 7571 | return false; | |||
| 7572 | } | |||
| 7573 | } | |||
| 7574 | return true; | |||
| 7575 | } | |||
| 7576 | ||||
| 7577 | bool VisitCallExpr(const CallExpr *E) { | |||
| 7578 | APValue Result; | |||
| 7579 | if (!handleCallExpr(E, Result, nullptr)) | |||
| 7580 | return false; | |||
| 7581 | return DerivedSuccess(Result, E); | |||
| 7582 | } | |||
| 7583 | ||||
| 7584 | bool handleCallExpr(const CallExpr *E, APValue &Result, | |||
| 7585 | const LValue *ResultSlot) { | |||
| 7586 | CallScopeRAII CallScope(Info); | |||
| 7587 | ||||
| 7588 | const Expr *Callee = E->getCallee()->IgnoreParens(); | |||
| 7589 | QualType CalleeType = Callee->getType(); | |||
| 7590 | ||||
| 7591 | const FunctionDecl *FD = nullptr; | |||
| 7592 | LValue *This = nullptr, ThisVal; | |||
| 7593 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | |||
| 7594 | bool HasQualifier = false; | |||
| 7595 | ||||
| 7596 | CallRef Call; | |||
| 7597 | ||||
| 7598 | // Extract function decl and 'this' pointer from the callee. | |||
| 7599 | if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { | |||
| ||||
| 7600 | const CXXMethodDecl *Member = nullptr; | |||
| 7601 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { | |||
| 7602 | // Explicit bound member calls, such as x.f() or p->g(); | |||
| 7603 | if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) | |||
| 7604 | return false; | |||
| 7605 | Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | |||
| 7606 | if (!Member) | |||
| 7607 | return Error(Callee); | |||
| 7608 | This = &ThisVal; | |||
| 7609 | HasQualifier = ME->hasQualifier(); | |||
| 7610 | } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { | |||
| 7611 | // Indirect bound member calls ('.*' or '->*'). | |||
| 7612 | const ValueDecl *D = | |||
| 7613 | HandleMemberPointerAccess(Info, BE, ThisVal, false); | |||
| 7614 | if (!D) | |||
| 7615 | return false; | |||
| 7616 | Member = dyn_cast<CXXMethodDecl>(D); | |||
| 7617 | if (!Member) | |||
| 7618 | return Error(Callee); | |||
| 7619 | This = &ThisVal; | |||
| 7620 | } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { | |||
| 7621 | if (!Info.getLangOpts().CPlusPlus20) | |||
| 7622 | Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); | |||
| 7623 | return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && | |||
| 7624 | HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); | |||
| 7625 | } else | |||
| 7626 | return Error(Callee); | |||
| 7627 | FD = Member; | |||
| 7628 | } else if (CalleeType->isFunctionPointerType()) { | |||
| 7629 | LValue CalleeLV; | |||
| 7630 | if (!EvaluatePointer(Callee, CalleeLV, Info)) | |||
| 7631 | return false; | |||
| 7632 | ||||
| 7633 | if (!CalleeLV.getLValueOffset().isZero()) | |||
| 7634 | return Error(Callee); | |||
| 7635 | FD = dyn_cast_or_null<FunctionDecl>( | |||
| 7636 | CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); | |||
| 7637 | if (!FD
| |||
| 7638 | return Error(Callee); | |||
| 7639 | // Don't call function pointers which have been cast to some other type. | |||
| 7640 | // Per DR (no number yet), the caller and callee can differ in noexcept. | |||
| 7641 | if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( | |||
| 7642 | CalleeType->getPointeeType(), FD->getType())) { | |||
| 7643 | return Error(E); | |||
| 7644 | } | |||
| 7645 | ||||
| 7646 | // For an (overloaded) assignment expression, evaluate the RHS before the | |||
| 7647 | // LHS. | |||
| 7648 | auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); | |||
| 7649 | if (OCE
| |||
| 7650 | assert(Args.size() == 2 && "wrong number of arguments in assignment")(static_cast <bool> (Args.size() == 2 && "wrong number of arguments in assignment" ) ? void (0) : __assert_fail ("Args.size() == 2 && \"wrong number of arguments in assignment\"" , "clang/lib/AST/ExprConstant.cpp", 7650, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7651 | Call = Info.CurrentCall->createCall(FD); | |||
| 7652 | if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, | |||
| 7653 | Info, FD, /*RightToLeft=*/true)) | |||
| 7654 | return false; | |||
| 7655 | } | |||
| 7656 | ||||
| 7657 | // Overloaded operator calls to member functions are represented as normal | |||
| 7658 | // calls with '*this' as the first argument. | |||
| 7659 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | |||
| 7660 | if (MD
| |||
| 7661 | // FIXME: When selecting an implicit conversion for an overloaded | |||
| 7662 | // operator delete, we sometimes try to evaluate calls to conversion | |||
| 7663 | // operators without a 'this' parameter! | |||
| 7664 | if (Args.empty()) | |||
| 7665 | return Error(E); | |||
| 7666 | ||||
| 7667 | if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) | |||
| 7668 | return false; | |||
| 7669 | This = &ThisVal; | |||
| 7670 | ||||
| 7671 | // If this is syntactically a simple assignment using a trivial | |||
| 7672 | // assignment operator, start the lifetimes of union members as needed, | |||
| 7673 | // per C++20 [class.union]5. | |||
| 7674 | if (Info.getLangOpts().CPlusPlus20 && OCE
| |||
| 7675 | OCE->getOperator() == OO_Equal && MD->isTrivial() && | |||
| 7676 | !HandleUnionActiveMemberChange(Info, Args[0], ThisVal)) | |||
| 7677 | return false; | |||
| 7678 | ||||
| 7679 | Args = Args.slice(1); | |||
| 7680 | } else if (MD && MD->isLambdaStaticInvoker()) { | |||
| 7681 | // Map the static invoker for the lambda back to the call operator. | |||
| 7682 | // Conveniently, we don't have to slice out the 'this' argument (as is | |||
| 7683 | // being done for the non-static case), since a static member function | |||
| 7684 | // doesn't have an implicit argument passed in. | |||
| 7685 | const CXXRecordDecl *ClosureClass = MD->getParent(); | |||
| 7686 | assert((static_cast <bool> (ClosureClass->captures_begin() == ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr" ) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "clang/lib/AST/ExprConstant.cpp", 7688, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7687 | ClosureClass->captures_begin() == ClosureClass->captures_end() &&(static_cast <bool> (ClosureClass->captures_begin() == ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr" ) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "clang/lib/AST/ExprConstant.cpp", 7688, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7688 | "Number of captures must be zero for conversion to function-ptr")(static_cast <bool> (ClosureClass->captures_begin() == ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr" ) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "clang/lib/AST/ExprConstant.cpp", 7688, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7689 | ||||
| 7690 | const CXXMethodDecl *LambdaCallOp = | |||
| 7691 | ClosureClass->getLambdaCallOperator(); | |||
| 7692 | ||||
| 7693 | // Set 'FD', the function that will be called below, to the call | |||
| 7694 | // operator. If the closure object represents a generic lambda, find | |||
| 7695 | // the corresponding specialization of the call operator. | |||
| 7696 | ||||
| 7697 | if (ClosureClass->isGenericLambda()) { | |||
| 7698 | assert(MD->isFunctionTemplateSpecialization() &&(static_cast <bool> (MD->isFunctionTemplateSpecialization () && "A generic lambda's static-invoker function must be a " "template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "clang/lib/AST/ExprConstant.cpp", 7700, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7699 | "A generic lambda's static-invoker function must be a "(static_cast <bool> (MD->isFunctionTemplateSpecialization () && "A generic lambda's static-invoker function must be a " "template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "clang/lib/AST/ExprConstant.cpp", 7700, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7700 | "template specialization")(static_cast <bool> (MD->isFunctionTemplateSpecialization () && "A generic lambda's static-invoker function must be a " "template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "clang/lib/AST/ExprConstant.cpp", 7700, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7701 | const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); | |||
| 7702 | FunctionTemplateDecl *CallOpTemplate = | |||
| 7703 | LambdaCallOp->getDescribedFunctionTemplate(); | |||
| 7704 | void *InsertPos = nullptr; | |||
| 7705 | FunctionDecl *CorrespondingCallOpSpecialization = | |||
| 7706 | CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); | |||
| 7707 | assert(CorrespondingCallOpSpecialization &&(static_cast <bool> (CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? void (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "clang/lib/AST/ExprConstant.cpp", 7709, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7708 | "We must always have a function call operator specialization "(static_cast <bool> (CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? void (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "clang/lib/AST/ExprConstant.cpp", 7709, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7709 | "that corresponds to our static invoker specialization")(static_cast <bool> (CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? void (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "clang/lib/AST/ExprConstant.cpp", 7709, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7710 | FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); | |||
| 7711 | } else | |||
| 7712 | FD = LambdaCallOp; | |||
| 7713 | } else if (FD->isReplaceableGlobalAllocationFunction()) { | |||
| 7714 | if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || | |||
| 7715 | FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { | |||
| 7716 | LValue Ptr; | |||
| 7717 | if (!HandleOperatorNewCall(Info, E, Ptr)) | |||
| 7718 | return false; | |||
| 7719 | Ptr.moveInto(Result); | |||
| 7720 | return CallScope.destroy(); | |||
| 7721 | } else { | |||
| 7722 | return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); | |||
| 7723 | } | |||
| 7724 | } | |||
| 7725 | } else | |||
| 7726 | return Error(E); | |||
| 7727 | ||||
| 7728 | // Evaluate the arguments now if we've not already done so. | |||
| 7729 | if (!Call) { | |||
| 7730 | Call = Info.CurrentCall->createCall(FD); | |||
| 7731 | if (!EvaluateArgs(Args, Call, Info, FD)) | |||
| 7732 | return false; | |||
| 7733 | } | |||
| 7734 | ||||
| 7735 | SmallVector<QualType, 4> CovariantAdjustmentPath; | |||
| 7736 | if (This) { | |||
| 7737 | auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); | |||
| 7738 | if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { | |||
| 7739 | // Perform virtual dispatch, if necessary. | |||
| 7740 | FD = HandleVirtualDispatch(Info, E, *This, NamedMember, | |||
| 7741 | CovariantAdjustmentPath); | |||
| 7742 | if (!FD) | |||
| 7743 | return false; | |||
| 7744 | } else { | |||
| 7745 | // Check that the 'this' pointer points to an object of the right type. | |||
| 7746 | // FIXME: If this is an assignment operator call, we may need to change | |||
| 7747 | // the active union member before we check this. | |||
| 7748 | if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) | |||
| 7749 | return false; | |||
| 7750 | } | |||
| 7751 | } | |||
| 7752 | ||||
| 7753 | // Destructor calls are different enough that they have their own codepath. | |||
| 7754 | if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { | |||
| 7755 | assert(This && "no 'this' pointer for destructor call")(static_cast <bool> (This && "no 'this' pointer for destructor call" ) ? void (0) : __assert_fail ("This && \"no 'this' pointer for destructor call\"" , "clang/lib/AST/ExprConstant.cpp", 7755, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7756 | return HandleDestruction(Info, E, *This, | |||
| 7757 | Info.Ctx.getRecordType(DD->getParent())) && | |||
| 7758 | CallScope.destroy(); | |||
| 7759 | } | |||
| 7760 | ||||
| 7761 | const FunctionDecl *Definition = nullptr; | |||
| 7762 | Stmt *Body = FD->getBody(Definition); | |||
| 7763 | ||||
| 7764 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || | |||
| 7765 | !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, | |||
| 7766 | Body, Info, Result, ResultSlot)) | |||
| 7767 | return false; | |||
| 7768 | ||||
| 7769 | if (!CovariantAdjustmentPath.empty() && | |||
| 7770 | !HandleCovariantReturnAdjustment(Info, E, Result, | |||
| 7771 | CovariantAdjustmentPath)) | |||
| 7772 | return false; | |||
| 7773 | ||||
| 7774 | return CallScope.destroy(); | |||
| 7775 | } | |||
| 7776 | ||||
| 7777 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | |||
| 7778 | return StmtVisitorTy::Visit(E->getInitializer()); | |||
| 7779 | } | |||
| 7780 | bool VisitInitListExpr(const InitListExpr *E) { | |||
| 7781 | if (E->getNumInits() == 0) | |||
| 7782 | return DerivedZeroInitialization(E); | |||
| 7783 | if (E->getNumInits() == 1) | |||
| 7784 | return StmtVisitorTy::Visit(E->getInit(0)); | |||
| 7785 | return Error(E); | |||
| 7786 | } | |||
| 7787 | bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { | |||
| 7788 | return DerivedZeroInitialization(E); | |||
| 7789 | } | |||
| 7790 | bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { | |||
| 7791 | return DerivedZeroInitialization(E); | |||
| 7792 | } | |||
| 7793 | bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { | |||
| 7794 | return DerivedZeroInitialization(E); | |||
| 7795 | } | |||
| 7796 | ||||
| 7797 | /// A member expression where the object is a prvalue is itself a prvalue. | |||
| 7798 | bool VisitMemberExpr(const MemberExpr *E) { | |||
| 7799 | assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&(static_cast <bool> (!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion") ? void (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "clang/lib/AST/ExprConstant.cpp", 7800, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7800 | "missing temporary materialization conversion")(static_cast <bool> (!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion") ? void (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "clang/lib/AST/ExprConstant.cpp", 7800, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7801 | assert(!E->isArrow() && "missing call to bound member function?")(static_cast <bool> (!E->isArrow() && "missing call to bound member function?" ) ? void (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\"" , "clang/lib/AST/ExprConstant.cpp", 7801, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7802 | ||||
| 7803 | APValue Val; | |||
| 7804 | if (!Evaluate(Val, Info, E->getBase())) | |||
| 7805 | return false; | |||
| 7806 | ||||
| 7807 | QualType BaseTy = E->getBase()->getType(); | |||
| 7808 | ||||
| 7809 | const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); | |||
| 7810 | if (!FD) return Error(E); | |||
| 7811 | assert(!FD->getType()->isReferenceType() && "prvalue reference?")(static_cast <bool> (!FD->getType()->isReferenceType () && "prvalue reference?") ? void (0) : __assert_fail ("!FD->getType()->isReferenceType() && \"prvalue reference?\"" , "clang/lib/AST/ExprConstant.cpp", 7811, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7812 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "clang/lib/AST/ExprConstant.cpp", 7813, __extension__ __PRETTY_FUNCTION__ )) | |||
| 7813 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "clang/lib/AST/ExprConstant.cpp", 7813, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7814 | ||||
| 7815 | // Note: there is no lvalue base here. But this case should only ever | |||
| 7816 | // happen in C or in C++98, where we cannot be evaluating a constexpr | |||
| 7817 | // constructor, which is the only case the base matters. | |||
| 7818 | CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); | |||
| 7819 | SubobjectDesignator Designator(BaseTy); | |||
| 7820 | Designator.addDeclUnchecked(FD); | |||
| 7821 | ||||
| 7822 | APValue Result; | |||
| 7823 | return extractSubobject(Info, E, Obj, Designator, Result) && | |||
| 7824 | DerivedSuccess(Result, E); | |||
| 7825 | } | |||
| 7826 | ||||
| 7827 | bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { | |||
| 7828 | APValue Val; | |||
| 7829 | if (!Evaluate(Val, Info, E->getBase())) | |||
| 7830 | return false; | |||
| 7831 | ||||
| 7832 | if (Val.isVector()) { | |||
| 7833 | SmallVector<uint32_t, 4> Indices; | |||
| 7834 | E->getEncodedElementAccess(Indices); | |||
| 7835 | if (Indices.size() == 1) { | |||
| 7836 | // Return scalar. | |||
| 7837 | return DerivedSuccess(Val.getVectorElt(Indices[0]), E); | |||
| 7838 | } else { | |||
| 7839 | // Construct new APValue vector. | |||
| 7840 | SmallVector<APValue, 4> Elts; | |||
| 7841 | for (unsigned I = 0; I < Indices.size(); ++I) { | |||
| 7842 | Elts.push_back(Val.getVectorElt(Indices[I])); | |||
| 7843 | } | |||
| 7844 | APValue VecResult(Elts.data(), Indices.size()); | |||
| 7845 | return DerivedSuccess(VecResult, E); | |||
| 7846 | } | |||
| 7847 | } | |||
| 7848 | ||||
| 7849 | return false; | |||
| 7850 | } | |||
| 7851 | ||||
| 7852 | bool VisitCastExpr(const CastExpr *E) { | |||
| 7853 | switch (E->getCastKind()) { | |||
| 7854 | default: | |||
| 7855 | break; | |||
| 7856 | ||||
| 7857 | case CK_AtomicToNonAtomic: { | |||
| 7858 | APValue AtomicVal; | |||
| 7859 | // This does not need to be done in place even for class/array types: | |||
| 7860 | // atomic-to-non-atomic conversion implies copying the object | |||
| 7861 | // representation. | |||
| 7862 | if (!Evaluate(AtomicVal, Info, E->getSubExpr())) | |||
| 7863 | return false; | |||
| 7864 | return DerivedSuccess(AtomicVal, E); | |||
| 7865 | } | |||
| 7866 | ||||
| 7867 | case CK_NoOp: | |||
| 7868 | case CK_UserDefinedConversion: | |||
| 7869 | return StmtVisitorTy::Visit(E->getSubExpr()); | |||
| 7870 | ||||
| 7871 | case CK_LValueToRValue: { | |||
| 7872 | LValue LVal; | |||
| 7873 | if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) | |||
| 7874 | return false; | |||
| 7875 | APValue RVal; | |||
| 7876 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | |||
| 7877 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | |||
| 7878 | LVal, RVal)) | |||
| 7879 | return false; | |||
| 7880 | return DerivedSuccess(RVal, E); | |||
| 7881 | } | |||
| 7882 | case CK_LValueToRValueBitCast: { | |||
| 7883 | APValue DestValue, SourceValue; | |||
| 7884 | if (!Evaluate(SourceValue, Info, E->getSubExpr())) | |||
| 7885 | return false; | |||
| 7886 | if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) | |||
| 7887 | return false; | |||
| 7888 | return DerivedSuccess(DestValue, E); | |||
| 7889 | } | |||
| 7890 | ||||
| 7891 | case CK_AddressSpaceConversion: { | |||
| 7892 | APValue Value; | |||
| 7893 | if (!Evaluate(Value, Info, E->getSubExpr())) | |||
| 7894 | return false; | |||
| 7895 | return DerivedSuccess(Value, E); | |||
| 7896 | } | |||
| 7897 | } | |||
| 7898 | ||||
| 7899 | return Error(E); | |||
| 7900 | } | |||
| 7901 | ||||
| 7902 | bool VisitUnaryPostInc(const UnaryOperator *UO) { | |||
| 7903 | return VisitUnaryPostIncDec(UO); | |||
| 7904 | } | |||
| 7905 | bool VisitUnaryPostDec(const UnaryOperator *UO) { | |||
| 7906 | return VisitUnaryPostIncDec(UO); | |||
| 7907 | } | |||
| 7908 | bool VisitUnaryPostIncDec(const UnaryOperator *UO) { | |||
| 7909 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | |||
| 7910 | return Error(UO); | |||
| 7911 | ||||
| 7912 | LValue LVal; | |||
| 7913 | if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) | |||
| 7914 | return false; | |||
| 7915 | APValue RVal; | |||
| 7916 | if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), | |||
| 7917 | UO->isIncrementOp(), &RVal)) | |||
| 7918 | return false; | |||
| 7919 | return DerivedSuccess(RVal, UO); | |||
| 7920 | } | |||
| 7921 | ||||
| 7922 | bool VisitStmtExpr(const StmtExpr *E) { | |||
| 7923 | // We will have checked the full-expressions inside the statement expression | |||
| 7924 | // when they were completed, and don't need to check them again now. | |||
| 7925 | llvm::SaveAndRestore<bool> NotCheckingForUB( | |||
| 7926 | Info.CheckingForUndefinedBehavior, false); | |||
| 7927 | ||||
| 7928 | const CompoundStmt *CS = E->getSubStmt(); | |||
| 7929 | if (CS->body_empty()) | |||
| 7930 | return true; | |||
| 7931 | ||||
| 7932 | BlockScopeRAII Scope(Info); | |||
| 7933 | for (CompoundStmt::const_body_iterator BI = CS->body_begin(), | |||
| 7934 | BE = CS->body_end(); | |||
| 7935 | /**/; ++BI) { | |||
| 7936 | if (BI + 1 == BE) { | |||
| 7937 | const Expr *FinalExpr = dyn_cast<Expr>(*BI); | |||
| 7938 | if (!FinalExpr) { | |||
| 7939 | Info.FFDiag((*BI)->getBeginLoc(), | |||
| 7940 | diag::note_constexpr_stmt_expr_unsupported); | |||
| 7941 | return false; | |||
| 7942 | } | |||
| 7943 | return this->Visit(FinalExpr) && Scope.destroy(); | |||
| 7944 | } | |||
| 7945 | ||||
| 7946 | APValue ReturnValue; | |||
| 7947 | StmtResult Result = { ReturnValue, nullptr }; | |||
| 7948 | EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); | |||
| 7949 | if (ESR != ESR_Succeeded) { | |||
| 7950 | // FIXME: If the statement-expression terminated due to 'return', | |||
| 7951 | // 'break', or 'continue', it would be nice to propagate that to | |||
| 7952 | // the outer statement evaluation rather than bailing out. | |||
| 7953 | if (ESR != ESR_Failed) | |||
| 7954 | Info.FFDiag((*BI)->getBeginLoc(), | |||
| 7955 | diag::note_constexpr_stmt_expr_unsupported); | |||
| 7956 | return false; | |||
| 7957 | } | |||
| 7958 | } | |||
| 7959 | ||||
| 7960 | llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above." , "clang/lib/AST/ExprConstant.cpp", 7960); | |||
| 7961 | } | |||
| 7962 | ||||
| 7963 | /// Visit a value which is evaluated, but whose value is ignored. | |||
| 7964 | void VisitIgnoredValue(const Expr *E) { | |||
| 7965 | EvaluateIgnoredValue(Info, E); | |||
| 7966 | } | |||
| 7967 | ||||
| 7968 | /// Potentially visit a MemberExpr's base expression. | |||
| 7969 | void VisitIgnoredBaseExpression(const Expr *E) { | |||
| 7970 | // While MSVC doesn't evaluate the base expression, it does diagnose the | |||
| 7971 | // presence of side-effecting behavior. | |||
| 7972 | if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) | |||
| 7973 | return; | |||
| 7974 | VisitIgnoredValue(E); | |||
| 7975 | } | |||
| 7976 | }; | |||
| 7977 | ||||
| 7978 | } // namespace | |||
| 7979 | ||||
| 7980 | //===----------------------------------------------------------------------===// | |||
| 7981 | // Common base class for lvalue and temporary evaluation. | |||
| 7982 | //===----------------------------------------------------------------------===// | |||
| 7983 | namespace { | |||
| 7984 | template<class Derived> | |||
| 7985 | class LValueExprEvaluatorBase | |||
| 7986 | : public ExprEvaluatorBase<Derived> { | |||
| 7987 | protected: | |||
| 7988 | LValue &Result; | |||
| 7989 | bool InvalidBaseOK; | |||
| 7990 | typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; | |||
| 7991 | typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; | |||
| 7992 | ||||
| 7993 | bool Success(APValue::LValueBase B) { | |||
| 7994 | Result.set(B); | |||
| 7995 | return true; | |||
| 7996 | } | |||
| 7997 | ||||
| 7998 | bool evaluatePointer(const Expr *E, LValue &Result) { | |||
| 7999 | return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); | |||
| 8000 | } | |||
| 8001 | ||||
| 8002 | public: | |||
| 8003 | LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) | |||
| 8004 | : ExprEvaluatorBaseTy(Info), Result(Result), | |||
| 8005 | InvalidBaseOK(InvalidBaseOK) {} | |||
| 8006 | ||||
| 8007 | bool Success(const APValue &V, const Expr *E) { | |||
| 8008 | Result.setFrom(this->Info.Ctx, V); | |||
| 8009 | return true; | |||
| 8010 | } | |||
| 8011 | ||||
| 8012 | bool VisitMemberExpr(const MemberExpr *E) { | |||
| 8013 | // Handle non-static data members. | |||
| 8014 | QualType BaseTy; | |||
| 8015 | bool EvalOK; | |||
| 8016 | if (E->isArrow()) { | |||
| 8017 | EvalOK = evaluatePointer(E->getBase(), Result); | |||
| 8018 | BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); | |||
| 8019 | } else if (E->getBase()->isPRValue()) { | |||
| 8020 | assert(E->getBase()->getType()->isRecordType())(static_cast <bool> (E->getBase()->getType()-> isRecordType()) ? void (0) : __assert_fail ("E->getBase()->getType()->isRecordType()" , "clang/lib/AST/ExprConstant.cpp", 8020, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8021 | EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); | |||
| 8022 | BaseTy = E->getBase()->getType(); | |||
| 8023 | } else { | |||
| 8024 | EvalOK = this->Visit(E->getBase()); | |||
| 8025 | BaseTy = E->getBase()->getType(); | |||
| 8026 | } | |||
| 8027 | if (!EvalOK) { | |||
| 8028 | if (!InvalidBaseOK) | |||
| 8029 | return false; | |||
| 8030 | Result.setInvalid(E); | |||
| 8031 | return true; | |||
| 8032 | } | |||
| 8033 | ||||
| 8034 | const ValueDecl *MD = E->getMemberDecl(); | |||
| 8035 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { | |||
| 8036 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "clang/lib/AST/ExprConstant.cpp", 8037, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8037 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "clang/lib/AST/ExprConstant.cpp", 8037, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8038 | (void)BaseTy; | |||
| 8039 | if (!HandleLValueMember(this->Info, E, Result, FD)) | |||
| 8040 | return false; | |||
| 8041 | } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { | |||
| 8042 | if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) | |||
| 8043 | return false; | |||
| 8044 | } else | |||
| 8045 | return this->Error(E); | |||
| 8046 | ||||
| 8047 | if (MD->getType()->isReferenceType()) { | |||
| 8048 | APValue RefValue; | |||
| 8049 | if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, | |||
| 8050 | RefValue)) | |||
| 8051 | return false; | |||
| 8052 | return Success(RefValue, E); | |||
| 8053 | } | |||
| 8054 | return true; | |||
| 8055 | } | |||
| 8056 | ||||
| 8057 | bool VisitBinaryOperator(const BinaryOperator *E) { | |||
| 8058 | switch (E->getOpcode()) { | |||
| 8059 | default: | |||
| 8060 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 8061 | ||||
| 8062 | case BO_PtrMemD: | |||
| 8063 | case BO_PtrMemI: | |||
| 8064 | return HandleMemberPointerAccess(this->Info, E, Result); | |||
| 8065 | } | |||
| 8066 | } | |||
| 8067 | ||||
| 8068 | bool VisitCastExpr(const CastExpr *E) { | |||
| 8069 | switch (E->getCastKind()) { | |||
| 8070 | default: | |||
| 8071 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 8072 | ||||
| 8073 | case CK_DerivedToBase: | |||
| 8074 | case CK_UncheckedDerivedToBase: | |||
| 8075 | if (!this->Visit(E->getSubExpr())) | |||
| 8076 | return false; | |||
| 8077 | ||||
| 8078 | // Now figure out the necessary offset to add to the base LV to get from | |||
| 8079 | // the derived class to the base class. | |||
| 8080 | return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), | |||
| 8081 | Result); | |||
| 8082 | } | |||
| 8083 | } | |||
| 8084 | }; | |||
| 8085 | } | |||
| 8086 | ||||
| 8087 | //===----------------------------------------------------------------------===// | |||
| 8088 | // LValue Evaluation | |||
| 8089 | // | |||
| 8090 | // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), | |||
| 8091 | // function designators (in C), decl references to void objects (in C), and | |||
| 8092 | // temporaries (if building with -Wno-address-of-temporary). | |||
| 8093 | // | |||
| 8094 | // LValue evaluation produces values comprising a base expression of one of the | |||
| 8095 | // following types: | |||
| 8096 | // - Declarations | |||
| 8097 | // * VarDecl | |||
| 8098 | // * FunctionDecl | |||
| 8099 | // - Literals | |||
| 8100 | // * CompoundLiteralExpr in C (and in global scope in C++) | |||
| 8101 | // * StringLiteral | |||
| 8102 | // * PredefinedExpr | |||
| 8103 | // * ObjCStringLiteralExpr | |||
| 8104 | // * ObjCEncodeExpr | |||
| 8105 | // * AddrLabelExpr | |||
| 8106 | // * BlockExpr | |||
| 8107 | // * CallExpr for a MakeStringConstant builtin | |||
| 8108 | // - typeid(T) expressions, as TypeInfoLValues | |||
| 8109 | // - Locals and temporaries | |||
| 8110 | // * MaterializeTemporaryExpr | |||
| 8111 | // * Any Expr, with a CallIndex indicating the function in which the temporary | |||
| 8112 | // was evaluated, for cases where the MaterializeTemporaryExpr is missing | |||
| 8113 | // from the AST (FIXME). | |||
| 8114 | // * A MaterializeTemporaryExpr that has static storage duration, with no | |||
| 8115 | // CallIndex, for a lifetime-extended temporary. | |||
| 8116 | // * The ConstantExpr that is currently being evaluated during evaluation of an | |||
| 8117 | // immediate invocation. | |||
| 8118 | // plus an offset in bytes. | |||
| 8119 | //===----------------------------------------------------------------------===// | |||
| 8120 | namespace { | |||
| 8121 | class LValueExprEvaluator | |||
| 8122 | : public LValueExprEvaluatorBase<LValueExprEvaluator> { | |||
| 8123 | public: | |||
| 8124 | LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : | |||
| 8125 | LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} | |||
| 8126 | ||||
| 8127 | bool VisitVarDecl(const Expr *E, const VarDecl *VD); | |||
| 8128 | bool VisitUnaryPreIncDec(const UnaryOperator *UO); | |||
| 8129 | ||||
| 8130 | bool VisitCallExpr(const CallExpr *E); | |||
| 8131 | bool VisitDeclRefExpr(const DeclRefExpr *E); | |||
| 8132 | bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } | |||
| 8133 | bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); | |||
| 8134 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); | |||
| 8135 | bool VisitMemberExpr(const MemberExpr *E); | |||
| 8136 | bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } | |||
| 8137 | bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } | |||
| 8138 | bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); | |||
| 8139 | bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); | |||
| 8140 | bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); | |||
| 8141 | bool VisitUnaryDeref(const UnaryOperator *E); | |||
| 8142 | bool VisitUnaryReal(const UnaryOperator *E); | |||
| 8143 | bool VisitUnaryImag(const UnaryOperator *E); | |||
| 8144 | bool VisitUnaryPreInc(const UnaryOperator *UO) { | |||
| 8145 | return VisitUnaryPreIncDec(UO); | |||
| 8146 | } | |||
| 8147 | bool VisitUnaryPreDec(const UnaryOperator *UO) { | |||
| 8148 | return VisitUnaryPreIncDec(UO); | |||
| 8149 | } | |||
| 8150 | bool VisitBinAssign(const BinaryOperator *BO); | |||
| 8151 | bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); | |||
| 8152 | ||||
| 8153 | bool VisitCastExpr(const CastExpr *E) { | |||
| 8154 | switch (E->getCastKind()) { | |||
| 8155 | default: | |||
| 8156 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 8157 | ||||
| 8158 | case CK_LValueBitCast: | |||
| 8159 | this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | |||
| 8160 | if (!Visit(E->getSubExpr())) | |||
| 8161 | return false; | |||
| 8162 | Result.Designator.setInvalid(); | |||
| 8163 | return true; | |||
| 8164 | ||||
| 8165 | case CK_BaseToDerived: | |||
| 8166 | if (!Visit(E->getSubExpr())) | |||
| 8167 | return false; | |||
| 8168 | return HandleBaseToDerivedCast(Info, E, Result); | |||
| 8169 | ||||
| 8170 | case CK_Dynamic: | |||
| 8171 | if (!Visit(E->getSubExpr())) | |||
| 8172 | return false; | |||
| 8173 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | |||
| 8174 | } | |||
| 8175 | } | |||
| 8176 | }; | |||
| 8177 | } // end anonymous namespace | |||
| 8178 | ||||
| 8179 | /// Evaluate an expression as an lvalue. This can be legitimately called on | |||
| 8180 | /// expressions which are not glvalues, in three cases: | |||
| 8181 | /// * function designators in C, and | |||
| 8182 | /// * "extern void" objects | |||
| 8183 | /// * @selector() expressions in Objective-C | |||
| 8184 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | |||
| 8185 | bool InvalidBaseOK) { | |||
| 8186 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 8186, __extension__ __PRETTY_FUNCTION__)); | |||
| 8187 | assert(E->isGLValue() || E->getType()->isFunctionType() ||(static_cast <bool> (E->isGLValue() || E->getType ()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)) ? void (0) : __assert_fail ( "E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "clang/lib/AST/ExprConstant.cpp", 8188, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8188 | E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E))(static_cast <bool> (E->isGLValue() || E->getType ()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)) ? void (0) : __assert_fail ( "E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "clang/lib/AST/ExprConstant.cpp", 8188, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8189 | return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | |||
| 8190 | } | |||
| 8191 | ||||
| 8192 | bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { | |||
| 8193 | const NamedDecl *D = E->getDecl(); | |||
| 8194 | if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl, | |||
| 8195 | UnnamedGlobalConstantDecl>(D)) | |||
| 8196 | return Success(cast<ValueDecl>(D)); | |||
| 8197 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | |||
| 8198 | return VisitVarDecl(E, VD); | |||
| 8199 | if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) | |||
| 8200 | return Visit(BD->getBinding()); | |||
| 8201 | return Error(E); | |||
| 8202 | } | |||
| 8203 | ||||
| 8204 | ||||
| 8205 | bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { | |||
| 8206 | ||||
| 8207 | // If we are within a lambda's call operator, check whether the 'VD' referred | |||
| 8208 | // to within 'E' actually represents a lambda-capture that maps to a | |||
| 8209 | // data-member/field within the closure object, and if so, evaluate to the | |||
| 8210 | // field or what the field refers to. | |||
| 8211 | if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && | |||
| 8212 | isa<DeclRefExpr>(E) && | |||
| 8213 | cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { | |||
| 8214 | // We don't always have a complete capture-map when checking or inferring if | |||
| 8215 | // the function call operator meets the requirements of a constexpr function | |||
| 8216 | // - but we don't need to evaluate the captures to determine constexprness | |||
| 8217 | // (dcl.constexpr C++17). | |||
| 8218 | if (Info.checkingPotentialConstantExpression()) | |||
| 8219 | return false; | |||
| 8220 | ||||
| 8221 | if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { | |||
| 8222 | // Start with 'Result' referring to the complete closure object... | |||
| 8223 | Result = *Info.CurrentCall->This; | |||
| 8224 | // ... then update it to refer to the field of the closure object | |||
| 8225 | // that represents the capture. | |||
| 8226 | if (!HandleLValueMember(Info, E, Result, FD)) | |||
| 8227 | return false; | |||
| 8228 | // And if the field is of reference type, update 'Result' to refer to what | |||
| 8229 | // the field refers to. | |||
| 8230 | if (FD->getType()->isReferenceType()) { | |||
| 8231 | APValue RVal; | |||
| 8232 | if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, | |||
| 8233 | RVal)) | |||
| 8234 | return false; | |||
| 8235 | Result.setFrom(Info.Ctx, RVal); | |||
| 8236 | } | |||
| 8237 | return true; | |||
| 8238 | } | |||
| 8239 | } | |||
| 8240 | ||||
| 8241 | CallStackFrame *Frame = nullptr; | |||
| 8242 | unsigned Version = 0; | |||
| 8243 | if (VD->hasLocalStorage()) { | |||
| 8244 | // Only if a local variable was declared in the function currently being | |||
| 8245 | // evaluated, do we expect to be able to find its value in the current | |||
| 8246 | // frame. (Otherwise it was likely declared in an enclosing context and | |||
| 8247 | // could either have a valid evaluatable value (for e.g. a constexpr | |||
| 8248 | // variable) or be ill-formed (and trigger an appropriate evaluation | |||
| 8249 | // diagnostic)). | |||
| 8250 | CallStackFrame *CurrFrame = Info.CurrentCall; | |||
| 8251 | if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { | |||
| 8252 | // Function parameters are stored in some caller's frame. (Usually the | |||
| 8253 | // immediate caller, but for an inherited constructor they may be more | |||
| 8254 | // distant.) | |||
| 8255 | if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { | |||
| 8256 | if (CurrFrame->Arguments) { | |||
| 8257 | VD = CurrFrame->Arguments.getOrigParam(PVD); | |||
| 8258 | Frame = | |||
| 8259 | Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; | |||
| 8260 | Version = CurrFrame->Arguments.Version; | |||
| 8261 | } | |||
| 8262 | } else { | |||
| 8263 | Frame = CurrFrame; | |||
| 8264 | Version = CurrFrame->getCurrentTemporaryVersion(VD); | |||
| 8265 | } | |||
| 8266 | } | |||
| 8267 | } | |||
| 8268 | ||||
| 8269 | if (!VD->getType()->isReferenceType()) { | |||
| 8270 | if (Frame) { | |||
| 8271 | Result.set({VD, Frame->Index, Version}); | |||
| 8272 | return true; | |||
| 8273 | } | |||
| 8274 | return Success(VD); | |||
| 8275 | } | |||
| 8276 | ||||
| 8277 | if (!Info.getLangOpts().CPlusPlus11) { | |||
| 8278 | Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) | |||
| 8279 | << VD << VD->getType(); | |||
| 8280 | Info.Note(VD->getLocation(), diag::note_declared_at); | |||
| 8281 | } | |||
| 8282 | ||||
| 8283 | APValue *V; | |||
| 8284 | if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) | |||
| 8285 | return false; | |||
| 8286 | if (!V->hasValue()) { | |||
| 8287 | // FIXME: Is it possible for V to be indeterminate here? If so, we should | |||
| 8288 | // adjust the diagnostic to say that. | |||
| 8289 | if (!Info.checkingPotentialConstantExpression()) | |||
| 8290 | Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); | |||
| 8291 | return false; | |||
| 8292 | } | |||
| 8293 | return Success(*V, E); | |||
| 8294 | } | |||
| 8295 | ||||
| 8296 | bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) { | |||
| 8297 | switch (E->getBuiltinCallee()) { | |||
| 8298 | case Builtin::BIas_const: | |||
| 8299 | case Builtin::BIforward: | |||
| 8300 | case Builtin::BImove: | |||
| 8301 | case Builtin::BImove_if_noexcept: | |||
| 8302 | if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr()) | |||
| 8303 | return Visit(E->getArg(0)); | |||
| 8304 | break; | |||
| 8305 | } | |||
| 8306 | ||||
| 8307 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | |||
| 8308 | } | |||
| 8309 | ||||
| 8310 | bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( | |||
| 8311 | const MaterializeTemporaryExpr *E) { | |||
| 8312 | // Walk through the expression to find the materialized temporary itself. | |||
| 8313 | SmallVector<const Expr *, 2> CommaLHSs; | |||
| 8314 | SmallVector<SubobjectAdjustment, 2> Adjustments; | |||
| 8315 | const Expr *Inner = | |||
| 8316 | E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); | |||
| 8317 | ||||
| 8318 | // If we passed any comma operators, evaluate their LHSs. | |||
| 8319 | for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) | |||
| 8320 | if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) | |||
| 8321 | return false; | |||
| 8322 | ||||
| 8323 | // A materialized temporary with static storage duration can appear within the | |||
| 8324 | // result of a constant expression evaluation, so we need to preserve its | |||
| 8325 | // value for use outside this evaluation. | |||
| 8326 | APValue *Value; | |||
| 8327 | if (E->getStorageDuration() == SD_Static) { | |||
| 8328 | // FIXME: What about SD_Thread? | |||
| 8329 | Value = E->getOrCreateValue(true); | |||
| 8330 | *Value = APValue(); | |||
| 8331 | Result.set(E); | |||
| 8332 | } else { | |||
| 8333 | Value = &Info.CurrentCall->createTemporary( | |||
| 8334 | E, E->getType(), | |||
| 8335 | E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression | |||
| 8336 | : ScopeKind::Block, | |||
| 8337 | Result); | |||
| 8338 | } | |||
| 8339 | ||||
| 8340 | QualType Type = Inner->getType(); | |||
| 8341 | ||||
| 8342 | // Materialize the temporary itself. | |||
| 8343 | if (!EvaluateInPlace(*Value, Info, Result, Inner)) { | |||
| 8344 | *Value = APValue(); | |||
| 8345 | return false; | |||
| 8346 | } | |||
| 8347 | ||||
| 8348 | // Adjust our lvalue to refer to the desired subobject. | |||
| 8349 | for (unsigned I = Adjustments.size(); I != 0; /**/) { | |||
| 8350 | --I; | |||
| 8351 | switch (Adjustments[I].Kind) { | |||
| 8352 | case SubobjectAdjustment::DerivedToBaseAdjustment: | |||
| 8353 | if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, | |||
| 8354 | Type, Result)) | |||
| 8355 | return false; | |||
| 8356 | Type = Adjustments[I].DerivedToBase.BasePath->getType(); | |||
| 8357 | break; | |||
| 8358 | ||||
| 8359 | case SubobjectAdjustment::FieldAdjustment: | |||
| 8360 | if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) | |||
| 8361 | return false; | |||
| 8362 | Type = Adjustments[I].Field->getType(); | |||
| 8363 | break; | |||
| 8364 | ||||
| 8365 | case SubobjectAdjustment::MemberPointerAdjustment: | |||
| 8366 | if (!HandleMemberPointerAccess(this->Info, Type, Result, | |||
| 8367 | Adjustments[I].Ptr.RHS)) | |||
| 8368 | return false; | |||
| 8369 | Type = Adjustments[I].Ptr.MPT->getPointeeType(); | |||
| 8370 | break; | |||
| 8371 | } | |||
| 8372 | } | |||
| 8373 | ||||
| 8374 | return true; | |||
| 8375 | } | |||
| 8376 | ||||
| 8377 | bool | |||
| 8378 | LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | |||
| 8379 | assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E ->isFileScope()) && "lvalue compound literal in c++?" ) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "clang/lib/AST/ExprConstant.cpp", 8380, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8380 | "lvalue compound literal in c++?")(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E ->isFileScope()) && "lvalue compound literal in c++?" ) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "clang/lib/AST/ExprConstant.cpp", 8380, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8381 | // Defer visiting the literal until the lvalue-to-rvalue conversion. We can | |||
| 8382 | // only see this when folding in C, so there's no standard to follow here. | |||
| 8383 | return Success(E); | |||
| 8384 | } | |||
| 8385 | ||||
| 8386 | bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { | |||
| 8387 | TypeInfoLValue TypeInfo; | |||
| 8388 | ||||
| 8389 | if (!E->isPotentiallyEvaluated()) { | |||
| 8390 | if (E->isTypeOperand()) | |||
| 8391 | TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); | |||
| 8392 | else | |||
| 8393 | TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); | |||
| 8394 | } else { | |||
| 8395 | if (!Info.Ctx.getLangOpts().CPlusPlus20) { | |||
| 8396 | Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) | |||
| 8397 | << E->getExprOperand()->getType() | |||
| 8398 | << E->getExprOperand()->getSourceRange(); | |||
| 8399 | } | |||
| 8400 | ||||
| 8401 | if (!Visit(E->getExprOperand())) | |||
| 8402 | return false; | |||
| 8403 | ||||
| 8404 | Optional<DynamicType> DynType = | |||
| 8405 | ComputeDynamicType(Info, E, Result, AK_TypeId); | |||
| 8406 | if (!DynType) | |||
| 8407 | return false; | |||
| 8408 | ||||
| 8409 | TypeInfo = | |||
| 8410 | TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); | |||
| 8411 | } | |||
| 8412 | ||||
| 8413 | return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); | |||
| 8414 | } | |||
| 8415 | ||||
| 8416 | bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { | |||
| 8417 | return Success(E->getGuidDecl()); | |||
| 8418 | } | |||
| 8419 | ||||
| 8420 | bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { | |||
| 8421 | // Handle static data members. | |||
| 8422 | if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { | |||
| 8423 | VisitIgnoredBaseExpression(E->getBase()); | |||
| 8424 | return VisitVarDecl(E, VD); | |||
| 8425 | } | |||
| 8426 | ||||
| 8427 | // Handle static member functions. | |||
| 8428 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { | |||
| 8429 | if (MD->isStatic()) { | |||
| 8430 | VisitIgnoredBaseExpression(E->getBase()); | |||
| 8431 | return Success(MD); | |||
| 8432 | } | |||
| 8433 | } | |||
| 8434 | ||||
| 8435 | // Handle non-static data members. | |||
| 8436 | return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); | |||
| 8437 | } | |||
| 8438 | ||||
| 8439 | bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { | |||
| 8440 | // FIXME: Deal with vectors as array subscript bases. | |||
| 8441 | if (E->getBase()->getType()->isVectorType() || | |||
| 8442 | E->getBase()->getType()->isVLSTBuiltinType()) | |||
| 8443 | return Error(E); | |||
| 8444 | ||||
| 8445 | APSInt Index; | |||
| 8446 | bool Success = true; | |||
| 8447 | ||||
| 8448 | // C++17's rules require us to evaluate the LHS first, regardless of which | |||
| 8449 | // side is the base. | |||
| 8450 | for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { | |||
| 8451 | if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) | |||
| 8452 | : !EvaluateInteger(SubExpr, Index, Info)) { | |||
| 8453 | if (!Info.noteFailure()) | |||
| 8454 | return false; | |||
| 8455 | Success = false; | |||
| 8456 | } | |||
| 8457 | } | |||
| 8458 | ||||
| 8459 | return Success && | |||
| 8460 | HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); | |||
| 8461 | } | |||
| 8462 | ||||
| 8463 | bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { | |||
| 8464 | return evaluatePointer(E->getSubExpr(), Result); | |||
| 8465 | } | |||
| 8466 | ||||
| 8467 | bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | |||
| 8468 | if (!Visit(E->getSubExpr())) | |||
| 8469 | return false; | |||
| 8470 | // __real is a no-op on scalar lvalues. | |||
| 8471 | if (E->getSubExpr()->getType()->isAnyComplexType()) | |||
| 8472 | HandleLValueComplexElement(Info, E, Result, E->getType(), false); | |||
| 8473 | return true; | |||
| 8474 | } | |||
| 8475 | ||||
| 8476 | bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | |||
| 8477 | assert(E->getSubExpr()->getType()->isAnyComplexType() &&(static_cast <bool> (E->getSubExpr()->getType()-> isAnyComplexType() && "lvalue __imag__ on scalar?") ? void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "clang/lib/AST/ExprConstant.cpp", 8478, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8478 | "lvalue __imag__ on scalar?")(static_cast <bool> (E->getSubExpr()->getType()-> isAnyComplexType() && "lvalue __imag__ on scalar?") ? void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "clang/lib/AST/ExprConstant.cpp", 8478, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8479 | if (!Visit(E->getSubExpr())) | |||
| 8480 | return false; | |||
| 8481 | HandleLValueComplexElement(Info, E, Result, E->getType(), true); | |||
| 8482 | return true; | |||
| 8483 | } | |||
| 8484 | ||||
| 8485 | bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { | |||
| 8486 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | |||
| 8487 | return Error(UO); | |||
| 8488 | ||||
| 8489 | if (!this->Visit(UO->getSubExpr())) | |||
| 8490 | return false; | |||
| 8491 | ||||
| 8492 | return handleIncDec( | |||
| 8493 | this->Info, UO, Result, UO->getSubExpr()->getType(), | |||
| 8494 | UO->isIncrementOp(), nullptr); | |||
| 8495 | } | |||
| 8496 | ||||
| 8497 | bool LValueExprEvaluator::VisitCompoundAssignOperator( | |||
| 8498 | const CompoundAssignOperator *CAO) { | |||
| 8499 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | |||
| 8500 | return Error(CAO); | |||
| 8501 | ||||
| 8502 | bool Success = true; | |||
| 8503 | ||||
| 8504 | // C++17 onwards require that we evaluate the RHS first. | |||
| 8505 | APValue RHS; | |||
| 8506 | if (!Evaluate(RHS, this->Info, CAO->getRHS())) { | |||
| 8507 | if (!Info.noteFailure()) | |||
| 8508 | return false; | |||
| 8509 | Success = false; | |||
| 8510 | } | |||
| 8511 | ||||
| 8512 | // The overall lvalue result is the result of evaluating the LHS. | |||
| 8513 | if (!this->Visit(CAO->getLHS()) || !Success) | |||
| 8514 | return false; | |||
| 8515 | ||||
| 8516 | return handleCompoundAssignment( | |||
| 8517 | this->Info, CAO, | |||
| 8518 | Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), | |||
| 8519 | CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); | |||
| 8520 | } | |||
| 8521 | ||||
| 8522 | bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { | |||
| 8523 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | |||
| 8524 | return Error(E); | |||
| 8525 | ||||
| 8526 | bool Success = true; | |||
| 8527 | ||||
| 8528 | // C++17 onwards require that we evaluate the RHS first. | |||
| 8529 | APValue NewVal; | |||
| 8530 | if (!Evaluate(NewVal, this->Info, E->getRHS())) { | |||
| 8531 | if (!Info.noteFailure()) | |||
| 8532 | return false; | |||
| 8533 | Success = false; | |||
| 8534 | } | |||
| 8535 | ||||
| 8536 | if (!this->Visit(E->getLHS()) || !Success) | |||
| 8537 | return false; | |||
| 8538 | ||||
| 8539 | if (Info.getLangOpts().CPlusPlus20 && | |||
| 8540 | !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) | |||
| 8541 | return false; | |||
| 8542 | ||||
| 8543 | return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), | |||
| 8544 | NewVal); | |||
| 8545 | } | |||
| 8546 | ||||
| 8547 | //===----------------------------------------------------------------------===// | |||
| 8548 | // Pointer Evaluation | |||
| 8549 | //===----------------------------------------------------------------------===// | |||
| 8550 | ||||
| 8551 | /// Attempts to compute the number of bytes available at the pointer | |||
| 8552 | /// returned by a function with the alloc_size attribute. Returns true if we | |||
| 8553 | /// were successful. Places an unsigned number into `Result`. | |||
| 8554 | /// | |||
| 8555 | /// This expects the given CallExpr to be a call to a function with an | |||
| 8556 | /// alloc_size attribute. | |||
| 8557 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | |||
| 8558 | const CallExpr *Call, | |||
| 8559 | llvm::APInt &Result) { | |||
| 8560 | const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); | |||
| 8561 | ||||
| 8562 | assert(AllocSize && AllocSize->getElemSizeParam().isValid())(static_cast <bool> (AllocSize && AllocSize-> getElemSizeParam().isValid()) ? void (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam().isValid()" , "clang/lib/AST/ExprConstant.cpp", 8562, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8563 | unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); | |||
| 8564 | unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); | |||
| 8565 | if (Call->getNumArgs() <= SizeArgNo) | |||
| 8566 | return false; | |||
| 8567 | ||||
| 8568 | auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { | |||
| 8569 | Expr::EvalResult ExprResult; | |||
| 8570 | if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) | |||
| 8571 | return false; | |||
| 8572 | Into = ExprResult.Val.getInt(); | |||
| 8573 | if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) | |||
| 8574 | return false; | |||
| 8575 | Into = Into.zextOrSelf(BitsInSizeT); | |||
| 8576 | return true; | |||
| 8577 | }; | |||
| 8578 | ||||
| 8579 | APSInt SizeOfElem; | |||
| 8580 | if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) | |||
| 8581 | return false; | |||
| 8582 | ||||
| 8583 | if (!AllocSize->getNumElemsParam().isValid()) { | |||
| 8584 | Result = std::move(SizeOfElem); | |||
| 8585 | return true; | |||
| 8586 | } | |||
| 8587 | ||||
| 8588 | APSInt NumberOfElems; | |||
| 8589 | unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); | |||
| 8590 | if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) | |||
| 8591 | return false; | |||
| 8592 | ||||
| 8593 | bool Overflow; | |||
| 8594 | llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); | |||
| 8595 | if (Overflow) | |||
| 8596 | return false; | |||
| 8597 | ||||
| 8598 | Result = std::move(BytesAvailable); | |||
| 8599 | return true; | |||
| 8600 | } | |||
| 8601 | ||||
| 8602 | /// Convenience function. LVal's base must be a call to an alloc_size | |||
| 8603 | /// function. | |||
| 8604 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | |||
| 8605 | const LValue &LVal, | |||
| 8606 | llvm::APInt &Result) { | |||
| 8607 | assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase ()) && "Can't get the size of a non alloc_size function" ) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "clang/lib/AST/ExprConstant.cpp", 8608, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8608 | "Can't get the size of a non alloc_size function")(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase ()) && "Can't get the size of a non alloc_size function" ) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "clang/lib/AST/ExprConstant.cpp", 8608, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8609 | const auto *Base = LVal.getLValueBase().get<const Expr *>(); | |||
| 8610 | const CallExpr *CE = tryUnwrapAllocSizeCall(Base); | |||
| 8611 | return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); | |||
| 8612 | } | |||
| 8613 | ||||
| 8614 | /// Attempts to evaluate the given LValueBase as the result of a call to | |||
| 8615 | /// a function with the alloc_size attribute. If it was possible to do so, this | |||
| 8616 | /// function will return true, make Result's Base point to said function call, | |||
| 8617 | /// and mark Result's Base as invalid. | |||
| 8618 | static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, | |||
| 8619 | LValue &Result) { | |||
| 8620 | if (Base.isNull()) | |||
| 8621 | return false; | |||
| 8622 | ||||
| 8623 | // Because we do no form of static analysis, we only support const variables. | |||
| 8624 | // | |||
| 8625 | // Additionally, we can't support parameters, nor can we support static | |||
| 8626 | // variables (in the latter case, use-before-assign isn't UB; in the former, | |||
| 8627 | // we have no clue what they'll be assigned to). | |||
| 8628 | const auto *VD = | |||
| 8629 | dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); | |||
| 8630 | if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) | |||
| 8631 | return false; | |||
| 8632 | ||||
| 8633 | const Expr *Init = VD->getAnyInitializer(); | |||
| 8634 | if (!Init) | |||
| 8635 | return false; | |||
| 8636 | ||||
| 8637 | const Expr *E = Init->IgnoreParens(); | |||
| 8638 | if (!tryUnwrapAllocSizeCall(E)) | |||
| 8639 | return false; | |||
| 8640 | ||||
| 8641 | // Store E instead of E unwrapped so that the type of the LValue's base is | |||
| 8642 | // what the user wanted. | |||
| 8643 | Result.setInvalid(E); | |||
| 8644 | ||||
| 8645 | QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); | |||
| 8646 | Result.addUnsizedArray(Info, E, Pointee); | |||
| 8647 | return true; | |||
| 8648 | } | |||
| 8649 | ||||
| 8650 | namespace { | |||
| 8651 | class PointerExprEvaluator | |||
| 8652 | : public ExprEvaluatorBase<PointerExprEvaluator> { | |||
| 8653 | LValue &Result; | |||
| 8654 | bool InvalidBaseOK; | |||
| 8655 | ||||
| 8656 | bool Success(const Expr *E) { | |||
| 8657 | Result.set(E); | |||
| 8658 | return true; | |||
| 8659 | } | |||
| 8660 | ||||
| 8661 | bool evaluateLValue(const Expr *E, LValue &Result) { | |||
| 8662 | return EvaluateLValue(E, Result, Info, InvalidBaseOK); | |||
| 8663 | } | |||
| 8664 | ||||
| 8665 | bool evaluatePointer(const Expr *E, LValue &Result) { | |||
| 8666 | return EvaluatePointer(E, Result, Info, InvalidBaseOK); | |||
| 8667 | } | |||
| 8668 | ||||
| 8669 | bool visitNonBuiltinCallExpr(const CallExpr *E); | |||
| 8670 | public: | |||
| 8671 | ||||
| 8672 | PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) | |||
| 8673 | : ExprEvaluatorBaseTy(info), Result(Result), | |||
| 8674 | InvalidBaseOK(InvalidBaseOK) {} | |||
| 8675 | ||||
| 8676 | bool Success(const APValue &V, const Expr *E) { | |||
| 8677 | Result.setFrom(Info.Ctx, V); | |||
| 8678 | return true; | |||
| 8679 | } | |||
| 8680 | bool ZeroInitialization(const Expr *E) { | |||
| 8681 | Result.setNull(Info.Ctx, E->getType()); | |||
| 8682 | return true; | |||
| 8683 | } | |||
| 8684 | ||||
| 8685 | bool VisitBinaryOperator(const BinaryOperator *E); | |||
| 8686 | bool VisitCastExpr(const CastExpr* E); | |||
| 8687 | bool VisitUnaryAddrOf(const UnaryOperator *E); | |||
| 8688 | bool VisitObjCStringLiteral(const ObjCStringLiteral *E) | |||
| 8689 | { return Success(E); } | |||
| 8690 | bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { | |||
| 8691 | if (E->isExpressibleAsConstantInitializer()) | |||
| 8692 | return Success(E); | |||
| 8693 | if (Info.noteFailure()) | |||
| 8694 | EvaluateIgnoredValue(Info, E->getSubExpr()); | |||
| 8695 | return Error(E); | |||
| 8696 | } | |||
| 8697 | bool VisitAddrLabelExpr(const AddrLabelExpr *E) | |||
| 8698 | { return Success(E); } | |||
| 8699 | bool VisitCallExpr(const CallExpr *E); | |||
| 8700 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | |||
| 8701 | bool VisitBlockExpr(const BlockExpr *E) { | |||
| 8702 | if (!E->getBlockDecl()->hasCaptures()) | |||
| 8703 | return Success(E); | |||
| 8704 | return Error(E); | |||
| 8705 | } | |||
| 8706 | bool VisitCXXThisExpr(const CXXThisExpr *E) { | |||
| 8707 | // Can't look at 'this' when checking a potential constant expression. | |||
| 8708 | if (Info.checkingPotentialConstantExpression()) | |||
| 8709 | return false; | |||
| 8710 | if (!Info.CurrentCall->This) { | |||
| 8711 | if (Info.getLangOpts().CPlusPlus11) | |||
| 8712 | Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); | |||
| 8713 | else | |||
| 8714 | Info.FFDiag(E); | |||
| 8715 | return false; | |||
| 8716 | } | |||
| 8717 | Result = *Info.CurrentCall->This; | |||
| 8718 | // If we are inside a lambda's call operator, the 'this' expression refers | |||
| 8719 | // to the enclosing '*this' object (either by value or reference) which is | |||
| 8720 | // either copied into the closure object's field that represents the '*this' | |||
| 8721 | // or refers to '*this'. | |||
| 8722 | if (isLambdaCallOperator(Info.CurrentCall->Callee)) { | |||
| 8723 | // Ensure we actually have captured 'this'. (an error will have | |||
| 8724 | // been previously reported if not). | |||
| 8725 | if (!Info.CurrentCall->LambdaThisCaptureField) | |||
| 8726 | return false; | |||
| 8727 | ||||
| 8728 | // Update 'Result' to refer to the data member/field of the closure object | |||
| 8729 | // that represents the '*this' capture. | |||
| 8730 | if (!HandleLValueMember(Info, E, Result, | |||
| 8731 | Info.CurrentCall->LambdaThisCaptureField)) | |||
| 8732 | return false; | |||
| 8733 | // If we captured '*this' by reference, replace the field with its referent. | |||
| 8734 | if (Info.CurrentCall->LambdaThisCaptureField->getType() | |||
| 8735 | ->isPointerType()) { | |||
| 8736 | APValue RVal; | |||
| 8737 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, | |||
| 8738 | RVal)) | |||
| 8739 | return false; | |||
| 8740 | ||||
| 8741 | Result.setFrom(Info.Ctx, RVal); | |||
| 8742 | } | |||
| 8743 | } | |||
| 8744 | return true; | |||
| 8745 | } | |||
| 8746 | ||||
| 8747 | bool VisitCXXNewExpr(const CXXNewExpr *E); | |||
| 8748 | ||||
| 8749 | bool VisitSourceLocExpr(const SourceLocExpr *E) { | |||
| 8750 | assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?")(static_cast <bool> (!E->isIntType() && "SourceLocExpr isn't a pointer type?" ) ? void (0) : __assert_fail ("!E->isIntType() && \"SourceLocExpr isn't a pointer type?\"" , "clang/lib/AST/ExprConstant.cpp", 8750, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8751 | APValue LValResult = E->EvaluateInContext( | |||
| 8752 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | |||
| 8753 | Result.setFrom(Info.Ctx, LValResult); | |||
| 8754 | return true; | |||
| 8755 | } | |||
| 8756 | ||||
| 8757 | bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { | |||
| 8758 | std::string ResultStr = E->ComputeName(Info.Ctx); | |||
| 8759 | ||||
| 8760 | QualType CharTy = Info.Ctx.CharTy.withConst(); | |||
| 8761 | APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), | |||
| 8762 | ResultStr.size() + 1); | |||
| 8763 | QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, | |||
| 8764 | ArrayType::Normal, 0); | |||
| 8765 | ||||
| 8766 | StringLiteral *SL = | |||
| 8767 | StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, | |||
| 8768 | /*Pascal*/ false, ArrayTy, E->getLocation()); | |||
| 8769 | ||||
| 8770 | evaluateLValue(SL, Result); | |||
| 8771 | Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); | |||
| 8772 | return true; | |||
| 8773 | } | |||
| 8774 | ||||
| 8775 | // FIXME: Missing: @protocol, @selector | |||
| 8776 | }; | |||
| 8777 | } // end anonymous namespace | |||
| 8778 | ||||
| 8779 | static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, | |||
| 8780 | bool InvalidBaseOK) { | |||
| 8781 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 8781, __extension__ __PRETTY_FUNCTION__)); | |||
| 8782 | assert(E->isPRValue() && E->getType()->hasPointerRepresentation())(static_cast <bool> (E->isPRValue() && E-> getType()->hasPointerRepresentation()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->hasPointerRepresentation()" , "clang/lib/AST/ExprConstant.cpp", 8782, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8783 | return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | |||
| 8784 | } | |||
| 8785 | ||||
| 8786 | bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | |||
| 8787 | if (E->getOpcode() != BO_Add && | |||
| 8788 | E->getOpcode() != BO_Sub) | |||
| 8789 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 8790 | ||||
| 8791 | const Expr *PExp = E->getLHS(); | |||
| 8792 | const Expr *IExp = E->getRHS(); | |||
| 8793 | if (IExp->getType()->isPointerType()) | |||
| 8794 | std::swap(PExp, IExp); | |||
| 8795 | ||||
| 8796 | bool EvalPtrOK = evaluatePointer(PExp, Result); | |||
| 8797 | if (!EvalPtrOK && !Info.noteFailure()) | |||
| 8798 | return false; | |||
| 8799 | ||||
| 8800 | llvm::APSInt Offset; | |||
| 8801 | if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) | |||
| 8802 | return false; | |||
| 8803 | ||||
| 8804 | if (E->getOpcode() == BO_Sub) | |||
| 8805 | negateAsSigned(Offset); | |||
| 8806 | ||||
| 8807 | QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); | |||
| 8808 | return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); | |||
| 8809 | } | |||
| 8810 | ||||
| 8811 | bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | |||
| 8812 | return evaluateLValue(E->getSubExpr(), Result); | |||
| 8813 | } | |||
| 8814 | ||||
| 8815 | // Is the provided decl 'std::source_location::current'? | |||
| 8816 | static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) { | |||
| 8817 | if (!FD) | |||
| 8818 | return false; | |||
| 8819 | const IdentifierInfo *FnII = FD->getIdentifier(); | |||
| 8820 | if (!FnII || !FnII->isStr("current")) | |||
| 8821 | return false; | |||
| 8822 | ||||
| 8823 | const auto *RD = dyn_cast<RecordDecl>(FD->getParent()); | |||
| 8824 | if (!RD) | |||
| 8825 | return false; | |||
| 8826 | ||||
| 8827 | const IdentifierInfo *ClassII = RD->getIdentifier(); | |||
| 8828 | return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location"); | |||
| 8829 | } | |||
| 8830 | ||||
| 8831 | bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 8832 | const Expr *SubExpr = E->getSubExpr(); | |||
| 8833 | ||||
| 8834 | switch (E->getCastKind()) { | |||
| 8835 | default: | |||
| 8836 | break; | |||
| 8837 | case CK_BitCast: | |||
| 8838 | case CK_CPointerToObjCPointerCast: | |||
| 8839 | case CK_BlockPointerToObjCPointerCast: | |||
| 8840 | case CK_AnyPointerToBlockPointerCast: | |||
| 8841 | case CK_AddressSpaceConversion: | |||
| 8842 | if (!Visit(SubExpr)) | |||
| 8843 | return false; | |||
| 8844 | // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are | |||
| 8845 | // permitted in constant expressions in C++11. Bitcasts from cv void* are | |||
| 8846 | // also static_casts, but we disallow them as a resolution to DR1312. | |||
| 8847 | if (!E->getType()->isVoidPointerType()) { | |||
| 8848 | // In some circumstances, we permit casting from void* to cv1 T*, when the | |||
| 8849 | // actual pointee object is actually a cv2 T. | |||
| 8850 | bool VoidPtrCastMaybeOK = | |||
| 8851 | !Result.InvalidBase && !Result.Designator.Invalid && | |||
| 8852 | !Result.IsNullPtr && | |||
| 8853 | Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), | |||
| 8854 | E->getType()->getPointeeType()); | |||
| 8855 | // 1. We'll allow it in std::allocator::allocate, and anything which that | |||
| 8856 | // calls. | |||
| 8857 | // 2. HACK 2022-03-28: Work around an issue with libstdc++'s | |||
| 8858 | // <source_location> header. Fixed in GCC 12 and later (2022-04-??). | |||
| 8859 | // We'll allow it in the body of std::source_location::current. GCC's | |||
| 8860 | // implementation had a parameter of type `void*`, and casts from | |||
| 8861 | // that back to `const __impl*` in its body. | |||
| 8862 | if (VoidPtrCastMaybeOK && | |||
| 8863 | (Info.getStdAllocatorCaller("allocate") || | |||
| 8864 | IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) { | |||
| 8865 | // Permitted. | |||
| 8866 | } else { | |||
| 8867 | Result.Designator.setInvalid(); | |||
| 8868 | if (SubExpr->getType()->isVoidPointerType()) | |||
| 8869 | CCEDiag(E, diag::note_constexpr_invalid_cast) | |||
| 8870 | << 3 << SubExpr->getType(); | |||
| 8871 | else | |||
| 8872 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | |||
| 8873 | } | |||
| 8874 | } | |||
| 8875 | if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) | |||
| 8876 | ZeroInitialization(E); | |||
| 8877 | return true; | |||
| 8878 | ||||
| 8879 | case CK_DerivedToBase: | |||
| 8880 | case CK_UncheckedDerivedToBase: | |||
| 8881 | if (!evaluatePointer(E->getSubExpr(), Result)) | |||
| 8882 | return false; | |||
| 8883 | if (!Result.Base && Result.Offset.isZero()) | |||
| 8884 | return true; | |||
| 8885 | ||||
| 8886 | // Now figure out the necessary offset to add to the base LV to get from | |||
| 8887 | // the derived class to the base class. | |||
| 8888 | return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> | |||
| 8889 | castAs<PointerType>()->getPointeeType(), | |||
| 8890 | Result); | |||
| 8891 | ||||
| 8892 | case CK_BaseToDerived: | |||
| 8893 | if (!Visit(E->getSubExpr())) | |||
| 8894 | return false; | |||
| 8895 | if (!Result.Base && Result.Offset.isZero()) | |||
| 8896 | return true; | |||
| 8897 | return HandleBaseToDerivedCast(Info, E, Result); | |||
| 8898 | ||||
| 8899 | case CK_Dynamic: | |||
| 8900 | if (!Visit(E->getSubExpr())) | |||
| 8901 | return false; | |||
| 8902 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | |||
| 8903 | ||||
| 8904 | case CK_NullToPointer: | |||
| 8905 | VisitIgnoredValue(E->getSubExpr()); | |||
| 8906 | return ZeroInitialization(E); | |||
| 8907 | ||||
| 8908 | case CK_IntegralToPointer: { | |||
| 8909 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | |||
| 8910 | ||||
| 8911 | APValue Value; | |||
| 8912 | if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) | |||
| 8913 | break; | |||
| 8914 | ||||
| 8915 | if (Value.isInt()) { | |||
| 8916 | unsigned Size = Info.Ctx.getTypeSize(E->getType()); | |||
| 8917 | uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); | |||
| 8918 | Result.Base = (Expr*)nullptr; | |||
| 8919 | Result.InvalidBase = false; | |||
| 8920 | Result.Offset = CharUnits::fromQuantity(N); | |||
| 8921 | Result.Designator.setInvalid(); | |||
| 8922 | Result.IsNullPtr = false; | |||
| 8923 | return true; | |||
| 8924 | } else { | |||
| 8925 | // Cast is of an lvalue, no need to change value. | |||
| 8926 | Result.setFrom(Info.Ctx, Value); | |||
| 8927 | return true; | |||
| 8928 | } | |||
| 8929 | } | |||
| 8930 | ||||
| 8931 | case CK_ArrayToPointerDecay: { | |||
| 8932 | if (SubExpr->isGLValue()) { | |||
| 8933 | if (!evaluateLValue(SubExpr, Result)) | |||
| 8934 | return false; | |||
| 8935 | } else { | |||
| 8936 | APValue &Value = Info.CurrentCall->createTemporary( | |||
| 8937 | SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); | |||
| 8938 | if (!EvaluateInPlace(Value, Info, Result, SubExpr)) | |||
| 8939 | return false; | |||
| 8940 | } | |||
| 8941 | // The result is a pointer to the first element of the array. | |||
| 8942 | auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); | |||
| 8943 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) | |||
| 8944 | Result.addArray(Info, E, CAT); | |||
| 8945 | else | |||
| 8946 | Result.addUnsizedArray(Info, E, AT->getElementType()); | |||
| 8947 | return true; | |||
| 8948 | } | |||
| 8949 | ||||
| 8950 | case CK_FunctionToPointerDecay: | |||
| 8951 | return evaluateLValue(SubExpr, Result); | |||
| 8952 | ||||
| 8953 | case CK_LValueToRValue: { | |||
| 8954 | LValue LVal; | |||
| 8955 | if (!evaluateLValue(E->getSubExpr(), LVal)) | |||
| 8956 | return false; | |||
| 8957 | ||||
| 8958 | APValue RVal; | |||
| 8959 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | |||
| 8960 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | |||
| 8961 | LVal, RVal)) | |||
| 8962 | return InvalidBaseOK && | |||
| 8963 | evaluateLValueAsAllocSize(Info, LVal.Base, Result); | |||
| 8964 | return Success(RVal, E); | |||
| 8965 | } | |||
| 8966 | } | |||
| 8967 | ||||
| 8968 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 8969 | } | |||
| 8970 | ||||
| 8971 | static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, | |||
| 8972 | UnaryExprOrTypeTrait ExprKind) { | |||
| 8973 | // C++ [expr.alignof]p3: | |||
| 8974 | // When alignof is applied to a reference type, the result is the | |||
| 8975 | // alignment of the referenced type. | |||
| 8976 | if (const ReferenceType *Ref = T->getAs<ReferenceType>()) | |||
| 8977 | T = Ref->getPointeeType(); | |||
| 8978 | ||||
| 8979 | if (T.getQualifiers().hasUnaligned()) | |||
| 8980 | return CharUnits::One(); | |||
| 8981 | ||||
| 8982 | const bool AlignOfReturnsPreferred = | |||
| 8983 | Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; | |||
| 8984 | ||||
| 8985 | // __alignof is defined to return the preferred alignment. | |||
| 8986 | // Before 8, clang returned the preferred alignment for alignof and _Alignof | |||
| 8987 | // as well. | |||
| 8988 | if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) | |||
| 8989 | return Info.Ctx.toCharUnitsFromBits( | |||
| 8990 | Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); | |||
| 8991 | // alignof and _Alignof are defined to return the ABI alignment. | |||
| 8992 | else if (ExprKind == UETT_AlignOf) | |||
| 8993 | return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); | |||
| 8994 | else | |||
| 8995 | llvm_unreachable("GetAlignOfType on a non-alignment ExprKind")::llvm::llvm_unreachable_internal("GetAlignOfType on a non-alignment ExprKind" , "clang/lib/AST/ExprConstant.cpp", 8995); | |||
| 8996 | } | |||
| 8997 | ||||
| 8998 | static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, | |||
| 8999 | UnaryExprOrTypeTrait ExprKind) { | |||
| 9000 | E = E->IgnoreParens(); | |||
| 9001 | ||||
| 9002 | // The kinds of expressions that we have special-case logic here for | |||
| 9003 | // should be kept up to date with the special checks for those | |||
| 9004 | // expressions in Sema. | |||
| 9005 | ||||
| 9006 | // alignof decl is always accepted, even if it doesn't make sense: we default | |||
| 9007 | // to 1 in those cases. | |||
| 9008 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
| 9009 | return Info.Ctx.getDeclAlign(DRE->getDecl(), | |||
| 9010 | /*RefAsPointee*/true); | |||
| 9011 | ||||
| 9012 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | |||
| 9013 | return Info.Ctx.getDeclAlign(ME->getMemberDecl(), | |||
| 9014 | /*RefAsPointee*/true); | |||
| 9015 | ||||
| 9016 | return GetAlignOfType(Info, E->getType(), ExprKind); | |||
| 9017 | } | |||
| 9018 | ||||
| 9019 | static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { | |||
| 9020 | if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) | |||
| 9021 | return Info.Ctx.getDeclAlign(VD); | |||
| 9022 | if (const auto *E = Value.Base.dyn_cast<const Expr *>()) | |||
| 9023 | return GetAlignOfExpr(Info, E, UETT_AlignOf); | |||
| 9024 | return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); | |||
| 9025 | } | |||
| 9026 | ||||
| 9027 | /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, | |||
| 9028 | /// __builtin_is_aligned and __builtin_assume_aligned. | |||
| 9029 | static bool getAlignmentArgument(const Expr *E, QualType ForType, | |||
| 9030 | EvalInfo &Info, APSInt &Alignment) { | |||
| 9031 | if (!EvaluateInteger(E, Alignment, Info)) | |||
| 9032 | return false; | |||
| 9033 | if (Alignment < 0 || !Alignment.isPowerOf2()) { | |||
| 9034 | Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; | |||
| 9035 | return false; | |||
| 9036 | } | |||
| 9037 | unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); | |||
| 9038 | APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); | |||
| 9039 | if (APSInt::compareValues(Alignment, MaxValue) > 0) { | |||
| 9040 | Info.FFDiag(E, diag::note_constexpr_alignment_too_big) | |||
| 9041 | << MaxValue << ForType << Alignment; | |||
| 9042 | return false; | |||
| 9043 | } | |||
| 9044 | // Ensure both alignment and source value have the same bit width so that we | |||
| 9045 | // don't assert when computing the resulting value. | |||
| 9046 | APSInt ExtAlignment = | |||
| 9047 | APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); | |||
| 9048 | assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&(static_cast <bool> (APSInt::compareValues(Alignment, ExtAlignment ) == 0 && "Alignment should not be changed by ext/trunc" ) ? void (0) : __assert_fail ("APSInt::compareValues(Alignment, ExtAlignment) == 0 && \"Alignment should not be changed by ext/trunc\"" , "clang/lib/AST/ExprConstant.cpp", 9049, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9049 | "Alignment should not be changed by ext/trunc")(static_cast <bool> (APSInt::compareValues(Alignment, ExtAlignment ) == 0 && "Alignment should not be changed by ext/trunc" ) ? void (0) : __assert_fail ("APSInt::compareValues(Alignment, ExtAlignment) == 0 && \"Alignment should not be changed by ext/trunc\"" , "clang/lib/AST/ExprConstant.cpp", 9049, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9050 | Alignment = ExtAlignment; | |||
| 9051 | assert(Alignment.getBitWidth() == SrcWidth)(static_cast <bool> (Alignment.getBitWidth() == SrcWidth ) ? void (0) : __assert_fail ("Alignment.getBitWidth() == SrcWidth" , "clang/lib/AST/ExprConstant.cpp", 9051, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9052 | return true; | |||
| 9053 | } | |||
| 9054 | ||||
| 9055 | // To be clear: this happily visits unsupported builtins. Better name welcomed. | |||
| 9056 | bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { | |||
| 9057 | if (ExprEvaluatorBaseTy::VisitCallExpr(E)) | |||
| 9058 | return true; | |||
| 9059 | ||||
| 9060 | if (!(InvalidBaseOK && getAllocSizeAttr(E))) | |||
| 9061 | return false; | |||
| 9062 | ||||
| 9063 | Result.setInvalid(E); | |||
| 9064 | QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); | |||
| 9065 | Result.addUnsizedArray(Info, E, PointeeTy); | |||
| 9066 | return true; | |||
| 9067 | } | |||
| 9068 | ||||
| 9069 | bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { | |||
| 9070 | if (IsConstantCall(E)) | |||
| 9071 | return Success(E); | |||
| 9072 | ||||
| 9073 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | |||
| 9074 | return VisitBuiltinCallExpr(E, BuiltinOp); | |||
| 9075 | ||||
| 9076 | return visitNonBuiltinCallExpr(E); | |||
| 9077 | } | |||
| 9078 | ||||
| 9079 | // Determine if T is a character type for which we guarantee that | |||
| 9080 | // sizeof(T) == 1. | |||
| 9081 | static bool isOneByteCharacterType(QualType T) { | |||
| 9082 | return T->isCharType() || T->isChar8Type(); | |||
| 9083 | } | |||
| 9084 | ||||
| 9085 | bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | |||
| 9086 | unsigned BuiltinOp) { | |||
| 9087 | switch (BuiltinOp) { | |||
| 9088 | case Builtin::BIaddressof: | |||
| 9089 | case Builtin::BI__addressof: | |||
| 9090 | case Builtin::BI__builtin_addressof: | |||
| 9091 | return evaluateLValue(E->getArg(0), Result); | |||
| 9092 | case Builtin::BI__builtin_assume_aligned: { | |||
| 9093 | // We need to be very careful here because: if the pointer does not have the | |||
| 9094 | // asserted alignment, then the behavior is undefined, and undefined | |||
| 9095 | // behavior is non-constant. | |||
| 9096 | if (!evaluatePointer(E->getArg(0), Result)) | |||
| 9097 | return false; | |||
| 9098 | ||||
| 9099 | LValue OffsetResult(Result); | |||
| 9100 | APSInt Alignment; | |||
| 9101 | if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, | |||
| 9102 | Alignment)) | |||
| 9103 | return false; | |||
| 9104 | CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); | |||
| 9105 | ||||
| 9106 | if (E->getNumArgs() > 2) { | |||
| 9107 | APSInt Offset; | |||
| 9108 | if (!EvaluateInteger(E->getArg(2), Offset, Info)) | |||
| 9109 | return false; | |||
| 9110 | ||||
| 9111 | int64_t AdditionalOffset = -Offset.getZExtValue(); | |||
| 9112 | OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); | |||
| 9113 | } | |||
| 9114 | ||||
| 9115 | // If there is a base object, then it must have the correct alignment. | |||
| 9116 | if (OffsetResult.Base) { | |||
| 9117 | CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); | |||
| 9118 | ||||
| 9119 | if (BaseAlignment < Align) { | |||
| 9120 | Result.Designator.setInvalid(); | |||
| 9121 | // FIXME: Add support to Diagnostic for long / long long. | |||
| 9122 | CCEDiag(E->getArg(0), | |||
| 9123 | diag::note_constexpr_baa_insufficient_alignment) << 0 | |||
| 9124 | << (unsigned)BaseAlignment.getQuantity() | |||
| 9125 | << (unsigned)Align.getQuantity(); | |||
| 9126 | return false; | |||
| 9127 | } | |||
| 9128 | } | |||
| 9129 | ||||
| 9130 | // The offset must also have the correct alignment. | |||
| 9131 | if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { | |||
| 9132 | Result.Designator.setInvalid(); | |||
| 9133 | ||||
| 9134 | (OffsetResult.Base | |||
| 9135 | ? CCEDiag(E->getArg(0), | |||
| 9136 | diag::note_constexpr_baa_insufficient_alignment) << 1 | |||
| 9137 | : CCEDiag(E->getArg(0), | |||
| 9138 | diag::note_constexpr_baa_value_insufficient_alignment)) | |||
| 9139 | << (int)OffsetResult.Offset.getQuantity() | |||
| 9140 | << (unsigned)Align.getQuantity(); | |||
| 9141 | return false; | |||
| 9142 | } | |||
| 9143 | ||||
| 9144 | return true; | |||
| 9145 | } | |||
| 9146 | case Builtin::BI__builtin_align_up: | |||
| 9147 | case Builtin::BI__builtin_align_down: { | |||
| 9148 | if (!evaluatePointer(E->getArg(0), Result)) | |||
| 9149 | return false; | |||
| 9150 | APSInt Alignment; | |||
| 9151 | if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, | |||
| 9152 | Alignment)) | |||
| 9153 | return false; | |||
| 9154 | CharUnits BaseAlignment = getBaseAlignment(Info, Result); | |||
| 9155 | CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); | |||
| 9156 | // For align_up/align_down, we can return the same value if the alignment | |||
| 9157 | // is known to be greater or equal to the requested value. | |||
| 9158 | if (PtrAlign.getQuantity() >= Alignment) | |||
| 9159 | return true; | |||
| 9160 | ||||
| 9161 | // The alignment could be greater than the minimum at run-time, so we cannot | |||
| 9162 | // infer much about the resulting pointer value. One case is possible: | |||
| 9163 | // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we | |||
| 9164 | // can infer the correct index if the requested alignment is smaller than | |||
| 9165 | // the base alignment so we can perform the computation on the offset. | |||
| 9166 | if (BaseAlignment.getQuantity() >= Alignment) { | |||
| 9167 | assert(Alignment.getBitWidth() <= 64 &&(static_cast <bool> (Alignment.getBitWidth() <= 64 && "Cannot handle > 64-bit address-space") ? void (0) : __assert_fail ("Alignment.getBitWidth() <= 64 && \"Cannot handle > 64-bit address-space\"" , "clang/lib/AST/ExprConstant.cpp", 9168, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9168 | "Cannot handle > 64-bit address-space")(static_cast <bool> (Alignment.getBitWidth() <= 64 && "Cannot handle > 64-bit address-space") ? void (0) : __assert_fail ("Alignment.getBitWidth() <= 64 && \"Cannot handle > 64-bit address-space\"" , "clang/lib/AST/ExprConstant.cpp", 9168, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9169 | uint64_t Alignment64 = Alignment.getZExtValue(); | |||
| 9170 | CharUnits NewOffset = CharUnits::fromQuantity( | |||
| 9171 | BuiltinOp == Builtin::BI__builtin_align_down | |||
| 9172 | ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) | |||
| 9173 | : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); | |||
| 9174 | Result.adjustOffset(NewOffset - Result.Offset); | |||
| 9175 | // TODO: diagnose out-of-bounds values/only allow for arrays? | |||
| 9176 | return true; | |||
| 9177 | } | |||
| 9178 | // Otherwise, we cannot constant-evaluate the result. | |||
| 9179 | Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) | |||
| 9180 | << Alignment; | |||
| 9181 | return false; | |||
| 9182 | } | |||
| 9183 | case Builtin::BI__builtin_operator_new: | |||
| 9184 | return HandleOperatorNewCall(Info, E, Result); | |||
| 9185 | case Builtin::BI__builtin_launder: | |||
| 9186 | return evaluatePointer(E->getArg(0), Result); | |||
| 9187 | case Builtin::BIstrchr: | |||
| 9188 | case Builtin::BIwcschr: | |||
| 9189 | case Builtin::BImemchr: | |||
| 9190 | case Builtin::BIwmemchr: | |||
| 9191 | if (Info.getLangOpts().CPlusPlus11) | |||
| 9192 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | |||
| 9193 | << /*isConstexpr*/0 << /*isConstructor*/0 | |||
| 9194 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | |||
| 9195 | else | |||
| 9196 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 9197 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 9198 | case Builtin::BI__builtin_strchr: | |||
| 9199 | case Builtin::BI__builtin_wcschr: | |||
| 9200 | case Builtin::BI__builtin_memchr: | |||
| 9201 | case Builtin::BI__builtin_char_memchr: | |||
| 9202 | case Builtin::BI__builtin_wmemchr: { | |||
| 9203 | if (!Visit(E->getArg(0))) | |||
| 9204 | return false; | |||
| 9205 | APSInt Desired; | |||
| 9206 | if (!EvaluateInteger(E->getArg(1), Desired, Info)) | |||
| 9207 | return false; | |||
| 9208 | uint64_t MaxLength = uint64_t(-1); | |||
| 9209 | if (BuiltinOp != Builtin::BIstrchr && | |||
| 9210 | BuiltinOp != Builtin::BIwcschr && | |||
| 9211 | BuiltinOp != Builtin::BI__builtin_strchr && | |||
| 9212 | BuiltinOp != Builtin::BI__builtin_wcschr) { | |||
| 9213 | APSInt N; | |||
| 9214 | if (!EvaluateInteger(E->getArg(2), N, Info)) | |||
| 9215 | return false; | |||
| 9216 | MaxLength = N.getExtValue(); | |||
| 9217 | } | |||
| 9218 | // We cannot find the value if there are no candidates to match against. | |||
| 9219 | if (MaxLength == 0u) | |||
| 9220 | return ZeroInitialization(E); | |||
| 9221 | if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || | |||
| 9222 | Result.Designator.Invalid) | |||
| 9223 | return false; | |||
| 9224 | QualType CharTy = Result.Designator.getType(Info.Ctx); | |||
| 9225 | bool IsRawByte = BuiltinOp == Builtin::BImemchr || | |||
| 9226 | BuiltinOp == Builtin::BI__builtin_memchr; | |||
| 9227 | assert(IsRawByte ||(static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType ( CharTy, E->getArg(0)->getType()->getPointeeType()) ) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "clang/lib/AST/ExprConstant.cpp", 9229, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9228 | Info.Ctx.hasSameUnqualifiedType((static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType ( CharTy, E->getArg(0)->getType()->getPointeeType()) ) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "clang/lib/AST/ExprConstant.cpp", 9229, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9229 | CharTy, E->getArg(0)->getType()->getPointeeType()))(static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType ( CharTy, E->getArg(0)->getType()->getPointeeType()) ) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "clang/lib/AST/ExprConstant.cpp", 9229, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9230 | // Pointers to const void may point to objects of incomplete type. | |||
| 9231 | if (IsRawByte && CharTy->isIncompleteType()) { | |||
| 9232 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; | |||
| 9233 | return false; | |||
| 9234 | } | |||
| 9235 | // Give up on byte-oriented matching against multibyte elements. | |||
| 9236 | // FIXME: We can compare the bytes in the correct order. | |||
| 9237 | if (IsRawByte && !isOneByteCharacterType(CharTy)) { | |||
| 9238 | Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) | |||
| 9239 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") | |||
| 9240 | << CharTy; | |||
| 9241 | return false; | |||
| 9242 | } | |||
| 9243 | // Figure out what value we're actually looking for (after converting to | |||
| 9244 | // the corresponding unsigned type if necessary). | |||
| 9245 | uint64_t DesiredVal; | |||
| 9246 | bool StopAtNull = false; | |||
| 9247 | switch (BuiltinOp) { | |||
| 9248 | case Builtin::BIstrchr: | |||
| 9249 | case Builtin::BI__builtin_strchr: | |||
| 9250 | // strchr compares directly to the passed integer, and therefore | |||
| 9251 | // always fails if given an int that is not a char. | |||
| 9252 | if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, | |||
| 9253 | E->getArg(1)->getType(), | |||
| 9254 | Desired), | |||
| 9255 | Desired)) | |||
| 9256 | return ZeroInitialization(E); | |||
| 9257 | StopAtNull = true; | |||
| 9258 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 9259 | case Builtin::BImemchr: | |||
| 9260 | case Builtin::BI__builtin_memchr: | |||
| 9261 | case Builtin::BI__builtin_char_memchr: | |||
| 9262 | // memchr compares by converting both sides to unsigned char. That's also | |||
| 9263 | // correct for strchr if we get this far (to cope with plain char being | |||
| 9264 | // unsigned in the strchr case). | |||
| 9265 | DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); | |||
| 9266 | break; | |||
| 9267 | ||||
| 9268 | case Builtin::BIwcschr: | |||
| 9269 | case Builtin::BI__builtin_wcschr: | |||
| 9270 | StopAtNull = true; | |||
| 9271 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 9272 | case Builtin::BIwmemchr: | |||
| 9273 | case Builtin::BI__builtin_wmemchr: | |||
| 9274 | // wcschr and wmemchr are given a wchar_t to look for. Just use it. | |||
| 9275 | DesiredVal = Desired.getZExtValue(); | |||
| 9276 | break; | |||
| 9277 | } | |||
| 9278 | ||||
| 9279 | for (; MaxLength; --MaxLength) { | |||
| 9280 | APValue Char; | |||
| 9281 | if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || | |||
| 9282 | !Char.isInt()) | |||
| 9283 | return false; | |||
| 9284 | if (Char.getInt().getZExtValue() == DesiredVal) | |||
| 9285 | return true; | |||
| 9286 | if (StopAtNull && !Char.getInt()) | |||
| 9287 | break; | |||
| 9288 | if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) | |||
| 9289 | return false; | |||
| 9290 | } | |||
| 9291 | // Not found: return nullptr. | |||
| 9292 | return ZeroInitialization(E); | |||
| 9293 | } | |||
| 9294 | ||||
| 9295 | case Builtin::BImemcpy: | |||
| 9296 | case Builtin::BImemmove: | |||
| 9297 | case Builtin::BIwmemcpy: | |||
| 9298 | case Builtin::BIwmemmove: | |||
| 9299 | if (Info.getLangOpts().CPlusPlus11) | |||
| 9300 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | |||
| 9301 | << /*isConstexpr*/0 << /*isConstructor*/0 | |||
| 9302 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | |||
| 9303 | else | |||
| 9304 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 9305 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 9306 | case Builtin::BI__builtin_memcpy: | |||
| 9307 | case Builtin::BI__builtin_memmove: | |||
| 9308 | case Builtin::BI__builtin_wmemcpy: | |||
| 9309 | case Builtin::BI__builtin_wmemmove: { | |||
| 9310 | bool WChar = BuiltinOp == Builtin::BIwmemcpy || | |||
| 9311 | BuiltinOp == Builtin::BIwmemmove || | |||
| 9312 | BuiltinOp == Builtin::BI__builtin_wmemcpy || | |||
| 9313 | BuiltinOp == Builtin::BI__builtin_wmemmove; | |||
| 9314 | bool Move = BuiltinOp == Builtin::BImemmove || | |||
| 9315 | BuiltinOp == Builtin::BIwmemmove || | |||
| 9316 | BuiltinOp == Builtin::BI__builtin_memmove || | |||
| 9317 | BuiltinOp == Builtin::BI__builtin_wmemmove; | |||
| 9318 | ||||
| 9319 | // The result of mem* is the first argument. | |||
| 9320 | if (!Visit(E->getArg(0))) | |||
| 9321 | return false; | |||
| 9322 | LValue Dest = Result; | |||
| 9323 | ||||
| 9324 | LValue Src; | |||
| 9325 | if (!EvaluatePointer(E->getArg(1), Src, Info)) | |||
| 9326 | return false; | |||
| 9327 | ||||
| 9328 | APSInt N; | |||
| 9329 | if (!EvaluateInteger(E->getArg(2), N, Info)) | |||
| 9330 | return false; | |||
| 9331 | assert(!N.isSigned() && "memcpy and friends take an unsigned size")(static_cast <bool> (!N.isSigned() && "memcpy and friends take an unsigned size" ) ? void (0) : __assert_fail ("!N.isSigned() && \"memcpy and friends take an unsigned size\"" , "clang/lib/AST/ExprConstant.cpp", 9331, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9332 | ||||
| 9333 | // If the size is zero, we treat this as always being a valid no-op. | |||
| 9334 | // (Even if one of the src and dest pointers is null.) | |||
| 9335 | if (!N) | |||
| 9336 | return true; | |||
| 9337 | ||||
| 9338 | // Otherwise, if either of the operands is null, we can't proceed. Don't | |||
| 9339 | // try to determine the type of the copied objects, because there aren't | |||
| 9340 | // any. | |||
| 9341 | if (!Src.Base || !Dest.Base) { | |||
| 9342 | APValue Val; | |||
| 9343 | (!Src.Base ? Src : Dest).moveInto(Val); | |||
| 9344 | Info.FFDiag(E, diag::note_constexpr_memcpy_null) | |||
| 9345 | << Move << WChar << !!Src.Base | |||
| 9346 | << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); | |||
| 9347 | return false; | |||
| 9348 | } | |||
| 9349 | if (Src.Designator.Invalid || Dest.Designator.Invalid) | |||
| 9350 | return false; | |||
| 9351 | ||||
| 9352 | // We require that Src and Dest are both pointers to arrays of | |||
| 9353 | // trivially-copyable type. (For the wide version, the designator will be | |||
| 9354 | // invalid if the designated object is not a wchar_t.) | |||
| 9355 | QualType T = Dest.Designator.getType(Info.Ctx); | |||
| 9356 | QualType SrcT = Src.Designator.getType(Info.Ctx); | |||
| 9357 | if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { | |||
| 9358 | // FIXME: Consider using our bit_cast implementation to support this. | |||
| 9359 | Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; | |||
| 9360 | return false; | |||
| 9361 | } | |||
| 9362 | if (T->isIncompleteType()) { | |||
| 9363 | Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; | |||
| 9364 | return false; | |||
| 9365 | } | |||
| 9366 | if (!T.isTriviallyCopyableType(Info.Ctx)) { | |||
| 9367 | Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; | |||
| 9368 | return false; | |||
| 9369 | } | |||
| 9370 | ||||
| 9371 | // Figure out how many T's we're copying. | |||
| 9372 | uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); | |||
| 9373 | if (!WChar) { | |||
| 9374 | uint64_t Remainder; | |||
| 9375 | llvm::APInt OrigN = N; | |||
| 9376 | llvm::APInt::udivrem(OrigN, TSize, N, Remainder); | |||
| 9377 | if (Remainder) { | |||
| 9378 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | |||
| 9379 | << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) | |||
| 9380 | << (unsigned)TSize; | |||
| 9381 | return false; | |||
| 9382 | } | |||
| 9383 | } | |||
| 9384 | ||||
| 9385 | // Check that the copying will remain within the arrays, just so that we | |||
| 9386 | // can give a more meaningful diagnostic. This implicitly also checks that | |||
| 9387 | // N fits into 64 bits. | |||
| 9388 | uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; | |||
| 9389 | uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; | |||
| 9390 | if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { | |||
| 9391 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | |||
| 9392 | << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T | |||
| 9393 | << toString(N, 10, /*Signed*/false); | |||
| 9394 | return false; | |||
| 9395 | } | |||
| 9396 | uint64_t NElems = N.getZExtValue(); | |||
| 9397 | uint64_t NBytes = NElems * TSize; | |||
| 9398 | ||||
| 9399 | // Check for overlap. | |||
| 9400 | int Direction = 1; | |||
| 9401 | if (HasSameBase(Src, Dest)) { | |||
| 9402 | uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); | |||
| 9403 | uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); | |||
| 9404 | if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { | |||
| 9405 | // Dest is inside the source region. | |||
| 9406 | if (!Move) { | |||
| 9407 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | |||
| 9408 | return false; | |||
| 9409 | } | |||
| 9410 | // For memmove and friends, copy backwards. | |||
| 9411 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || | |||
| 9412 | !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) | |||
| 9413 | return false; | |||
| 9414 | Direction = -1; | |||
| 9415 | } else if (!Move && SrcOffset >= DestOffset && | |||
| 9416 | SrcOffset - DestOffset < NBytes) { | |||
| 9417 | // Src is inside the destination region for memcpy: invalid. | |||
| 9418 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | |||
| 9419 | return false; | |||
| 9420 | } | |||
| 9421 | } | |||
| 9422 | ||||
| 9423 | while (true) { | |||
| 9424 | APValue Val; | |||
| 9425 | // FIXME: Set WantObjectRepresentation to true if we're copying a | |||
| 9426 | // char-like type? | |||
| 9427 | if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || | |||
| 9428 | !handleAssignment(Info, E, Dest, T, Val)) | |||
| 9429 | return false; | |||
| 9430 | // Do not iterate past the last element; if we're copying backwards, that | |||
| 9431 | // might take us off the start of the array. | |||
| 9432 | if (--NElems == 0) | |||
| 9433 | return true; | |||
| 9434 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || | |||
| 9435 | !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) | |||
| 9436 | return false; | |||
| 9437 | } | |||
| 9438 | } | |||
| 9439 | ||||
| 9440 | default: | |||
| 9441 | break; | |||
| 9442 | } | |||
| 9443 | ||||
| 9444 | return visitNonBuiltinCallExpr(E); | |||
| 9445 | } | |||
| 9446 | ||||
| 9447 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | |||
| 9448 | APValue &Result, const InitListExpr *ILE, | |||
| 9449 | QualType AllocType); | |||
| 9450 | static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, | |||
| 9451 | APValue &Result, | |||
| 9452 | const CXXConstructExpr *CCE, | |||
| 9453 | QualType AllocType); | |||
| 9454 | ||||
| 9455 | bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { | |||
| 9456 | if (!Info.getLangOpts().CPlusPlus20) | |||
| 9457 | Info.CCEDiag(E, diag::note_constexpr_new); | |||
| 9458 | ||||
| 9459 | // We cannot speculatively evaluate a delete expression. | |||
| 9460 | if (Info.SpeculativeEvaluationDepth) | |||
| 9461 | return false; | |||
| 9462 | ||||
| 9463 | FunctionDecl *OperatorNew = E->getOperatorNew(); | |||
| 9464 | ||||
| 9465 | bool IsNothrow = false; | |||
| 9466 | bool IsPlacement = false; | |||
| 9467 | if (OperatorNew->isReservedGlobalPlacementOperator() && | |||
| 9468 | Info.CurrentCall->isStdFunction() && !E->isArray()) { | |||
| 9469 | // FIXME Support array placement new. | |||
| 9470 | assert(E->getNumPlacementArgs() == 1)(static_cast <bool> (E->getNumPlacementArgs() == 1) ? void (0) : __assert_fail ("E->getNumPlacementArgs() == 1" , "clang/lib/AST/ExprConstant.cpp", 9470, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9471 | if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) | |||
| 9472 | return false; | |||
| 9473 | if (Result.Designator.Invalid) | |||
| 9474 | return false; | |||
| 9475 | IsPlacement = true; | |||
| 9476 | } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { | |||
| 9477 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | |||
| 9478 | << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; | |||
| 9479 | return false; | |||
| 9480 | } else if (E->getNumPlacementArgs()) { | |||
| 9481 | // The only new-placement list we support is of the form (std::nothrow). | |||
| 9482 | // | |||
| 9483 | // FIXME: There is no restriction on this, but it's not clear that any | |||
| 9484 | // other form makes any sense. We get here for cases such as: | |||
| 9485 | // | |||
| 9486 | // new (std::align_val_t{N}) X(int) | |||
| 9487 | // | |||
| 9488 | // (which should presumably be valid only if N is a multiple of | |||
| 9489 | // alignof(int), and in any case can't be deallocated unless N is | |||
| 9490 | // alignof(X) and X has new-extended alignment). | |||
| 9491 | if (E->getNumPlacementArgs() != 1 || | |||
| 9492 | !E->getPlacementArg(0)->getType()->isNothrowT()) | |||
| 9493 | return Error(E, diag::note_constexpr_new_placement); | |||
| 9494 | ||||
| 9495 | LValue Nothrow; | |||
| 9496 | if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) | |||
| 9497 | return false; | |||
| 9498 | IsNothrow = true; | |||
| 9499 | } | |||
| 9500 | ||||
| 9501 | const Expr *Init = E->getInitializer(); | |||
| 9502 | const InitListExpr *ResizedArrayILE = nullptr; | |||
| 9503 | const CXXConstructExpr *ResizedArrayCCE = nullptr; | |||
| 9504 | bool ValueInit = false; | |||
| 9505 | ||||
| 9506 | QualType AllocType = E->getAllocatedType(); | |||
| 9507 | if (Optional<const Expr *> ArraySize = E->getArraySize()) { | |||
| 9508 | const Expr *Stripped = *ArraySize; | |||
| 9509 | for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); | |||
| 9510 | Stripped = ICE->getSubExpr()) | |||
| 9511 | if (ICE->getCastKind() != CK_NoOp && | |||
| 9512 | ICE->getCastKind() != CK_IntegralCast) | |||
| 9513 | break; | |||
| 9514 | ||||
| 9515 | llvm::APSInt ArrayBound; | |||
| 9516 | if (!EvaluateInteger(Stripped, ArrayBound, Info)) | |||
| 9517 | return false; | |||
| 9518 | ||||
| 9519 | // C++ [expr.new]p9: | |||
| 9520 | // The expression is erroneous if: | |||
| 9521 | // -- [...] its value before converting to size_t [or] applying the | |||
| 9522 | // second standard conversion sequence is less than zero | |||
| 9523 | if (ArrayBound.isSigned() && ArrayBound.isNegative()) { | |||
| 9524 | if (IsNothrow) | |||
| 9525 | return ZeroInitialization(E); | |||
| 9526 | ||||
| 9527 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) | |||
| 9528 | << ArrayBound << (*ArraySize)->getSourceRange(); | |||
| 9529 | return false; | |||
| 9530 | } | |||
| 9531 | ||||
| 9532 | // -- its value is such that the size of the allocated object would | |||
| 9533 | // exceed the implementation-defined limit | |||
| 9534 | if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, | |||
| 9535 | ArrayBound) > | |||
| 9536 | ConstantArrayType::getMaxSizeBits(Info.Ctx)) { | |||
| 9537 | if (IsNothrow) | |||
| 9538 | return ZeroInitialization(E); | |||
| 9539 | ||||
| 9540 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) | |||
| 9541 | << ArrayBound << (*ArraySize)->getSourceRange(); | |||
| 9542 | return false; | |||
| 9543 | } | |||
| 9544 | ||||
| 9545 | // -- the new-initializer is a braced-init-list and the number of | |||
| 9546 | // array elements for which initializers are provided [...] | |||
| 9547 | // exceeds the number of elements to initialize | |||
| 9548 | if (!Init) { | |||
| 9549 | // No initialization is performed. | |||
| 9550 | } else if (isa<CXXScalarValueInitExpr>(Init) || | |||
| 9551 | isa<ImplicitValueInitExpr>(Init)) { | |||
| 9552 | ValueInit = true; | |||
| 9553 | } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { | |||
| 9554 | ResizedArrayCCE = CCE; | |||
| 9555 | } else { | |||
| 9556 | auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); | |||
| 9557 | assert(CAT && "unexpected type for array initializer")(static_cast <bool> (CAT && "unexpected type for array initializer" ) ? void (0) : __assert_fail ("CAT && \"unexpected type for array initializer\"" , "clang/lib/AST/ExprConstant.cpp", 9557, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9558 | ||||
| 9559 | unsigned Bits = | |||
| 9560 | std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); | |||
| 9561 | llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); | |||
| 9562 | llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); | |||
| 9563 | if (InitBound.ugt(AllocBound)) { | |||
| 9564 | if (IsNothrow) | |||
| 9565 | return ZeroInitialization(E); | |||
| 9566 | ||||
| 9567 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) | |||
| 9568 | << toString(AllocBound, 10, /*Signed=*/false) | |||
| 9569 | << toString(InitBound, 10, /*Signed=*/false) | |||
| 9570 | << (*ArraySize)->getSourceRange(); | |||
| 9571 | return false; | |||
| 9572 | } | |||
| 9573 | ||||
| 9574 | // If the sizes differ, we must have an initializer list, and we need | |||
| 9575 | // special handling for this case when we initialize. | |||
| 9576 | if (InitBound != AllocBound) | |||
| 9577 | ResizedArrayILE = cast<InitListExpr>(Init); | |||
| 9578 | } | |||
| 9579 | ||||
| 9580 | AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, | |||
| 9581 | ArrayType::Normal, 0); | |||
| 9582 | } else { | |||
| 9583 | assert(!AllocType->isArrayType() &&(static_cast <bool> (!AllocType->isArrayType() && "array allocation with non-array new") ? void (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "clang/lib/AST/ExprConstant.cpp", 9584, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9584 | "array allocation with non-array new")(static_cast <bool> (!AllocType->isArrayType() && "array allocation with non-array new") ? void (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "clang/lib/AST/ExprConstant.cpp", 9584, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9585 | } | |||
| 9586 | ||||
| 9587 | APValue *Val; | |||
| 9588 | if (IsPlacement) { | |||
| 9589 | AccessKinds AK = AK_Construct; | |||
| 9590 | struct FindObjectHandler { | |||
| 9591 | EvalInfo &Info; | |||
| 9592 | const Expr *E; | |||
| 9593 | QualType AllocType; | |||
| 9594 | const AccessKinds AccessKind; | |||
| 9595 | APValue *Value; | |||
| 9596 | ||||
| 9597 | typedef bool result_type; | |||
| 9598 | bool failed() { return false; } | |||
| 9599 | bool found(APValue &Subobj, QualType SubobjType) { | |||
| 9600 | // FIXME: Reject the cases where [basic.life]p8 would not permit the | |||
| 9601 | // old name of the object to be used to name the new object. | |||
| 9602 | if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { | |||
| 9603 | Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << | |||
| 9604 | SubobjType << AllocType; | |||
| 9605 | return false; | |||
| 9606 | } | |||
| 9607 | Value = &Subobj; | |||
| 9608 | return true; | |||
| 9609 | } | |||
| 9610 | bool found(APSInt &Value, QualType SubobjType) { | |||
| 9611 | Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); | |||
| 9612 | return false; | |||
| 9613 | } | |||
| 9614 | bool found(APFloat &Value, QualType SubobjType) { | |||
| 9615 | Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); | |||
| 9616 | return false; | |||
| 9617 | } | |||
| 9618 | } Handler = {Info, E, AllocType, AK, nullptr}; | |||
| 9619 | ||||
| 9620 | CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); | |||
| 9621 | if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) | |||
| 9622 | return false; | |||
| 9623 | ||||
| 9624 | Val = Handler.Value; | |||
| 9625 | ||||
| 9626 | // [basic.life]p1: | |||
| 9627 | // The lifetime of an object o of type T ends when [...] the storage | |||
| 9628 | // which the object occupies is [...] reused by an object that is not | |||
| 9629 | // nested within o (6.6.2). | |||
| 9630 | *Val = APValue(); | |||
| 9631 | } else { | |||
| 9632 | // Perform the allocation and obtain a pointer to the resulting object. | |||
| 9633 | Val = Info.createHeapAlloc(E, AllocType, Result); | |||
| 9634 | if (!Val) | |||
| 9635 | return false; | |||
| 9636 | } | |||
| 9637 | ||||
| 9638 | if (ValueInit) { | |||
| 9639 | ImplicitValueInitExpr VIE(AllocType); | |||
| 9640 | if (!EvaluateInPlace(*Val, Info, Result, &VIE)) | |||
| 9641 | return false; | |||
| 9642 | } else if (ResizedArrayILE) { | |||
| 9643 | if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, | |||
| 9644 | AllocType)) | |||
| 9645 | return false; | |||
| 9646 | } else if (ResizedArrayCCE) { | |||
| 9647 | if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, | |||
| 9648 | AllocType)) | |||
| 9649 | return false; | |||
| 9650 | } else if (Init) { | |||
| 9651 | if (!EvaluateInPlace(*Val, Info, Result, Init)) | |||
| 9652 | return false; | |||
| 9653 | } else if (!getDefaultInitValue(AllocType, *Val)) { | |||
| 9654 | return false; | |||
| 9655 | } | |||
| 9656 | ||||
| 9657 | // Array new returns a pointer to the first element, not a pointer to the | |||
| 9658 | // array. | |||
| 9659 | if (auto *AT = AllocType->getAsArrayTypeUnsafe()) | |||
| 9660 | Result.addArray(Info, E, cast<ConstantArrayType>(AT)); | |||
| 9661 | ||||
| 9662 | return true; | |||
| 9663 | } | |||
| 9664 | //===----------------------------------------------------------------------===// | |||
| 9665 | // Member Pointer Evaluation | |||
| 9666 | //===----------------------------------------------------------------------===// | |||
| 9667 | ||||
| 9668 | namespace { | |||
| 9669 | class MemberPointerExprEvaluator | |||
| 9670 | : public ExprEvaluatorBase<MemberPointerExprEvaluator> { | |||
| 9671 | MemberPtr &Result; | |||
| 9672 | ||||
| 9673 | bool Success(const ValueDecl *D) { | |||
| 9674 | Result = MemberPtr(D); | |||
| 9675 | return true; | |||
| 9676 | } | |||
| 9677 | public: | |||
| 9678 | ||||
| 9679 | MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) | |||
| 9680 | : ExprEvaluatorBaseTy(Info), Result(Result) {} | |||
| 9681 | ||||
| 9682 | bool Success(const APValue &V, const Expr *E) { | |||
| 9683 | Result.setFrom(V); | |||
| 9684 | return true; | |||
| 9685 | } | |||
| 9686 | bool ZeroInitialization(const Expr *E) { | |||
| 9687 | return Success((const ValueDecl*)nullptr); | |||
| 9688 | } | |||
| 9689 | ||||
| 9690 | bool VisitCastExpr(const CastExpr *E); | |||
| 9691 | bool VisitUnaryAddrOf(const UnaryOperator *E); | |||
| 9692 | }; | |||
| 9693 | } // end anonymous namespace | |||
| 9694 | ||||
| 9695 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | |||
| 9696 | EvalInfo &Info) { | |||
| 9697 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 9697, __extension__ __PRETTY_FUNCTION__)); | |||
| 9698 | assert(E->isPRValue() && E->getType()->isMemberPointerType())(static_cast <bool> (E->isPRValue() && E-> getType()->isMemberPointerType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isMemberPointerType()" , "clang/lib/AST/ExprConstant.cpp", 9698, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9699 | return MemberPointerExprEvaluator(Info, Result).Visit(E); | |||
| 9700 | } | |||
| 9701 | ||||
| 9702 | bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 9703 | switch (E->getCastKind()) { | |||
| 9704 | default: | |||
| 9705 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 9706 | ||||
| 9707 | case CK_NullToMemberPointer: | |||
| 9708 | VisitIgnoredValue(E->getSubExpr()); | |||
| 9709 | return ZeroInitialization(E); | |||
| 9710 | ||||
| 9711 | case CK_BaseToDerivedMemberPointer: { | |||
| 9712 | if (!Visit(E->getSubExpr())) | |||
| 9713 | return false; | |||
| 9714 | if (E->path_empty()) | |||
| 9715 | return true; | |||
| 9716 | // Base-to-derived member pointer casts store the path in derived-to-base | |||
| 9717 | // order, so iterate backwards. The CXXBaseSpecifier also provides us with | |||
| 9718 | // the wrong end of the derived->base arc, so stagger the path by one class. | |||
| 9719 | typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; | |||
| 9720 | for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); | |||
| 9721 | PathI != PathE; ++PathI) { | |||
| 9722 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() && "memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "clang/lib/AST/ExprConstant.cpp", 9722, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9723 | const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); | |||
| 9724 | if (!Result.castToDerived(Derived)) | |||
| 9725 | return Error(E); | |||
| 9726 | } | |||
| 9727 | const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); | |||
| 9728 | if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) | |||
| 9729 | return Error(E); | |||
| 9730 | return true; | |||
| 9731 | } | |||
| 9732 | ||||
| 9733 | case CK_DerivedToBaseMemberPointer: | |||
| 9734 | if (!Visit(E->getSubExpr())) | |||
| 9735 | return false; | |||
| 9736 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | |||
| 9737 | PathE = E->path_end(); PathI != PathE; ++PathI) { | |||
| 9738 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() && "memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "clang/lib/AST/ExprConstant.cpp", 9738, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9739 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | |||
| 9740 | if (!Result.castToBase(Base)) | |||
| 9741 | return Error(E); | |||
| 9742 | } | |||
| 9743 | return true; | |||
| 9744 | } | |||
| 9745 | } | |||
| 9746 | ||||
| 9747 | bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | |||
| 9748 | // C++11 [expr.unary.op]p3 has very strict rules on how the address of a | |||
| 9749 | // member can be formed. | |||
| 9750 | return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); | |||
| 9751 | } | |||
| 9752 | ||||
| 9753 | //===----------------------------------------------------------------------===// | |||
| 9754 | // Record Evaluation | |||
| 9755 | //===----------------------------------------------------------------------===// | |||
| 9756 | ||||
| 9757 | namespace { | |||
| 9758 | class RecordExprEvaluator | |||
| 9759 | : public ExprEvaluatorBase<RecordExprEvaluator> { | |||
| 9760 | const LValue &This; | |||
| 9761 | APValue &Result; | |||
| 9762 | public: | |||
| 9763 | ||||
| 9764 | RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) | |||
| 9765 | : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} | |||
| 9766 | ||||
| 9767 | bool Success(const APValue &V, const Expr *E) { | |||
| 9768 | Result = V; | |||
| 9769 | return true; | |||
| 9770 | } | |||
| 9771 | bool ZeroInitialization(const Expr *E) { | |||
| 9772 | return ZeroInitialization(E, E->getType()); | |||
| 9773 | } | |||
| 9774 | bool ZeroInitialization(const Expr *E, QualType T); | |||
| 9775 | ||||
| 9776 | bool VisitCallExpr(const CallExpr *E) { | |||
| 9777 | return handleCallExpr(E, Result, &This); | |||
| 9778 | } | |||
| 9779 | bool VisitCastExpr(const CastExpr *E); | |||
| 9780 | bool VisitInitListExpr(const InitListExpr *E); | |||
| 9781 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | |||
| 9782 | return VisitCXXConstructExpr(E, E->getType()); | |||
| 9783 | } | |||
| 9784 | bool VisitLambdaExpr(const LambdaExpr *E); | |||
| 9785 | bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); | |||
| 9786 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); | |||
| 9787 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); | |||
| 9788 | bool VisitBinCmp(const BinaryOperator *E); | |||
| 9789 | }; | |||
| 9790 | } | |||
| 9791 | ||||
| 9792 | /// Perform zero-initialization on an object of non-union class type. | |||
| 9793 | /// C++11 [dcl.init]p5: | |||
| 9794 | /// To zero-initialize an object or reference of type T means: | |||
| 9795 | /// [...] | |||
| 9796 | /// -- if T is a (possibly cv-qualified) non-union class type, | |||
| 9797 | /// each non-static data member and each base-class subobject is | |||
| 9798 | /// zero-initialized | |||
| 9799 | static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, | |||
| 9800 | const RecordDecl *RD, | |||
| 9801 | const LValue &This, APValue &Result) { | |||
| 9802 | assert(!RD->isUnion() && "Expected non-union class type")(static_cast <bool> (!RD->isUnion() && "Expected non-union class type" ) ? void (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\"" , "clang/lib/AST/ExprConstant.cpp", 9802, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9803 | const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); | |||
| 9804 | Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, | |||
| 9805 | std::distance(RD->field_begin(), RD->field_end())); | |||
| 9806 | ||||
| 9807 | if (RD->isInvalidDecl()) return false; | |||
| 9808 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | |||
| 9809 | ||||
| 9810 | if (CD) { | |||
| 9811 | unsigned Index = 0; | |||
| 9812 | for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), | |||
| 9813 | End = CD->bases_end(); I != End; ++I, ++Index) { | |||
| 9814 | const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); | |||
| 9815 | LValue Subobject = This; | |||
| 9816 | if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) | |||
| 9817 | return false; | |||
| 9818 | if (!HandleClassZeroInitialization(Info, E, Base, Subobject, | |||
| 9819 | Result.getStructBase(Index))) | |||
| 9820 | return false; | |||
| 9821 | } | |||
| 9822 | } | |||
| 9823 | ||||
| 9824 | for (const auto *I : RD->fields()) { | |||
| 9825 | // -- if T is a reference type, no initialization is performed. | |||
| 9826 | if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) | |||
| 9827 | continue; | |||
| 9828 | ||||
| 9829 | LValue Subobject = This; | |||
| 9830 | if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) | |||
| 9831 | return false; | |||
| 9832 | ||||
| 9833 | ImplicitValueInitExpr VIE(I->getType()); | |||
| 9834 | if (!EvaluateInPlace( | |||
| 9835 | Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) | |||
| 9836 | return false; | |||
| 9837 | } | |||
| 9838 | ||||
| 9839 | return true; | |||
| 9840 | } | |||
| 9841 | ||||
| 9842 | bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { | |||
| 9843 | const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); | |||
| 9844 | if (RD->isInvalidDecl()) return false; | |||
| 9845 | if (RD->isUnion()) { | |||
| 9846 | // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the | |||
| 9847 | // object's first non-static named data member is zero-initialized | |||
| 9848 | RecordDecl::field_iterator I = RD->field_begin(); | |||
| 9849 | while (I != RD->field_end() && (*I)->isUnnamedBitfield()) | |||
| 9850 | ++I; | |||
| 9851 | if (I == RD->field_end()) { | |||
| 9852 | Result = APValue((const FieldDecl*)nullptr); | |||
| 9853 | return true; | |||
| 9854 | } | |||
| 9855 | ||||
| 9856 | LValue Subobject = This; | |||
| 9857 | if (!HandleLValueMember(Info, E, Subobject, *I)) | |||
| 9858 | return false; | |||
| 9859 | Result = APValue(*I); | |||
| 9860 | ImplicitValueInitExpr VIE(I->getType()); | |||
| 9861 | return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); | |||
| 9862 | } | |||
| 9863 | ||||
| 9864 | if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { | |||
| 9865 | Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; | |||
| 9866 | return false; | |||
| 9867 | } | |||
| 9868 | ||||
| 9869 | return HandleClassZeroInitialization(Info, E, RD, This, Result); | |||
| 9870 | } | |||
| 9871 | ||||
| 9872 | bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 9873 | switch (E->getCastKind()) { | |||
| 9874 | default: | |||
| 9875 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 9876 | ||||
| 9877 | case CK_ConstructorConversion: | |||
| 9878 | return Visit(E->getSubExpr()); | |||
| 9879 | ||||
| 9880 | case CK_DerivedToBase: | |||
| 9881 | case CK_UncheckedDerivedToBase: { | |||
| 9882 | APValue DerivedObject; | |||
| 9883 | if (!Evaluate(DerivedObject, Info, E->getSubExpr())) | |||
| 9884 | return false; | |||
| 9885 | if (!DerivedObject.isStruct()) | |||
| 9886 | return Error(E->getSubExpr()); | |||
| 9887 | ||||
| 9888 | // Derived-to-base rvalue conversion: just slice off the derived part. | |||
| 9889 | APValue *Value = &DerivedObject; | |||
| 9890 | const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); | |||
| 9891 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | |||
| 9892 | PathE = E->path_end(); PathI != PathE; ++PathI) { | |||
| 9893 | assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")(static_cast <bool> (!(*PathI)->isVirtual() && "record rvalue with virtual base") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"record rvalue with virtual base\"" , "clang/lib/AST/ExprConstant.cpp", 9893, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9894 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | |||
| 9895 | Value = &Value->getStructBase(getBaseIndex(RD, Base)); | |||
| 9896 | RD = Base; | |||
| 9897 | } | |||
| 9898 | Result = *Value; | |||
| 9899 | return true; | |||
| 9900 | } | |||
| 9901 | } | |||
| 9902 | } | |||
| 9903 | ||||
| 9904 | bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | |||
| 9905 | if (E->isTransparent()) | |||
| 9906 | return Visit(E->getInit(0)); | |||
| 9907 | ||||
| 9908 | const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); | |||
| 9909 | if (RD->isInvalidDecl()) return false; | |||
| 9910 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | |||
| 9911 | auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); | |||
| 9912 | ||||
| 9913 | EvalInfo::EvaluatingConstructorRAII EvalObj( | |||
| 9914 | Info, | |||
| 9915 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | |||
| 9916 | CXXRD && CXXRD->getNumBases()); | |||
| 9917 | ||||
| 9918 | if (RD->isUnion()) { | |||
| 9919 | const FieldDecl *Field = E->getInitializedFieldInUnion(); | |||
| 9920 | Result = APValue(Field); | |||
| 9921 | if (!Field) | |||
| 9922 | return true; | |||
| 9923 | ||||
| 9924 | // If the initializer list for a union does not contain any elements, the | |||
| 9925 | // first element of the union is value-initialized. | |||
| 9926 | // FIXME: The element should be initialized from an initializer list. | |||
| 9927 | // Is this difference ever observable for initializer lists which | |||
| 9928 | // we don't build? | |||
| 9929 | ImplicitValueInitExpr VIE(Field->getType()); | |||
| 9930 | const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; | |||
| 9931 | ||||
| 9932 | LValue Subobject = This; | |||
| 9933 | if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) | |||
| 9934 | return false; | |||
| 9935 | ||||
| 9936 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | |||
| 9937 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | |||
| 9938 | isa<CXXDefaultInitExpr>(InitExpr)); | |||
| 9939 | ||||
| 9940 | if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { | |||
| 9941 | if (Field->isBitField()) | |||
| 9942 | return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), | |||
| 9943 | Field); | |||
| 9944 | return true; | |||
| 9945 | } | |||
| 9946 | ||||
| 9947 | return false; | |||
| 9948 | } | |||
| 9949 | ||||
| 9950 | if (!Result.hasValue()) | |||
| 9951 | Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, | |||
| 9952 | std::distance(RD->field_begin(), RD->field_end())); | |||
| 9953 | unsigned ElementNo = 0; | |||
| 9954 | bool Success = true; | |||
| 9955 | ||||
| 9956 | // Initialize base classes. | |||
| 9957 | if (CXXRD && CXXRD->getNumBases()) { | |||
| 9958 | for (const auto &Base : CXXRD->bases()) { | |||
| 9959 | assert(ElementNo < E->getNumInits() && "missing init for base class")(static_cast <bool> (ElementNo < E->getNumInits() && "missing init for base class") ? void (0) : __assert_fail ("ElementNo < E->getNumInits() && \"missing init for base class\"" , "clang/lib/AST/ExprConstant.cpp", 9959, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9960 | const Expr *Init = E->getInit(ElementNo); | |||
| 9961 | ||||
| 9962 | LValue Subobject = This; | |||
| 9963 | if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) | |||
| 9964 | return false; | |||
| 9965 | ||||
| 9966 | APValue &FieldVal = Result.getStructBase(ElementNo); | |||
| 9967 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { | |||
| 9968 | if (!Info.noteFailure()) | |||
| 9969 | return false; | |||
| 9970 | Success = false; | |||
| 9971 | } | |||
| 9972 | ++ElementNo; | |||
| 9973 | } | |||
| 9974 | ||||
| 9975 | EvalObj.finishedConstructingBases(); | |||
| 9976 | } | |||
| 9977 | ||||
| 9978 | // Initialize members. | |||
| 9979 | for (const auto *Field : RD->fields()) { | |||
| 9980 | // Anonymous bit-fields are not considered members of the class for | |||
| 9981 | // purposes of aggregate initialization. | |||
| 9982 | if (Field->isUnnamedBitfield()) | |||
| 9983 | continue; | |||
| 9984 | ||||
| 9985 | LValue Subobject = This; | |||
| 9986 | ||||
| 9987 | bool HaveInit = ElementNo < E->getNumInits(); | |||
| 9988 | ||||
| 9989 | // FIXME: Diagnostics here should point to the end of the initializer | |||
| 9990 | // list, not the start. | |||
| 9991 | if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, | |||
| 9992 | Subobject, Field, &Layout)) | |||
| 9993 | return false; | |||
| 9994 | ||||
| 9995 | // Perform an implicit value-initialization for members beyond the end of | |||
| 9996 | // the initializer list. | |||
| 9997 | ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); | |||
| 9998 | const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; | |||
| 9999 | ||||
| 10000 | if (Field->getType()->isIncompleteArrayType()) { | |||
| 10001 | if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) { | |||
| 10002 | if (!CAT->getSize().isZero()) { | |||
| 10003 | // Bail out for now. This might sort of "work", but the rest of the | |||
| 10004 | // code isn't really prepared to handle it. | |||
| 10005 | Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array); | |||
| 10006 | return false; | |||
| 10007 | } | |||
| 10008 | } | |||
| 10009 | } | |||
| 10010 | ||||
| 10011 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | |||
| 10012 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | |||
| 10013 | isa<CXXDefaultInitExpr>(Init)); | |||
| 10014 | ||||
| 10015 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | |||
| 10016 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || | |||
| 10017 | (Field->isBitField() && !truncateBitfieldValue(Info, Init, | |||
| 10018 | FieldVal, Field))) { | |||
| 10019 | if (!Info.noteFailure()) | |||
| 10020 | return false; | |||
| 10021 | Success = false; | |||
| 10022 | } | |||
| 10023 | } | |||
| 10024 | ||||
| 10025 | EvalObj.finishedConstructingFields(); | |||
| 10026 | ||||
| 10027 | return Success; | |||
| 10028 | } | |||
| 10029 | ||||
| 10030 | bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | |||
| 10031 | QualType T) { | |||
| 10032 | // Note that E's type is not necessarily the type of our class here; we might | |||
| 10033 | // be initializing an array element instead. | |||
| 10034 | const CXXConstructorDecl *FD = E->getConstructor(); | |||
| 10035 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; | |||
| 10036 | ||||
| 10037 | bool ZeroInit = E->requiresZeroInitialization(); | |||
| 10038 | if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { | |||
| 10039 | // If we've already performed zero-initialization, we're already done. | |||
| 10040 | if (Result.hasValue()) | |||
| 10041 | return true; | |||
| 10042 | ||||
| 10043 | if (ZeroInit) | |||
| 10044 | return ZeroInitialization(E, T); | |||
| 10045 | ||||
| 10046 | return getDefaultInitValue(T, Result); | |||
| 10047 | } | |||
| 10048 | ||||
| 10049 | const FunctionDecl *Definition = nullptr; | |||
| 10050 | auto Body = FD->getBody(Definition); | |||
| 10051 | ||||
| 10052 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | |||
| 10053 | return false; | |||
| 10054 | ||||
| 10055 | // Avoid materializing a temporary for an elidable copy/move constructor. | |||
| 10056 | if (E->isElidable() && !ZeroInit) { | |||
| 10057 | // FIXME: This only handles the simplest case, where the source object | |||
| 10058 | // is passed directly as the first argument to the constructor. | |||
| 10059 | // This should also handle stepping though implicit casts and | |||
| 10060 | // and conversion sequences which involve two steps, with a | |||
| 10061 | // conversion operator followed by a converting constructor. | |||
| 10062 | const Expr *SrcObj = E->getArg(0); | |||
| 10063 | assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()))(static_cast <bool> (SrcObj->isTemporaryObject(Info. Ctx, FD->getParent())) ? void (0) : __assert_fail ("SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())" , "clang/lib/AST/ExprConstant.cpp", 10063, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10064 | assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()))(static_cast <bool> (Info.Ctx.hasSameUnqualifiedType(E-> getType(), SrcObj->getType())) ? void (0) : __assert_fail ( "Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())" , "clang/lib/AST/ExprConstant.cpp", 10064, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10065 | if (const MaterializeTemporaryExpr *ME = | |||
| 10066 | dyn_cast<MaterializeTemporaryExpr>(SrcObj)) | |||
| 10067 | return Visit(ME->getSubExpr()); | |||
| 10068 | } | |||
| 10069 | ||||
| 10070 | if (ZeroInit && !ZeroInitialization(E, T)) | |||
| 10071 | return false; | |||
| 10072 | ||||
| 10073 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | |||
| 10074 | return HandleConstructorCall(E, This, Args, | |||
| 10075 | cast<CXXConstructorDecl>(Definition), Info, | |||
| 10076 | Result); | |||
| 10077 | } | |||
| 10078 | ||||
| 10079 | bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( | |||
| 10080 | const CXXInheritedCtorInitExpr *E) { | |||
| 10081 | if (!Info.CurrentCall) { | |||
| 10082 | assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression ()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "clang/lib/AST/ExprConstant.cpp", 10082, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10083 | return false; | |||
| 10084 | } | |||
| 10085 | ||||
| 10086 | const CXXConstructorDecl *FD = E->getConstructor(); | |||
| 10087 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) | |||
| 10088 | return false; | |||
| 10089 | ||||
| 10090 | const FunctionDecl *Definition = nullptr; | |||
| 10091 | auto Body = FD->getBody(Definition); | |||
| 10092 | ||||
| 10093 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | |||
| 10094 | return false; | |||
| 10095 | ||||
| 10096 | return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, | |||
| 10097 | cast<CXXConstructorDecl>(Definition), Info, | |||
| 10098 | Result); | |||
| 10099 | } | |||
| 10100 | ||||
| 10101 | bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( | |||
| 10102 | const CXXStdInitializerListExpr *E) { | |||
| 10103 | const ConstantArrayType *ArrayType = | |||
| 10104 | Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); | |||
| 10105 | ||||
| 10106 | LValue Array; | |||
| 10107 | if (!EvaluateLValue(E->getSubExpr(), Array, Info)) | |||
| 10108 | return false; | |||
| 10109 | ||||
| 10110 | // Get a pointer to the first element of the array. | |||
| 10111 | Array.addArray(Info, E, ArrayType); | |||
| 10112 | ||||
| 10113 | auto InvalidType = [&] { | |||
| 10114 | Info.FFDiag(E, diag::note_constexpr_unsupported_layout) | |||
| 10115 | << E->getType(); | |||
| 10116 | return false; | |||
| 10117 | }; | |||
| 10118 | ||||
| 10119 | // FIXME: Perform the checks on the field types in SemaInit. | |||
| 10120 | RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); | |||
| 10121 | RecordDecl::field_iterator Field = Record->field_begin(); | |||
| 10122 | if (Field == Record->field_end()) | |||
| 10123 | return InvalidType(); | |||
| 10124 | ||||
| 10125 | // Start pointer. | |||
| 10126 | if (!Field->getType()->isPointerType() || | |||
| 10127 | !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | |||
| 10128 | ArrayType->getElementType())) | |||
| 10129 | return InvalidType(); | |||
| 10130 | ||||
| 10131 | // FIXME: What if the initializer_list type has base classes, etc? | |||
| 10132 | Result = APValue(APValue::UninitStruct(), 0, 2); | |||
| 10133 | Array.moveInto(Result.getStructField(0)); | |||
| 10134 | ||||
| 10135 | if (++Field == Record->field_end()) | |||
| 10136 | return InvalidType(); | |||
| 10137 | ||||
| 10138 | if (Field->getType()->isPointerType() && | |||
| 10139 | Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | |||
| 10140 | ArrayType->getElementType())) { | |||
| 10141 | // End pointer. | |||
| 10142 | if (!HandleLValueArrayAdjustment(Info, E, Array, | |||
| 10143 | ArrayType->getElementType(), | |||
| 10144 | ArrayType->getSize().getZExtValue())) | |||
| 10145 | return false; | |||
| 10146 | Array.moveInto(Result.getStructField(1)); | |||
| 10147 | } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) | |||
| 10148 | // Length. | |||
| 10149 | Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); | |||
| 10150 | else | |||
| 10151 | return InvalidType(); | |||
| 10152 | ||||
| 10153 | if (++Field != Record->field_end()) | |||
| 10154 | return InvalidType(); | |||
| 10155 | ||||
| 10156 | return true; | |||
| 10157 | } | |||
| 10158 | ||||
| 10159 | bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { | |||
| 10160 | const CXXRecordDecl *ClosureClass = E->getLambdaClass(); | |||
| 10161 | if (ClosureClass->isInvalidDecl()) | |||
| 10162 | return false; | |||
| 10163 | ||||
| 10164 | const size_t NumFields = | |||
| 10165 | std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); | |||
| 10166 | ||||
| 10167 | assert(NumFields == (size_t)std::distance(E->capture_init_begin(),(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "clang/lib/AST/ExprConstant.cpp", 10170, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10168 | E->capture_init_end()) &&(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "clang/lib/AST/ExprConstant.cpp", 10170, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10169 | "The number of lambda capture initializers should equal the number of "(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "clang/lib/AST/ExprConstant.cpp", 10170, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10170 | "fields within the closure type")(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "clang/lib/AST/ExprConstant.cpp", 10170, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10171 | ||||
| 10172 | Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); | |||
| 10173 | // Iterate through all the lambda's closure object's fields and initialize | |||
| 10174 | // them. | |||
| 10175 | auto *CaptureInitIt = E->capture_init_begin(); | |||
| 10176 | bool Success = true; | |||
| 10177 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); | |||
| 10178 | for (const auto *Field : ClosureClass->fields()) { | |||
| 10179 | assert(CaptureInitIt != E->capture_init_end())(static_cast <bool> (CaptureInitIt != E->capture_init_end ()) ? void (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()" , "clang/lib/AST/ExprConstant.cpp", 10179, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10180 | // Get the initializer for this field | |||
| 10181 | Expr *const CurFieldInit = *CaptureInitIt++; | |||
| 10182 | ||||
| 10183 | // If there is no initializer, either this is a VLA or an error has | |||
| 10184 | // occurred. | |||
| 10185 | if (!CurFieldInit) | |||
| 10186 | return Error(E); | |||
| 10187 | ||||
| 10188 | LValue Subobject = This; | |||
| 10189 | ||||
| 10190 | if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) | |||
| 10191 | return false; | |||
| 10192 | ||||
| 10193 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | |||
| 10194 | if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { | |||
| 10195 | if (!Info.keepEvaluatingAfterFailure()) | |||
| 10196 | return false; | |||
| 10197 | Success = false; | |||
| 10198 | } | |||
| 10199 | } | |||
| 10200 | return Success; | |||
| 10201 | } | |||
| 10202 | ||||
| 10203 | static bool EvaluateRecord(const Expr *E, const LValue &This, | |||
| 10204 | APValue &Result, EvalInfo &Info) { | |||
| 10205 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 10205, __extension__ __PRETTY_FUNCTION__)); | |||
| 10206 | assert(E->isPRValue() && E->getType()->isRecordType() &&(static_cast <bool> (E->isPRValue() && E-> getType()->isRecordType() && "can't evaluate expression as a record rvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10207, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10207 | "can't evaluate expression as a record rvalue")(static_cast <bool> (E->isPRValue() && E-> getType()->isRecordType() && "can't evaluate expression as a record rvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10207, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10208 | return RecordExprEvaluator(Info, This, Result).Visit(E); | |||
| 10209 | } | |||
| 10210 | ||||
| 10211 | //===----------------------------------------------------------------------===// | |||
| 10212 | // Temporary Evaluation | |||
| 10213 | // | |||
| 10214 | // Temporaries are represented in the AST as rvalues, but generally behave like | |||
| 10215 | // lvalues. The full-object of which the temporary is a subobject is implicitly | |||
| 10216 | // materialized so that a reference can bind to it. | |||
| 10217 | //===----------------------------------------------------------------------===// | |||
| 10218 | namespace { | |||
| 10219 | class TemporaryExprEvaluator | |||
| 10220 | : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { | |||
| 10221 | public: | |||
| 10222 | TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : | |||
| 10223 | LValueExprEvaluatorBaseTy(Info, Result, false) {} | |||
| 10224 | ||||
| 10225 | /// Visit an expression which constructs the value of this temporary. | |||
| 10226 | bool VisitConstructExpr(const Expr *E) { | |||
| 10227 | APValue &Value = Info.CurrentCall->createTemporary( | |||
| 10228 | E, E->getType(), ScopeKind::FullExpression, Result); | |||
| 10229 | return EvaluateInPlace(Value, Info, Result, E); | |||
| 10230 | } | |||
| 10231 | ||||
| 10232 | bool VisitCastExpr(const CastExpr *E) { | |||
| 10233 | switch (E->getCastKind()) { | |||
| 10234 | default: | |||
| 10235 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 10236 | ||||
| 10237 | case CK_ConstructorConversion: | |||
| 10238 | return VisitConstructExpr(E->getSubExpr()); | |||
| 10239 | } | |||
| 10240 | } | |||
| 10241 | bool VisitInitListExpr(const InitListExpr *E) { | |||
| 10242 | return VisitConstructExpr(E); | |||
| 10243 | } | |||
| 10244 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | |||
| 10245 | return VisitConstructExpr(E); | |||
| 10246 | } | |||
| 10247 | bool VisitCallExpr(const CallExpr *E) { | |||
| 10248 | return VisitConstructExpr(E); | |||
| 10249 | } | |||
| 10250 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { | |||
| 10251 | return VisitConstructExpr(E); | |||
| 10252 | } | |||
| 10253 | bool VisitLambdaExpr(const LambdaExpr *E) { | |||
| 10254 | return VisitConstructExpr(E); | |||
| 10255 | } | |||
| 10256 | }; | |||
| 10257 | } // end anonymous namespace | |||
| 10258 | ||||
| 10259 | /// Evaluate an expression of record type as a temporary. | |||
| 10260 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { | |||
| 10261 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 10261, __extension__ __PRETTY_FUNCTION__)); | |||
| 10262 | assert(E->isPRValue() && E->getType()->isRecordType())(static_cast <bool> (E->isPRValue() && E-> getType()->isRecordType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType()" , "clang/lib/AST/ExprConstant.cpp", 10262, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10263 | return TemporaryExprEvaluator(Info, Result).Visit(E); | |||
| 10264 | } | |||
| 10265 | ||||
| 10266 | //===----------------------------------------------------------------------===// | |||
| 10267 | // Vector Evaluation | |||
| 10268 | //===----------------------------------------------------------------------===// | |||
| 10269 | ||||
| 10270 | namespace { | |||
| 10271 | class VectorExprEvaluator | |||
| 10272 | : public ExprEvaluatorBase<VectorExprEvaluator> { | |||
| 10273 | APValue &Result; | |||
| 10274 | public: | |||
| 10275 | ||||
| 10276 | VectorExprEvaluator(EvalInfo &info, APValue &Result) | |||
| 10277 | : ExprEvaluatorBaseTy(info), Result(Result) {} | |||
| 10278 | ||||
| 10279 | bool Success(ArrayRef<APValue> V, const Expr *E) { | |||
| 10280 | assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())(static_cast <bool> (V.size() == E->getType()->castAs <VectorType>()->getNumElements()) ? void (0) : __assert_fail ("V.size() == E->getType()->castAs<VectorType>()->getNumElements()" , "clang/lib/AST/ExprConstant.cpp", 10280, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10281 | // FIXME: remove this APValue copy. | |||
| 10282 | Result = APValue(V.data(), V.size()); | |||
| 10283 | return true; | |||
| 10284 | } | |||
| 10285 | bool Success(const APValue &V, const Expr *E) { | |||
| 10286 | assert(V.isVector())(static_cast <bool> (V.isVector()) ? void (0) : __assert_fail ("V.isVector()", "clang/lib/AST/ExprConstant.cpp", 10286, __extension__ __PRETTY_FUNCTION__)); | |||
| 10287 | Result = V; | |||
| 10288 | return true; | |||
| 10289 | } | |||
| 10290 | bool ZeroInitialization(const Expr *E); | |||
| 10291 | ||||
| 10292 | bool VisitUnaryReal(const UnaryOperator *E) | |||
| 10293 | { return Visit(E->getSubExpr()); } | |||
| 10294 | bool VisitCastExpr(const CastExpr* E); | |||
| 10295 | bool VisitInitListExpr(const InitListExpr *E); | |||
| 10296 | bool VisitUnaryImag(const UnaryOperator *E); | |||
| 10297 | bool VisitBinaryOperator(const BinaryOperator *E); | |||
| 10298 | bool VisitUnaryOperator(const UnaryOperator *E); | |||
| 10299 | // FIXME: Missing: conditional operator (for GNU | |||
| 10300 | // conditional select), shufflevector, ExtVectorElementExpr | |||
| 10301 | }; | |||
| 10302 | } // end anonymous namespace | |||
| 10303 | ||||
| 10304 | static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { | |||
| 10305 | assert(E->isPRValue() && E->getType()->isVectorType() &&(static_cast <bool> (E->isPRValue() && E-> getType()->isVectorType() && "not a vector prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVectorType() && \"not a vector prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10306, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10306 | "not a vector prvalue")(static_cast <bool> (E->isPRValue() && E-> getType()->isVectorType() && "not a vector prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVectorType() && \"not a vector prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10306, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10307 | return VectorExprEvaluator(Info, Result).Visit(E); | |||
| 10308 | } | |||
| 10309 | ||||
| 10310 | bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 10311 | const VectorType *VTy = E->getType()->castAs<VectorType>(); | |||
| 10312 | unsigned NElts = VTy->getNumElements(); | |||
| 10313 | ||||
| 10314 | const Expr *SE = E->getSubExpr(); | |||
| 10315 | QualType SETy = SE->getType(); | |||
| 10316 | ||||
| 10317 | switch (E->getCastKind()) { | |||
| 10318 | case CK_VectorSplat: { | |||
| 10319 | APValue Val = APValue(); | |||
| 10320 | if (SETy->isIntegerType()) { | |||
| 10321 | APSInt IntResult; | |||
| 10322 | if (!EvaluateInteger(SE, IntResult, Info)) | |||
| 10323 | return false; | |||
| 10324 | Val = APValue(std::move(IntResult)); | |||
| 10325 | } else if (SETy->isRealFloatingType()) { | |||
| 10326 | APFloat FloatResult(0.0); | |||
| 10327 | if (!EvaluateFloat(SE, FloatResult, Info)) | |||
| 10328 | return false; | |||
| 10329 | Val = APValue(std::move(FloatResult)); | |||
| 10330 | } else { | |||
| 10331 | return Error(E); | |||
| 10332 | } | |||
| 10333 | ||||
| 10334 | // Splat and create vector APValue. | |||
| 10335 | SmallVector<APValue, 4> Elts(NElts, Val); | |||
| 10336 | return Success(Elts, E); | |||
| 10337 | } | |||
| 10338 | case CK_BitCast: { | |||
| 10339 | // Evaluate the operand into an APInt we can extract from. | |||
| 10340 | llvm::APInt SValInt; | |||
| 10341 | if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) | |||
| 10342 | return false; | |||
| 10343 | // Extract the elements | |||
| 10344 | QualType EltTy = VTy->getElementType(); | |||
| 10345 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | |||
| 10346 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | |||
| 10347 | SmallVector<APValue, 4> Elts; | |||
| 10348 | if (EltTy->isRealFloatingType()) { | |||
| 10349 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); | |||
| 10350 | unsigned FloatEltSize = EltSize; | |||
| 10351 | if (&Sem == &APFloat::x87DoubleExtended()) | |||
| 10352 | FloatEltSize = 80; | |||
| 10353 | for (unsigned i = 0; i < NElts; i++) { | |||
| 10354 | llvm::APInt Elt; | |||
| 10355 | if (BigEndian) | |||
| 10356 | Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); | |||
| 10357 | else | |||
| 10358 | Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); | |||
| 10359 | Elts.push_back(APValue(APFloat(Sem, Elt))); | |||
| 10360 | } | |||
| 10361 | } else if (EltTy->isIntegerType()) { | |||
| 10362 | for (unsigned i = 0; i < NElts; i++) { | |||
| 10363 | llvm::APInt Elt; | |||
| 10364 | if (BigEndian) | |||
| 10365 | Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); | |||
| 10366 | else | |||
| 10367 | Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); | |||
| 10368 | Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); | |||
| 10369 | } | |||
| 10370 | } else { | |||
| 10371 | return Error(E); | |||
| 10372 | } | |||
| 10373 | return Success(Elts, E); | |||
| 10374 | } | |||
| 10375 | default: | |||
| 10376 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 10377 | } | |||
| 10378 | } | |||
| 10379 | ||||
| 10380 | bool | |||
| 10381 | VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | |||
| 10382 | const VectorType *VT = E->getType()->castAs<VectorType>(); | |||
| 10383 | unsigned NumInits = E->getNumInits(); | |||
| 10384 | unsigned NumElements = VT->getNumElements(); | |||
| 10385 | ||||
| 10386 | QualType EltTy = VT->getElementType(); | |||
| 10387 | SmallVector<APValue, 4> Elements; | |||
| 10388 | ||||
| 10389 | // The number of initializers can be less than the number of | |||
| 10390 | // vector elements. For OpenCL, this can be due to nested vector | |||
| 10391 | // initialization. For GCC compatibility, missing trailing elements | |||
| 10392 | // should be initialized with zeroes. | |||
| 10393 | unsigned CountInits = 0, CountElts = 0; | |||
| 10394 | while (CountElts < NumElements) { | |||
| 10395 | // Handle nested vector initialization. | |||
| 10396 | if (CountInits < NumInits | |||
| 10397 | && E->getInit(CountInits)->getType()->isVectorType()) { | |||
| 10398 | APValue v; | |||
| 10399 | if (!EvaluateVector(E->getInit(CountInits), v, Info)) | |||
| 10400 | return Error(E); | |||
| 10401 | unsigned vlen = v.getVectorLength(); | |||
| 10402 | for (unsigned j = 0; j < vlen; j++) | |||
| 10403 | Elements.push_back(v.getVectorElt(j)); | |||
| 10404 | CountElts += vlen; | |||
| 10405 | } else if (EltTy->isIntegerType()) { | |||
| 10406 | llvm::APSInt sInt(32); | |||
| 10407 | if (CountInits < NumInits) { | |||
| 10408 | if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) | |||
| 10409 | return false; | |||
| 10410 | } else // trailing integer zero. | |||
| 10411 | sInt = Info.Ctx.MakeIntValue(0, EltTy); | |||
| 10412 | Elements.push_back(APValue(sInt)); | |||
| 10413 | CountElts++; | |||
| 10414 | } else { | |||
| 10415 | llvm::APFloat f(0.0); | |||
| 10416 | if (CountInits < NumInits) { | |||
| 10417 | if (!EvaluateFloat(E->getInit(CountInits), f, Info)) | |||
| 10418 | return false; | |||
| 10419 | } else // trailing float zero. | |||
| 10420 | f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); | |||
| 10421 | Elements.push_back(APValue(f)); | |||
| 10422 | CountElts++; | |||
| 10423 | } | |||
| 10424 | CountInits++; | |||
| 10425 | } | |||
| 10426 | return Success(Elements, E); | |||
| 10427 | } | |||
| 10428 | ||||
| 10429 | bool | |||
| 10430 | VectorExprEvaluator::ZeroInitialization(const Expr *E) { | |||
| 10431 | const auto *VT = E->getType()->castAs<VectorType>(); | |||
| 10432 | QualType EltTy = VT->getElementType(); | |||
| 10433 | APValue ZeroElement; | |||
| 10434 | if (EltTy->isIntegerType()) | |||
| 10435 | ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); | |||
| 10436 | else | |||
| 10437 | ZeroElement = | |||
| 10438 | APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); | |||
| 10439 | ||||
| 10440 | SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); | |||
| 10441 | return Success(Elements, E); | |||
| 10442 | } | |||
| 10443 | ||||
| 10444 | bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | |||
| 10445 | VisitIgnoredValue(E->getSubExpr()); | |||
| 10446 | return ZeroInitialization(E); | |||
| 10447 | } | |||
| 10448 | ||||
| 10449 | bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | |||
| 10450 | BinaryOperatorKind Op = E->getOpcode(); | |||
| 10451 | assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&(static_cast <bool> (Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && \"Operation not supported on vector types\"" , "clang/lib/AST/ExprConstant.cpp", 10452, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10452 | "Operation not supported on vector types")(static_cast <bool> (Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && \"Operation not supported on vector types\"" , "clang/lib/AST/ExprConstant.cpp", 10452, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10453 | ||||
| 10454 | if (Op == BO_Comma) | |||
| 10455 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 10456 | ||||
| 10457 | Expr *LHS = E->getLHS(); | |||
| 10458 | Expr *RHS = E->getRHS(); | |||
| 10459 | ||||
| 10460 | assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&(static_cast <bool> (LHS->getType()->isVectorType () && RHS->getType()->isVectorType() && "Must both be vector types") ? void (0) : __assert_fail ("LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && \"Must both be vector types\"" , "clang/lib/AST/ExprConstant.cpp", 10461, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10461 | "Must both be vector types")(static_cast <bool> (LHS->getType()->isVectorType () && RHS->getType()->isVectorType() && "Must both be vector types") ? void (0) : __assert_fail ("LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && \"Must both be vector types\"" , "clang/lib/AST/ExprConstant.cpp", 10461, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10462 | // Checking JUST the types are the same would be fine, except shifts don't | |||
| 10463 | // need to have their types be the same (since you always shift by an int). | |||
| 10464 | assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "clang/lib/AST/ExprConstant.cpp", 10468, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10465 | E->getType()->castAs<VectorType>()->getNumElements() &&(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "clang/lib/AST/ExprConstant.cpp", 10468, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10466 | RHS->getType()->castAs<VectorType>()->getNumElements() ==(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "clang/lib/AST/ExprConstant.cpp", 10468, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10467 | E->getType()->castAs<VectorType>()->getNumElements() &&(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "clang/lib/AST/ExprConstant.cpp", 10468, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10468 | "All operands must be the same size.")(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "clang/lib/AST/ExprConstant.cpp", 10468, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10469 | ||||
| 10470 | APValue LHSValue; | |||
| 10471 | APValue RHSValue; | |||
| 10472 | bool LHSOK = Evaluate(LHSValue, Info, LHS); | |||
| 10473 | if (!LHSOK && !Info.noteFailure()) | |||
| 10474 | return false; | |||
| 10475 | if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) | |||
| 10476 | return false; | |||
| 10477 | ||||
| 10478 | if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) | |||
| 10479 | return false; | |||
| 10480 | ||||
| 10481 | return Success(LHSValue, E); | |||
| 10482 | } | |||
| 10483 | ||||
| 10484 | static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, | |||
| 10485 | QualType ResultTy, | |||
| 10486 | UnaryOperatorKind Op, | |||
| 10487 | APValue Elt) { | |||
| 10488 | switch (Op) { | |||
| 10489 | case UO_Plus: | |||
| 10490 | // Nothing to do here. | |||
| 10491 | return Elt; | |||
| 10492 | case UO_Minus: | |||
| 10493 | if (Elt.getKind() == APValue::Int) { | |||
| 10494 | Elt.getInt().negate(); | |||
| 10495 | } else { | |||
| 10496 | assert(Elt.getKind() == APValue::Float &&(static_cast <bool> (Elt.getKind() == APValue::Float && "Vector can only be int or float type") ? void (0) : __assert_fail ("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\"" , "clang/lib/AST/ExprConstant.cpp", 10497, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10497 | "Vector can only be int or float type")(static_cast <bool> (Elt.getKind() == APValue::Float && "Vector can only be int or float type") ? void (0) : __assert_fail ("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\"" , "clang/lib/AST/ExprConstant.cpp", 10497, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10498 | Elt.getFloat().changeSign(); | |||
| 10499 | } | |||
| 10500 | return Elt; | |||
| 10501 | case UO_Not: | |||
| 10502 | // This is only valid for integral types anyway, so we don't have to handle | |||
| 10503 | // float here. | |||
| 10504 | assert(Elt.getKind() == APValue::Int &&(static_cast <bool> (Elt.getKind() == APValue::Int && "Vector operator ~ can only be int") ? void (0) : __assert_fail ("Elt.getKind() == APValue::Int && \"Vector operator ~ can only be int\"" , "clang/lib/AST/ExprConstant.cpp", 10505, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10505 | "Vector operator ~ can only be int")(static_cast <bool> (Elt.getKind() == APValue::Int && "Vector operator ~ can only be int") ? void (0) : __assert_fail ("Elt.getKind() == APValue::Int && \"Vector operator ~ can only be int\"" , "clang/lib/AST/ExprConstant.cpp", 10505, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10506 | Elt.getInt().flipAllBits(); | |||
| 10507 | return Elt; | |||
| 10508 | case UO_LNot: { | |||
| 10509 | if (Elt.getKind() == APValue::Int) { | |||
| 10510 | Elt.getInt() = !Elt.getInt(); | |||
| 10511 | // operator ! on vectors returns -1 for 'truth', so negate it. | |||
| 10512 | Elt.getInt().negate(); | |||
| 10513 | return Elt; | |||
| 10514 | } | |||
| 10515 | assert(Elt.getKind() == APValue::Float &&(static_cast <bool> (Elt.getKind() == APValue::Float && "Vector can only be int or float type") ? void (0) : __assert_fail ("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\"" , "clang/lib/AST/ExprConstant.cpp", 10516, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10516 | "Vector can only be int or float type")(static_cast <bool> (Elt.getKind() == APValue::Float && "Vector can only be int or float type") ? void (0) : __assert_fail ("Elt.getKind() == APValue::Float && \"Vector can only be int or float type\"" , "clang/lib/AST/ExprConstant.cpp", 10516, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10517 | // Float types result in an int of the same size, but -1 for true, or 0 for | |||
| 10518 | // false. | |||
| 10519 | APSInt EltResult{Ctx.getIntWidth(ResultTy), | |||
| 10520 | ResultTy->isUnsignedIntegerType()}; | |||
| 10521 | if (Elt.getFloat().isZero()) | |||
| 10522 | EltResult.setAllBits(); | |||
| 10523 | else | |||
| 10524 | EltResult.clearAllBits(); | |||
| 10525 | ||||
| 10526 | return APValue{EltResult}; | |||
| 10527 | } | |||
| 10528 | default: | |||
| 10529 | // FIXME: Implement the rest of the unary operators. | |||
| 10530 | return llvm::None; | |||
| 10531 | } | |||
| 10532 | } | |||
| 10533 | ||||
| 10534 | bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | |||
| 10535 | Expr *SubExpr = E->getSubExpr(); | |||
| 10536 | const auto *VD = SubExpr->getType()->castAs<VectorType>(); | |||
| 10537 | // This result element type differs in the case of negating a floating point | |||
| 10538 | // vector, since the result type is the a vector of the equivilant sized | |||
| 10539 | // integer. | |||
| 10540 | const QualType ResultEltTy = VD->getElementType(); | |||
| 10541 | UnaryOperatorKind Op = E->getOpcode(); | |||
| 10542 | ||||
| 10543 | APValue SubExprValue; | |||
| 10544 | if (!Evaluate(SubExprValue, Info, SubExpr)) | |||
| 10545 | return false; | |||
| 10546 | ||||
| 10547 | // FIXME: This vector evaluator someday needs to be changed to be LValue | |||
| 10548 | // aware/keep LValue information around, rather than dealing with just vector | |||
| 10549 | // types directly. Until then, we cannot handle cases where the operand to | |||
| 10550 | // these unary operators is an LValue. The only case I've been able to see | |||
| 10551 | // cause this is operator++ assigning to a member expression (only valid in | |||
| 10552 | // altivec compilations) in C mode, so this shouldn't limit us too much. | |||
| 10553 | if (SubExprValue.isLValue()) | |||
| 10554 | return false; | |||
| 10555 | ||||
| 10556 | assert(SubExprValue.getVectorLength() == VD->getNumElements() &&(static_cast <bool> (SubExprValue.getVectorLength() == VD ->getNumElements() && "Vector length doesn't match type?" ) ? void (0) : __assert_fail ("SubExprValue.getVectorLength() == VD->getNumElements() && \"Vector length doesn't match type?\"" , "clang/lib/AST/ExprConstant.cpp", 10557, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10557 | "Vector length doesn't match type?")(static_cast <bool> (SubExprValue.getVectorLength() == VD ->getNumElements() && "Vector length doesn't match type?" ) ? void (0) : __assert_fail ("SubExprValue.getVectorLength() == VD->getNumElements() && \"Vector length doesn't match type?\"" , "clang/lib/AST/ExprConstant.cpp", 10557, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10558 | ||||
| 10559 | SmallVector<APValue, 4> ResultElements; | |||
| 10560 | for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { | |||
| 10561 | llvm::Optional<APValue> Elt = handleVectorUnaryOperator( | |||
| 10562 | Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); | |||
| 10563 | if (!Elt) | |||
| 10564 | return false; | |||
| 10565 | ResultElements.push_back(*Elt); | |||
| 10566 | } | |||
| 10567 | return Success(APValue(ResultElements.data(), ResultElements.size()), E); | |||
| 10568 | } | |||
| 10569 | ||||
| 10570 | //===----------------------------------------------------------------------===// | |||
| 10571 | // Array Evaluation | |||
| 10572 | //===----------------------------------------------------------------------===// | |||
| 10573 | ||||
| 10574 | namespace { | |||
| 10575 | class ArrayExprEvaluator | |||
| 10576 | : public ExprEvaluatorBase<ArrayExprEvaluator> { | |||
| 10577 | const LValue &This; | |||
| 10578 | APValue &Result; | |||
| 10579 | public: | |||
| 10580 | ||||
| 10581 | ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) | |||
| 10582 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | |||
| 10583 | ||||
| 10584 | bool Success(const APValue &V, const Expr *E) { | |||
| 10585 | assert(V.isArray() && "expected array")(static_cast <bool> (V.isArray() && "expected array" ) ? void (0) : __assert_fail ("V.isArray() && \"expected array\"" , "clang/lib/AST/ExprConstant.cpp", 10585, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10586 | Result = V; | |||
| 10587 | return true; | |||
| 10588 | } | |||
| 10589 | ||||
| 10590 | bool ZeroInitialization(const Expr *E) { | |||
| 10591 | const ConstantArrayType *CAT = | |||
| 10592 | Info.Ctx.getAsConstantArrayType(E->getType()); | |||
| 10593 | if (!CAT) { | |||
| 10594 | if (E->getType()->isIncompleteArrayType()) { | |||
| 10595 | // We can be asked to zero-initialize a flexible array member; this | |||
| 10596 | // is represented as an ImplicitValueInitExpr of incomplete array | |||
| 10597 | // type. In this case, the array has zero elements. | |||
| 10598 | Result = APValue(APValue::UninitArray(), 0, 0); | |||
| 10599 | return true; | |||
| 10600 | } | |||
| 10601 | // FIXME: We could handle VLAs here. | |||
| 10602 | return Error(E); | |||
| 10603 | } | |||
| 10604 | ||||
| 10605 | Result = APValue(APValue::UninitArray(), 0, | |||
| 10606 | CAT->getSize().getZExtValue()); | |||
| 10607 | if (!Result.hasArrayFiller()) | |||
| 10608 | return true; | |||
| 10609 | ||||
| 10610 | // Zero-initialize all elements. | |||
| 10611 | LValue Subobject = This; | |||
| 10612 | Subobject.addArray(Info, E, CAT); | |||
| 10613 | ImplicitValueInitExpr VIE(CAT->getElementType()); | |||
| 10614 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); | |||
| 10615 | } | |||
| 10616 | ||||
| 10617 | bool VisitCallExpr(const CallExpr *E) { | |||
| 10618 | return handleCallExpr(E, Result, &This); | |||
| 10619 | } | |||
| 10620 | bool VisitInitListExpr(const InitListExpr *E, | |||
| 10621 | QualType AllocType = QualType()); | |||
| 10622 | bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); | |||
| 10623 | bool VisitCXXConstructExpr(const CXXConstructExpr *E); | |||
| 10624 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, | |||
| 10625 | const LValue &Subobject, | |||
| 10626 | APValue *Value, QualType Type); | |||
| 10627 | bool VisitStringLiteral(const StringLiteral *E, | |||
| 10628 | QualType AllocType = QualType()) { | |||
| 10629 | expandStringLiteral(Info, E, Result, AllocType); | |||
| 10630 | return true; | |||
| 10631 | } | |||
| 10632 | }; | |||
| 10633 | } // end anonymous namespace | |||
| 10634 | ||||
| 10635 | static bool EvaluateArray(const Expr *E, const LValue &This, | |||
| 10636 | APValue &Result, EvalInfo &Info) { | |||
| 10637 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 10637, __extension__ __PRETTY_FUNCTION__)); | |||
| 10638 | assert(E->isPRValue() && E->getType()->isArrayType() &&(static_cast <bool> (E->isPRValue() && E-> getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isArrayType() && \"not an array prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10639, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10639 | "not an array prvalue")(static_cast <bool> (E->isPRValue() && E-> getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isArrayType() && \"not an array prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10639, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10640 | return ArrayExprEvaluator(Info, This, Result).Visit(E); | |||
| 10641 | } | |||
| 10642 | ||||
| 10643 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | |||
| 10644 | APValue &Result, const InitListExpr *ILE, | |||
| 10645 | QualType AllocType) { | |||
| 10646 | assert(!ILE->isValueDependent())(static_cast <bool> (!ILE->isValueDependent()) ? void (0) : __assert_fail ("!ILE->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 10646, __extension__ __PRETTY_FUNCTION__)); | |||
| 10647 | assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&(static_cast <bool> (ILE->isPRValue() && ILE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("ILE->isPRValue() && ILE->getType()->isArrayType() && \"not an array prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10648, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10648 | "not an array prvalue")(static_cast <bool> (ILE->isPRValue() && ILE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("ILE->isPRValue() && ILE->getType()->isArrayType() && \"not an array prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10648, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10649 | return ArrayExprEvaluator(Info, This, Result) | |||
| 10650 | .VisitInitListExpr(ILE, AllocType); | |||
| 10651 | } | |||
| 10652 | ||||
| 10653 | static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, | |||
| 10654 | APValue &Result, | |||
| 10655 | const CXXConstructExpr *CCE, | |||
| 10656 | QualType AllocType) { | |||
| 10657 | assert(!CCE->isValueDependent())(static_cast <bool> (!CCE->isValueDependent()) ? void (0) : __assert_fail ("!CCE->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 10657, __extension__ __PRETTY_FUNCTION__)); | |||
| 10658 | assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&(static_cast <bool> (CCE->isPRValue() && CCE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("CCE->isPRValue() && CCE->getType()->isArrayType() && \"not an array prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10659, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10659 | "not an array prvalue")(static_cast <bool> (CCE->isPRValue() && CCE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("CCE->isPRValue() && CCE->getType()->isArrayType() && \"not an array prvalue\"" , "clang/lib/AST/ExprConstant.cpp", 10659, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10660 | return ArrayExprEvaluator(Info, This, Result) | |||
| 10661 | .VisitCXXConstructExpr(CCE, This, &Result, AllocType); | |||
| 10662 | } | |||
| 10663 | ||||
| 10664 | // Return true iff the given array filler may depend on the element index. | |||
| 10665 | static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { | |||
| 10666 | // For now, just allow non-class value-initialization and initialization | |||
| 10667 | // lists comprised of them. | |||
| 10668 | if (isa<ImplicitValueInitExpr>(FillerExpr)) | |||
| 10669 | return false; | |||
| 10670 | if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { | |||
| 10671 | for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { | |||
| 10672 | if (MaybeElementDependentArrayFiller(ILE->getInit(I))) | |||
| 10673 | return true; | |||
| 10674 | } | |||
| 10675 | return false; | |||
| 10676 | } | |||
| 10677 | return true; | |||
| 10678 | } | |||
| 10679 | ||||
| 10680 | bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, | |||
| 10681 | QualType AllocType) { | |||
| 10682 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | |||
| 10683 | AllocType.isNull() ? E->getType() : AllocType); | |||
| 10684 | if (!CAT) | |||
| 10685 | return Error(E); | |||
| 10686 | ||||
| 10687 | // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] | |||
| 10688 | // an appropriately-typed string literal enclosed in braces. | |||
| 10689 | if (E->isStringLiteralInit()) { | |||
| 10690 | auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); | |||
| 10691 | // FIXME: Support ObjCEncodeExpr here once we support it in | |||
| 10692 | // ArrayExprEvaluator generally. | |||
| 10693 | if (!SL) | |||
| 10694 | return Error(E); | |||
| 10695 | return VisitStringLiteral(SL, AllocType); | |||
| 10696 | } | |||
| 10697 | // Any other transparent list init will need proper handling of the | |||
| 10698 | // AllocType; we can't just recurse to the inner initializer. | |||
| 10699 | assert(!E->isTransparent() &&(static_cast <bool> (!E->isTransparent() && "transparent array list initialization is not string literal init?" ) ? void (0) : __assert_fail ("!E->isTransparent() && \"transparent array list initialization is not string literal init?\"" , "clang/lib/AST/ExprConstant.cpp", 10700, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10700 | "transparent array list initialization is not string literal init?")(static_cast <bool> (!E->isTransparent() && "transparent array list initialization is not string literal init?" ) ? void (0) : __assert_fail ("!E->isTransparent() && \"transparent array list initialization is not string literal init?\"" , "clang/lib/AST/ExprConstant.cpp", 10700, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10701 | ||||
| 10702 | bool Success = true; | |||
| 10703 | ||||
| 10704 | assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts () == 0) && "zero-initialized array shouldn't have any initialized elts" ) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "clang/lib/AST/ExprConstant.cpp", 10705, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10705 | "zero-initialized array shouldn't have any initialized elts")(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts () == 0) && "zero-initialized array shouldn't have any initialized elts" ) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "clang/lib/AST/ExprConstant.cpp", 10705, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10706 | APValue Filler; | |||
| 10707 | if (Result.isArray() && Result.hasArrayFiller()) | |||
| 10708 | Filler = Result.getArrayFiller(); | |||
| 10709 | ||||
| 10710 | unsigned NumEltsToInit = E->getNumInits(); | |||
| 10711 | unsigned NumElts = CAT->getSize().getZExtValue(); | |||
| 10712 | const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; | |||
| 10713 | ||||
| 10714 | // If the initializer might depend on the array index, run it for each | |||
| 10715 | // array element. | |||
| 10716 | if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) | |||
| 10717 | NumEltsToInit = NumElts; | |||
| 10718 | ||||
| 10719 | LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: " << NumEltsToInit << ".\n"; } } while (false) | |||
| 10720 | << NumEltsToInit << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: " << NumEltsToInit << ".\n"; } } while (false); | |||
| 10721 | ||||
| 10722 | Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); | |||
| 10723 | ||||
| 10724 | // If the array was previously zero-initialized, preserve the | |||
| 10725 | // zero-initialized values. | |||
| 10726 | if (Filler.hasValue()) { | |||
| 10727 | for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) | |||
| 10728 | Result.getArrayInitializedElt(I) = Filler; | |||
| 10729 | if (Result.hasArrayFiller()) | |||
| 10730 | Result.getArrayFiller() = Filler; | |||
| 10731 | } | |||
| 10732 | ||||
| 10733 | LValue Subobject = This; | |||
| 10734 | Subobject.addArray(Info, E, CAT); | |||
| 10735 | for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { | |||
| 10736 | const Expr *Init = | |||
| 10737 | Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; | |||
| 10738 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | |||
| 10739 | Info, Subobject, Init) || | |||
| 10740 | !HandleLValueArrayAdjustment(Info, Init, Subobject, | |||
| 10741 | CAT->getElementType(), 1)) { | |||
| 10742 | if (!Info.noteFailure()) | |||
| 10743 | return false; | |||
| 10744 | Success = false; | |||
| 10745 | } | |||
| 10746 | } | |||
| 10747 | ||||
| 10748 | if (!Result.hasArrayFiller()) | |||
| 10749 | return Success; | |||
| 10750 | ||||
| 10751 | // If we get here, we have a trivial filler, which we can just evaluate | |||
| 10752 | // once and splat over the rest of the array elements. | |||
| 10753 | assert(FillerExpr && "no array filler for incomplete init list")(static_cast <bool> (FillerExpr && "no array filler for incomplete init list" ) ? void (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\"" , "clang/lib/AST/ExprConstant.cpp", 10753, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10754 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, | |||
| 10755 | FillerExpr) && Success; | |||
| 10756 | } | |||
| 10757 | ||||
| 10758 | bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { | |||
| 10759 | LValue CommonLV; | |||
| 10760 | if (E->getCommonExpr() && | |||
| 10761 | !Evaluate(Info.CurrentCall->createTemporary( | |||
| 10762 | E->getCommonExpr(), | |||
| 10763 | getStorageType(Info.Ctx, E->getCommonExpr()), | |||
| 10764 | ScopeKind::FullExpression, CommonLV), | |||
| 10765 | Info, E->getCommonExpr()->getSourceExpr())) | |||
| 10766 | return false; | |||
| 10767 | ||||
| 10768 | auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); | |||
| 10769 | ||||
| 10770 | uint64_t Elements = CAT->getSize().getZExtValue(); | |||
| 10771 | Result = APValue(APValue::UninitArray(), Elements, Elements); | |||
| 10772 | ||||
| 10773 | LValue Subobject = This; | |||
| 10774 | Subobject.addArray(Info, E, CAT); | |||
| 10775 | ||||
| 10776 | bool Success = true; | |||
| 10777 | for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { | |||
| 10778 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | |||
| 10779 | Info, Subobject, E->getSubExpr()) || | |||
| 10780 | !HandleLValueArrayAdjustment(Info, E, Subobject, | |||
| 10781 | CAT->getElementType(), 1)) { | |||
| 10782 | if (!Info.noteFailure()) | |||
| 10783 | return false; | |||
| 10784 | Success = false; | |||
| 10785 | } | |||
| 10786 | } | |||
| 10787 | ||||
| 10788 | return Success; | |||
| 10789 | } | |||
| 10790 | ||||
| 10791 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { | |||
| 10792 | return VisitCXXConstructExpr(E, This, &Result, E->getType()); | |||
| 10793 | } | |||
| 10794 | ||||
| 10795 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | |||
| 10796 | const LValue &Subobject, | |||
| 10797 | APValue *Value, | |||
| 10798 | QualType Type) { | |||
| 10799 | bool HadZeroInit = Value->hasValue(); | |||
| 10800 | ||||
| 10801 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { | |||
| 10802 | unsigned FinalSize = CAT->getSize().getZExtValue(); | |||
| 10803 | ||||
| 10804 | // Preserve the array filler if we had prior zero-initialization. | |||
| 10805 | APValue Filler = | |||
| 10806 | HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() | |||
| 10807 | : APValue(); | |||
| 10808 | ||||
| 10809 | *Value = APValue(APValue::UninitArray(), 0, FinalSize); | |||
| 10810 | if (FinalSize == 0) | |||
| 10811 | return true; | |||
| 10812 | ||||
| 10813 | LValue ArrayElt = Subobject; | |||
| 10814 | ArrayElt.addArray(Info, E, CAT); | |||
| 10815 | // We do the whole initialization in two passes, first for just one element, | |||
| 10816 | // then for the whole array. It's possible we may find out we can't do const | |||
| 10817 | // init in the first pass, in which case we avoid allocating a potentially | |||
| 10818 | // large array. We don't do more passes because expanding array requires | |||
| 10819 | // copying the data, which is wasteful. | |||
| 10820 | for (const unsigned N : {1u, FinalSize}) { | |||
| 10821 | unsigned OldElts = Value->getArrayInitializedElts(); | |||
| 10822 | if (OldElts == N) | |||
| 10823 | break; | |||
| 10824 | ||||
| 10825 | // Expand the array to appropriate size. | |||
| 10826 | APValue NewValue(APValue::UninitArray(), N, FinalSize); | |||
| 10827 | for (unsigned I = 0; I < OldElts; ++I) | |||
| 10828 | NewValue.getArrayInitializedElt(I).swap( | |||
| 10829 | Value->getArrayInitializedElt(I)); | |||
| 10830 | Value->swap(NewValue); | |||
| 10831 | ||||
| 10832 | if (HadZeroInit) | |||
| 10833 | for (unsigned I = OldElts; I < N; ++I) | |||
| 10834 | Value->getArrayInitializedElt(I) = Filler; | |||
| 10835 | ||||
| 10836 | // Initialize the elements. | |||
| 10837 | for (unsigned I = OldElts; I < N; ++I) { | |||
| 10838 | if (!VisitCXXConstructExpr(E, ArrayElt, | |||
| 10839 | &Value->getArrayInitializedElt(I), | |||
| 10840 | CAT->getElementType()) || | |||
| 10841 | !HandleLValueArrayAdjustment(Info, E, ArrayElt, | |||
| 10842 | CAT->getElementType(), 1)) | |||
| 10843 | return false; | |||
| 10844 | // When checking for const initilization any diagnostic is considered | |||
| 10845 | // an error. | |||
| 10846 | if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && | |||
| 10847 | !Info.keepEvaluatingAfterFailure()) | |||
| 10848 | return false; | |||
| 10849 | } | |||
| 10850 | } | |||
| 10851 | ||||
| 10852 | return true; | |||
| 10853 | } | |||
| 10854 | ||||
| 10855 | if (!Type->isRecordType()) | |||
| 10856 | return Error(E); | |||
| 10857 | ||||
| 10858 | return RecordExprEvaluator(Info, Subobject, *Value) | |||
| 10859 | .VisitCXXConstructExpr(E, Type); | |||
| 10860 | } | |||
| 10861 | ||||
| 10862 | //===----------------------------------------------------------------------===// | |||
| 10863 | // Integer Evaluation | |||
| 10864 | // | |||
| 10865 | // As a GNU extension, we support casting pointers to sufficiently-wide integer | |||
| 10866 | // types and back in constant folding. Integer values are thus represented | |||
| 10867 | // either as an integer-valued APValue, or as an lvalue-valued APValue. | |||
| 10868 | //===----------------------------------------------------------------------===// | |||
| 10869 | ||||
| 10870 | namespace { | |||
| 10871 | class IntExprEvaluator | |||
| 10872 | : public ExprEvaluatorBase<IntExprEvaluator> { | |||
| 10873 | APValue &Result; | |||
| 10874 | public: | |||
| 10875 | IntExprEvaluator(EvalInfo &info, APValue &result) | |||
| 10876 | : ExprEvaluatorBaseTy(info), Result(result) {} | |||
| 10877 | ||||
| 10878 | bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { | |||
| 10879 | assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10880, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10880 | "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10880, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10881 | assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&(static_cast <bool> (SI.isSigned() == E->getType()-> isSignedIntegerOrEnumerationType() && "Invalid evaluation result." ) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10882, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10882 | "Invalid evaluation result.")(static_cast <bool> (SI.isSigned() == E->getType()-> isSignedIntegerOrEnumerationType() && "Invalid evaluation result." ) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10882, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10883 | assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10884, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10884 | "Invalid evaluation result.")(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10884, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10885 | Result = APValue(SI); | |||
| 10886 | return true; | |||
| 10887 | } | |||
| 10888 | bool Success(const llvm::APSInt &SI, const Expr *E) { | |||
| 10889 | return Success(SI, E, Result); | |||
| 10890 | } | |||
| 10891 | ||||
| 10892 | bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { | |||
| 10893 | assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10894, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10894 | "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10894, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10895 | assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10896, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10896 | "Invalid evaluation result.")(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10896, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10897 | Result = APValue(APSInt(I)); | |||
| 10898 | Result.getInt().setIsUnsigned( | |||
| 10899 | E->getType()->isUnsignedIntegerOrEnumerationType()); | |||
| 10900 | return true; | |||
| 10901 | } | |||
| 10902 | bool Success(const llvm::APInt &I, const Expr *E) { | |||
| 10903 | return Success(I, E, Result); | |||
| 10904 | } | |||
| 10905 | ||||
| 10906 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | |||
| 10907 | assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10908, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10908 | "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 10908, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10909 | Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); | |||
| 10910 | return true; | |||
| 10911 | } | |||
| 10912 | bool Success(uint64_t Value, const Expr *E) { | |||
| 10913 | return Success(Value, E, Result); | |||
| 10914 | } | |||
| 10915 | ||||
| 10916 | bool Success(CharUnits Size, const Expr *E) { | |||
| 10917 | return Success(Size.getQuantity(), E); | |||
| 10918 | } | |||
| 10919 | ||||
| 10920 | bool Success(const APValue &V, const Expr *E) { | |||
| 10921 | if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { | |||
| 10922 | Result = V; | |||
| 10923 | return true; | |||
| 10924 | } | |||
| 10925 | return Success(V.getInt(), E); | |||
| 10926 | } | |||
| 10927 | ||||
| 10928 | bool ZeroInitialization(const Expr *E) { return Success(0, E); } | |||
| 10929 | ||||
| 10930 | //===--------------------------------------------------------------------===// | |||
| 10931 | // Visitor Methods | |||
| 10932 | //===--------------------------------------------------------------------===// | |||
| 10933 | ||||
| 10934 | bool VisitIntegerLiteral(const IntegerLiteral *E) { | |||
| 10935 | return Success(E->getValue(), E); | |||
| 10936 | } | |||
| 10937 | bool VisitCharacterLiteral(const CharacterLiteral *E) { | |||
| 10938 | return Success(E->getValue(), E); | |||
| 10939 | } | |||
| 10940 | ||||
| 10941 | bool CheckReferencedDecl(const Expr *E, const Decl *D); | |||
| 10942 | bool VisitDeclRefExpr(const DeclRefExpr *E) { | |||
| 10943 | if (CheckReferencedDecl(E, E->getDecl())) | |||
| 10944 | return true; | |||
| 10945 | ||||
| 10946 | return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); | |||
| 10947 | } | |||
| 10948 | bool VisitMemberExpr(const MemberExpr *E) { | |||
| 10949 | if (CheckReferencedDecl(E, E->getMemberDecl())) { | |||
| 10950 | VisitIgnoredBaseExpression(E->getBase()); | |||
| 10951 | return true; | |||
| 10952 | } | |||
| 10953 | ||||
| 10954 | return ExprEvaluatorBaseTy::VisitMemberExpr(E); | |||
| 10955 | } | |||
| 10956 | ||||
| 10957 | bool VisitCallExpr(const CallExpr *E); | |||
| 10958 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | |||
| 10959 | bool VisitBinaryOperator(const BinaryOperator *E); | |||
| 10960 | bool VisitOffsetOfExpr(const OffsetOfExpr *E); | |||
| 10961 | bool VisitUnaryOperator(const UnaryOperator *E); | |||
| 10962 | ||||
| 10963 | bool VisitCastExpr(const CastExpr* E); | |||
| 10964 | bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); | |||
| 10965 | ||||
| 10966 | bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { | |||
| 10967 | return Success(E->getValue(), E); | |||
| 10968 | } | |||
| 10969 | ||||
| 10970 | bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { | |||
| 10971 | return Success(E->getValue(), E); | |||
| 10972 | } | |||
| 10973 | ||||
| 10974 | bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { | |||
| 10975 | if (Info.ArrayInitIndex == uint64_t(-1)) { | |||
| 10976 | // We were asked to evaluate this subexpression independent of the | |||
| 10977 | // enclosing ArrayInitLoopExpr. We can't do that. | |||
| 10978 | Info.FFDiag(E); | |||
| 10979 | return false; | |||
| 10980 | } | |||
| 10981 | return Success(Info.ArrayInitIndex, E); | |||
| 10982 | } | |||
| 10983 | ||||
| 10984 | // Note, GNU defines __null as an integer, not a pointer. | |||
| 10985 | bool VisitGNUNullExpr(const GNUNullExpr *E) { | |||
| 10986 | return ZeroInitialization(E); | |||
| 10987 | } | |||
| 10988 | ||||
| 10989 | bool VisitTypeTraitExpr(const TypeTraitExpr *E) { | |||
| 10990 | return Success(E->getValue(), E); | |||
| 10991 | } | |||
| 10992 | ||||
| 10993 | bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { | |||
| 10994 | return Success(E->getValue(), E); | |||
| 10995 | } | |||
| 10996 | ||||
| 10997 | bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { | |||
| 10998 | return Success(E->getValue(), E); | |||
| 10999 | } | |||
| 11000 | ||||
| 11001 | bool VisitUnaryReal(const UnaryOperator *E); | |||
| 11002 | bool VisitUnaryImag(const UnaryOperator *E); | |||
| 11003 | ||||
| 11004 | bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); | |||
| 11005 | bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); | |||
| 11006 | bool VisitSourceLocExpr(const SourceLocExpr *E); | |||
| 11007 | bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); | |||
| 11008 | bool VisitRequiresExpr(const RequiresExpr *E); | |||
| 11009 | // FIXME: Missing: array subscript of vector, member of vector | |||
| 11010 | }; | |||
| 11011 | ||||
| 11012 | class FixedPointExprEvaluator | |||
| 11013 | : public ExprEvaluatorBase<FixedPointExprEvaluator> { | |||
| 11014 | APValue &Result; | |||
| 11015 | ||||
| 11016 | public: | |||
| 11017 | FixedPointExprEvaluator(EvalInfo &info, APValue &result) | |||
| 11018 | : ExprEvaluatorBaseTy(info), Result(result) {} | |||
| 11019 | ||||
| 11020 | bool Success(const llvm::APInt &I, const Expr *E) { | |||
| 11021 | return Success( | |||
| 11022 | APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); | |||
| 11023 | } | |||
| 11024 | ||||
| 11025 | bool Success(uint64_t Value, const Expr *E) { | |||
| 11026 | return Success( | |||
| 11027 | APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); | |||
| 11028 | } | |||
| 11029 | ||||
| 11030 | bool Success(const APValue &V, const Expr *E) { | |||
| 11031 | return Success(V.getFixedPoint(), E); | |||
| 11032 | } | |||
| 11033 | ||||
| 11034 | bool Success(const APFixedPoint &V, const Expr *E) { | |||
| 11035 | assert(E->getType()->isFixedPointType() && "Invalid evaluation result.")(static_cast <bool> (E->getType()->isFixedPointType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isFixedPointType() && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 11035, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11036 | assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (V.getWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 11037, __extension__ __PRETTY_FUNCTION__ )) | |||
| 11037 | "Invalid evaluation result.")(static_cast <bool> (V.getWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "clang/lib/AST/ExprConstant.cpp", 11037, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11038 | Result = APValue(V); | |||
| 11039 | return true; | |||
| 11040 | } | |||
| 11041 | ||||
| 11042 | //===--------------------------------------------------------------------===// | |||
| 11043 | // Visitor Methods | |||
| 11044 | //===--------------------------------------------------------------------===// | |||
| 11045 | ||||
| 11046 | bool VisitFixedPointLiteral(const FixedPointLiteral *E) { | |||
| 11047 | return Success(E->getValue(), E); | |||
| 11048 | } | |||
| 11049 | ||||
| 11050 | bool VisitCastExpr(const CastExpr *E); | |||
| 11051 | bool VisitUnaryOperator(const UnaryOperator *E); | |||
| 11052 | bool VisitBinaryOperator(const BinaryOperator *E); | |||
| 11053 | }; | |||
| 11054 | } // end anonymous namespace | |||
| 11055 | ||||
| 11056 | /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and | |||
| 11057 | /// produce either the integer value or a pointer. | |||
| 11058 | /// | |||
| 11059 | /// GCC has a heinous extension which folds casts between pointer types and | |||
| 11060 | /// pointer-sized integral types. We support this by allowing the evaluation of | |||
| 11061 | /// an integer rvalue to produce a pointer (represented as an lvalue) instead. | |||
| 11062 | /// Some simple arithmetic on such values is supported (they are treated much | |||
| 11063 | /// like char*). | |||
| 11064 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | |||
| 11065 | EvalInfo &Info) { | |||
| 11066 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 11066, __extension__ __PRETTY_FUNCTION__)); | |||
| 11067 | assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->isPRValue() && E-> getType()->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isIntegralOrEnumerationType()" , "clang/lib/AST/ExprConstant.cpp", 11067, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11068 | return IntExprEvaluator(Info, Result).Visit(E); | |||
| 11069 | } | |||
| 11070 | ||||
| 11071 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { | |||
| 11072 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 11072, __extension__ __PRETTY_FUNCTION__)); | |||
| 11073 | APValue Val; | |||
| 11074 | if (!EvaluateIntegerOrLValue(E, Val, Info)) | |||
| 11075 | return false; | |||
| 11076 | if (!Val.isInt()) { | |||
| 11077 | // FIXME: It would be better to produce the diagnostic for casting | |||
| 11078 | // a pointer to an integer. | |||
| 11079 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 11080 | return false; | |||
| 11081 | } | |||
| 11082 | Result = Val.getInt(); | |||
| 11083 | return true; | |||
| 11084 | } | |||
| 11085 | ||||
| 11086 | bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { | |||
| 11087 | APValue Evaluated = E->EvaluateInContext( | |||
| 11088 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | |||
| 11089 | return Success(Evaluated, E); | |||
| 11090 | } | |||
| 11091 | ||||
| 11092 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | |||
| 11093 | EvalInfo &Info) { | |||
| 11094 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 11094, __extension__ __PRETTY_FUNCTION__)); | |||
| 11095 | if (E->getType()->isFixedPointType()) { | |||
| 11096 | APValue Val; | |||
| 11097 | if (!FixedPointExprEvaluator(Info, Val).Visit(E)) | |||
| 11098 | return false; | |||
| 11099 | if (!Val.isFixedPoint()) | |||
| 11100 | return false; | |||
| 11101 | ||||
| 11102 | Result = Val.getFixedPoint(); | |||
| 11103 | return true; | |||
| 11104 | } | |||
| 11105 | return false; | |||
| 11106 | } | |||
| 11107 | ||||
| 11108 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | |||
| 11109 | EvalInfo &Info) { | |||
| 11110 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 11110, __extension__ __PRETTY_FUNCTION__)); | |||
| 11111 | if (E->getType()->isIntegerType()) { | |||
| 11112 | auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); | |||
| 11113 | APSInt Val; | |||
| 11114 | if (!EvaluateInteger(E, Val, Info)) | |||
| 11115 | return false; | |||
| 11116 | Result = APFixedPoint(Val, FXSema); | |||
| 11117 | return true; | |||
| 11118 | } else if (E->getType()->isFixedPointType()) { | |||
| 11119 | return EvaluateFixedPoint(E, Result, Info); | |||
| 11120 | } | |||
| 11121 | return false; | |||
| 11122 | } | |||
| 11123 | ||||
| 11124 | /// Check whether the given declaration can be directly converted to an integral | |||
| 11125 | /// rvalue. If not, no diagnostic is produced; there are other things we can | |||
| 11126 | /// try. | |||
| 11127 | bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { | |||
| 11128 | // Enums are integer constant exprs. | |||
| 11129 | if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { | |||
| 11130 | // Check for signedness/width mismatches between E type and ECD value. | |||
| 11131 | bool SameSign = (ECD->getInitVal().isSigned() | |||
| 11132 | == E->getType()->isSignedIntegerOrEnumerationType()); | |||
| 11133 | bool SameWidth = (ECD->getInitVal().getBitWidth() | |||
| 11134 | == Info.Ctx.getIntWidth(E->getType())); | |||
| 11135 | if (SameSign && SameWidth) | |||
| 11136 | return Success(ECD->getInitVal(), E); | |||
| 11137 | else { | |||
| 11138 | // Get rid of mismatch (otherwise Success assertions will fail) | |||
| 11139 | // by computing a new value matching the type of E. | |||
| 11140 | llvm::APSInt Val = ECD->getInitVal(); | |||
| 11141 | if (!SameSign) | |||
| 11142 | Val.setIsSigned(!ECD->getInitVal().isSigned()); | |||
| 11143 | if (!SameWidth) | |||
| 11144 | Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); | |||
| 11145 | return Success(Val, E); | |||
| 11146 | } | |||
| 11147 | } | |||
| 11148 | return false; | |||
| 11149 | } | |||
| 11150 | ||||
| 11151 | /// Values returned by __builtin_classify_type, chosen to match the values | |||
| 11152 | /// produced by GCC's builtin. | |||
| 11153 | enum class GCCTypeClass { | |||
| 11154 | None = -1, | |||
| 11155 | Void = 0, | |||
| 11156 | Integer = 1, | |||
| 11157 | // GCC reserves 2 for character types, but instead classifies them as | |||
| 11158 | // integers. | |||
| 11159 | Enum = 3, | |||
| 11160 | Bool = 4, | |||
| 11161 | Pointer = 5, | |||
| 11162 | // GCC reserves 6 for references, but appears to never use it (because | |||
| 11163 | // expressions never have reference type, presumably). | |||
| 11164 | PointerToDataMember = 7, | |||
| 11165 | RealFloat = 8, | |||
| 11166 | Complex = 9, | |||
| 11167 | // GCC reserves 10 for functions, but does not use it since GCC version 6 due | |||
| 11168 | // to decay to pointer. (Prior to version 6 it was only used in C++ mode). | |||
| 11169 | // GCC claims to reserve 11 for pointers to member functions, but *actually* | |||
| 11170 | // uses 12 for that purpose, same as for a class or struct. Maybe it | |||
| 11171 | // internally implements a pointer to member as a struct? Who knows. | |||
| 11172 | PointerToMemberFunction = 12, // Not a bug, see above. | |||
| 11173 | ClassOrStruct = 12, | |||
| 11174 | Union = 13, | |||
| 11175 | // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to | |||
| 11176 | // decay to pointer. (Prior to version 6 it was only used in C++ mode). | |||
| 11177 | // GCC reserves 15 for strings, but actually uses 5 (pointer) for string | |||
| 11178 | // literals. | |||
| 11179 | }; | |||
| 11180 | ||||
| 11181 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | |||
| 11182 | /// as GCC. | |||
| 11183 | static GCCTypeClass | |||
| 11184 | EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { | |||
| 11185 | assert(!T->isDependentType() && "unexpected dependent type")(static_cast <bool> (!T->isDependentType() && "unexpected dependent type") ? void (0) : __assert_fail ("!T->isDependentType() && \"unexpected dependent type\"" , "clang/lib/AST/ExprConstant.cpp", 11185, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11186 | ||||
| 11187 | QualType CanTy = T.getCanonicalType(); | |||
| 11188 | const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); | |||
| 11189 | ||||
| 11190 | switch (CanTy->getTypeClass()) { | |||
| 11191 | #define TYPE(ID, BASE) | |||
| 11192 | #define DEPENDENT_TYPE(ID, BASE) case Type::ID: | |||
| 11193 | #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: | |||
| 11194 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: | |||
| 11195 | #include "clang/AST/TypeNodes.inc" | |||
| 11196 | case Type::Auto: | |||
| 11197 | case Type::DeducedTemplateSpecialization: | |||
| 11198 | llvm_unreachable("unexpected non-canonical or dependent type")::llvm::llvm_unreachable_internal("unexpected non-canonical or dependent type" , "clang/lib/AST/ExprConstant.cpp", 11198); | |||
| 11199 | ||||
| 11200 | case Type::Builtin: | |||
| 11201 | switch (BT->getKind()) { | |||
| 11202 | #define BUILTIN_TYPE(ID, SINGLETON_ID) | |||
| 11203 | #define SIGNED_TYPE(ID, SINGLETON_ID) \ | |||
| 11204 | case BuiltinType::ID: return GCCTypeClass::Integer; | |||
| 11205 | #define FLOATING_TYPE(ID, SINGLETON_ID) \ | |||
| 11206 | case BuiltinType::ID: return GCCTypeClass::RealFloat; | |||
| 11207 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ | |||
| 11208 | case BuiltinType::ID: break; | |||
| 11209 | #include "clang/AST/BuiltinTypes.def" | |||
| 11210 | case BuiltinType::Void: | |||
| 11211 | return GCCTypeClass::Void; | |||
| 11212 | ||||
| 11213 | case BuiltinType::Bool: | |||
| 11214 | return GCCTypeClass::Bool; | |||
| 11215 | ||||
| 11216 | case BuiltinType::Char_U: | |||
| 11217 | case BuiltinType::UChar: | |||
| 11218 | case BuiltinType::WChar_U: | |||
| 11219 | case BuiltinType::Char8: | |||
| 11220 | case BuiltinType::Char16: | |||
| 11221 | case BuiltinType::Char32: | |||
| 11222 | case BuiltinType::UShort: | |||
| 11223 | case BuiltinType::UInt: | |||
| 11224 | case BuiltinType::ULong: | |||
| 11225 | case BuiltinType::ULongLong: | |||
| 11226 | case BuiltinType::UInt128: | |||
| 11227 | return GCCTypeClass::Integer; | |||
| 11228 | ||||
| 11229 | case BuiltinType::UShortAccum: | |||
| 11230 | case BuiltinType::UAccum: | |||
| 11231 | case BuiltinType::ULongAccum: | |||
| 11232 | case BuiltinType::UShortFract: | |||
| 11233 | case BuiltinType::UFract: | |||
| 11234 | case BuiltinType::ULongFract: | |||
| 11235 | case BuiltinType::SatUShortAccum: | |||
| 11236 | case BuiltinType::SatUAccum: | |||
| 11237 | case BuiltinType::SatULongAccum: | |||
| 11238 | case BuiltinType::SatUShortFract: | |||
| 11239 | case BuiltinType::SatUFract: | |||
| 11240 | case BuiltinType::SatULongFract: | |||
| 11241 | return GCCTypeClass::None; | |||
| 11242 | ||||
| 11243 | case BuiltinType::NullPtr: | |||
| 11244 | ||||
| 11245 | case BuiltinType::ObjCId: | |||
| 11246 | case BuiltinType::ObjCClass: | |||
| 11247 | case BuiltinType::ObjCSel: | |||
| 11248 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
| 11249 | case BuiltinType::Id: | |||
| 11250 | #include "clang/Basic/OpenCLImageTypes.def" | |||
| 11251 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | |||
| 11252 | case BuiltinType::Id: | |||
| 11253 | #include "clang/Basic/OpenCLExtensionTypes.def" | |||
| 11254 | case BuiltinType::OCLSampler: | |||
| 11255 | case BuiltinType::OCLEvent: | |||
| 11256 | case BuiltinType::OCLClkEvent: | |||
| 11257 | case BuiltinType::OCLQueue: | |||
| 11258 | case BuiltinType::OCLReserveID: | |||
| 11259 | #define SVE_TYPE(Name, Id, SingletonId) \ | |||
| 11260 | case BuiltinType::Id: | |||
| 11261 | #include "clang/Basic/AArch64SVEACLETypes.def" | |||
| 11262 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | |||
| 11263 | case BuiltinType::Id: | |||
| 11264 | #include "clang/Basic/PPCTypes.def" | |||
| 11265 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | |||
| 11266 | #include "clang/Basic/RISCVVTypes.def" | |||
| 11267 | return GCCTypeClass::None; | |||
| 11268 | ||||
| 11269 | case BuiltinType::Dependent: | |||
| 11270 | llvm_unreachable("unexpected dependent type")::llvm::llvm_unreachable_internal("unexpected dependent type" , "clang/lib/AST/ExprConstant.cpp", 11270); | |||
| 11271 | }; | |||
| 11272 | llvm_unreachable("unexpected placeholder type")::llvm::llvm_unreachable_internal("unexpected placeholder type" , "clang/lib/AST/ExprConstant.cpp", 11272); | |||
| 11273 | ||||
| 11274 | case Type::Enum: | |||
| 11275 | return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; | |||
| 11276 | ||||
| 11277 | case Type::Pointer: | |||
| 11278 | case Type::ConstantArray: | |||
| 11279 | case Type::VariableArray: | |||
| 11280 | case Type::IncompleteArray: | |||
| 11281 | case Type::FunctionNoProto: | |||
| 11282 | case Type::FunctionProto: | |||
| 11283 | return GCCTypeClass::Pointer; | |||
| 11284 | ||||
| 11285 | case Type::MemberPointer: | |||
| 11286 | return CanTy->isMemberDataPointerType() | |||
| 11287 | ? GCCTypeClass::PointerToDataMember | |||
| 11288 | : GCCTypeClass::PointerToMemberFunction; | |||
| 11289 | ||||
| 11290 | case Type::Complex: | |||
| 11291 | return GCCTypeClass::Complex; | |||
| 11292 | ||||
| 11293 | case Type::Record: | |||
| 11294 | return CanTy->isUnionType() ? GCCTypeClass::Union | |||
| 11295 | : GCCTypeClass::ClassOrStruct; | |||
| 11296 | ||||
| 11297 | case Type::Atomic: | |||
| 11298 | // GCC classifies _Atomic T the same as T. | |||
| 11299 | return EvaluateBuiltinClassifyType( | |||
| 11300 | CanTy->castAs<AtomicType>()->getValueType(), LangOpts); | |||
| 11301 | ||||
| 11302 | case Type::BlockPointer: | |||
| 11303 | case Type::Vector: | |||
| 11304 | case Type::ExtVector: | |||
| 11305 | case Type::ConstantMatrix: | |||
| 11306 | case Type::ObjCObject: | |||
| 11307 | case Type::ObjCInterface: | |||
| 11308 | case Type::ObjCObjectPointer: | |||
| 11309 | case Type::Pipe: | |||
| 11310 | case Type::BitInt: | |||
| 11311 | // GCC classifies vectors as None. We follow its lead and classify all | |||
| 11312 | // other types that don't fit into the regular classification the same way. | |||
| 11313 | return GCCTypeClass::None; | |||
| 11314 | ||||
| 11315 | case Type::LValueReference: | |||
| 11316 | case Type::RValueReference: | |||
| 11317 | llvm_unreachable("invalid type for expression")::llvm::llvm_unreachable_internal("invalid type for expression" , "clang/lib/AST/ExprConstant.cpp", 11317); | |||
| 11318 | } | |||
| 11319 | ||||
| 11320 | llvm_unreachable("unexpected type class")::llvm::llvm_unreachable_internal("unexpected type class", "clang/lib/AST/ExprConstant.cpp" , 11320); | |||
| 11321 | } | |||
| 11322 | ||||
| 11323 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | |||
| 11324 | /// as GCC. | |||
| 11325 | static GCCTypeClass | |||
| 11326 | EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { | |||
| 11327 | // If no argument was supplied, default to None. This isn't | |||
| 11328 | // ideal, however it is what gcc does. | |||
| 11329 | if (E->getNumArgs() == 0) | |||
| 11330 | return GCCTypeClass::None; | |||
| 11331 | ||||
| 11332 | // FIXME: Bizarrely, GCC treats a call with more than one argument as not | |||
| 11333 | // being an ICE, but still folds it to a constant using the type of the first | |||
| 11334 | // argument. | |||
| 11335 | return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); | |||
| 11336 | } | |||
| 11337 | ||||
| 11338 | /// EvaluateBuiltinConstantPForLValue - Determine the result of | |||
| 11339 | /// __builtin_constant_p when applied to the given pointer. | |||
| 11340 | /// | |||
| 11341 | /// A pointer is only "constant" if it is null (or a pointer cast to integer) | |||
| 11342 | /// or it points to the first character of a string literal. | |||
| 11343 | static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { | |||
| 11344 | APValue::LValueBase Base = LV.getLValueBase(); | |||
| 11345 | if (Base.isNull()) { | |||
| 11346 | // A null base is acceptable. | |||
| 11347 | return true; | |||
| 11348 | } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { | |||
| 11349 | if (!isa<StringLiteral>(E)) | |||
| 11350 | return false; | |||
| 11351 | return LV.getLValueOffset().isZero(); | |||
| 11352 | } else if (Base.is<TypeInfoLValue>()) { | |||
| 11353 | // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to | |||
| 11354 | // evaluate to true. | |||
| 11355 | return true; | |||
| 11356 | } else { | |||
| 11357 | // Any other base is not constant enough for GCC. | |||
| 11358 | return false; | |||
| 11359 | } | |||
| 11360 | } | |||
| 11361 | ||||
| 11362 | /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to | |||
| 11363 | /// GCC as we can manage. | |||
| 11364 | static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { | |||
| 11365 | // This evaluation is not permitted to have side-effects, so evaluate it in | |||
| 11366 | // a speculative evaluation context. | |||
| 11367 | SpeculativeEvaluationRAII SpeculativeEval(Info); | |||
| 11368 | ||||
| 11369 | // Constant-folding is always enabled for the operand of __builtin_constant_p | |||
| 11370 | // (even when the enclosing evaluation context otherwise requires a strict | |||
| 11371 | // language-specific constant expression). | |||
| 11372 | FoldConstant Fold(Info, true); | |||
| 11373 | ||||
| 11374 | QualType ArgType = Arg->getType(); | |||
| 11375 | ||||
| 11376 | // __builtin_constant_p always has one operand. The rules which gcc follows | |||
| 11377 | // are not precisely documented, but are as follows: | |||
| 11378 | // | |||
| 11379 | // - If the operand is of integral, floating, complex or enumeration type, | |||
| 11380 | // and can be folded to a known value of that type, it returns 1. | |||
| 11381 | // - If the operand can be folded to a pointer to the first character | |||
| 11382 | // of a string literal (or such a pointer cast to an integral type) | |||
| 11383 | // or to a null pointer or an integer cast to a pointer, it returns 1. | |||
| 11384 | // | |||
| 11385 | // Otherwise, it returns 0. | |||
| 11386 | // | |||
| 11387 | // FIXME: GCC also intends to return 1 for literals of aggregate types, but | |||
| 11388 | // its support for this did not work prior to GCC 9 and is not yet well | |||
| 11389 | // understood. | |||
| 11390 | if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || | |||
| 11391 | ArgType->isAnyComplexType() || ArgType->isPointerType() || | |||
| 11392 | ArgType->isNullPtrType()) { | |||
| 11393 | APValue V; | |||
| 11394 | if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { | |||
| 11395 | Fold.keepDiagnostics(); | |||
| 11396 | return false; | |||
| 11397 | } | |||
| 11398 | ||||
| 11399 | // For a pointer (possibly cast to integer), there are special rules. | |||
| 11400 | if (V.getKind() == APValue::LValue) | |||
| 11401 | return EvaluateBuiltinConstantPForLValue(V); | |||
| 11402 | ||||
| 11403 | // Otherwise, any constant value is good enough. | |||
| 11404 | return V.hasValue(); | |||
| 11405 | } | |||
| 11406 | ||||
| 11407 | // Anything else isn't considered to be sufficiently constant. | |||
| 11408 | return false; | |||
| 11409 | } | |||
| 11410 | ||||
| 11411 | /// Retrieves the "underlying object type" of the given expression, | |||
| 11412 | /// as used by __builtin_object_size. | |||
| 11413 | static QualType getObjectType(APValue::LValueBase B) { | |||
| 11414 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | |||
| 11415 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | |||
| 11416 | return VD->getType(); | |||
| 11417 | } else if (const Expr *E = B.dyn_cast<const Expr*>()) { | |||
| 11418 | if (isa<CompoundLiteralExpr>(E)) | |||
| 11419 | return E->getType(); | |||
| 11420 | } else if (B.is<TypeInfoLValue>()) { | |||
| 11421 | return B.getTypeInfoType(); | |||
| 11422 | } else if (B.is<DynamicAllocLValue>()) { | |||
| 11423 | return B.getDynamicAllocType(); | |||
| 11424 | } | |||
| 11425 | ||||
| 11426 | return QualType(); | |||
| 11427 | } | |||
| 11428 | ||||
| 11429 | /// A more selective version of E->IgnoreParenCasts for | |||
| 11430 | /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only | |||
| 11431 | /// to change the type of E. | |||
| 11432 | /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` | |||
| 11433 | /// | |||
| 11434 | /// Always returns an RValue with a pointer representation. | |||
| 11435 | static const Expr *ignorePointerCastsAndParens(const Expr *E) { | |||
| 11436 | assert(E->isPRValue() && E->getType()->hasPointerRepresentation())(static_cast <bool> (E->isPRValue() && E-> getType()->hasPointerRepresentation()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->hasPointerRepresentation()" , "clang/lib/AST/ExprConstant.cpp", 11436, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11437 | ||||
| 11438 | auto *NoParens = E->IgnoreParens(); | |||
| 11439 | auto *Cast = dyn_cast<CastExpr>(NoParens); | |||
| 11440 | if (Cast == nullptr) | |||
| 11441 | return NoParens; | |||
| 11442 | ||||
| 11443 | // We only conservatively allow a few kinds of casts, because this code is | |||
| 11444 | // inherently a simple solution that seeks to support the common case. | |||
| 11445 | auto CastKind = Cast->getCastKind(); | |||
| 11446 | if (CastKind != CK_NoOp && CastKind != CK_BitCast && | |||
| 11447 | CastKind != CK_AddressSpaceConversion) | |||
| 11448 | return NoParens; | |||
| 11449 | ||||
| 11450 | auto *SubExpr = Cast->getSubExpr(); | |||
| 11451 | if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) | |||
| 11452 | return NoParens; | |||
| 11453 | return ignorePointerCastsAndParens(SubExpr); | |||
| 11454 | } | |||
| 11455 | ||||
| 11456 | /// Checks to see if the given LValue's Designator is at the end of the LValue's | |||
| 11457 | /// record layout. e.g. | |||
| 11458 | /// struct { struct { int a, b; } fst, snd; } obj; | |||
| 11459 | /// obj.fst // no | |||
| 11460 | /// obj.snd // yes | |||
| 11461 | /// obj.fst.a // no | |||
| 11462 | /// obj.fst.b // no | |||
| 11463 | /// obj.snd.a // no | |||
| 11464 | /// obj.snd.b // yes | |||
| 11465 | /// | |||
| 11466 | /// Please note: this function is specialized for how __builtin_object_size | |||
| 11467 | /// views "objects". | |||
| 11468 | /// | |||
| 11469 | /// If this encounters an invalid RecordDecl or otherwise cannot determine the | |||
| 11470 | /// correct result, it will always return true. | |||
| 11471 | static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { | |||
| 11472 | assert(!LVal.Designator.Invalid)(static_cast <bool> (!LVal.Designator.Invalid) ? void ( 0) : __assert_fail ("!LVal.Designator.Invalid", "clang/lib/AST/ExprConstant.cpp" , 11472, __extension__ __PRETTY_FUNCTION__)); | |||
| 11473 | ||||
| 11474 | auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { | |||
| 11475 | const RecordDecl *Parent = FD->getParent(); | |||
| 11476 | Invalid = Parent->isInvalidDecl(); | |||
| 11477 | if (Invalid || Parent->isUnion()) | |||
| 11478 | return true; | |||
| 11479 | const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); | |||
| 11480 | return FD->getFieldIndex() + 1 == Layout.getFieldCount(); | |||
| 11481 | }; | |||
| 11482 | ||||
| 11483 | auto &Base = LVal.getLValueBase(); | |||
| 11484 | if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { | |||
| 11485 | if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { | |||
| 11486 | bool Invalid; | |||
| 11487 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | |||
| 11488 | return Invalid; | |||
| 11489 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { | |||
| 11490 | for (auto *FD : IFD->chain()) { | |||
| 11491 | bool Invalid; | |||
| 11492 | if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) | |||
| 11493 | return Invalid; | |||
| 11494 | } | |||
| 11495 | } | |||
| 11496 | } | |||
| 11497 | ||||
| 11498 | unsigned I = 0; | |||
| 11499 | QualType BaseType = getType(Base); | |||
| 11500 | if (LVal.Designator.FirstEntryIsAnUnsizedArray) { | |||
| 11501 | // If we don't know the array bound, conservatively assume we're looking at | |||
| 11502 | // the final array element. | |||
| 11503 | ++I; | |||
| 11504 | if (BaseType->isIncompleteArrayType()) | |||
| 11505 | BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); | |||
| 11506 | else | |||
| 11507 | BaseType = BaseType->castAs<PointerType>()->getPointeeType(); | |||
| 11508 | } | |||
| 11509 | ||||
| 11510 | for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { | |||
| 11511 | const auto &Entry = LVal.Designator.Entries[I]; | |||
| 11512 | if (BaseType->isArrayType()) { | |||
| 11513 | // Because __builtin_object_size treats arrays as objects, we can ignore | |||
| 11514 | // the index iff this is the last array in the Designator. | |||
| 11515 | if (I + 1 == E) | |||
| 11516 | return true; | |||
| 11517 | const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); | |||
| 11518 | uint64_t Index = Entry.getAsArrayIndex(); | |||
| 11519 | if (Index + 1 != CAT->getSize()) | |||
| 11520 | return false; | |||
| 11521 | BaseType = CAT->getElementType(); | |||
| 11522 | } else if (BaseType->isAnyComplexType()) { | |||
| 11523 | const auto *CT = BaseType->castAs<ComplexType>(); | |||
| 11524 | uint64_t Index = Entry.getAsArrayIndex(); | |||
| 11525 | if (Index != 1) | |||
| 11526 | return false; | |||
| 11527 | BaseType = CT->getElementType(); | |||
| 11528 | } else if (auto *FD = getAsField(Entry)) { | |||
| 11529 | bool Invalid; | |||
| 11530 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | |||
| 11531 | return Invalid; | |||
| 11532 | BaseType = FD->getType(); | |||
| 11533 | } else { | |||
| 11534 | assert(getAsBaseClass(Entry) && "Expecting cast to a base class")(static_cast <bool> (getAsBaseClass(Entry) && "Expecting cast to a base class" ) ? void (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\"" , "clang/lib/AST/ExprConstant.cpp", 11534, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11535 | return false; | |||
| 11536 | } | |||
| 11537 | } | |||
| 11538 | return true; | |||
| 11539 | } | |||
| 11540 | ||||
| 11541 | /// Tests to see if the LValue has a user-specified designator (that isn't | |||
| 11542 | /// necessarily valid). Note that this always returns 'true' if the LValue has | |||
| 11543 | /// an unsized array as its first designator entry, because there's currently no | |||
| 11544 | /// way to tell if the user typed *foo or foo[0]. | |||
| 11545 | static bool refersToCompleteObject(const LValue &LVal) { | |||
| 11546 | if (LVal.Designator.Invalid) | |||
| 11547 | return false; | |||
| 11548 | ||||
| 11549 | if (!LVal.Designator.Entries.empty()) | |||
| 11550 | return LVal.Designator.isMostDerivedAnUnsizedArray(); | |||
| 11551 | ||||
| 11552 | if (!LVal.InvalidBase) | |||
| 11553 | return true; | |||
| 11554 | ||||
| 11555 | // If `E` is a MemberExpr, then the first part of the designator is hiding in | |||
| 11556 | // the LValueBase. | |||
| 11557 | const auto *E = LVal.Base.dyn_cast<const Expr *>(); | |||
| 11558 | return !E || !isa<MemberExpr>(E); | |||
| 11559 | } | |||
| 11560 | ||||
| 11561 | /// Attempts to detect a user writing into a piece of memory that's impossible | |||
| 11562 | /// to figure out the size of by just using types. | |||
| 11563 | static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { | |||
| 11564 | const SubobjectDesignator &Designator = LVal.Designator; | |||
| 11565 | // Notes: | |||
| 11566 | // - Users can only write off of the end when we have an invalid base. Invalid | |||
| 11567 | // bases imply we don't know where the memory came from. | |||
| 11568 | // - We used to be a bit more aggressive here; we'd only be conservative if | |||
| 11569 | // the array at the end was flexible, or if it had 0 or 1 elements. This | |||
| 11570 | // broke some common standard library extensions (PR30346), but was | |||
| 11571 | // otherwise seemingly fine. It may be useful to reintroduce this behavior | |||
| 11572 | // with some sort of list. OTOH, it seems that GCC is always | |||
| 11573 | // conservative with the last element in structs (if it's an array), so our | |||
| 11574 | // current behavior is more compatible than an explicit list approach would | |||
| 11575 | // be. | |||
| 11576 | return LVal.InvalidBase && | |||
| 11577 | Designator.Entries.size() == Designator.MostDerivedPathLength && | |||
| 11578 | Designator.MostDerivedIsArrayElement && | |||
| 11579 | isDesignatorAtObjectEnd(Ctx, LVal); | |||
| 11580 | } | |||
| 11581 | ||||
| 11582 | /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. | |||
| 11583 | /// Fails if the conversion would cause loss of precision. | |||
| 11584 | static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, | |||
| 11585 | CharUnits &Result) { | |||
| 11586 | auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); | |||
| 11587 | if (Int.ugt(CharUnitsMax)) | |||
| 11588 | return false; | |||
| 11589 | Result = CharUnits::fromQuantity(Int.getZExtValue()); | |||
| 11590 | return true; | |||
| 11591 | } | |||
| 11592 | ||||
| 11593 | /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will | |||
| 11594 | /// determine how many bytes exist from the beginning of the object to either | |||
| 11595 | /// the end of the current subobject, or the end of the object itself, depending | |||
| 11596 | /// on what the LValue looks like + the value of Type. | |||
| 11597 | /// | |||
| 11598 | /// If this returns false, the value of Result is undefined. | |||
| 11599 | static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, | |||
| 11600 | unsigned Type, const LValue &LVal, | |||
| 11601 | CharUnits &EndOffset) { | |||
| 11602 | bool DetermineForCompleteObject = refersToCompleteObject(LVal); | |||
| 11603 | ||||
| 11604 | auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { | |||
| 11605 | if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) | |||
| 11606 | return false; | |||
| 11607 | return HandleSizeof(Info, ExprLoc, Ty, Result); | |||
| 11608 | }; | |||
| 11609 | ||||
| 11610 | // We want to evaluate the size of the entire object. This is a valid fallback | |||
| 11611 | // for when Type=1 and the designator is invalid, because we're asked for an | |||
| 11612 | // upper-bound. | |||
| 11613 | if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { | |||
| 11614 | // Type=3 wants a lower bound, so we can't fall back to this. | |||
| 11615 | if (Type == 3 && !DetermineForCompleteObject) | |||
| 11616 | return false; | |||
| 11617 | ||||
| 11618 | llvm::APInt APEndOffset; | |||
| 11619 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | |||
| 11620 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | |||
| 11621 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | |||
| 11622 | ||||
| 11623 | if (LVal.InvalidBase) | |||
| 11624 | return false; | |||
| 11625 | ||||
| 11626 | QualType BaseTy = getObjectType(LVal.getLValueBase()); | |||
| 11627 | return CheckedHandleSizeof(BaseTy, EndOffset); | |||
| 11628 | } | |||
| 11629 | ||||
| 11630 | // We want to evaluate the size of a subobject. | |||
| 11631 | const SubobjectDesignator &Designator = LVal.Designator; | |||
| 11632 | ||||
| 11633 | // The following is a moderately common idiom in C: | |||
| 11634 | // | |||
| 11635 | // struct Foo { int a; char c[1]; }; | |||
| 11636 | // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); | |||
| 11637 | // strcpy(&F->c[0], Bar); | |||
| 11638 | // | |||
| 11639 | // In order to not break too much legacy code, we need to support it. | |||
| 11640 | if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { | |||
| 11641 | // If we can resolve this to an alloc_size call, we can hand that back, | |||
| 11642 | // because we know for certain how many bytes there are to write to. | |||
| 11643 | llvm::APInt APEndOffset; | |||
| 11644 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | |||
| 11645 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | |||
| 11646 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | |||
| 11647 | ||||
| 11648 | // If we cannot determine the size of the initial allocation, then we can't | |||
| 11649 | // given an accurate upper-bound. However, we are still able to give | |||
| 11650 | // conservative lower-bounds for Type=3. | |||
| 11651 | if (Type == 1) | |||
| 11652 | return false; | |||
| 11653 | } | |||
| 11654 | ||||
| 11655 | CharUnits BytesPerElem; | |||
| 11656 | if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) | |||
| 11657 | return false; | |||
| 11658 | ||||
| 11659 | // According to the GCC documentation, we want the size of the subobject | |||
| 11660 | // denoted by the pointer. But that's not quite right -- what we actually | |||
| 11661 | // want is the size of the immediately-enclosing array, if there is one. | |||
| 11662 | int64_t ElemsRemaining; | |||
| 11663 | if (Designator.MostDerivedIsArrayElement && | |||
| 11664 | Designator.Entries.size() == Designator.MostDerivedPathLength) { | |||
| 11665 | uint64_t ArraySize = Designator.getMostDerivedArraySize(); | |||
| 11666 | uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); | |||
| 11667 | ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; | |||
| 11668 | } else { | |||
| 11669 | ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; | |||
| 11670 | } | |||
| 11671 | ||||
| 11672 | EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; | |||
| 11673 | return true; | |||
| 11674 | } | |||
| 11675 | ||||
| 11676 | /// Tries to evaluate the __builtin_object_size for @p E. If successful, | |||
| 11677 | /// returns true and stores the result in @p Size. | |||
| 11678 | /// | |||
| 11679 | /// If @p WasError is non-null, this will report whether the failure to evaluate | |||
| 11680 | /// is to be treated as an Error in IntExprEvaluator. | |||
| 11681 | static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, | |||
| 11682 | EvalInfo &Info, uint64_t &Size) { | |||
| 11683 | // Determine the denoted object. | |||
| 11684 | LValue LVal; | |||
| 11685 | { | |||
| 11686 | // The operand of __builtin_object_size is never evaluated for side-effects. | |||
| 11687 | // If there are any, but we can determine the pointed-to object anyway, then | |||
| 11688 | // ignore the side-effects. | |||
| 11689 | SpeculativeEvaluationRAII SpeculativeEval(Info); | |||
| 11690 | IgnoreSideEffectsRAII Fold(Info); | |||
| 11691 | ||||
| 11692 | if (E->isGLValue()) { | |||
| 11693 | // It's possible for us to be given GLValues if we're called via | |||
| 11694 | // Expr::tryEvaluateObjectSize. | |||
| 11695 | APValue RVal; | |||
| 11696 | if (!EvaluateAsRValue(Info, E, RVal)) | |||
| 11697 | return false; | |||
| 11698 | LVal.setFrom(Info.Ctx, RVal); | |||
| 11699 | } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, | |||
| 11700 | /*InvalidBaseOK=*/true)) | |||
| 11701 | return false; | |||
| 11702 | } | |||
| 11703 | ||||
| 11704 | // If we point to before the start of the object, there are no accessible | |||
| 11705 | // bytes. | |||
| 11706 | if (LVal.getLValueOffset().isNegative()) { | |||
| 11707 | Size = 0; | |||
| 11708 | return true; | |||
| 11709 | } | |||
| 11710 | ||||
| 11711 | CharUnits EndOffset; | |||
| 11712 | if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) | |||
| 11713 | return false; | |||
| 11714 | ||||
| 11715 | // If we've fallen outside of the end offset, just pretend there's nothing to | |||
| 11716 | // write to/read from. | |||
| 11717 | if (EndOffset <= LVal.getLValueOffset()) | |||
| 11718 | Size = 0; | |||
| 11719 | else | |||
| 11720 | Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); | |||
| 11721 | return true; | |||
| 11722 | } | |||
| 11723 | ||||
| 11724 | bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { | |||
| 11725 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | |||
| 11726 | return VisitBuiltinCallExpr(E, BuiltinOp); | |||
| 11727 | ||||
| 11728 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | |||
| 11729 | } | |||
| 11730 | ||||
| 11731 | static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, | |||
| 11732 | APValue &Val, APSInt &Alignment) { | |||
| 11733 | QualType SrcTy = E->getArg(0)->getType(); | |||
| 11734 | if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) | |||
| 11735 | return false; | |||
| 11736 | // Even though we are evaluating integer expressions we could get a pointer | |||
| 11737 | // argument for the __builtin_is_aligned() case. | |||
| 11738 | if (SrcTy->isPointerType()) { | |||
| 11739 | LValue Ptr; | |||
| 11740 | if (!EvaluatePointer(E->getArg(0), Ptr, Info)) | |||
| 11741 | return false; | |||
| 11742 | Ptr.moveInto(Val); | |||
| 11743 | } else if (!SrcTy->isIntegralOrEnumerationType()) { | |||
| 11744 | Info.FFDiag(E->getArg(0)); | |||
| 11745 | return false; | |||
| 11746 | } else { | |||
| 11747 | APSInt SrcInt; | |||
| 11748 | if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) | |||
| 11749 | return false; | |||
| 11750 | assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&(static_cast <bool> (SrcInt.getBitWidth() >= Alignment .getBitWidth() && "Bit widths must be the same") ? void (0) : __assert_fail ("SrcInt.getBitWidth() >= Alignment.getBitWidth() && \"Bit widths must be the same\"" , "clang/lib/AST/ExprConstant.cpp", 11751, __extension__ __PRETTY_FUNCTION__ )) | |||
| 11751 | "Bit widths must be the same")(static_cast <bool> (SrcInt.getBitWidth() >= Alignment .getBitWidth() && "Bit widths must be the same") ? void (0) : __assert_fail ("SrcInt.getBitWidth() >= Alignment.getBitWidth() && \"Bit widths must be the same\"" , "clang/lib/AST/ExprConstant.cpp", 11751, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11752 | Val = APValue(SrcInt); | |||
| 11753 | } | |||
| 11754 | assert(Val.hasValue())(static_cast <bool> (Val.hasValue()) ? void (0) : __assert_fail ("Val.hasValue()", "clang/lib/AST/ExprConstant.cpp", 11754, __extension__ __PRETTY_FUNCTION__)); | |||
| 11755 | return true; | |||
| 11756 | } | |||
| 11757 | ||||
| 11758 | bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | |||
| 11759 | unsigned BuiltinOp) { | |||
| 11760 | switch (BuiltinOp) { | |||
| 11761 | default: | |||
| 11762 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | |||
| 11763 | ||||
| 11764 | case Builtin::BI__builtin_dynamic_object_size: | |||
| 11765 | case Builtin::BI__builtin_object_size: { | |||
| 11766 | // The type was checked when we built the expression. | |||
| 11767 | unsigned Type = | |||
| 11768 | E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | |||
| 11769 | assert(Type <= 3 && "unexpected type")(static_cast <bool> (Type <= 3 && "unexpected type" ) ? void (0) : __assert_fail ("Type <= 3 && \"unexpected type\"" , "clang/lib/AST/ExprConstant.cpp", 11769, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11770 | ||||
| 11771 | uint64_t Size; | |||
| 11772 | if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) | |||
| 11773 | return Success(Size, E); | |||
| 11774 | ||||
| 11775 | if (E->getArg(0)->HasSideEffects(Info.Ctx)) | |||
| 11776 | return Success((Type & 2) ? 0 : -1, E); | |||
| 11777 | ||||
| 11778 | // Expression had no side effects, but we couldn't statically determine the | |||
| 11779 | // size of the referenced object. | |||
| 11780 | switch (Info.EvalMode) { | |||
| 11781 | case EvalInfo::EM_ConstantExpression: | |||
| 11782 | case EvalInfo::EM_ConstantFold: | |||
| 11783 | case EvalInfo::EM_IgnoreSideEffects: | |||
| 11784 | // Leave it to IR generation. | |||
| 11785 | return Error(E); | |||
| 11786 | case EvalInfo::EM_ConstantExpressionUnevaluated: | |||
| 11787 | // Reduce it to a constant now. | |||
| 11788 | return Success((Type & 2) ? 0 : -1, E); | |||
| 11789 | } | |||
| 11790 | ||||
| 11791 | llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "clang/lib/AST/ExprConstant.cpp" , 11791); | |||
| 11792 | } | |||
| 11793 | ||||
| 11794 | case Builtin::BI__builtin_os_log_format_buffer_size: { | |||
| 11795 | analyze_os_log::OSLogBufferLayout Layout; | |||
| 11796 | analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); | |||
| 11797 | return Success(Layout.size().getQuantity(), E); | |||
| 11798 | } | |||
| 11799 | ||||
| 11800 | case Builtin::BI__builtin_is_aligned: { | |||
| 11801 | APValue Src; | |||
| 11802 | APSInt Alignment; | |||
| 11803 | if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) | |||
| 11804 | return false; | |||
| 11805 | if (Src.isLValue()) { | |||
| 11806 | // If we evaluated a pointer, check the minimum known alignment. | |||
| 11807 | LValue Ptr; | |||
| 11808 | Ptr.setFrom(Info.Ctx, Src); | |||
| 11809 | CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); | |||
| 11810 | CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); | |||
| 11811 | // We can return true if the known alignment at the computed offset is | |||
| 11812 | // greater than the requested alignment. | |||
| 11813 | assert(PtrAlign.isPowerOfTwo())(static_cast <bool> (PtrAlign.isPowerOfTwo()) ? void (0 ) : __assert_fail ("PtrAlign.isPowerOfTwo()", "clang/lib/AST/ExprConstant.cpp" , 11813, __extension__ __PRETTY_FUNCTION__)); | |||
| 11814 | assert(Alignment.isPowerOf2())(static_cast <bool> (Alignment.isPowerOf2()) ? void (0) : __assert_fail ("Alignment.isPowerOf2()", "clang/lib/AST/ExprConstant.cpp" , 11814, __extension__ __PRETTY_FUNCTION__)); | |||
| 11815 | if (PtrAlign.getQuantity() >= Alignment) | |||
| 11816 | return Success(1, E); | |||
| 11817 | // If the alignment is not known to be sufficient, some cases could still | |||
| 11818 | // be aligned at run time. However, if the requested alignment is less or | |||
| 11819 | // equal to the base alignment and the offset is not aligned, we know that | |||
| 11820 | // the run-time value can never be aligned. | |||
| 11821 | if (BaseAlignment.getQuantity() >= Alignment && | |||
| 11822 | PtrAlign.getQuantity() < Alignment) | |||
| 11823 | return Success(0, E); | |||
| 11824 | // Otherwise we can't infer whether the value is sufficiently aligned. | |||
| 11825 | // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) | |||
| 11826 | // in cases where we can't fully evaluate the pointer. | |||
| 11827 | Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) | |||
| 11828 | << Alignment; | |||
| 11829 | return false; | |||
| 11830 | } | |||
| 11831 | assert(Src.isInt())(static_cast <bool> (Src.isInt()) ? void (0) : __assert_fail ("Src.isInt()", "clang/lib/AST/ExprConstant.cpp", 11831, __extension__ __PRETTY_FUNCTION__)); | |||
| 11832 | return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); | |||
| 11833 | } | |||
| 11834 | case Builtin::BI__builtin_align_up: { | |||
| 11835 | APValue Src; | |||
| 11836 | APSInt Alignment; | |||
| 11837 | if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) | |||
| 11838 | return false; | |||
| 11839 | if (!Src.isInt()) | |||
| 11840 | return Error(E); | |||
| 11841 | APSInt AlignedVal = | |||
| 11842 | APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), | |||
| 11843 | Src.getInt().isUnsigned()); | |||
| 11844 | assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth())(static_cast <bool> (AlignedVal.getBitWidth() == Src.getInt ().getBitWidth()) ? void (0) : __assert_fail ("AlignedVal.getBitWidth() == Src.getInt().getBitWidth()" , "clang/lib/AST/ExprConstant.cpp", 11844, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11845 | return Success(AlignedVal, E); | |||
| 11846 | } | |||
| 11847 | case Builtin::BI__builtin_align_down: { | |||
| 11848 | APValue Src; | |||
| 11849 | APSInt Alignment; | |||
| 11850 | if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) | |||
| 11851 | return false; | |||
| 11852 | if (!Src.isInt()) | |||
| 11853 | return Error(E); | |||
| 11854 | APSInt AlignedVal = | |||
| 11855 | APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); | |||
| 11856 | assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth())(static_cast <bool> (AlignedVal.getBitWidth() == Src.getInt ().getBitWidth()) ? void (0) : __assert_fail ("AlignedVal.getBitWidth() == Src.getInt().getBitWidth()" , "clang/lib/AST/ExprConstant.cpp", 11856, __extension__ __PRETTY_FUNCTION__ )); | |||
| 11857 | return Success(AlignedVal, E); | |||
| 11858 | } | |||
| 11859 | ||||
| 11860 | case Builtin::BI__builtin_bitreverse8: | |||
| 11861 | case Builtin::BI__builtin_bitreverse16: | |||
| 11862 | case Builtin::BI__builtin_bitreverse32: | |||
| 11863 | case Builtin::BI__builtin_bitreverse64: { | |||
| 11864 | APSInt Val; | |||
| 11865 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 11866 | return false; | |||
| 11867 | ||||
| 11868 | return Success(Val.reverseBits(), E); | |||
| 11869 | } | |||
| 11870 | ||||
| 11871 | case Builtin::BI__builtin_bswap16: | |||
| 11872 | case Builtin::BI__builtin_bswap32: | |||
| 11873 | case Builtin::BI__builtin_bswap64: { | |||
| 11874 | APSInt Val; | |||
| 11875 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 11876 | return false; | |||
| 11877 | ||||
| 11878 | return Success(Val.byteSwap(), E); | |||
| 11879 | } | |||
| 11880 | ||||
| 11881 | case Builtin::BI__builtin_classify_type: | |||
| 11882 | return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); | |||
| 11883 | ||||
| 11884 | case Builtin::BI__builtin_clrsb: | |||
| 11885 | case Builtin::BI__builtin_clrsbl: | |||
| 11886 | case Builtin::BI__builtin_clrsbll: { | |||
| 11887 | APSInt Val; | |||
| 11888 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 11889 | return false; | |||
| 11890 | ||||
| 11891 | return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); | |||
| 11892 | } | |||
| 11893 | ||||
| 11894 | case Builtin::BI__builtin_clz: | |||
| 11895 | case Builtin::BI__builtin_clzl: | |||
| 11896 | case Builtin::BI__builtin_clzll: | |||
| 11897 | case Builtin::BI__builtin_clzs: { | |||
| 11898 | APSInt Val; | |||
| 11899 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 11900 | return false; | |||
| 11901 | if (!Val) | |||
| 11902 | return Error(E); | |||
| 11903 | ||||
| 11904 | return Success(Val.countLeadingZeros(), E); | |||
| 11905 | } | |||
| 11906 | ||||
| 11907 | case Builtin::BI__builtin_constant_p: { | |||
| 11908 | const Expr *Arg = E->getArg(0); | |||
| 11909 | if (EvaluateBuiltinConstantP(Info, Arg)) | |||
| 11910 | return Success(true, E); | |||
| 11911 | if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { | |||
| 11912 | // Outside a constant context, eagerly evaluate to false in the presence | |||
| 11913 | // of side-effects in order to avoid -Wunsequenced false-positives in | |||
| 11914 | // a branch on __builtin_constant_p(expr). | |||
| 11915 | return Success(false, E); | |||
| 11916 | } | |||
| 11917 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 11918 | return false; | |||
| 11919 | } | |||
| 11920 | ||||
| 11921 | case Builtin::BI__builtin_is_constant_evaluated: { | |||
| 11922 | const auto *Callee = Info.CurrentCall->getCallee(); | |||
| 11923 | if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && | |||
| 11924 | (Info.CallStackDepth == 1 || | |||
| 11925 | (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && | |||
| 11926 | Callee->getIdentifier() && | |||
| 11927 | Callee->getIdentifier()->isStr("is_constant_evaluated")))) { | |||
| 11928 | // FIXME: Find a better way to avoid duplicated diagnostics. | |||
| 11929 | if (Info.EvalStatus.Diag) | |||
| 11930 | Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() | |||
| 11931 | : Info.CurrentCall->CallLoc, | |||
| 11932 | diag::warn_is_constant_evaluated_always_true_constexpr) | |||
| 11933 | << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" | |||
| 11934 | : "std::is_constant_evaluated"); | |||
| 11935 | } | |||
| 11936 | ||||
| 11937 | return Success(Info.InConstantContext, E); | |||
| 11938 | } | |||
| 11939 | ||||
| 11940 | case Builtin::BI__builtin_ctz: | |||
| 11941 | case Builtin::BI__builtin_ctzl: | |||
| 11942 | case Builtin::BI__builtin_ctzll: | |||
| 11943 | case Builtin::BI__builtin_ctzs: { | |||
| 11944 | APSInt Val; | |||
| 11945 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 11946 | return false; | |||
| 11947 | if (!Val) | |||
| 11948 | return Error(E); | |||
| 11949 | ||||
| 11950 | return Success(Val.countTrailingZeros(), E); | |||
| 11951 | } | |||
| 11952 | ||||
| 11953 | case Builtin::BI__builtin_eh_return_data_regno: { | |||
| 11954 | int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | |||
| 11955 | Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); | |||
| 11956 | return Success(Operand, E); | |||
| 11957 | } | |||
| 11958 | ||||
| 11959 | case Builtin::BI__builtin_expect: | |||
| 11960 | case Builtin::BI__builtin_expect_with_probability: | |||
| 11961 | return Visit(E->getArg(0)); | |||
| 11962 | ||||
| 11963 | case Builtin::BI__builtin_ffs: | |||
| 11964 | case Builtin::BI__builtin_ffsl: | |||
| 11965 | case Builtin::BI__builtin_ffsll: { | |||
| 11966 | APSInt Val; | |||
| 11967 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 11968 | return false; | |||
| 11969 | ||||
| 11970 | unsigned N = Val.countTrailingZeros(); | |||
| 11971 | return Success(N == Val.getBitWidth() ? 0 : N + 1, E); | |||
| 11972 | } | |||
| 11973 | ||||
| 11974 | case Builtin::BI__builtin_fpclassify: { | |||
| 11975 | APFloat Val(0.0); | |||
| 11976 | if (!EvaluateFloat(E->getArg(5), Val, Info)) | |||
| 11977 | return false; | |||
| 11978 | unsigned Arg; | |||
| 11979 | switch (Val.getCategory()) { | |||
| 11980 | case APFloat::fcNaN: Arg = 0; break; | |||
| 11981 | case APFloat::fcInfinity: Arg = 1; break; | |||
| 11982 | case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; | |||
| 11983 | case APFloat::fcZero: Arg = 4; break; | |||
| 11984 | } | |||
| 11985 | return Visit(E->getArg(Arg)); | |||
| 11986 | } | |||
| 11987 | ||||
| 11988 | case Builtin::BI__builtin_isinf_sign: { | |||
| 11989 | APFloat Val(0.0); | |||
| 11990 | return EvaluateFloat(E->getArg(0), Val, Info) && | |||
| 11991 | Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); | |||
| 11992 | } | |||
| 11993 | ||||
| 11994 | case Builtin::BI__builtin_isinf: { | |||
| 11995 | APFloat Val(0.0); | |||
| 11996 | return EvaluateFloat(E->getArg(0), Val, Info) && | |||
| 11997 | Success(Val.isInfinity() ? 1 : 0, E); | |||
| 11998 | } | |||
| 11999 | ||||
| 12000 | case Builtin::BI__builtin_isfinite: { | |||
| 12001 | APFloat Val(0.0); | |||
| 12002 | return EvaluateFloat(E->getArg(0), Val, Info) && | |||
| 12003 | Success(Val.isFinite() ? 1 : 0, E); | |||
| 12004 | } | |||
| 12005 | ||||
| 12006 | case Builtin::BI__builtin_isnan: { | |||
| 12007 | APFloat Val(0.0); | |||
| 12008 | return EvaluateFloat(E->getArg(0), Val, Info) && | |||
| 12009 | Success(Val.isNaN() ? 1 : 0, E); | |||
| 12010 | } | |||
| 12011 | ||||
| 12012 | case Builtin::BI__builtin_isnormal: { | |||
| 12013 | APFloat Val(0.0); | |||
| 12014 | return EvaluateFloat(E->getArg(0), Val, Info) && | |||
| 12015 | Success(Val.isNormal() ? 1 : 0, E); | |||
| 12016 | } | |||
| 12017 | ||||
| 12018 | case Builtin::BI__builtin_parity: | |||
| 12019 | case Builtin::BI__builtin_parityl: | |||
| 12020 | case Builtin::BI__builtin_parityll: { | |||
| 12021 | APSInt Val; | |||
| 12022 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 12023 | return false; | |||
| 12024 | ||||
| 12025 | return Success(Val.countPopulation() % 2, E); | |||
| 12026 | } | |||
| 12027 | ||||
| 12028 | case Builtin::BI__builtin_popcount: | |||
| 12029 | case Builtin::BI__builtin_popcountl: | |||
| 12030 | case Builtin::BI__builtin_popcountll: { | |||
| 12031 | APSInt Val; | |||
| 12032 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | |||
| 12033 | return false; | |||
| 12034 | ||||
| 12035 | return Success(Val.countPopulation(), E); | |||
| 12036 | } | |||
| 12037 | ||||
| 12038 | case Builtin::BI__builtin_rotateleft8: | |||
| 12039 | case Builtin::BI__builtin_rotateleft16: | |||
| 12040 | case Builtin::BI__builtin_rotateleft32: | |||
| 12041 | case Builtin::BI__builtin_rotateleft64: | |||
| 12042 | case Builtin::BI_rotl8: // Microsoft variants of rotate right | |||
| 12043 | case Builtin::BI_rotl16: | |||
| 12044 | case Builtin::BI_rotl: | |||
| 12045 | case Builtin::BI_lrotl: | |||
| 12046 | case Builtin::BI_rotl64: { | |||
| 12047 | APSInt Val, Amt; | |||
| 12048 | if (!EvaluateInteger(E->getArg(0), Val, Info) || | |||
| 12049 | !EvaluateInteger(E->getArg(1), Amt, Info)) | |||
| 12050 | return false; | |||
| 12051 | ||||
| 12052 | return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); | |||
| 12053 | } | |||
| 12054 | ||||
| 12055 | case Builtin::BI__builtin_rotateright8: | |||
| 12056 | case Builtin::BI__builtin_rotateright16: | |||
| 12057 | case Builtin::BI__builtin_rotateright32: | |||
| 12058 | case Builtin::BI__builtin_rotateright64: | |||
| 12059 | case Builtin::BI_rotr8: // Microsoft variants of rotate right | |||
| 12060 | case Builtin::BI_rotr16: | |||
| 12061 | case Builtin::BI_rotr: | |||
| 12062 | case Builtin::BI_lrotr: | |||
| 12063 | case Builtin::BI_rotr64: { | |||
| 12064 | APSInt Val, Amt; | |||
| 12065 | if (!EvaluateInteger(E->getArg(0), Val, Info) || | |||
| 12066 | !EvaluateInteger(E->getArg(1), Amt, Info)) | |||
| 12067 | return false; | |||
| 12068 | ||||
| 12069 | return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); | |||
| 12070 | } | |||
| 12071 | ||||
| 12072 | case Builtin::BIstrlen: | |||
| 12073 | case Builtin::BIwcslen: | |||
| 12074 | // A call to strlen is not a constant expression. | |||
| 12075 | if (Info.getLangOpts().CPlusPlus11) | |||
| 12076 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | |||
| 12077 | << /*isConstexpr*/0 << /*isConstructor*/0 | |||
| 12078 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | |||
| 12079 | else | |||
| 12080 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 12081 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 12082 | case Builtin::BI__builtin_strlen: | |||
| 12083 | case Builtin::BI__builtin_wcslen: { | |||
| 12084 | // As an extension, we support __builtin_strlen() as a constant expression, | |||
| 12085 | // and support folding strlen() to a constant. | |||
| 12086 | uint64_t StrLen; | |||
| 12087 | if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) | |||
| 12088 | return Success(StrLen, E); | |||
| 12089 | return false; | |||
| 12090 | } | |||
| 12091 | ||||
| 12092 | case Builtin::BIstrcmp: | |||
| 12093 | case Builtin::BIwcscmp: | |||
| 12094 | case Builtin::BIstrncmp: | |||
| 12095 | case Builtin::BIwcsncmp: | |||
| 12096 | case Builtin::BImemcmp: | |||
| 12097 | case Builtin::BIbcmp: | |||
| 12098 | case Builtin::BIwmemcmp: | |||
| 12099 | // A call to strlen is not a constant expression. | |||
| 12100 | if (Info.getLangOpts().CPlusPlus11) | |||
| 12101 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | |||
| 12102 | << /*isConstexpr*/0 << /*isConstructor*/0 | |||
| 12103 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | |||
| 12104 | else | |||
| 12105 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 12106 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 12107 | case Builtin::BI__builtin_strcmp: | |||
| 12108 | case Builtin::BI__builtin_wcscmp: | |||
| 12109 | case Builtin::BI__builtin_strncmp: | |||
| 12110 | case Builtin::BI__builtin_wcsncmp: | |||
| 12111 | case Builtin::BI__builtin_memcmp: | |||
| 12112 | case Builtin::BI__builtin_bcmp: | |||
| 12113 | case Builtin::BI__builtin_wmemcmp: { | |||
| 12114 | LValue String1, String2; | |||
| 12115 | if (!EvaluatePointer(E->getArg(0), String1, Info) || | |||
| 12116 | !EvaluatePointer(E->getArg(1), String2, Info)) | |||
| 12117 | return false; | |||
| 12118 | ||||
| 12119 | uint64_t MaxLength = uint64_t(-1); | |||
| 12120 | if (BuiltinOp != Builtin::BIstrcmp && | |||
| 12121 | BuiltinOp != Builtin::BIwcscmp && | |||
| 12122 | BuiltinOp != Builtin::BI__builtin_strcmp && | |||
| 12123 | BuiltinOp != Builtin::BI__builtin_wcscmp) { | |||
| 12124 | APSInt N; | |||
| 12125 | if (!EvaluateInteger(E->getArg(2), N, Info)) | |||
| 12126 | return false; | |||
| 12127 | MaxLength = N.getExtValue(); | |||
| 12128 | } | |||
| 12129 | ||||
| 12130 | // Empty substrings compare equal by definition. | |||
| 12131 | if (MaxLength == 0u) | |||
| 12132 | return Success(0, E); | |||
| 12133 | ||||
| 12134 | if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || | |||
| 12135 | !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || | |||
| 12136 | String1.Designator.Invalid || String2.Designator.Invalid) | |||
| 12137 | return false; | |||
| 12138 | ||||
| 12139 | QualType CharTy1 = String1.Designator.getType(Info.Ctx); | |||
| 12140 | QualType CharTy2 = String2.Designator.getType(Info.Ctx); | |||
| 12141 | ||||
| 12142 | bool IsRawByte = BuiltinOp == Builtin::BImemcmp || | |||
| 12143 | BuiltinOp == Builtin::BIbcmp || | |||
| 12144 | BuiltinOp == Builtin::BI__builtin_memcmp || | |||
| 12145 | BuiltinOp == Builtin::BI__builtin_bcmp; | |||
| 12146 | ||||
| 12147 | assert(IsRawByte ||(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "clang/lib/AST/ExprConstant.cpp", 12150, __extension__ __PRETTY_FUNCTION__ )) | |||
| 12148 | (Info.Ctx.hasSameUnqualifiedType((static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "clang/lib/AST/ExprConstant.cpp", 12150, __extension__ __PRETTY_FUNCTION__ )) | |||
| 12149 | CharTy1, E->getArg(0)->getType()->getPointeeType()) &&(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "clang/lib/AST/ExprConstant.cpp", 12150, __extension__ __PRETTY_FUNCTION__ )) | |||
| 12150 | Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)))(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "clang/lib/AST/ExprConstant.cpp", 12150, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12151 | ||||
| 12152 | // For memcmp, allow comparing any arrays of '[[un]signed] char' or | |||
| 12153 | // 'char8_t', but no other types. | |||
| 12154 | if (IsRawByte && | |||
| 12155 | !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { | |||
| 12156 | // FIXME: Consider using our bit_cast implementation to support this. | |||
| 12157 | Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) | |||
| 12158 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") | |||
| 12159 | << CharTy1 << CharTy2; | |||
| 12160 | return false; | |||
| 12161 | } | |||
| 12162 | ||||
| 12163 | const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { | |||
| 12164 | return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && | |||
| 12165 | handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && | |||
| 12166 | Char1.isInt() && Char2.isInt(); | |||
| 12167 | }; | |||
| 12168 | const auto &AdvanceElems = [&] { | |||
| 12169 | return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && | |||
| 12170 | HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); | |||
| 12171 | }; | |||
| 12172 | ||||
| 12173 | bool StopAtNull = | |||
| 12174 | (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && | |||
| 12175 | BuiltinOp != Builtin::BIwmemcmp && | |||
| 12176 | BuiltinOp != Builtin::BI__builtin_memcmp && | |||
| 12177 | BuiltinOp != Builtin::BI__builtin_bcmp && | |||
| 12178 | BuiltinOp != Builtin::BI__builtin_wmemcmp); | |||
| 12179 | bool IsWide = BuiltinOp == Builtin::BIwcscmp || | |||
| 12180 | BuiltinOp == Builtin::BIwcsncmp || | |||
| 12181 | BuiltinOp == Builtin::BIwmemcmp || | |||
| 12182 | BuiltinOp == Builtin::BI__builtin_wcscmp || | |||
| 12183 | BuiltinOp == Builtin::BI__builtin_wcsncmp || | |||
| 12184 | BuiltinOp == Builtin::BI__builtin_wmemcmp; | |||
| 12185 | ||||
| 12186 | for (; MaxLength; --MaxLength) { | |||
| 12187 | APValue Char1, Char2; | |||
| 12188 | if (!ReadCurElems(Char1, Char2)) | |||
| 12189 | return false; | |||
| 12190 | if (Char1.getInt().ne(Char2.getInt())) { | |||
| 12191 | if (IsWide) // wmemcmp compares with wchar_t signedness. | |||
| 12192 | return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); | |||
| 12193 | // memcmp always compares unsigned chars. | |||
| 12194 | return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); | |||
| 12195 | } | |||
| 12196 | if (StopAtNull && !Char1.getInt()) | |||
| 12197 | return Success(0, E); | |||
| 12198 | assert(!(StopAtNull && !Char2.getInt()))(static_cast <bool> (!(StopAtNull && !Char2.getInt ())) ? void (0) : __assert_fail ("!(StopAtNull && !Char2.getInt())" , "clang/lib/AST/ExprConstant.cpp", 12198, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12199 | if (!AdvanceElems()) | |||
| 12200 | return false; | |||
| 12201 | } | |||
| 12202 | // We hit the strncmp / memcmp limit. | |||
| 12203 | return Success(0, E); | |||
| 12204 | } | |||
| 12205 | ||||
| 12206 | case Builtin::BI__atomic_always_lock_free: | |||
| 12207 | case Builtin::BI__atomic_is_lock_free: | |||
| 12208 | case Builtin::BI__c11_atomic_is_lock_free: { | |||
| 12209 | APSInt SizeVal; | |||
| 12210 | if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) | |||
| 12211 | return false; | |||
| 12212 | ||||
| 12213 | // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power | |||
| 12214 | // of two less than or equal to the maximum inline atomic width, we know it | |||
| 12215 | // is lock-free. If the size isn't a power of two, or greater than the | |||
| 12216 | // maximum alignment where we promote atomics, we know it is not lock-free | |||
| 12217 | // (at least not in the sense of atomic_is_lock_free). Otherwise, | |||
| 12218 | // the answer can only be determined at runtime; for example, 16-byte | |||
| 12219 | // atomics have lock-free implementations on some, but not all, | |||
| 12220 | // x86-64 processors. | |||
| 12221 | ||||
| 12222 | // Check power-of-two. | |||
| 12223 | CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); | |||
| 12224 | if (Size.isPowerOfTwo()) { | |||
| 12225 | // Check against inlining width. | |||
| 12226 | unsigned InlineWidthBits = | |||
| 12227 | Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); | |||
| 12228 | if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { | |||
| 12229 | if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || | |||
| 12230 | Size == CharUnits::One() || | |||
| 12231 | E->getArg(1)->isNullPointerConstant(Info.Ctx, | |||
| 12232 | Expr::NPC_NeverValueDependent)) | |||
| 12233 | // OK, we will inline appropriately-aligned operations of this size, | |||
| 12234 | // and _Atomic(T) is appropriately-aligned. | |||
| 12235 | return Success(1, E); | |||
| 12236 | ||||
| 12237 | QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> | |||
| 12238 | castAs<PointerType>()->getPointeeType(); | |||
| 12239 | if (!PointeeType->isIncompleteType() && | |||
| 12240 | Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { | |||
| 12241 | // OK, we will inline operations on this object. | |||
| 12242 | return Success(1, E); | |||
| 12243 | } | |||
| 12244 | } | |||
| 12245 | } | |||
| 12246 | ||||
| 12247 | return BuiltinOp == Builtin::BI__atomic_always_lock_free ? | |||
| 12248 | Success(0, E) : Error(E); | |||
| 12249 | } | |||
| 12250 | case Builtin::BI__builtin_add_overflow: | |||
| 12251 | case Builtin::BI__builtin_sub_overflow: | |||
| 12252 | case Builtin::BI__builtin_mul_overflow: | |||
| 12253 | case Builtin::BI__builtin_sadd_overflow: | |||
| 12254 | case Builtin::BI__builtin_uadd_overflow: | |||
| 12255 | case Builtin::BI__builtin_uaddl_overflow: | |||
| 12256 | case Builtin::BI__builtin_uaddll_overflow: | |||
| 12257 | case Builtin::BI__builtin_usub_overflow: | |||
| 12258 | case Builtin::BI__builtin_usubl_overflow: | |||
| 12259 | case Builtin::BI__builtin_usubll_overflow: | |||
| 12260 | case Builtin::BI__builtin_umul_overflow: | |||
| 12261 | case Builtin::BI__builtin_umull_overflow: | |||
| 12262 | case Builtin::BI__builtin_umulll_overflow: | |||
| 12263 | case Builtin::BI__builtin_saddl_overflow: | |||
| 12264 | case Builtin::BI__builtin_saddll_overflow: | |||
| 12265 | case Builtin::BI__builtin_ssub_overflow: | |||
| 12266 | case Builtin::BI__builtin_ssubl_overflow: | |||
| 12267 | case Builtin::BI__builtin_ssubll_overflow: | |||
| 12268 | case Builtin::BI__builtin_smul_overflow: | |||
| 12269 | case Builtin::BI__builtin_smull_overflow: | |||
| 12270 | case Builtin::BI__builtin_smulll_overflow: { | |||
| 12271 | LValue ResultLValue; | |||
| 12272 | APSInt LHS, RHS; | |||
| 12273 | ||||
| 12274 | QualType ResultType = E->getArg(2)->getType()->getPointeeType(); | |||
| 12275 | if (!EvaluateInteger(E->getArg(0), LHS, Info) || | |||
| 12276 | !EvaluateInteger(E->getArg(1), RHS, Info) || | |||
| 12277 | !EvaluatePointer(E->getArg(2), ResultLValue, Info)) | |||
| 12278 | return false; | |||
| 12279 | ||||
| 12280 | APSInt Result; | |||
| 12281 | bool DidOverflow = false; | |||
| 12282 | ||||
| 12283 | // If the types don't have to match, enlarge all 3 to the largest of them. | |||
| 12284 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | |||
| 12285 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | |||
| 12286 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | |||
| 12287 | bool IsSigned = LHS.isSigned() || RHS.isSigned() || | |||
| 12288 | ResultType->isSignedIntegerOrEnumerationType(); | |||
| 12289 | bool AllSigned = LHS.isSigned() && RHS.isSigned() && | |||
| 12290 | ResultType->isSignedIntegerOrEnumerationType(); | |||
| 12291 | uint64_t LHSSize = LHS.getBitWidth(); | |||
| 12292 | uint64_t RHSSize = RHS.getBitWidth(); | |||
| 12293 | uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); | |||
| 12294 | uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); | |||
| 12295 | ||||
| 12296 | // Add an additional bit if the signedness isn't uniformly agreed to. We | |||
| 12297 | // could do this ONLY if there is a signed and an unsigned that both have | |||
| 12298 | // MaxBits, but the code to check that is pretty nasty. The issue will be | |||
| 12299 | // caught in the shrink-to-result later anyway. | |||
| 12300 | if (IsSigned && !AllSigned) | |||
| 12301 | ++MaxBits; | |||
| 12302 | ||||
| 12303 | LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); | |||
| 12304 | RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); | |||
| 12305 | Result = APSInt(MaxBits, !IsSigned); | |||
| 12306 | } | |||
| 12307 | ||||
| 12308 | // Find largest int. | |||
| 12309 | switch (BuiltinOp) { | |||
| 12310 | default: | |||
| 12311 | llvm_unreachable("Invalid value for BuiltinOp")::llvm::llvm_unreachable_internal("Invalid value for BuiltinOp" , "clang/lib/AST/ExprConstant.cpp", 12311); | |||
| 12312 | case Builtin::BI__builtin_add_overflow: | |||
| 12313 | case Builtin::BI__builtin_sadd_overflow: | |||
| 12314 | case Builtin::BI__builtin_saddl_overflow: | |||
| 12315 | case Builtin::BI__builtin_saddll_overflow: | |||
| 12316 | case Builtin::BI__builtin_uadd_overflow: | |||
| 12317 | case Builtin::BI__builtin_uaddl_overflow: | |||
| 12318 | case Builtin::BI__builtin_uaddll_overflow: | |||
| 12319 | Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) | |||
| 12320 | : LHS.uadd_ov(RHS, DidOverflow); | |||
| 12321 | break; | |||
| 12322 | case Builtin::BI__builtin_sub_overflow: | |||
| 12323 | case Builtin::BI__builtin_ssub_overflow: | |||
| 12324 | case Builtin::BI__builtin_ssubl_overflow: | |||
| 12325 | case Builtin::BI__builtin_ssubll_overflow: | |||
| 12326 | case Builtin::BI__builtin_usub_overflow: | |||
| 12327 | case Builtin::BI__builtin_usubl_overflow: | |||
| 12328 | case Builtin::BI__builtin_usubll_overflow: | |||
| 12329 | Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) | |||
| 12330 | : LHS.usub_ov(RHS, DidOverflow); | |||
| 12331 | break; | |||
| 12332 | case Builtin::BI__builtin_mul_overflow: | |||
| 12333 | case Builtin::BI__builtin_smul_overflow: | |||
| 12334 | case Builtin::BI__builtin_smull_overflow: | |||
| 12335 | case Builtin::BI__builtin_smulll_overflow: | |||
| 12336 | case Builtin::BI__builtin_umul_overflow: | |||
| 12337 | case Builtin::BI__builtin_umull_overflow: | |||
| 12338 | case Builtin::BI__builtin_umulll_overflow: | |||
| 12339 | Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) | |||
| 12340 | : LHS.umul_ov(RHS, DidOverflow); | |||
| 12341 | break; | |||
| 12342 | } | |||
| 12343 | ||||
| 12344 | // In the case where multiple sizes are allowed, truncate and see if | |||
| 12345 | // the values are the same. | |||
| 12346 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | |||
| 12347 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | |||
| 12348 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | |||
| 12349 | // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, | |||
| 12350 | // since it will give us the behavior of a TruncOrSelf in the case where | |||
| 12351 | // its parameter <= its size. We previously set Result to be at least the | |||
| 12352 | // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth | |||
| 12353 | // will work exactly like TruncOrSelf. | |||
| 12354 | APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); | |||
| 12355 | Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); | |||
| 12356 | ||||
| 12357 | if (!APSInt::isSameValue(Temp, Result)) | |||
| 12358 | DidOverflow = true; | |||
| 12359 | Result = Temp; | |||
| 12360 | } | |||
| 12361 | ||||
| 12362 | APValue APV{Result}; | |||
| 12363 | if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) | |||
| 12364 | return false; | |||
| 12365 | return Success(DidOverflow, E); | |||
| 12366 | } | |||
| 12367 | } | |||
| 12368 | } | |||
| 12369 | ||||
| 12370 | /// Determine whether this is a pointer past the end of the complete | |||
| 12371 | /// object referred to by the lvalue. | |||
| 12372 | static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, | |||
| 12373 | const LValue &LV) { | |||
| 12374 | // A null pointer can be viewed as being "past the end" but we don't | |||
| 12375 | // choose to look at it that way here. | |||
| 12376 | if (!LV.getLValueBase()) | |||
| 12377 | return false; | |||
| 12378 | ||||
| 12379 | // If the designator is valid and refers to a subobject, we're not pointing | |||
| 12380 | // past the end. | |||
| 12381 | if (!LV.getLValueDesignator().Invalid && | |||
| 12382 | !LV.getLValueDesignator().isOnePastTheEnd()) | |||
| 12383 | return false; | |||
| 12384 | ||||
| 12385 | // A pointer to an incomplete type might be past-the-end if the type's size is | |||
| 12386 | // zero. We cannot tell because the type is incomplete. | |||
| 12387 | QualType Ty = getType(LV.getLValueBase()); | |||
| 12388 | if (Ty->isIncompleteType()) | |||
| 12389 | return true; | |||
| 12390 | ||||
| 12391 | // We're a past-the-end pointer if we point to the byte after the object, | |||
| 12392 | // no matter what our type or path is. | |||
| 12393 | auto Size = Ctx.getTypeSizeInChars(Ty); | |||
| 12394 | return LV.getLValueOffset() == Size; | |||
| 12395 | } | |||
| 12396 | ||||
| 12397 | namespace { | |||
| 12398 | ||||
| 12399 | /// Data recursive integer evaluator of certain binary operators. | |||
| 12400 | /// | |||
| 12401 | /// We use a data recursive algorithm for binary operators so that we are able | |||
| 12402 | /// to handle extreme cases of chained binary operators without causing stack | |||
| 12403 | /// overflow. | |||
| 12404 | class DataRecursiveIntBinOpEvaluator { | |||
| 12405 | struct EvalResult { | |||
| 12406 | APValue Val; | |||
| 12407 | bool Failed; | |||
| 12408 | ||||
| 12409 | EvalResult() : Failed(false) { } | |||
| 12410 | ||||
| 12411 | void swap(EvalResult &RHS) { | |||
| 12412 | Val.swap(RHS.Val); | |||
| 12413 | Failed = RHS.Failed; | |||
| 12414 | RHS.Failed = false; | |||
| 12415 | } | |||
| 12416 | }; | |||
| 12417 | ||||
| 12418 | struct Job { | |||
| 12419 | const Expr *E; | |||
| 12420 | EvalResult LHSResult; // meaningful only for binary operator expression. | |||
| 12421 | enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; | |||
| 12422 | ||||
| 12423 | Job() = default; | |||
| 12424 | Job(Job &&) = default; | |||
| 12425 | ||||
| 12426 | void startSpeculativeEval(EvalInfo &Info) { | |||
| 12427 | SpecEvalRAII = SpeculativeEvaluationRAII(Info); | |||
| 12428 | } | |||
| 12429 | ||||
| 12430 | private: | |||
| 12431 | SpeculativeEvaluationRAII SpecEvalRAII; | |||
| 12432 | }; | |||
| 12433 | ||||
| 12434 | SmallVector<Job, 16> Queue; | |||
| 12435 | ||||
| 12436 | IntExprEvaluator &IntEval; | |||
| 12437 | EvalInfo &Info; | |||
| 12438 | APValue &FinalResult; | |||
| 12439 | ||||
| 12440 | public: | |||
| 12441 | DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) | |||
| 12442 | : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } | |||
| 12443 | ||||
| 12444 | /// True if \param E is a binary operator that we are going to handle | |||
| 12445 | /// data recursively. | |||
| 12446 | /// We handle binary operators that are comma, logical, or that have operands | |||
| 12447 | /// with integral or enumeration type. | |||
| 12448 | static bool shouldEnqueue(const BinaryOperator *E) { | |||
| 12449 | return E->getOpcode() == BO_Comma || E->isLogicalOp() || | |||
| 12450 | (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && | |||
| 12451 | E->getLHS()->getType()->isIntegralOrEnumerationType() && | |||
| 12452 | E->getRHS()->getType()->isIntegralOrEnumerationType()); | |||
| 12453 | } | |||
| 12454 | ||||
| 12455 | bool Traverse(const BinaryOperator *E) { | |||
| 12456 | enqueue(E); | |||
| 12457 | EvalResult PrevResult; | |||
| 12458 | while (!Queue.empty()) | |||
| 12459 | process(PrevResult); | |||
| 12460 | ||||
| 12461 | if (PrevResult.Failed) return false; | |||
| 12462 | ||||
| 12463 | FinalResult.swap(PrevResult.Val); | |||
| 12464 | return true; | |||
| 12465 | } | |||
| 12466 | ||||
| 12467 | private: | |||
| 12468 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | |||
| 12469 | return IntEval.Success(Value, E, Result); | |||
| 12470 | } | |||
| 12471 | bool Success(const APSInt &Value, const Expr *E, APValue &Result) { | |||
| 12472 | return IntEval.Success(Value, E, Result); | |||
| 12473 | } | |||
| 12474 | bool Error(const Expr *E) { | |||
| 12475 | return IntEval.Error(E); | |||
| 12476 | } | |||
| 12477 | bool Error(const Expr *E, diag::kind D) { | |||
| 12478 | return IntEval.Error(E, D); | |||
| 12479 | } | |||
| 12480 | ||||
| 12481 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | |||
| 12482 | return Info.CCEDiag(E, D); | |||
| 12483 | } | |||
| 12484 | ||||
| 12485 | // Returns true if visiting the RHS is necessary, false otherwise. | |||
| 12486 | bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | |||
| 12487 | bool &SuppressRHSDiags); | |||
| 12488 | ||||
| 12489 | bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | |||
| 12490 | const BinaryOperator *E, APValue &Result); | |||
| 12491 | ||||
| 12492 | void EvaluateExpr(const Expr *E, EvalResult &Result) { | |||
| 12493 | Result.Failed = !Evaluate(Result.Val, Info, E); | |||
| 12494 | if (Result.Failed) | |||
| 12495 | Result.Val = APValue(); | |||
| 12496 | } | |||
| 12497 | ||||
| 12498 | void process(EvalResult &Result); | |||
| 12499 | ||||
| 12500 | void enqueue(const Expr *E) { | |||
| 12501 | E = E->IgnoreParens(); | |||
| 12502 | Queue.resize(Queue.size()+1); | |||
| 12503 | Queue.back().E = E; | |||
| 12504 | Queue.back().Kind = Job::AnyExprKind; | |||
| 12505 | } | |||
| 12506 | }; | |||
| 12507 | ||||
| 12508 | } | |||
| 12509 | ||||
| 12510 | bool DataRecursiveIntBinOpEvaluator:: | |||
| 12511 | VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | |||
| 12512 | bool &SuppressRHSDiags) { | |||
| 12513 | if (E->getOpcode() == BO_Comma) { | |||
| 12514 | // Ignore LHS but note if we could not evaluate it. | |||
| 12515 | if (LHSResult.Failed) | |||
| 12516 | return Info.noteSideEffect(); | |||
| 12517 | return true; | |||
| 12518 | } | |||
| 12519 | ||||
| 12520 | if (E->isLogicalOp()) { | |||
| 12521 | bool LHSAsBool; | |||
| 12522 | if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { | |||
| 12523 | // We were able to evaluate the LHS, see if we can get away with not | |||
| 12524 | // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 | |||
| 12525 | if (LHSAsBool == (E->getOpcode() == BO_LOr)) { | |||
| 12526 | Success(LHSAsBool, E, LHSResult.Val); | |||
| 12527 | return false; // Ignore RHS | |||
| 12528 | } | |||
| 12529 | } else { | |||
| 12530 | LHSResult.Failed = true; | |||
| 12531 | ||||
| 12532 | // Since we weren't able to evaluate the left hand side, it | |||
| 12533 | // might have had side effects. | |||
| 12534 | if (!Info.noteSideEffect()) | |||
| 12535 | return false; | |||
| 12536 | ||||
| 12537 | // We can't evaluate the LHS; however, sometimes the result | |||
| 12538 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | |||
| 12539 | // Don't ignore RHS and suppress diagnostics from this arm. | |||
| 12540 | SuppressRHSDiags = true; | |||
| 12541 | } | |||
| 12542 | ||||
| 12543 | return true; | |||
| 12544 | } | |||
| 12545 | ||||
| 12546 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "clang/lib/AST/ExprConstant.cpp", 12547, __extension__ __PRETTY_FUNCTION__ )) | |||
| 12547 | E->getRHS()->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "clang/lib/AST/ExprConstant.cpp", 12547, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12548 | ||||
| 12549 | if (LHSResult.Failed && !Info.noteFailure()) | |||
| 12550 | return false; // Ignore RHS; | |||
| 12551 | ||||
| 12552 | return true; | |||
| 12553 | } | |||
| 12554 | ||||
| 12555 | static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, | |||
| 12556 | bool IsSub) { | |||
| 12557 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | |||
| 12558 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | |||
| 12559 | // offsets. | |||
| 12560 | assert(!LVal.hasLValuePath() && "have designator for integer lvalue")(static_cast <bool> (!LVal.hasLValuePath() && "have designator for integer lvalue" ) ? void (0) : __assert_fail ("!LVal.hasLValuePath() && \"have designator for integer lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 12560, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12561 | CharUnits &Offset = LVal.getLValueOffset(); | |||
| 12562 | uint64_t Offset64 = Offset.getQuantity(); | |||
| 12563 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | |||
| 12564 | Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 | |||
| 12565 | : Offset64 + Index64); | |||
| 12566 | } | |||
| 12567 | ||||
| 12568 | bool DataRecursiveIntBinOpEvaluator:: | |||
| 12569 | VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | |||
| 12570 | const BinaryOperator *E, APValue &Result) { | |||
| 12571 | if (E->getOpcode() == BO_Comma) { | |||
| 12572 | if (RHSResult.Failed) | |||
| 12573 | return false; | |||
| 12574 | Result = RHSResult.Val; | |||
| 12575 | return true; | |||
| 12576 | } | |||
| 12577 | ||||
| 12578 | if (E->isLogicalOp()) { | |||
| 12579 | bool lhsResult, rhsResult; | |||
| 12580 | bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); | |||
| 12581 | bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); | |||
| 12582 | ||||
| 12583 | if (LHSIsOK) { | |||
| 12584 | if (RHSIsOK) { | |||
| 12585 | if (E->getOpcode() == BO_LOr) | |||
| 12586 | return Success(lhsResult || rhsResult, E, Result); | |||
| 12587 | else | |||
| 12588 | return Success(lhsResult && rhsResult, E, Result); | |||
| 12589 | } | |||
| 12590 | } else { | |||
| 12591 | if (RHSIsOK) { | |||
| 12592 | // We can't evaluate the LHS; however, sometimes the result | |||
| 12593 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | |||
| 12594 | if (rhsResult == (E->getOpcode() == BO_LOr)) | |||
| 12595 | return Success(rhsResult, E, Result); | |||
| 12596 | } | |||
| 12597 | } | |||
| 12598 | ||||
| 12599 | return false; | |||
| 12600 | } | |||
| 12601 | ||||
| 12602 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "clang/lib/AST/ExprConstant.cpp", 12603, __extension__ __PRETTY_FUNCTION__ )) | |||
| 12603 | E->getRHS()->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "clang/lib/AST/ExprConstant.cpp", 12603, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12604 | ||||
| 12605 | if (LHSResult.Failed || RHSResult.Failed) | |||
| 12606 | return false; | |||
| 12607 | ||||
| 12608 | const APValue &LHSVal = LHSResult.Val; | |||
| 12609 | const APValue &RHSVal = RHSResult.Val; | |||
| 12610 | ||||
| 12611 | // Handle cases like (unsigned long)&a + 4. | |||
| 12612 | if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { | |||
| 12613 | Result = LHSVal; | |||
| 12614 | addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); | |||
| 12615 | return true; | |||
| 12616 | } | |||
| 12617 | ||||
| 12618 | // Handle cases like 4 + (unsigned long)&a | |||
| 12619 | if (E->getOpcode() == BO_Add && | |||
| 12620 | RHSVal.isLValue() && LHSVal.isInt()) { | |||
| 12621 | Result = RHSVal; | |||
| 12622 | addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); | |||
| 12623 | return true; | |||
| 12624 | } | |||
| 12625 | ||||
| 12626 | if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { | |||
| 12627 | // Handle (intptr_t)&&A - (intptr_t)&&B. | |||
| 12628 | if (!LHSVal.getLValueOffset().isZero() || | |||
| 12629 | !RHSVal.getLValueOffset().isZero()) | |||
| 12630 | return false; | |||
| 12631 | const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); | |||
| 12632 | const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); | |||
| 12633 | if (!LHSExpr || !RHSExpr) | |||
| 12634 | return false; | |||
| 12635 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | |||
| 12636 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | |||
| 12637 | if (!LHSAddrExpr || !RHSAddrExpr) | |||
| 12638 | return false; | |||
| 12639 | // Make sure both labels come from the same function. | |||
| 12640 | if (LHSAddrExpr->getLabel()->getDeclContext() != | |||
| 12641 | RHSAddrExpr->getLabel()->getDeclContext()) | |||
| 12642 | return false; | |||
| 12643 | Result = APValue(LHSAddrExpr, RHSAddrExpr); | |||
| 12644 | return true; | |||
| 12645 | } | |||
| 12646 | ||||
| 12647 | // All the remaining cases expect both operands to be an integer | |||
| 12648 | if (!LHSVal.isInt() || !RHSVal.isInt()) | |||
| 12649 | return Error(E); | |||
| 12650 | ||||
| 12651 | // Set up the width and signedness manually, in case it can't be deduced | |||
| 12652 | // from the operation we're performing. | |||
| 12653 | // FIXME: Don't do this in the cases where we can deduce it. | |||
| 12654 | APSInt Value(Info.Ctx.getIntWidth(E->getType()), | |||
| 12655 | E->getType()->isUnsignedIntegerOrEnumerationType()); | |||
| 12656 | if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), | |||
| 12657 | RHSVal.getInt(), Value)) | |||
| 12658 | return false; | |||
| 12659 | return Success(Value, E, Result); | |||
| 12660 | } | |||
| 12661 | ||||
| 12662 | void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { | |||
| 12663 | Job &job = Queue.back(); | |||
| 12664 | ||||
| 12665 | switch (job.Kind) { | |||
| 12666 | case Job::AnyExprKind: { | |||
| 12667 | if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { | |||
| 12668 | if (shouldEnqueue(Bop)) { | |||
| 12669 | job.Kind = Job::BinOpKind; | |||
| 12670 | enqueue(Bop->getLHS()); | |||
| 12671 | return; | |||
| 12672 | } | |||
| 12673 | } | |||
| 12674 | ||||
| 12675 | EvaluateExpr(job.E, Result); | |||
| 12676 | Queue.pop_back(); | |||
| 12677 | return; | |||
| 12678 | } | |||
| 12679 | ||||
| 12680 | case Job::BinOpKind: { | |||
| 12681 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | |||
| 12682 | bool SuppressRHSDiags = false; | |||
| 12683 | if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { | |||
| 12684 | Queue.pop_back(); | |||
| 12685 | return; | |||
| 12686 | } | |||
| 12687 | if (SuppressRHSDiags) | |||
| 12688 | job.startSpeculativeEval(Info); | |||
| 12689 | job.LHSResult.swap(Result); | |||
| 12690 | job.Kind = Job::BinOpVisitedLHSKind; | |||
| 12691 | enqueue(Bop->getRHS()); | |||
| 12692 | return; | |||
| 12693 | } | |||
| 12694 | ||||
| 12695 | case Job::BinOpVisitedLHSKind: { | |||
| 12696 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | |||
| 12697 | EvalResult RHS; | |||
| 12698 | RHS.swap(Result); | |||
| 12699 | Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); | |||
| 12700 | Queue.pop_back(); | |||
| 12701 | return; | |||
| 12702 | } | |||
| 12703 | } | |||
| 12704 | ||||
| 12705 | llvm_unreachable("Invalid Job::Kind!")::llvm::llvm_unreachable_internal("Invalid Job::Kind!", "clang/lib/AST/ExprConstant.cpp" , 12705); | |||
| 12706 | } | |||
| 12707 | ||||
| 12708 | namespace { | |||
| 12709 | enum class CmpResult { | |||
| 12710 | Unequal, | |||
| 12711 | Less, | |||
| 12712 | Equal, | |||
| 12713 | Greater, | |||
| 12714 | Unordered, | |||
| 12715 | }; | |||
| 12716 | } | |||
| 12717 | ||||
| 12718 | template <class SuccessCB, class AfterCB> | |||
| 12719 | static bool | |||
| 12720 | EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, | |||
| 12721 | SuccessCB &&Success, AfterCB &&DoAfter) { | |||
| 12722 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 12722, __extension__ __PRETTY_FUNCTION__)); | |||
| 12723 | assert(E->isComparisonOp() && "expected comparison operator")(static_cast <bool> (E->isComparisonOp() && "expected comparison operator" ) ? void (0) : __assert_fail ("E->isComparisonOp() && \"expected comparison operator\"" , "clang/lib/AST/ExprConstant.cpp", 12723, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12724 | assert((E->getOpcode() == BO_Cmp ||(static_cast <bool> ((E->getOpcode() == BO_Cmp || E-> getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation" ) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "clang/lib/AST/ExprConstant.cpp", 12726, __extension__ __PRETTY_FUNCTION__ )) | |||
| 12725 | E->getType()->isIntegralOrEnumerationType()) &&(static_cast <bool> ((E->getOpcode() == BO_Cmp || E-> getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation" ) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "clang/lib/AST/ExprConstant.cpp", 12726, __extension__ __PRETTY_FUNCTION__ )) | |||
| 12726 | "unsupported binary expression evaluation")(static_cast <bool> ((E->getOpcode() == BO_Cmp || E-> getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation" ) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "clang/lib/AST/ExprConstant.cpp", 12726, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12727 | auto Error = [&](const Expr *E) { | |||
| 12728 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 12729 | return false; | |||
| 12730 | }; | |||
| 12731 | ||||
| 12732 | bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; | |||
| 12733 | bool IsEquality = E->isEqualityOp(); | |||
| 12734 | ||||
| 12735 | QualType LHSTy = E->getLHS()->getType(); | |||
| 12736 | QualType RHSTy = E->getRHS()->getType(); | |||
| 12737 | ||||
| 12738 | if (LHSTy->isIntegralOrEnumerationType() && | |||
| 12739 | RHSTy->isIntegralOrEnumerationType()) { | |||
| 12740 | APSInt LHS, RHS; | |||
| 12741 | bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); | |||
| 12742 | if (!LHSOK && !Info.noteFailure()) | |||
| 12743 | return false; | |||
| 12744 | if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) | |||
| 12745 | return false; | |||
| 12746 | if (LHS < RHS) | |||
| 12747 | return Success(CmpResult::Less, E); | |||
| 12748 | if (LHS > RHS) | |||
| 12749 | return Success(CmpResult::Greater, E); | |||
| 12750 | return Success(CmpResult::Equal, E); | |||
| 12751 | } | |||
| 12752 | ||||
| 12753 | if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { | |||
| 12754 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); | |||
| 12755 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); | |||
| 12756 | ||||
| 12757 | bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); | |||
| 12758 | if (!LHSOK && !Info.noteFailure()) | |||
| 12759 | return false; | |||
| 12760 | if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) | |||
| 12761 | return false; | |||
| 12762 | if (LHSFX < RHSFX) | |||
| 12763 | return Success(CmpResult::Less, E); | |||
| 12764 | if (LHSFX > RHSFX) | |||
| 12765 | return Success(CmpResult::Greater, E); | |||
| 12766 | return Success(CmpResult::Equal, E); | |||
| 12767 | } | |||
| 12768 | ||||
| 12769 | if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { | |||
| 12770 | ComplexValue LHS, RHS; | |||
| 12771 | bool LHSOK; | |||
| 12772 | if (E->isAssignmentOp()) { | |||
| 12773 | LValue LV; | |||
| 12774 | EvaluateLValue(E->getLHS(), LV, Info); | |||
| 12775 | LHSOK = false; | |||
| 12776 | } else if (LHSTy->isRealFloatingType()) { | |||
| 12777 | LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); | |||
| 12778 | if (LHSOK) { | |||
| 12779 | LHS.makeComplexFloat(); | |||
| 12780 | LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); | |||
| 12781 | } | |||
| 12782 | } else { | |||
| 12783 | LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); | |||
| 12784 | } | |||
| 12785 | if (!LHSOK && !Info.noteFailure()) | |||
| 12786 | return false; | |||
| 12787 | ||||
| 12788 | if (E->getRHS()->getType()->isRealFloatingType()) { | |||
| 12789 | if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) | |||
| 12790 | return false; | |||
| 12791 | RHS.makeComplexFloat(); | |||
| 12792 | RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); | |||
| 12793 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | |||
| 12794 | return false; | |||
| 12795 | ||||
| 12796 | if (LHS.isComplexFloat()) { | |||
| 12797 | APFloat::cmpResult CR_r = | |||
| 12798 | LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); | |||
| 12799 | APFloat::cmpResult CR_i = | |||
| 12800 | LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); | |||
| 12801 | bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; | |||
| 12802 | return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); | |||
| 12803 | } else { | |||
| 12804 | assert(IsEquality && "invalid complex comparison")(static_cast <bool> (IsEquality && "invalid complex comparison" ) ? void (0) : __assert_fail ("IsEquality && \"invalid complex comparison\"" , "clang/lib/AST/ExprConstant.cpp", 12804, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12805 | bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && | |||
| 12806 | LHS.getComplexIntImag() == RHS.getComplexIntImag(); | |||
| 12807 | return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); | |||
| 12808 | } | |||
| 12809 | } | |||
| 12810 | ||||
| 12811 | if (LHSTy->isRealFloatingType() && | |||
| 12812 | RHSTy->isRealFloatingType()) { | |||
| 12813 | APFloat RHS(0.0), LHS(0.0); | |||
| 12814 | ||||
| 12815 | bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); | |||
| 12816 | if (!LHSOK && !Info.noteFailure()) | |||
| 12817 | return false; | |||
| 12818 | ||||
| 12819 | if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) | |||
| 12820 | return false; | |||
| 12821 | ||||
| 12822 | assert(E->isComparisonOp() && "Invalid binary operator!")(static_cast <bool> (E->isComparisonOp() && "Invalid binary operator!" ) ? void (0) : __assert_fail ("E->isComparisonOp() && \"Invalid binary operator!\"" , "clang/lib/AST/ExprConstant.cpp", 12822, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12823 | llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); | |||
| 12824 | if (!Info.InConstantContext && | |||
| 12825 | APFloatCmpResult == APFloat::cmpUnordered && | |||
| 12826 | E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { | |||
| 12827 | // Note: Compares may raise invalid in some cases involving NaN or sNaN. | |||
| 12828 | Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); | |||
| 12829 | return false; | |||
| 12830 | } | |||
| 12831 | auto GetCmpRes = [&]() { | |||
| 12832 | switch (APFloatCmpResult) { | |||
| 12833 | case APFloat::cmpEqual: | |||
| 12834 | return CmpResult::Equal; | |||
| 12835 | case APFloat::cmpLessThan: | |||
| 12836 | return CmpResult::Less; | |||
| 12837 | case APFloat::cmpGreaterThan: | |||
| 12838 | return CmpResult::Greater; | |||
| 12839 | case APFloat::cmpUnordered: | |||
| 12840 | return CmpResult::Unordered; | |||
| 12841 | } | |||
| 12842 | llvm_unreachable("Unrecognised APFloat::cmpResult enum")::llvm::llvm_unreachable_internal("Unrecognised APFloat::cmpResult enum" , "clang/lib/AST/ExprConstant.cpp", 12842); | |||
| 12843 | }; | |||
| 12844 | return Success(GetCmpRes(), E); | |||
| 12845 | } | |||
| 12846 | ||||
| 12847 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) { | |||
| 12848 | LValue LHSValue, RHSValue; | |||
| 12849 | ||||
| 12850 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | |||
| 12851 | if (!LHSOK && !Info.noteFailure()) | |||
| 12852 | return false; | |||
| 12853 | ||||
| 12854 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) | |||
| 12855 | return false; | |||
| 12856 | ||||
| 12857 | // Reject differing bases from the normal codepath; we special-case | |||
| 12858 | // comparisons to null. | |||
| 12859 | if (!HasSameBase(LHSValue, RHSValue)) { | |||
| 12860 | // Inequalities and subtractions between unrelated pointers have | |||
| 12861 | // unspecified or undefined behavior. | |||
| 12862 | if (!IsEquality) { | |||
| 12863 | Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); | |||
| 12864 | return false; | |||
| 12865 | } | |||
| 12866 | // A constant address may compare equal to the address of a symbol. | |||
| 12867 | // The one exception is that address of an object cannot compare equal | |||
| 12868 | // to a null pointer constant. | |||
| 12869 | if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || | |||
| 12870 | (!RHSValue.Base && !RHSValue.Offset.isZero())) | |||
| 12871 | return Error(E); | |||
| 12872 | // It's implementation-defined whether distinct literals will have | |||
| 12873 | // distinct addresses. In clang, the result of such a comparison is | |||
| 12874 | // unspecified, so it is not a constant expression. However, we do know | |||
| 12875 | // that the address of a literal will be non-null. | |||
| 12876 | if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && | |||
| 12877 | LHSValue.Base && RHSValue.Base) | |||
| 12878 | return Error(E); | |||
| 12879 | // We can't tell whether weak symbols will end up pointing to the same | |||
| 12880 | // object. | |||
| 12881 | if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) | |||
| 12882 | return Error(E); | |||
| 12883 | // We can't compare the address of the start of one object with the | |||
| 12884 | // past-the-end address of another object, per C++ DR1652. | |||
| 12885 | if ((LHSValue.Base && LHSValue.Offset.isZero() && | |||
| 12886 | isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || | |||
| 12887 | (RHSValue.Base && RHSValue.Offset.isZero() && | |||
| 12888 | isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) | |||
| 12889 | return Error(E); | |||
| 12890 | // We can't tell whether an object is at the same address as another | |||
| 12891 | // zero sized object. | |||
| 12892 | if ((RHSValue.Base && isZeroSized(LHSValue)) || | |||
| 12893 | (LHSValue.Base && isZeroSized(RHSValue))) | |||
| 12894 | return Error(E); | |||
| 12895 | return Success(CmpResult::Unequal, E); | |||
| 12896 | } | |||
| 12897 | ||||
| 12898 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | |||
| 12899 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | |||
| 12900 | ||||
| 12901 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | |||
| 12902 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | |||
| 12903 | ||||
| 12904 | // C++11 [expr.rel]p3: | |||
| 12905 | // Pointers to void (after pointer conversions) can be compared, with a | |||
| 12906 | // result defined as follows: If both pointers represent the same | |||
| 12907 | // address or are both the null pointer value, the result is true if the | |||
| 12908 | // operator is <= or >= and false otherwise; otherwise the result is | |||
| 12909 | // unspecified. | |||
| 12910 | // We interpret this as applying to pointers to *cv* void. | |||
| 12911 | if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) | |||
| 12912 | Info.CCEDiag(E, diag::note_constexpr_void_comparison); | |||
| 12913 | ||||
| 12914 | // C++11 [expr.rel]p2: | |||
| 12915 | // - If two pointers point to non-static data members of the same object, | |||
| 12916 | // or to subobjects or array elements fo such members, recursively, the | |||
| 12917 | // pointer to the later declared member compares greater provided the | |||
| 12918 | // two members have the same access control and provided their class is | |||
| 12919 | // not a union. | |||
| 12920 | // [...] | |||
| 12921 | // - Otherwise pointer comparisons are unspecified. | |||
| 12922 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { | |||
| 12923 | bool WasArrayIndex; | |||
| 12924 | unsigned Mismatch = FindDesignatorMismatch( | |||
| 12925 | getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); | |||
| 12926 | // At the point where the designators diverge, the comparison has a | |||
| 12927 | // specified value if: | |||
| 12928 | // - we are comparing array indices | |||
| 12929 | // - we are comparing fields of a union, or fields with the same access | |||
| 12930 | // Otherwise, the result is unspecified and thus the comparison is not a | |||
| 12931 | // constant expression. | |||
| 12932 | if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && | |||
| 12933 | Mismatch < RHSDesignator.Entries.size()) { | |||
| 12934 | const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); | |||
| 12935 | const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); | |||
| 12936 | if (!LF && !RF) | |||
| 12937 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); | |||
| 12938 | else if (!LF) | |||
| 12939 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | |||
| 12940 | << getAsBaseClass(LHSDesignator.Entries[Mismatch]) | |||
| 12941 | << RF->getParent() << RF; | |||
| 12942 | else if (!RF) | |||
| 12943 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | |||
| 12944 | << getAsBaseClass(RHSDesignator.Entries[Mismatch]) | |||
| 12945 | << LF->getParent() << LF; | |||
| 12946 | else if (!LF->getParent()->isUnion() && | |||
| 12947 | LF->getAccess() != RF->getAccess()) | |||
| 12948 | Info.CCEDiag(E, | |||
| 12949 | diag::note_constexpr_pointer_comparison_differing_access) | |||
| 12950 | << LF << LF->getAccess() << RF << RF->getAccess() | |||
| 12951 | << LF->getParent(); | |||
| 12952 | } | |||
| 12953 | } | |||
| 12954 | ||||
| 12955 | // The comparison here must be unsigned, and performed with the same | |||
| 12956 | // width as the pointer. | |||
| 12957 | unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); | |||
| 12958 | uint64_t CompareLHS = LHSOffset.getQuantity(); | |||
| 12959 | uint64_t CompareRHS = RHSOffset.getQuantity(); | |||
| 12960 | assert(PtrSize <= 64 && "Unexpected pointer width")(static_cast <bool> (PtrSize <= 64 && "Unexpected pointer width" ) ? void (0) : __assert_fail ("PtrSize <= 64 && \"Unexpected pointer width\"" , "clang/lib/AST/ExprConstant.cpp", 12960, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12961 | uint64_t Mask = ~0ULL >> (64 - PtrSize); | |||
| 12962 | CompareLHS &= Mask; | |||
| 12963 | CompareRHS &= Mask; | |||
| 12964 | ||||
| 12965 | // If there is a base and this is a relational operator, we can only | |||
| 12966 | // compare pointers within the object in question; otherwise, the result | |||
| 12967 | // depends on where the object is located in memory. | |||
| 12968 | if (!LHSValue.Base.isNull() && IsRelational) { | |||
| 12969 | QualType BaseTy = getType(LHSValue.Base); | |||
| 12970 | if (BaseTy->isIncompleteType()) | |||
| 12971 | return Error(E); | |||
| 12972 | CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); | |||
| 12973 | uint64_t OffsetLimit = Size.getQuantity(); | |||
| 12974 | if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) | |||
| 12975 | return Error(E); | |||
| 12976 | } | |||
| 12977 | ||||
| 12978 | if (CompareLHS < CompareRHS) | |||
| 12979 | return Success(CmpResult::Less, E); | |||
| 12980 | if (CompareLHS > CompareRHS) | |||
| 12981 | return Success(CmpResult::Greater, E); | |||
| 12982 | return Success(CmpResult::Equal, E); | |||
| 12983 | } | |||
| 12984 | ||||
| 12985 | if (LHSTy->isMemberPointerType()) { | |||
| 12986 | assert(IsEquality && "unexpected member pointer operation")(static_cast <bool> (IsEquality && "unexpected member pointer operation" ) ? void (0) : __assert_fail ("IsEquality && \"unexpected member pointer operation\"" , "clang/lib/AST/ExprConstant.cpp", 12986, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12987 | assert(RHSTy->isMemberPointerType() && "invalid comparison")(static_cast <bool> (RHSTy->isMemberPointerType() && "invalid comparison") ? void (0) : __assert_fail ("RHSTy->isMemberPointerType() && \"invalid comparison\"" , "clang/lib/AST/ExprConstant.cpp", 12987, __extension__ __PRETTY_FUNCTION__ )); | |||
| 12988 | ||||
| 12989 | MemberPtr LHSValue, RHSValue; | |||
| 12990 | ||||
| 12991 | bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); | |||
| 12992 | if (!LHSOK && !Info.noteFailure()) | |||
| 12993 | return false; | |||
| 12994 | ||||
| 12995 | if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) | |||
| 12996 | return false; | |||
| 12997 | ||||
| 12998 | // C++11 [expr.eq]p2: | |||
| 12999 | // If both operands are null, they compare equal. Otherwise if only one is | |||
| 13000 | // null, they compare unequal. | |||
| 13001 | if (!LHSValue.getDecl() || !RHSValue.getDecl()) { | |||
| 13002 | bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); | |||
| 13003 | return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); | |||
| 13004 | } | |||
| 13005 | ||||
| 13006 | // Otherwise if either is a pointer to a virtual member function, the | |||
| 13007 | // result is unspecified. | |||
| 13008 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) | |||
| 13009 | if (MD->isVirtual()) | |||
| 13010 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | |||
| 13011 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) | |||
| 13012 | if (MD->isVirtual()) | |||
| 13013 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | |||
| 13014 | ||||
| 13015 | // Otherwise they compare equal if and only if they would refer to the | |||
| 13016 | // same member of the same most derived object or the same subobject if | |||
| 13017 | // they were dereferenced with a hypothetical object of the associated | |||
| 13018 | // class type. | |||
| 13019 | bool Equal = LHSValue == RHSValue; | |||
| 13020 | return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); | |||
| 13021 | } | |||
| 13022 | ||||
| 13023 | if (LHSTy->isNullPtrType()) { | |||
| 13024 | assert(E->isComparisonOp() && "unexpected nullptr operation")(static_cast <bool> (E->isComparisonOp() && "unexpected nullptr operation" ) ? void (0) : __assert_fail ("E->isComparisonOp() && \"unexpected nullptr operation\"" , "clang/lib/AST/ExprConstant.cpp", 13024, __extension__ __PRETTY_FUNCTION__ )); | |||
| 13025 | assert(RHSTy->isNullPtrType() && "missing pointer conversion")(static_cast <bool> (RHSTy->isNullPtrType() && "missing pointer conversion") ? void (0) : __assert_fail ("RHSTy->isNullPtrType() && \"missing pointer conversion\"" , "clang/lib/AST/ExprConstant.cpp", 13025, __extension__ __PRETTY_FUNCTION__ )); | |||
| 13026 | // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t | |||
| 13027 | // are compared, the result is true of the operator is <=, >= or ==, and | |||
| 13028 | // false otherwise. | |||
| 13029 | return Success(CmpResult::Equal, E); | |||
| 13030 | } | |||
| 13031 | ||||
| 13032 | return DoAfter(); | |||
| 13033 | } | |||
| 13034 | ||||
| 13035 | bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { | |||
| 13036 | if (!CheckLiteralType(Info, E)) | |||
| 13037 | return false; | |||
| 13038 | ||||
| 13039 | auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { | |||
| 13040 | ComparisonCategoryResult CCR; | |||
| 13041 | switch (CR) { | |||
| 13042 | case CmpResult::Unequal: | |||
| 13043 | llvm_unreachable("should never produce Unequal for three-way comparison")::llvm::llvm_unreachable_internal("should never produce Unequal for three-way comparison" , "clang/lib/AST/ExprConstant.cpp", 13043); | |||
| 13044 | case CmpResult::Less: | |||
| 13045 | CCR = ComparisonCategoryResult::Less; | |||
| 13046 | break; | |||
| 13047 | case CmpResult::Equal: | |||
| 13048 | CCR = ComparisonCategoryResult::Equal; | |||
| 13049 | break; | |||
| 13050 | case CmpResult::Greater: | |||
| 13051 | CCR = ComparisonCategoryResult::Greater; | |||
| 13052 | break; | |||
| 13053 | case CmpResult::Unordered: | |||
| 13054 | CCR = ComparisonCategoryResult::Unordered; | |||
| 13055 | break; | |||
| 13056 | } | |||
| 13057 | // Evaluation succeeded. Lookup the information for the comparison category | |||
| 13058 | // type and fetch the VarDecl for the result. | |||
| 13059 | const ComparisonCategoryInfo &CmpInfo = | |||
| 13060 | Info.Ctx.CompCategories.getInfoForType(E->getType()); | |||
| 13061 | const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; | |||
| 13062 | // Check and evaluate the result as a constant expression. | |||
| 13063 | LValue LV; | |||
| 13064 | LV.set(VD); | |||
| 13065 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | |||
| 13066 | return false; | |||
| 13067 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, | |||
| 13068 | ConstantExprKind::Normal); | |||
| 13069 | }; | |||
| 13070 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | |||
| 13071 | return ExprEvaluatorBaseTy::VisitBinCmp(E); | |||
| 13072 | }); | |||
| 13073 | } | |||
| 13074 | ||||
| 13075 | bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | |||
| 13076 | // We don't support assignment in C. C++ assignments don't get here because | |||
| 13077 | // assignment is an lvalue in C++. | |||
| 13078 | if (E->isAssignmentOp()) { | |||
| 13079 | Error(E); | |||
| 13080 | if (!Info.noteFailure()) | |||
| 13081 | return false; | |||
| 13082 | } | |||
| 13083 | ||||
| 13084 | if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) | |||
| 13085 | return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); | |||
| 13086 | ||||
| 13087 | assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||(static_cast <bool> ((!E->getLHS()->getType()-> isIntegralOrEnumerationType() || !E->getRHS()->getType( )->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "clang/lib/AST/ExprConstant.cpp", 13089, __extension__ __PRETTY_FUNCTION__ )) | |||
| 13088 | !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&(static_cast <bool> ((!E->getLHS()->getType()-> isIntegralOrEnumerationType() || !E->getRHS()->getType( )->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "clang/lib/AST/ExprConstant.cpp", 13089, __extension__ __PRETTY_FUNCTION__ )) | |||
| 13089 | "DataRecursiveIntBinOpEvaluator should have handled integral types")(static_cast <bool> ((!E->getLHS()->getType()-> isIntegralOrEnumerationType() || !E->getRHS()->getType( )->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "clang/lib/AST/ExprConstant.cpp", 13089, __extension__ __PRETTY_FUNCTION__ )); | |||
| 13090 | ||||
| 13091 | if (E->isComparisonOp()) { | |||
| 13092 | // Evaluate builtin binary comparisons by evaluating them as three-way | |||
| 13093 | // comparisons and then translating the result. | |||
| 13094 | auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { | |||
| 13095 | assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&(static_cast <bool> ((CR != CmpResult::Unequal || E-> isEqualityOp()) && "should only produce Unequal for equality comparisons" ) ? void (0) : __assert_fail ("(CR != CmpResult::Unequal || E->isEqualityOp()) && \"should only produce Unequal for equality comparisons\"" , "clang/lib/AST/ExprConstant.cpp", 13096, __extension__ __PRETTY_FUNCTION__ )) | |||
| 13096 | "should only produce Unequal for equality comparisons")(static_cast <bool> ((CR != CmpResult::Unequal || E-> isEqualityOp()) && "should only produce Unequal for equality comparisons" ) ? void (0) : __assert_fail ("(CR != CmpResult::Unequal || E->isEqualityOp()) && \"should only produce Unequal for equality comparisons\"" , "clang/lib/AST/ExprConstant.cpp", 13096, __extension__ __PRETTY_FUNCTION__ )); | |||
| 13097 | bool IsEqual = CR == CmpResult::Equal, | |||
| 13098 | IsLess = CR == CmpResult::Less, | |||
| 13099 | IsGreater = CR == CmpResult::Greater; | |||
| 13100 | auto Op = E->getOpcode(); | |||
| 13101 | switch (Op) { | |||
| 13102 | default: | |||
| 13103 | llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator" , "clang/lib/AST/ExprConstant.cpp", 13103); | |||
| 13104 | case BO_EQ: | |||
| 13105 | case BO_NE: | |||
| 13106 | return Success(IsEqual == (Op == BO_EQ), E); | |||
| 13107 | case BO_LT: | |||
| 13108 | return Success(IsLess, E); | |||
| 13109 | case BO_GT: | |||
| 13110 | return Success(IsGreater, E); | |||
| 13111 | case BO_LE: | |||
| 13112 | return Success(IsEqual || IsLess, E); | |||
| 13113 | case BO_GE: | |||
| 13114 | return Success(IsEqual || IsGreater, E); | |||
| 13115 | } | |||
| 13116 | }; | |||
| 13117 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | |||
| 13118 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 13119 | }); | |||
| 13120 | } | |||
| 13121 | ||||
| 13122 | QualType LHSTy = E->getLHS()->getType(); | |||
| 13123 | QualType RHSTy = E->getRHS()->getType(); | |||
| 13124 | ||||
| 13125 | if (LHSTy->isPointerType() && RHSTy->isPointerType() && | |||
| 13126 | E->getOpcode() == BO_Sub) { | |||
| 13127 | LValue LHSValue, RHSValue; | |||
| 13128 | ||||
| 13129 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | |||
| 13130 | if (!LHSOK && !Info.noteFailure()) | |||
| 13131 | return false; | |||
| 13132 | ||||
| 13133 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) | |||
| 13134 | return false; | |||
| 13135 | ||||
| 13136 | // Reject differing bases from the normal codepath; we special-case | |||
| 13137 | // comparisons to null. | |||
| 13138 | if (!HasSameBase(LHSValue, RHSValue)) { | |||
| 13139 | // Handle &&A - &&B. | |||
| 13140 | if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) | |||
| 13141 | return Error(E); | |||
| 13142 | const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); | |||
| 13143 | const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); | |||
| 13144 | if (!LHSExpr || !RHSExpr) | |||
| 13145 | return Error(E); | |||
| 13146 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | |||
| 13147 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | |||
| 13148 | if (!LHSAddrExpr || !RHSAddrExpr) | |||
| 13149 | return Error(E); | |||
| 13150 | // Make sure both labels come from the same function. | |||
| 13151 | if (LHSAddrExpr->getLabel()->getDeclContext() != | |||
| 13152 | RHSAddrExpr->getLabel()->getDeclContext()) | |||
| 13153 | return Error(E); | |||
| 13154 | return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); | |||
| 13155 | } | |||
| 13156 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | |||
| 13157 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | |||
| 13158 | ||||
| 13159 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | |||
| 13160 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | |||
| 13161 | ||||
| 13162 | // C++11 [expr.add]p6: | |||
| 13163 | // Unless both pointers point to elements of the same array object, or | |||
| 13164 | // one past the last element of the array object, the behavior is | |||
| 13165 | // undefined. | |||
| 13166 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && | |||
| 13167 | !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, | |||
| 13168 | RHSDesignator)) | |||
| 13169 | Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); | |||
| 13170 | ||||
| 13171 | QualType Type = E->getLHS()->getType(); | |||
| 13172 | QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); | |||
| 13173 | ||||
| 13174 | CharUnits ElementSize; | |||
| 13175 | if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) | |||
| 13176 | return false; | |||
| 13177 | ||||
| 13178 | // As an extension, a type may have zero size (empty struct or union in | |||
| 13179 | // C, array of zero length). Pointer subtraction in such cases has | |||
| 13180 | // undefined behavior, so is not constant. | |||
| 13181 | if (ElementSize.isZero()) { | |||
| 13182 | Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) | |||
| 13183 | << ElementType; | |||
| 13184 | return false; | |||
| 13185 | } | |||
| 13186 | ||||
| 13187 | // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, | |||
| 13188 | // and produce incorrect results when it overflows. Such behavior | |||
| 13189 | // appears to be non-conforming, but is common, so perhaps we should | |||
| 13190 | // assume the standard intended for such cases to be undefined behavior | |||
| 13191 | // and check for them. | |||
| 13192 | ||||
| 13193 | // Compute (LHSOffset - RHSOffset) / Size carefully, checking for | |||
| 13194 | // overflow in the final conversion to ptrdiff_t. | |||
| 13195 | APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); | |||
| 13196 | APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); | |||
| 13197 | APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), | |||
| 13198 | false); | |||
| 13199 | APSInt TrueResult = (LHS - RHS) / ElemSize; | |||
| 13200 | APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); | |||
| 13201 | ||||
| 13202 | if (Result.extend(65) != TrueResult && | |||
| 13203 | !HandleOverflow(Info, E, TrueResult, E->getType())) | |||
| 13204 | return false; | |||
| 13205 | return Success(Result, E); | |||
| 13206 | } | |||
| 13207 | ||||
| 13208 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 13209 | } | |||
| 13210 | ||||
| 13211 | /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with | |||
| 13212 | /// a result as the expression's type. | |||
| 13213 | bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( | |||
| 13214 | const UnaryExprOrTypeTraitExpr *E) { | |||
| 13215 | switch(E->getKind()) { | |||
| 13216 | case UETT_PreferredAlignOf: | |||
| 13217 | case UETT_AlignOf: { | |||
| 13218 | if (E->isArgumentType()) | |||
| 13219 | return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), | |||
| 13220 | E); | |||
| 13221 | else | |||
| 13222 | return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), | |||
| 13223 | E); | |||
| 13224 | } | |||
| 13225 | ||||
| 13226 | case UETT_VecStep: { | |||
| 13227 | QualType Ty = E->getTypeOfArgument(); | |||
| 13228 | ||||
| 13229 | if (Ty->isVectorType()) { | |||
| 13230 | unsigned n = Ty->castAs<VectorType>()->getNumElements(); | |||
| 13231 | ||||
| 13232 | // The vec_step built-in functions that take a 3-component | |||
| 13233 | // vector return 4. (OpenCL 1.1 spec 6.11.12) | |||
| 13234 | if (n == 3) | |||
| 13235 | n = 4; | |||
| 13236 | ||||
| 13237 | return Success(n, E); | |||
| 13238 | } else | |||
| 13239 | return Success(1, E); | |||
| 13240 | } | |||
| 13241 | ||||
| 13242 | case UETT_SizeOf: { | |||
| 13243 | QualType SrcTy = E->getTypeOfArgument(); | |||
| 13244 | // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, | |||
| 13245 | // the result is the size of the referenced type." | |||
| 13246 | if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) | |||
| 13247 | SrcTy = Ref->getPointeeType(); | |||
| 13248 | ||||
| 13249 | CharUnits Sizeof; | |||
| 13250 | if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) | |||
| 13251 | return false; | |||
| 13252 | return Success(Sizeof, E); | |||
| 13253 | } | |||
| 13254 | case UETT_OpenMPRequiredSimdAlign: | |||
| 13255 | assert(E->isArgumentType())(static_cast <bool> (E->isArgumentType()) ? void (0) : __assert_fail ("E->isArgumentType()", "clang/lib/AST/ExprConstant.cpp" , 13255, __extension__ __PRETTY_FUNCTION__)); | |||
| 13256 | return Success( | |||
| 13257 | Info.Ctx.toCharUnitsFromBits( | |||
| 13258 | Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) | |||
| 13259 | .getQuantity(), | |||
| 13260 | E); | |||
| 13261 | } | |||
| 13262 | ||||
| 13263 | llvm_unreachable("unknown expr/type trait")::llvm::llvm_unreachable_internal("unknown expr/type trait", "clang/lib/AST/ExprConstant.cpp" , 13263); | |||
| 13264 | } | |||
| 13265 | ||||
| 13266 | bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { | |||
| 13267 | CharUnits Result; | |||
| 13268 | unsigned n = OOE->getNumComponents(); | |||
| 13269 | if (n == 0) | |||
| 13270 | return Error(OOE); | |||
| 13271 | QualType CurrentType = OOE->getTypeSourceInfo()->getType(); | |||
| 13272 | for (unsigned i = 0; i != n; ++i) { | |||
| 13273 | OffsetOfNode ON = OOE->getComponent(i); | |||
| 13274 | switch (ON.getKind()) { | |||
| 13275 | case OffsetOfNode::Array: { | |||
| 13276 | const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); | |||
| 13277 | APSInt IdxResult; | |||
| 13278 | if (!EvaluateInteger(Idx, IdxResult, Info)) | |||
| 13279 | return false; | |||
| 13280 | const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); | |||
| 13281 | if (!AT) | |||
| 13282 | return Error(OOE); | |||
| 13283 | CurrentType = AT->getElementType(); | |||
| 13284 | CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); | |||
| 13285 | Result += IdxResult.getSExtValue() * ElementSize; | |||
| 13286 | break; | |||
| 13287 | } | |||
| 13288 | ||||
| 13289 | case OffsetOfNode::Field: { | |||
| 13290 | FieldDecl *MemberDecl = ON.getField(); | |||
| 13291 | const RecordType *RT = CurrentType->getAs<RecordType>(); | |||
| 13292 | if (!RT) | |||
| 13293 | return Error(OOE); | |||
| 13294 | RecordDecl *RD = RT->getDecl(); | |||
| 13295 | if (RD->isInvalidDecl()) return false; | |||
| 13296 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | |||
| 13297 | unsigned i = MemberDecl->getFieldIndex(); | |||
| 13298 | assert(i < RL.getFieldCount() && "offsetof field in wrong type")(static_cast <bool> (i < RL.getFieldCount() && "offsetof field in wrong type") ? void (0) : __assert_fail ( "i < RL.getFieldCount() && \"offsetof field in wrong type\"" , "clang/lib/AST/ExprConstant.cpp", 13298, __extension__ __PRETTY_FUNCTION__ )); | |||
| 13299 | Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); | |||
| 13300 | CurrentType = MemberDecl->getType().getNonReferenceType(); | |||
| 13301 | break; | |||
| 13302 | } | |||
| 13303 | ||||
| 13304 | case OffsetOfNode::Identifier: | |||
| 13305 | llvm_unreachable("dependent __builtin_offsetof")::llvm::llvm_unreachable_internal("dependent __builtin_offsetof" , "clang/lib/AST/ExprConstant.cpp", 13305); | |||
| 13306 | ||||
| 13307 | case OffsetOfNode::Base: { | |||
| 13308 | CXXBaseSpecifier *BaseSpec = ON.getBase(); | |||
| 13309 | if (BaseSpec->isVirtual()) | |||
| 13310 | return Error(OOE); | |||
| 13311 | ||||
| 13312 | // Find the layout of the class whose base we are looking into. | |||
| 13313 | const RecordType *RT = CurrentType->getAs<RecordType>(); | |||
| 13314 | if (!RT) | |||
| 13315 | return Error(OOE); | |||
| 13316 | RecordDecl *RD = RT->getDecl(); | |||
| 13317 | if (RD->isInvalidDecl()) return false; | |||
| 13318 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | |||
| 13319 | ||||
| 13320 | // Find the base class itself. | |||
| 13321 | CurrentType = BaseSpec->getType(); | |||
| 13322 | const RecordType *BaseRT = CurrentType->getAs<RecordType>(); | |||
| 13323 | if (!BaseRT) | |||
| 13324 | return Error(OOE); | |||
| 13325 | ||||
| 13326 | // Add the offset to the base. | |||
| 13327 | Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); | |||
| 13328 | break; | |||
| 13329 | } | |||
| 13330 | } | |||
| 13331 | } | |||
| 13332 | return Success(Result, OOE); | |||
| 13333 | } | |||
| 13334 | ||||
| 13335 | bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | |||
| 13336 | switch (E->getOpcode()) { | |||
| 13337 | default: | |||
| 13338 | // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. | |||
| 13339 | // See C99 6.6p3. | |||
| 13340 | return Error(E); | |||
| 13341 | case UO_Extension: | |||
| 13342 | // FIXME: Should extension allow i-c-e extension expressions in its scope? | |||
| 13343 | // If so, we could clear the diagnostic ID. | |||
| 13344 | return Visit(E->getSubExpr()); | |||
| 13345 | case UO_Plus: | |||
| 13346 | // The result is just the value. | |||
| 13347 | return Visit(E->getSubExpr()); | |||
| 13348 | case UO_Minus: { | |||
| 13349 | if (!Visit(E->getSubExpr())) | |||
| 13350 | return false; | |||
| 13351 | if (!Result.isInt()) return Error(E); | |||
| 13352 | const APSInt &Value = Result.getInt(); | |||
| 13353 | if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && | |||
| 13354 | !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), | |||
| 13355 | E->getType())) | |||
| 13356 | return false; | |||
| 13357 | return Success(-Value, E); | |||
| 13358 | } | |||
| 13359 | case UO_Not: { | |||
| 13360 | if (!Visit(E->getSubExpr())) | |||
| 13361 | return false; | |||
| 13362 | if (!Result.isInt()) return Error(E); | |||
| 13363 | return Success(~Result.getInt(), E); | |||
| 13364 | } | |||
| 13365 | case UO_LNot: { | |||
| 13366 | bool bres; | |||
| 13367 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | |||
| 13368 | return false; | |||
| 13369 | return Success(!bres, E); | |||
| 13370 | } | |||
| 13371 | } | |||
| 13372 | } | |||
| 13373 | ||||
| 13374 | /// HandleCast - This is used to evaluate implicit or explicit casts where the | |||
| 13375 | /// result type is integer. | |||
| 13376 | bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 13377 | const Expr *SubExpr = E->getSubExpr(); | |||
| 13378 | QualType DestType = E->getType(); | |||
| 13379 | QualType SrcType = SubExpr->getType(); | |||
| 13380 | ||||
| 13381 | switch (E->getCastKind()) { | |||
| 13382 | case CK_BaseToDerived: | |||
| 13383 | case CK_DerivedToBase: | |||
| 13384 | case CK_UncheckedDerivedToBase: | |||
| 13385 | case CK_Dynamic: | |||
| 13386 | case CK_ToUnion: | |||
| 13387 | case CK_ArrayToPointerDecay: | |||
| 13388 | case CK_FunctionToPointerDecay: | |||
| 13389 | case CK_NullToPointer: | |||
| 13390 | case CK_NullToMemberPointer: | |||
| 13391 | case CK_BaseToDerivedMemberPointer: | |||
| 13392 | case CK_DerivedToBaseMemberPointer: | |||
| 13393 | case CK_ReinterpretMemberPointer: | |||
| 13394 | case CK_ConstructorConversion: | |||
| 13395 | case CK_IntegralToPointer: | |||
| 13396 | case CK_ToVoid: | |||
| 13397 | case CK_VectorSplat: | |||
| 13398 | case CK_IntegralToFloating: | |||
| 13399 | case CK_FloatingCast: | |||
| 13400 | case CK_CPointerToObjCPointerCast: | |||
| 13401 | case CK_BlockPointerToObjCPointerCast: | |||
| 13402 | case CK_AnyPointerToBlockPointerCast: | |||
| 13403 | case CK_ObjCObjectLValueCast: | |||
| 13404 | case CK_FloatingRealToComplex: | |||
| 13405 | case CK_FloatingComplexToReal: | |||
| 13406 | case CK_FloatingComplexCast: | |||
| 13407 | case CK_FloatingComplexToIntegralComplex: | |||
| 13408 | case CK_IntegralRealToComplex: | |||
| 13409 | case CK_IntegralComplexCast: | |||
| 13410 | case CK_IntegralComplexToFloatingComplex: | |||
| 13411 | case CK_BuiltinFnToFnPtr: | |||
| 13412 | case CK_ZeroToOCLOpaqueType: | |||
| 13413 | case CK_NonAtomicToAtomic: | |||
| 13414 | case CK_AddressSpaceConversion: | |||
| 13415 | case CK_IntToOCLSampler: | |||
| 13416 | case CK_FloatingToFixedPoint: | |||
| 13417 | case CK_FixedPointToFloating: | |||
| 13418 | case CK_FixedPointCast: | |||
| 13419 | case CK_IntegralToFixedPoint: | |||
| 13420 | case CK_MatrixCast: | |||
| 13421 | llvm_unreachable("invalid cast kind for integral value")::llvm::llvm_unreachable_internal("invalid cast kind for integral value" , "clang/lib/AST/ExprConstant.cpp", 13421); | |||
| 13422 | ||||
| 13423 | case CK_BitCast: | |||
| 13424 | case CK_Dependent: | |||
| 13425 | case CK_LValueBitCast: | |||
| 13426 | case CK_ARCProduceObject: | |||
| 13427 | case CK_ARCConsumeObject: | |||
| 13428 | case CK_ARCReclaimReturnedObject: | |||
| 13429 | case CK_ARCExtendBlockObject: | |||
| 13430 | case CK_CopyAndAutoreleaseBlockObject: | |||
| 13431 | return Error(E); | |||
| 13432 | ||||
| 13433 | case CK_UserDefinedConversion: | |||
| 13434 | case CK_LValueToRValue: | |||
| 13435 | case CK_AtomicToNonAtomic: | |||
| 13436 | case CK_NoOp: | |||
| 13437 | case CK_LValueToRValueBitCast: | |||
| 13438 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 13439 | ||||
| 13440 | case CK_MemberPointerToBoolean: | |||
| 13441 | case CK_PointerToBoolean: | |||
| 13442 | case CK_IntegralToBoolean: | |||
| 13443 | case CK_FloatingToBoolean: | |||
| 13444 | case CK_BooleanToSignedIntegral: | |||
| 13445 | case CK_FloatingComplexToBoolean: | |||
| 13446 | case CK_IntegralComplexToBoolean: { | |||
| 13447 | bool BoolResult; | |||
| 13448 | if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) | |||
| 13449 | return false; | |||
| 13450 | uint64_t IntResult = BoolResult; | |||
| 13451 | if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) | |||
| 13452 | IntResult = (uint64_t)-1; | |||
| 13453 | return Success(IntResult, E); | |||
| 13454 | } | |||
| 13455 | ||||
| 13456 | case CK_FixedPointToIntegral: { | |||
| 13457 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); | |||
| 13458 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | |||
| 13459 | return false; | |||
| 13460 | bool Overflowed; | |||
| 13461 | llvm::APSInt Result = Src.convertToInt( | |||
| 13462 | Info.Ctx.getIntWidth(DestType), | |||
| 13463 | DestType->isSignedIntegerOrEnumerationType(), &Overflowed); | |||
| 13464 | if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) | |||
| 13465 | return false; | |||
| 13466 | return Success(Result, E); | |||
| 13467 | } | |||
| 13468 | ||||
| 13469 | case CK_FixedPointToBoolean: { | |||
| 13470 | // Unsigned padding does not affect this. | |||
| 13471 | APValue Val; | |||
| 13472 | if (!Evaluate(Val, Info, SubExpr)) | |||
| 13473 | return false; | |||
| 13474 | return Success(Val.getFixedPoint().getBoolValue(), E); | |||
| 13475 | } | |||
| 13476 | ||||
| 13477 | case CK_IntegralCast: { | |||
| 13478 | if (!Visit(SubExpr)) | |||
| 13479 | return false; | |||
| 13480 | ||||
| 13481 | if (!Result.isInt()) { | |||
| 13482 | // Allow casts of address-of-label differences if they are no-ops | |||
| 13483 | // or narrowing. (The narrowing case isn't actually guaranteed to | |||
| 13484 | // be constant-evaluatable except in some narrow cases which are hard | |||
| 13485 | // to detect here. We let it through on the assumption the user knows | |||
| 13486 | // what they are doing.) | |||
| 13487 | if (Result.isAddrLabelDiff()) | |||
| 13488 | return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); | |||
| 13489 | // Only allow casts of lvalues if they are lossless. | |||
| 13490 | return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); | |||
| 13491 | } | |||
| 13492 | ||||
| 13493 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, | |||
| 13494 | Result.getInt()), E); | |||
| 13495 | } | |||
| 13496 | ||||
| 13497 | case CK_PointerToIntegral: { | |||
| 13498 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | |||
| 13499 | ||||
| 13500 | LValue LV; | |||
| 13501 | if (!EvaluatePointer(SubExpr, LV, Info)) | |||
| 13502 | return false; | |||
| 13503 | ||||
| 13504 | if (LV.getLValueBase()) { | |||
| 13505 | // Only allow based lvalue casts if they are lossless. | |||
| 13506 | // FIXME: Allow a larger integer size than the pointer size, and allow | |||
| 13507 | // narrowing back down to pointer width in subsequent integral casts. | |||
| 13508 | // FIXME: Check integer type's active bits, not its type size. | |||
| 13509 | if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) | |||
| 13510 | return Error(E); | |||
| 13511 | ||||
| 13512 | LV.Designator.setInvalid(); | |||
| 13513 | LV.moveInto(Result); | |||
| 13514 | return true; | |||
| 13515 | } | |||
| 13516 | ||||
| 13517 | APSInt AsInt; | |||
| 13518 | APValue V; | |||
| 13519 | LV.moveInto(V); | |||
| 13520 | if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) | |||
| 13521 | llvm_unreachable("Can't cast this!")::llvm::llvm_unreachable_internal("Can't cast this!", "clang/lib/AST/ExprConstant.cpp" , 13521); | |||
| 13522 | ||||
| 13523 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); | |||
| 13524 | } | |||
| 13525 | ||||
| 13526 | case CK_IntegralComplexToReal: { | |||
| 13527 | ComplexValue C; | |||
| 13528 | if (!EvaluateComplex(SubExpr, C, Info)) | |||
| 13529 | return false; | |||
| 13530 | return Success(C.getComplexIntReal(), E); | |||
| 13531 | } | |||
| 13532 | ||||
| 13533 | case CK_FloatingToIntegral: { | |||
| 13534 | APFloat F(0.0); | |||
| 13535 | if (!EvaluateFloat(SubExpr, F, Info)) | |||
| 13536 | return false; | |||
| 13537 | ||||
| 13538 | APSInt Value; | |||
| 13539 | if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) | |||
| 13540 | return false; | |||
| 13541 | return Success(Value, E); | |||
| 13542 | } | |||
| 13543 | } | |||
| 13544 | ||||
| 13545 | llvm_unreachable("unknown cast resulting in integral value")::llvm::llvm_unreachable_internal("unknown cast resulting in integral value" , "clang/lib/AST/ExprConstant.cpp", 13545); | |||
| 13546 | } | |||
| 13547 | ||||
| 13548 | bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | |||
| 13549 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | |||
| 13550 | ComplexValue LV; | |||
| 13551 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | |||
| 13552 | return false; | |||
| 13553 | if (!LV.isComplexInt()) | |||
| 13554 | return Error(E); | |||
| 13555 | return Success(LV.getComplexIntReal(), E); | |||
| 13556 | } | |||
| 13557 | ||||
| 13558 | return Visit(E->getSubExpr()); | |||
| 13559 | } | |||
| 13560 | ||||
| 13561 | bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | |||
| 13562 | if (E->getSubExpr()->getType()->isComplexIntegerType()) { | |||
| 13563 | ComplexValue LV; | |||
| 13564 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | |||
| 13565 | return false; | |||
| 13566 | if (!LV.isComplexInt()) | |||
| 13567 | return Error(E); | |||
| 13568 | return Success(LV.getComplexIntImag(), E); | |||
| 13569 | } | |||
| 13570 | ||||
| 13571 | VisitIgnoredValue(E->getSubExpr()); | |||
| 13572 | return Success(0, E); | |||
| 13573 | } | |||
| 13574 | ||||
| 13575 | bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { | |||
| 13576 | return Success(E->getPackLength(), E); | |||
| 13577 | } | |||
| 13578 | ||||
| 13579 | bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { | |||
| 13580 | return Success(E->getValue(), E); | |||
| 13581 | } | |||
| 13582 | ||||
| 13583 | bool IntExprEvaluator::VisitConceptSpecializationExpr( | |||
| 13584 | const ConceptSpecializationExpr *E) { | |||
| 13585 | return Success(E->isSatisfied(), E); | |||
| 13586 | } | |||
| 13587 | ||||
| 13588 | bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { | |||
| 13589 | return Success(E->isSatisfied(), E); | |||
| 13590 | } | |||
| 13591 | ||||
| 13592 | bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | |||
| 13593 | switch (E->getOpcode()) { | |||
| 13594 | default: | |||
| 13595 | // Invalid unary operators | |||
| 13596 | return Error(E); | |||
| 13597 | case UO_Plus: | |||
| 13598 | // The result is just the value. | |||
| 13599 | return Visit(E->getSubExpr()); | |||
| 13600 | case UO_Minus: { | |||
| 13601 | if (!Visit(E->getSubExpr())) return false; | |||
| 13602 | if (!Result.isFixedPoint()) | |||
| 13603 | return Error(E); | |||
| 13604 | bool Overflowed; | |||
| 13605 | APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); | |||
| 13606 | if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) | |||
| 13607 | return false; | |||
| 13608 | return Success(Negated, E); | |||
| 13609 | } | |||
| 13610 | case UO_LNot: { | |||
| 13611 | bool bres; | |||
| 13612 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | |||
| 13613 | return false; | |||
| 13614 | return Success(!bres, E); | |||
| 13615 | } | |||
| 13616 | } | |||
| 13617 | } | |||
| 13618 | ||||
| 13619 | bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 13620 | const Expr *SubExpr = E->getSubExpr(); | |||
| 13621 | QualType DestType = E->getType(); | |||
| 13622 | assert(DestType->isFixedPointType() &&(static_cast <bool> (DestType->isFixedPointType() && "Expected destination type to be a fixed point type") ? void (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "clang/lib/AST/ExprConstant.cpp", 13623, __extension__ __PRETTY_FUNCTION__ )) | |||
| 13623 | "Expected destination type to be a fixed point type")(static_cast <bool> (DestType->isFixedPointType() && "Expected destination type to be a fixed point type") ? void (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "clang/lib/AST/ExprConstant.cpp", 13623, __extension__ __PRETTY_FUNCTION__ )); | |||
| 13624 | auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); | |||
| 13625 | ||||
| 13626 | switch (E->getCastKind()) { | |||
| 13627 | case CK_FixedPointCast: { | |||
| 13628 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); | |||
| 13629 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | |||
| 13630 | return false; | |||
| 13631 | bool Overflowed; | |||
| 13632 | APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); | |||
| 13633 | if (Overflowed) { | |||
| 13634 | if (Info.checkingForUndefinedBehavior()) | |||
| 13635 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | |||
| 13636 | diag::warn_fixedpoint_constant_overflow) | |||
| 13637 | << Result.toString() << E->getType(); | |||
| 13638 | if (!HandleOverflow(Info, E, Result, E->getType())) | |||
| 13639 | return false; | |||
| 13640 | } | |||
| 13641 | return Success(Result, E); | |||
| 13642 | } | |||
| 13643 | case CK_IntegralToFixedPoint: { | |||
| 13644 | APSInt Src; | |||
| 13645 | if (!EvaluateInteger(SubExpr, Src, Info)) | |||
| 13646 | return false; | |||
| 13647 | ||||
| 13648 | bool Overflowed; | |||
| 13649 | APFixedPoint IntResult = APFixedPoint::getFromIntValue( | |||
| 13650 | Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); | |||
| 13651 | ||||
| 13652 | if (Overflowed) { | |||
| 13653 | if (Info.checkingForUndefinedBehavior()) | |||
| 13654 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | |||
| 13655 | diag::warn_fixedpoint_constant_overflow) | |||
| 13656 | << IntResult.toString() << E->getType(); | |||
| 13657 | if (!HandleOverflow(Info, E, IntResult, E->getType())) | |||
| 13658 | return false; | |||
| 13659 | } | |||
| 13660 | ||||
| 13661 | return Success(IntResult, E); | |||
| 13662 | } | |||
| 13663 | case CK_FloatingToFixedPoint: { | |||
| 13664 | APFloat Src(0.0); | |||
| 13665 | if (!EvaluateFloat(SubExpr, Src, Info)) | |||
| 13666 | return false; | |||
| 13667 | ||||
| 13668 | bool Overflowed; | |||
| 13669 | APFixedPoint Result = APFixedPoint::getFromFloatValue( | |||
| 13670 | Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); | |||
| 13671 | ||||
| 13672 | if (Overflowed) { | |||
| 13673 | if (Info.checkingForUndefinedBehavior()) | |||
| 13674 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | |||
| 13675 | diag::warn_fixedpoint_constant_overflow) | |||
| 13676 | << Result.toString() << E->getType(); | |||
| 13677 | if (!HandleOverflow(Info, E, Result, E->getType())) | |||
| 13678 | return false; | |||
| 13679 | } | |||
| 13680 | ||||
| 13681 | return Success(Result, E); | |||
| 13682 | } | |||
| 13683 | case CK_NoOp: | |||
| 13684 | case CK_LValueToRValue: | |||
| 13685 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 13686 | default: | |||
| 13687 | return Error(E); | |||
| 13688 | } | |||
| 13689 | } | |||
| 13690 | ||||
| 13691 | bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | |||
| 13692 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | |||
| 13693 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 13694 | ||||
| 13695 | const Expr *LHS = E->getLHS(); | |||
| 13696 | const Expr *RHS = E->getRHS(); | |||
| 13697 | FixedPointSemantics ResultFXSema = | |||
| 13698 | Info.Ctx.getFixedPointSemantics(E->getType()); | |||
| 13699 | ||||
| 13700 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); | |||
| 13701 | if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) | |||
| 13702 | return false; | |||
| 13703 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); | |||
| 13704 | if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) | |||
| 13705 | return false; | |||
| 13706 | ||||
| 13707 | bool OpOverflow = false, ConversionOverflow = false; | |||
| 13708 | APFixedPoint Result(LHSFX.getSemantics()); | |||
| 13709 | switch (E->getOpcode()) { | |||
| 13710 | case BO_Add: { | |||
| 13711 | Result = LHSFX.add(RHSFX, &OpOverflow) | |||
| 13712 | .convert(ResultFXSema, &ConversionOverflow); | |||
| 13713 | break; | |||
| 13714 | } | |||
| 13715 | case BO_Sub: { | |||
| 13716 | Result = LHSFX.sub(RHSFX, &OpOverflow) | |||
| 13717 | .convert(ResultFXSema, &ConversionOverflow); | |||
| 13718 | break; | |||
| 13719 | } | |||
| 13720 | case BO_Mul: { | |||
| 13721 | Result = LHSFX.mul(RHSFX, &OpOverflow) | |||
| 13722 | .convert(ResultFXSema, &ConversionOverflow); | |||
| 13723 | break; | |||
| 13724 | } | |||
| 13725 | case BO_Div: { | |||
| 13726 | if (RHSFX.getValue() == 0) { | |||
| 13727 | Info.FFDiag(E, diag::note_expr_divide_by_zero); | |||
| 13728 | return false; | |||
| 13729 | } | |||
| 13730 | Result = LHSFX.div(RHSFX, &OpOverflow) | |||
| 13731 | .convert(ResultFXSema, &ConversionOverflow); | |||
| 13732 | break; | |||
| 13733 | } | |||
| 13734 | case BO_Shl: | |||
| 13735 | case BO_Shr: { | |||
| 13736 | FixedPointSemantics LHSSema = LHSFX.getSemantics(); | |||
| 13737 | llvm::APSInt RHSVal = RHSFX.getValue(); | |||
| 13738 | ||||
| 13739 | unsigned ShiftBW = | |||
| 13740 | LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); | |||
| 13741 | unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); | |||
| 13742 | // Embedded-C 4.1.6.2.2: | |||
| 13743 | // The right operand must be nonnegative and less than the total number | |||
| 13744 | // of (nonpadding) bits of the fixed-point operand ... | |||
| 13745 | if (RHSVal.isNegative()) | |||
| 13746 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; | |||
| 13747 | else if (Amt != RHSVal) | |||
| 13748 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | |||
| 13749 | << RHSVal << E->getType() << ShiftBW; | |||
| 13750 | ||||
| 13751 | if (E->getOpcode() == BO_Shl) | |||
| 13752 | Result = LHSFX.shl(Amt, &OpOverflow); | |||
| 13753 | else | |||
| 13754 | Result = LHSFX.shr(Amt, &OpOverflow); | |||
| 13755 | break; | |||
| 13756 | } | |||
| 13757 | default: | |||
| 13758 | return false; | |||
| 13759 | } | |||
| 13760 | if (OpOverflow || ConversionOverflow) { | |||
| 13761 | if (Info.checkingForUndefinedBehavior()) | |||
| 13762 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | |||
| 13763 | diag::warn_fixedpoint_constant_overflow) | |||
| 13764 | << Result.toString() << E->getType(); | |||
| 13765 | if (!HandleOverflow(Info, E, Result, E->getType())) | |||
| 13766 | return false; | |||
| 13767 | } | |||
| 13768 | return Success(Result, E); | |||
| 13769 | } | |||
| 13770 | ||||
| 13771 | //===----------------------------------------------------------------------===// | |||
| 13772 | // Float Evaluation | |||
| 13773 | //===----------------------------------------------------------------------===// | |||
| 13774 | ||||
| 13775 | namespace { | |||
| 13776 | class FloatExprEvaluator | |||
| 13777 | : public ExprEvaluatorBase<FloatExprEvaluator> { | |||
| 13778 | APFloat &Result; | |||
| 13779 | public: | |||
| 13780 | FloatExprEvaluator(EvalInfo &info, APFloat &result) | |||
| 13781 | : ExprEvaluatorBaseTy(info), Result(result) {} | |||
| 13782 | ||||
| 13783 | bool Success(const APValue &V, const Expr *e) { | |||
| 13784 | Result = V.getFloat(); | |||
| 13785 | return true; | |||
| 13786 | } | |||
| 13787 | ||||
| 13788 | bool ZeroInitialization(const Expr *E) { | |||
| 13789 | Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); | |||
| 13790 | return true; | |||
| 13791 | } | |||
| 13792 | ||||
| 13793 | bool VisitCallExpr(const CallExpr *E); | |||
| 13794 | ||||
| 13795 | bool VisitUnaryOperator(const UnaryOperator *E); | |||
| 13796 | bool VisitBinaryOperator(const BinaryOperator *E); | |||
| 13797 | bool VisitFloatingLiteral(const FloatingLiteral *E); | |||
| 13798 | bool VisitCastExpr(const CastExpr *E); | |||
| 13799 | ||||
| 13800 | bool VisitUnaryReal(const UnaryOperator *E); | |||
| 13801 | bool VisitUnaryImag(const UnaryOperator *E); | |||
| 13802 | ||||
| 13803 | // FIXME: Missing: array subscript of vector, member of vector | |||
| 13804 | }; | |||
| 13805 | } // end anonymous namespace | |||
| 13806 | ||||
| 13807 | static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { | |||
| 13808 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 13808, __extension__ __PRETTY_FUNCTION__)); | |||
| 13809 | assert(E->isPRValue() && E->getType()->isRealFloatingType())(static_cast <bool> (E->isPRValue() && E-> getType()->isRealFloatingType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRealFloatingType()" , "clang/lib/AST/ExprConstant.cpp", 13809, __extension__ __PRETTY_FUNCTION__ )); | |||
| 13810 | return FloatExprEvaluator(Info, Result).Visit(E); | |||
| 13811 | } | |||
| 13812 | ||||
| 13813 | static bool TryEvaluateBuiltinNaN(const ASTContext &Context, | |||
| 13814 | QualType ResultTy, | |||
| 13815 | const Expr *Arg, | |||
| 13816 | bool SNaN, | |||
| 13817 | llvm::APFloat &Result) { | |||
| 13818 | const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); | |||
| 13819 | if (!S) return false; | |||
| 13820 | ||||
| 13821 | const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); | |||
| 13822 | ||||
| 13823 | llvm::APInt fill; | |||
| 13824 | ||||
| 13825 | // Treat empty strings as if they were zero. | |||
| 13826 | if (S->getString().empty()) | |||
| 13827 | fill = llvm::APInt(32, 0); | |||
| 13828 | else if (S->getString().getAsInteger(0, fill)) | |||
| 13829 | return false; | |||
| 13830 | ||||
| 13831 | if (Context.getTargetInfo().isNan2008()) { | |||
| 13832 | if (SNaN) | |||
| 13833 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | |||
| 13834 | else | |||
| 13835 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | |||
| 13836 | } else { | |||
| 13837 | // Prior to IEEE 754-2008, architectures were allowed to choose whether | |||
| 13838 | // the first bit of their significand was set for qNaN or sNaN. MIPS chose | |||
| 13839 | // a different encoding to what became a standard in 2008, and for pre- | |||
| 13840 | // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as | |||
| 13841 | // sNaN. This is now known as "legacy NaN" encoding. | |||
| 13842 | if (SNaN) | |||
| 13843 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | |||
| 13844 | else | |||
| 13845 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | |||
| 13846 | } | |||
| 13847 | ||||
| 13848 | return true; | |||
| 13849 | } | |||
| 13850 | ||||
| 13851 | bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { | |||
| 13852 | switch (E->getBuiltinCallee()) { | |||
| 13853 | default: | |||
| 13854 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | |||
| 13855 | ||||
| 13856 | case Builtin::BI__builtin_huge_val: | |||
| 13857 | case Builtin::BI__builtin_huge_valf: | |||
| 13858 | case Builtin::BI__builtin_huge_vall: | |||
| 13859 | case Builtin::BI__builtin_huge_valf128: | |||
| 13860 | case Builtin::BI__builtin_inf: | |||
| 13861 | case Builtin::BI__builtin_inff: | |||
| 13862 | case Builtin::BI__builtin_infl: | |||
| 13863 | case Builtin::BI__builtin_inff128: { | |||
| 13864 | const llvm::fltSemantics &Sem = | |||
| 13865 | Info.Ctx.getFloatTypeSemantics(E->getType()); | |||
| 13866 | Result = llvm::APFloat::getInf(Sem); | |||
| 13867 | return true; | |||
| 13868 | } | |||
| 13869 | ||||
| 13870 | case Builtin::BI__builtin_nans: | |||
| 13871 | case Builtin::BI__builtin_nansf: | |||
| 13872 | case Builtin::BI__builtin_nansl: | |||
| 13873 | case Builtin::BI__builtin_nansf128: | |||
| 13874 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | |||
| 13875 | true, Result)) | |||
| 13876 | return Error(E); | |||
| 13877 | return true; | |||
| 13878 | ||||
| 13879 | case Builtin::BI__builtin_nan: | |||
| 13880 | case Builtin::BI__builtin_nanf: | |||
| 13881 | case Builtin::BI__builtin_nanl: | |||
| 13882 | case Builtin::BI__builtin_nanf128: | |||
| 13883 | // If this is __builtin_nan() turn this into a nan, otherwise we | |||
| 13884 | // can't constant fold it. | |||
| 13885 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | |||
| 13886 | false, Result)) | |||
| 13887 | return Error(E); | |||
| 13888 | return true; | |||
| 13889 | ||||
| 13890 | case Builtin::BI__builtin_fabs: | |||
| 13891 | case Builtin::BI__builtin_fabsf: | |||
| 13892 | case Builtin::BI__builtin_fabsl: | |||
| 13893 | case Builtin::BI__builtin_fabsf128: | |||
| 13894 | // The C standard says "fabs raises no floating-point exceptions, | |||
| 13895 | // even if x is a signaling NaN. The returned value is independent of | |||
| 13896 | // the current rounding direction mode." Therefore constant folding can | |||
| 13897 | // proceed without regard to the floating point settings. | |||
| 13898 | // Reference, WG14 N2478 F.10.4.3 | |||
| 13899 | if (!EvaluateFloat(E->getArg(0), Result, Info)) | |||
| 13900 | return false; | |||
| 13901 | ||||
| 13902 | if (Result.isNegative()) | |||
| 13903 | Result.changeSign(); | |||
| 13904 | return true; | |||
| 13905 | ||||
| 13906 | case Builtin::BI__arithmetic_fence: | |||
| 13907 | return EvaluateFloat(E->getArg(0), Result, Info); | |||
| 13908 | ||||
| 13909 | // FIXME: Builtin::BI__builtin_powi | |||
| 13910 | // FIXME: Builtin::BI__builtin_powif | |||
| 13911 | // FIXME: Builtin::BI__builtin_powil | |||
| 13912 | ||||
| 13913 | case Builtin::BI__builtin_copysign: | |||
| 13914 | case Builtin::BI__builtin_copysignf: | |||
| 13915 | case Builtin::BI__builtin_copysignl: | |||
| 13916 | case Builtin::BI__builtin_copysignf128: { | |||
| 13917 | APFloat RHS(0.); | |||
| 13918 | if (!EvaluateFloat(E->getArg(0), Result, Info) || | |||
| 13919 | !EvaluateFloat(E->getArg(1), RHS, Info)) | |||
| 13920 | return false; | |||
| 13921 | Result.copySign(RHS); | |||
| 13922 | return true; | |||
| 13923 | } | |||
| 13924 | } | |||
| 13925 | } | |||
| 13926 | ||||
| 13927 | bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | |||
| 13928 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | |||
| 13929 | ComplexValue CV; | |||
| 13930 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | |||
| 13931 | return false; | |||
| 13932 | Result = CV.FloatReal; | |||
| 13933 | return true; | |||
| 13934 | } | |||
| 13935 | ||||
| 13936 | return Visit(E->getSubExpr()); | |||
| 13937 | } | |||
| 13938 | ||||
| 13939 | bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | |||
| 13940 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | |||
| 13941 | ComplexValue CV; | |||
| 13942 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | |||
| 13943 | return false; | |||
| 13944 | Result = CV.FloatImag; | |||
| 13945 | return true; | |||
| 13946 | } | |||
| 13947 | ||||
| 13948 | VisitIgnoredValue(E->getSubExpr()); | |||
| 13949 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); | |||
| 13950 | Result = llvm::APFloat::getZero(Sem); | |||
| 13951 | return true; | |||
| 13952 | } | |||
| 13953 | ||||
| 13954 | bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | |||
| 13955 | switch (E->getOpcode()) { | |||
| 13956 | default: return Error(E); | |||
| 13957 | case UO_Plus: | |||
| 13958 | return EvaluateFloat(E->getSubExpr(), Result, Info); | |||
| 13959 | case UO_Minus: | |||
| 13960 | // In C standard, WG14 N2478 F.3 p4 | |||
| 13961 | // "the unary - raises no floating point exceptions, | |||
| 13962 | // even if the operand is signalling." | |||
| 13963 | if (!EvaluateFloat(E->getSubExpr(), Result, Info)) | |||
| 13964 | return false; | |||
| 13965 | Result.changeSign(); | |||
| 13966 | return true; | |||
| 13967 | } | |||
| 13968 | } | |||
| 13969 | ||||
| 13970 | bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | |||
| 13971 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | |||
| 13972 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 13973 | ||||
| 13974 | APFloat RHS(0.0); | |||
| 13975 | bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); | |||
| 13976 | if (!LHSOK && !Info.noteFailure()) | |||
| 13977 | return false; | |||
| 13978 | return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && | |||
| 13979 | handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); | |||
| 13980 | } | |||
| 13981 | ||||
| 13982 | bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { | |||
| 13983 | Result = E->getValue(); | |||
| 13984 | return true; | |||
| 13985 | } | |||
| 13986 | ||||
| 13987 | bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 13988 | const Expr* SubExpr = E->getSubExpr(); | |||
| 13989 | ||||
| 13990 | switch (E->getCastKind()) { | |||
| 13991 | default: | |||
| 13992 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 13993 | ||||
| 13994 | case CK_IntegralToFloating: { | |||
| 13995 | APSInt IntResult; | |||
| 13996 | const FPOptions FPO = E->getFPFeaturesInEffect( | |||
| 13997 | Info.Ctx.getLangOpts()); | |||
| 13998 | return EvaluateInteger(SubExpr, IntResult, Info) && | |||
| 13999 | HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), | |||
| 14000 | IntResult, E->getType(), Result); | |||
| 14001 | } | |||
| 14002 | ||||
| 14003 | case CK_FixedPointToFloating: { | |||
| 14004 | APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); | |||
| 14005 | if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) | |||
| 14006 | return false; | |||
| 14007 | Result = | |||
| 14008 | FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); | |||
| 14009 | return true; | |||
| 14010 | } | |||
| 14011 | ||||
| 14012 | case CK_FloatingCast: { | |||
| 14013 | if (!Visit(SubExpr)) | |||
| 14014 | return false; | |||
| 14015 | return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), | |||
| 14016 | Result); | |||
| 14017 | } | |||
| 14018 | ||||
| 14019 | case CK_FloatingComplexToReal: { | |||
| 14020 | ComplexValue V; | |||
| 14021 | if (!EvaluateComplex(SubExpr, V, Info)) | |||
| 14022 | return false; | |||
| 14023 | Result = V.getComplexFloatReal(); | |||
| 14024 | return true; | |||
| 14025 | } | |||
| 14026 | } | |||
| 14027 | } | |||
| 14028 | ||||
| 14029 | //===----------------------------------------------------------------------===// | |||
| 14030 | // Complex Evaluation (for float and integer) | |||
| 14031 | //===----------------------------------------------------------------------===// | |||
| 14032 | ||||
| 14033 | namespace { | |||
| 14034 | class ComplexExprEvaluator | |||
| 14035 | : public ExprEvaluatorBase<ComplexExprEvaluator> { | |||
| 14036 | ComplexValue &Result; | |||
| 14037 | ||||
| 14038 | public: | |||
| 14039 | ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) | |||
| 14040 | : ExprEvaluatorBaseTy(info), Result(Result) {} | |||
| 14041 | ||||
| 14042 | bool Success(const APValue &V, const Expr *e) { | |||
| 14043 | Result.setFrom(V); | |||
| 14044 | return true; | |||
| 14045 | } | |||
| 14046 | ||||
| 14047 | bool ZeroInitialization(const Expr *E); | |||
| 14048 | ||||
| 14049 | //===--------------------------------------------------------------------===// | |||
| 14050 | // Visitor Methods | |||
| 14051 | //===--------------------------------------------------------------------===// | |||
| 14052 | ||||
| 14053 | bool VisitImaginaryLiteral(const ImaginaryLiteral *E); | |||
| 14054 | bool VisitCastExpr(const CastExpr *E); | |||
| 14055 | bool VisitBinaryOperator(const BinaryOperator *E); | |||
| 14056 | bool VisitUnaryOperator(const UnaryOperator *E); | |||
| 14057 | bool VisitInitListExpr(const InitListExpr *E); | |||
| 14058 | bool VisitCallExpr(const CallExpr *E); | |||
| 14059 | }; | |||
| 14060 | } // end anonymous namespace | |||
| 14061 | ||||
| 14062 | static bool EvaluateComplex(const Expr *E, ComplexValue &Result, | |||
| 14063 | EvalInfo &Info) { | |||
| 14064 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14064, __extension__ __PRETTY_FUNCTION__)); | |||
| 14065 | assert(E->isPRValue() && E->getType()->isAnyComplexType())(static_cast <bool> (E->isPRValue() && E-> getType()->isAnyComplexType()) ? void (0) : __assert_fail ( "E->isPRValue() && E->getType()->isAnyComplexType()" , "clang/lib/AST/ExprConstant.cpp", 14065, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14066 | return ComplexExprEvaluator(Info, Result).Visit(E); | |||
| 14067 | } | |||
| 14068 | ||||
| 14069 | bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { | |||
| 14070 | QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14071 | if (ElemTy->isRealFloatingType()) { | |||
| 14072 | Result.makeComplexFloat(); | |||
| 14073 | APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); | |||
| 14074 | Result.FloatReal = Zero; | |||
| 14075 | Result.FloatImag = Zero; | |||
| 14076 | } else { | |||
| 14077 | Result.makeComplexInt(); | |||
| 14078 | APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); | |||
| 14079 | Result.IntReal = Zero; | |||
| 14080 | Result.IntImag = Zero; | |||
| 14081 | } | |||
| 14082 | return true; | |||
| 14083 | } | |||
| 14084 | ||||
| 14085 | bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { | |||
| 14086 | const Expr* SubExpr = E->getSubExpr(); | |||
| 14087 | ||||
| 14088 | if (SubExpr->getType()->isRealFloatingType()) { | |||
| 14089 | Result.makeComplexFloat(); | |||
| 14090 | APFloat &Imag = Result.FloatImag; | |||
| 14091 | if (!EvaluateFloat(SubExpr, Imag, Info)) | |||
| 14092 | return false; | |||
| 14093 | ||||
| 14094 | Result.FloatReal = APFloat(Imag.getSemantics()); | |||
| 14095 | return true; | |||
| 14096 | } else { | |||
| 14097 | assert(SubExpr->getType()->isIntegerType() &&(static_cast <bool> (SubExpr->getType()->isIntegerType () && "Unexpected imaginary literal.") ? void (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "clang/lib/AST/ExprConstant.cpp", 14098, __extension__ __PRETTY_FUNCTION__ )) | |||
| 14098 | "Unexpected imaginary literal.")(static_cast <bool> (SubExpr->getType()->isIntegerType () && "Unexpected imaginary literal.") ? void (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "clang/lib/AST/ExprConstant.cpp", 14098, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14099 | ||||
| 14100 | Result.makeComplexInt(); | |||
| 14101 | APSInt &Imag = Result.IntImag; | |||
| 14102 | if (!EvaluateInteger(SubExpr, Imag, Info)) | |||
| 14103 | return false; | |||
| 14104 | ||||
| 14105 | Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); | |||
| 14106 | return true; | |||
| 14107 | } | |||
| 14108 | } | |||
| 14109 | ||||
| 14110 | bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { | |||
| 14111 | ||||
| 14112 | switch (E->getCastKind()) { | |||
| 14113 | case CK_BitCast: | |||
| 14114 | case CK_BaseToDerived: | |||
| 14115 | case CK_DerivedToBase: | |||
| 14116 | case CK_UncheckedDerivedToBase: | |||
| 14117 | case CK_Dynamic: | |||
| 14118 | case CK_ToUnion: | |||
| 14119 | case CK_ArrayToPointerDecay: | |||
| 14120 | case CK_FunctionToPointerDecay: | |||
| 14121 | case CK_NullToPointer: | |||
| 14122 | case CK_NullToMemberPointer: | |||
| 14123 | case CK_BaseToDerivedMemberPointer: | |||
| 14124 | case CK_DerivedToBaseMemberPointer: | |||
| 14125 | case CK_MemberPointerToBoolean: | |||
| 14126 | case CK_ReinterpretMemberPointer: | |||
| 14127 | case CK_ConstructorConversion: | |||
| 14128 | case CK_IntegralToPointer: | |||
| 14129 | case CK_PointerToIntegral: | |||
| 14130 | case CK_PointerToBoolean: | |||
| 14131 | case CK_ToVoid: | |||
| 14132 | case CK_VectorSplat: | |||
| 14133 | case CK_IntegralCast: | |||
| 14134 | case CK_BooleanToSignedIntegral: | |||
| 14135 | case CK_IntegralToBoolean: | |||
| 14136 | case CK_IntegralToFloating: | |||
| 14137 | case CK_FloatingToIntegral: | |||
| 14138 | case CK_FloatingToBoolean: | |||
| 14139 | case CK_FloatingCast: | |||
| 14140 | case CK_CPointerToObjCPointerCast: | |||
| 14141 | case CK_BlockPointerToObjCPointerCast: | |||
| 14142 | case CK_AnyPointerToBlockPointerCast: | |||
| 14143 | case CK_ObjCObjectLValueCast: | |||
| 14144 | case CK_FloatingComplexToReal: | |||
| 14145 | case CK_FloatingComplexToBoolean: | |||
| 14146 | case CK_IntegralComplexToReal: | |||
| 14147 | case CK_IntegralComplexToBoolean: | |||
| 14148 | case CK_ARCProduceObject: | |||
| 14149 | case CK_ARCConsumeObject: | |||
| 14150 | case CK_ARCReclaimReturnedObject: | |||
| 14151 | case CK_ARCExtendBlockObject: | |||
| 14152 | case CK_CopyAndAutoreleaseBlockObject: | |||
| 14153 | case CK_BuiltinFnToFnPtr: | |||
| 14154 | case CK_ZeroToOCLOpaqueType: | |||
| 14155 | case CK_NonAtomicToAtomic: | |||
| 14156 | case CK_AddressSpaceConversion: | |||
| 14157 | case CK_IntToOCLSampler: | |||
| 14158 | case CK_FloatingToFixedPoint: | |||
| 14159 | case CK_FixedPointToFloating: | |||
| 14160 | case CK_FixedPointCast: | |||
| 14161 | case CK_FixedPointToBoolean: | |||
| 14162 | case CK_FixedPointToIntegral: | |||
| 14163 | case CK_IntegralToFixedPoint: | |||
| 14164 | case CK_MatrixCast: | |||
| 14165 | llvm_unreachable("invalid cast kind for complex value")::llvm::llvm_unreachable_internal("invalid cast kind for complex value" , "clang/lib/AST/ExprConstant.cpp", 14165); | |||
| 14166 | ||||
| 14167 | case CK_LValueToRValue: | |||
| 14168 | case CK_AtomicToNonAtomic: | |||
| 14169 | case CK_NoOp: | |||
| 14170 | case CK_LValueToRValueBitCast: | |||
| 14171 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 14172 | ||||
| 14173 | case CK_Dependent: | |||
| 14174 | case CK_LValueBitCast: | |||
| 14175 | case CK_UserDefinedConversion: | |||
| 14176 | return Error(E); | |||
| 14177 | ||||
| 14178 | case CK_FloatingRealToComplex: { | |||
| 14179 | APFloat &Real = Result.FloatReal; | |||
| 14180 | if (!EvaluateFloat(E->getSubExpr(), Real, Info)) | |||
| 14181 | return false; | |||
| 14182 | ||||
| 14183 | Result.makeComplexFloat(); | |||
| 14184 | Result.FloatImag = APFloat(Real.getSemantics()); | |||
| 14185 | return true; | |||
| 14186 | } | |||
| 14187 | ||||
| 14188 | case CK_FloatingComplexCast: { | |||
| 14189 | if (!Visit(E->getSubExpr())) | |||
| 14190 | return false; | |||
| 14191 | ||||
| 14192 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14193 | QualType From | |||
| 14194 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14195 | ||||
| 14196 | return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && | |||
| 14197 | HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); | |||
| 14198 | } | |||
| 14199 | ||||
| 14200 | case CK_FloatingComplexToIntegralComplex: { | |||
| 14201 | if (!Visit(E->getSubExpr())) | |||
| 14202 | return false; | |||
| 14203 | ||||
| 14204 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14205 | QualType From | |||
| 14206 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14207 | Result.makeComplexInt(); | |||
| 14208 | return HandleFloatToIntCast(Info, E, From, Result.FloatReal, | |||
| 14209 | To, Result.IntReal) && | |||
| 14210 | HandleFloatToIntCast(Info, E, From, Result.FloatImag, | |||
| 14211 | To, Result.IntImag); | |||
| 14212 | } | |||
| 14213 | ||||
| 14214 | case CK_IntegralRealToComplex: { | |||
| 14215 | APSInt &Real = Result.IntReal; | |||
| 14216 | if (!EvaluateInteger(E->getSubExpr(), Real, Info)) | |||
| 14217 | return false; | |||
| 14218 | ||||
| 14219 | Result.makeComplexInt(); | |||
| 14220 | Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); | |||
| 14221 | return true; | |||
| 14222 | } | |||
| 14223 | ||||
| 14224 | case CK_IntegralComplexCast: { | |||
| 14225 | if (!Visit(E->getSubExpr())) | |||
| 14226 | return false; | |||
| 14227 | ||||
| 14228 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14229 | QualType From | |||
| 14230 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14231 | ||||
| 14232 | Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); | |||
| 14233 | Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); | |||
| 14234 | return true; | |||
| 14235 | } | |||
| 14236 | ||||
| 14237 | case CK_IntegralComplexToFloatingComplex: { | |||
| 14238 | if (!Visit(E->getSubExpr())) | |||
| 14239 | return false; | |||
| 14240 | ||||
| 14241 | const FPOptions FPO = E->getFPFeaturesInEffect( | |||
| 14242 | Info.Ctx.getLangOpts()); | |||
| 14243 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14244 | QualType From | |||
| 14245 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | |||
| 14246 | Result.makeComplexFloat(); | |||
| 14247 | return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, | |||
| 14248 | To, Result.FloatReal) && | |||
| 14249 | HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, | |||
| 14250 | To, Result.FloatImag); | |||
| 14251 | } | |||
| 14252 | } | |||
| 14253 | ||||
| 14254 | llvm_unreachable("unknown cast resulting in complex value")::llvm::llvm_unreachable_internal("unknown cast resulting in complex value" , "clang/lib/AST/ExprConstant.cpp", 14254); | |||
| 14255 | } | |||
| 14256 | ||||
| 14257 | bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | |||
| 14258 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | |||
| 14259 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | |||
| 14260 | ||||
| 14261 | // Track whether the LHS or RHS is real at the type system level. When this is | |||
| 14262 | // the case we can simplify our evaluation strategy. | |||
| 14263 | bool LHSReal = false, RHSReal = false; | |||
| 14264 | ||||
| 14265 | bool LHSOK; | |||
| 14266 | if (E->getLHS()->getType()->isRealFloatingType()) { | |||
| 14267 | LHSReal = true; | |||
| 14268 | APFloat &Real = Result.FloatReal; | |||
| 14269 | LHSOK = EvaluateFloat(E->getLHS(), Real, Info); | |||
| 14270 | if (LHSOK) { | |||
| 14271 | Result.makeComplexFloat(); | |||
| 14272 | Result.FloatImag = APFloat(Real.getSemantics()); | |||
| 14273 | } | |||
| 14274 | } else { | |||
| 14275 | LHSOK = Visit(E->getLHS()); | |||
| 14276 | } | |||
| 14277 | if (!LHSOK && !Info.noteFailure()) | |||
| 14278 | return false; | |||
| 14279 | ||||
| 14280 | ComplexValue RHS; | |||
| 14281 | if (E->getRHS()->getType()->isRealFloatingType()) { | |||
| 14282 | RHSReal = true; | |||
| 14283 | APFloat &Real = RHS.FloatReal; | |||
| 14284 | if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) | |||
| 14285 | return false; | |||
| 14286 | RHS.makeComplexFloat(); | |||
| 14287 | RHS.FloatImag = APFloat(Real.getSemantics()); | |||
| 14288 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | |||
| 14289 | return false; | |||
| 14290 | ||||
| 14291 | assert(!(LHSReal && RHSReal) &&(static_cast <bool> (!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real.") ? void (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "clang/lib/AST/ExprConstant.cpp", 14292, __extension__ __PRETTY_FUNCTION__ )) | |||
| 14292 | "Cannot have both operands of a complex operation be real.")(static_cast <bool> (!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real.") ? void (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "clang/lib/AST/ExprConstant.cpp", 14292, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14293 | switch (E->getOpcode()) { | |||
| 14294 | default: return Error(E); | |||
| 14295 | case BO_Add: | |||
| 14296 | if (Result.isComplexFloat()) { | |||
| 14297 | Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), | |||
| 14298 | APFloat::rmNearestTiesToEven); | |||
| 14299 | if (LHSReal) | |||
| 14300 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | |||
| 14301 | else if (!RHSReal) | |||
| 14302 | Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), | |||
| 14303 | APFloat::rmNearestTiesToEven); | |||
| 14304 | } else { | |||
| 14305 | Result.getComplexIntReal() += RHS.getComplexIntReal(); | |||
| 14306 | Result.getComplexIntImag() += RHS.getComplexIntImag(); | |||
| 14307 | } | |||
| 14308 | break; | |||
| 14309 | case BO_Sub: | |||
| 14310 | if (Result.isComplexFloat()) { | |||
| 14311 | Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), | |||
| 14312 | APFloat::rmNearestTiesToEven); | |||
| 14313 | if (LHSReal) { | |||
| 14314 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | |||
| 14315 | Result.getComplexFloatImag().changeSign(); | |||
| 14316 | } else if (!RHSReal) { | |||
| 14317 | Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), | |||
| 14318 | APFloat::rmNearestTiesToEven); | |||
| 14319 | } | |||
| 14320 | } else { | |||
| 14321 | Result.getComplexIntReal() -= RHS.getComplexIntReal(); | |||
| 14322 | Result.getComplexIntImag() -= RHS.getComplexIntImag(); | |||
| 14323 | } | |||
| 14324 | break; | |||
| 14325 | case BO_Mul: | |||
| 14326 | if (Result.isComplexFloat()) { | |||
| 14327 | // This is an implementation of complex multiplication according to the | |||
| 14328 | // constraints laid out in C11 Annex G. The implementation uses the | |||
| 14329 | // following naming scheme: | |||
| 14330 | // (a + ib) * (c + id) | |||
| 14331 | ComplexValue LHS = Result; | |||
| 14332 | APFloat &A = LHS.getComplexFloatReal(); | |||
| 14333 | APFloat &B = LHS.getComplexFloatImag(); | |||
| 14334 | APFloat &C = RHS.getComplexFloatReal(); | |||
| 14335 | APFloat &D = RHS.getComplexFloatImag(); | |||
| 14336 | APFloat &ResR = Result.getComplexFloatReal(); | |||
| 14337 | APFloat &ResI = Result.getComplexFloatImag(); | |||
| 14338 | if (LHSReal) { | |||
| 14339 | assert(!RHSReal && "Cannot have two real operands for a complex op!")(static_cast <bool> (!RHSReal && "Cannot have two real operands for a complex op!" ) ? void (0) : __assert_fail ("!RHSReal && \"Cannot have two real operands for a complex op!\"" , "clang/lib/AST/ExprConstant.cpp", 14339, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14340 | ResR = A * C; | |||
| 14341 | ResI = A * D; | |||
| 14342 | } else if (RHSReal) { | |||
| 14343 | ResR = C * A; | |||
| 14344 | ResI = C * B; | |||
| 14345 | } else { | |||
| 14346 | // In the fully general case, we need to handle NaNs and infinities | |||
| 14347 | // robustly. | |||
| 14348 | APFloat AC = A * C; | |||
| 14349 | APFloat BD = B * D; | |||
| 14350 | APFloat AD = A * D; | |||
| 14351 | APFloat BC = B * C; | |||
| 14352 | ResR = AC - BD; | |||
| 14353 | ResI = AD + BC; | |||
| 14354 | if (ResR.isNaN() && ResI.isNaN()) { | |||
| 14355 | bool Recalc = false; | |||
| 14356 | if (A.isInfinity() || B.isInfinity()) { | |||
| 14357 | A = APFloat::copySign( | |||
| 14358 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | |||
| 14359 | B = APFloat::copySign( | |||
| 14360 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | |||
| 14361 | if (C.isNaN()) | |||
| 14362 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | |||
| 14363 | if (D.isNaN()) | |||
| 14364 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | |||
| 14365 | Recalc = true; | |||
| 14366 | } | |||
| 14367 | if (C.isInfinity() || D.isInfinity()) { | |||
| 14368 | C = APFloat::copySign( | |||
| 14369 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | |||
| 14370 | D = APFloat::copySign( | |||
| 14371 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | |||
| 14372 | if (A.isNaN()) | |||
| 14373 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | |||
| 14374 | if (B.isNaN()) | |||
| 14375 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | |||
| 14376 | Recalc = true; | |||
| 14377 | } | |||
| 14378 | if (!Recalc && (AC.isInfinity() || BD.isInfinity() || | |||
| 14379 | AD.isInfinity() || BC.isInfinity())) { | |||
| 14380 | if (A.isNaN()) | |||
| 14381 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | |||
| 14382 | if (B.isNaN()) | |||
| 14383 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | |||
| 14384 | if (C.isNaN()) | |||
| 14385 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | |||
| 14386 | if (D.isNaN()) | |||
| 14387 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | |||
| 14388 | Recalc = true; | |||
| 14389 | } | |||
| 14390 | if (Recalc) { | |||
| 14391 | ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); | |||
| 14392 | ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); | |||
| 14393 | } | |||
| 14394 | } | |||
| 14395 | } | |||
| 14396 | } else { | |||
| 14397 | ComplexValue LHS = Result; | |||
| 14398 | Result.getComplexIntReal() = | |||
| 14399 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() - | |||
| 14400 | LHS.getComplexIntImag() * RHS.getComplexIntImag()); | |||
| 14401 | Result.getComplexIntImag() = | |||
| 14402 | (LHS.getComplexIntReal() * RHS.getComplexIntImag() + | |||
| 14403 | LHS.getComplexIntImag() * RHS.getComplexIntReal()); | |||
| 14404 | } | |||
| 14405 | break; | |||
| 14406 | case BO_Div: | |||
| 14407 | if (Result.isComplexFloat()) { | |||
| 14408 | // This is an implementation of complex division according to the | |||
| 14409 | // constraints laid out in C11 Annex G. The implementation uses the | |||
| 14410 | // following naming scheme: | |||
| 14411 | // (a + ib) / (c + id) | |||
| 14412 | ComplexValue LHS = Result; | |||
| 14413 | APFloat &A = LHS.getComplexFloatReal(); | |||
| 14414 | APFloat &B = LHS.getComplexFloatImag(); | |||
| 14415 | APFloat &C = RHS.getComplexFloatReal(); | |||
| 14416 | APFloat &D = RHS.getComplexFloatImag(); | |||
| 14417 | APFloat &ResR = Result.getComplexFloatReal(); | |||
| 14418 | APFloat &ResI = Result.getComplexFloatImag(); | |||
| 14419 | if (RHSReal) { | |||
| 14420 | ResR = A / C; | |||
| 14421 | ResI = B / C; | |||
| 14422 | } else { | |||
| 14423 | if (LHSReal) { | |||
| 14424 | // No real optimizations we can do here, stub out with zero. | |||
| 14425 | B = APFloat::getZero(A.getSemantics()); | |||
| 14426 | } | |||
| 14427 | int DenomLogB = 0; | |||
| 14428 | APFloat MaxCD = maxnum(abs(C), abs(D)); | |||
| 14429 | if (MaxCD.isFinite()) { | |||
| 14430 | DenomLogB = ilogb(MaxCD); | |||
| 14431 | C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); | |||
| 14432 | D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); | |||
| 14433 | } | |||
| 14434 | APFloat Denom = C * C + D * D; | |||
| 14435 | ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, | |||
| 14436 | APFloat::rmNearestTiesToEven); | |||
| 14437 | ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, | |||
| 14438 | APFloat::rmNearestTiesToEven); | |||
| 14439 | if (ResR.isNaN() && ResI.isNaN()) { | |||
| 14440 | if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { | |||
| 14441 | ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; | |||
| 14442 | ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; | |||
| 14443 | } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && | |||
| 14444 | D.isFinite()) { | |||
| 14445 | A = APFloat::copySign( | |||
| 14446 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | |||
| 14447 | B = APFloat::copySign( | |||
| 14448 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | |||
| 14449 | ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); | |||
| 14450 | ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); | |||
| 14451 | } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { | |||
| 14452 | C = APFloat::copySign( | |||
| 14453 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | |||
| 14454 | D = APFloat::copySign( | |||
| 14455 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | |||
| 14456 | ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); | |||
| 14457 | ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); | |||
| 14458 | } | |||
| 14459 | } | |||
| 14460 | } | |||
| 14461 | } else { | |||
| 14462 | if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) | |||
| 14463 | return Error(E, diag::note_expr_divide_by_zero); | |||
| 14464 | ||||
| 14465 | ComplexValue LHS = Result; | |||
| 14466 | APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + | |||
| 14467 | RHS.getComplexIntImag() * RHS.getComplexIntImag(); | |||
| 14468 | Result.getComplexIntReal() = | |||
| 14469 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() + | |||
| 14470 | LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; | |||
| 14471 | Result.getComplexIntImag() = | |||
| 14472 | (LHS.getComplexIntImag() * RHS.getComplexIntReal() - | |||
| 14473 | LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; | |||
| 14474 | } | |||
| 14475 | break; | |||
| 14476 | } | |||
| 14477 | ||||
| 14478 | return true; | |||
| 14479 | } | |||
| 14480 | ||||
| 14481 | bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | |||
| 14482 | // Get the operand value into 'Result'. | |||
| 14483 | if (!Visit(E->getSubExpr())) | |||
| 14484 | return false; | |||
| 14485 | ||||
| 14486 | switch (E->getOpcode()) { | |||
| 14487 | default: | |||
| 14488 | return Error(E); | |||
| 14489 | case UO_Extension: | |||
| 14490 | return true; | |||
| 14491 | case UO_Plus: | |||
| 14492 | // The result is always just the subexpr. | |||
| 14493 | return true; | |||
| 14494 | case UO_Minus: | |||
| 14495 | if (Result.isComplexFloat()) { | |||
| 14496 | Result.getComplexFloatReal().changeSign(); | |||
| 14497 | Result.getComplexFloatImag().changeSign(); | |||
| 14498 | } | |||
| 14499 | else { | |||
| 14500 | Result.getComplexIntReal() = -Result.getComplexIntReal(); | |||
| 14501 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | |||
| 14502 | } | |||
| 14503 | return true; | |||
| 14504 | case UO_Not: | |||
| 14505 | if (Result.isComplexFloat()) | |||
| 14506 | Result.getComplexFloatImag().changeSign(); | |||
| 14507 | else | |||
| 14508 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | |||
| 14509 | return true; | |||
| 14510 | } | |||
| 14511 | } | |||
| 14512 | ||||
| 14513 | bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | |||
| 14514 | if (E->getNumInits() == 2) { | |||
| 14515 | if (E->getType()->isComplexType()) { | |||
| 14516 | Result.makeComplexFloat(); | |||
| 14517 | if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) | |||
| 14518 | return false; | |||
| 14519 | if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) | |||
| 14520 | return false; | |||
| 14521 | } else { | |||
| 14522 | Result.makeComplexInt(); | |||
| 14523 | if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) | |||
| 14524 | return false; | |||
| 14525 | if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) | |||
| 14526 | return false; | |||
| 14527 | } | |||
| 14528 | return true; | |||
| 14529 | } | |||
| 14530 | return ExprEvaluatorBaseTy::VisitInitListExpr(E); | |||
| 14531 | } | |||
| 14532 | ||||
| 14533 | bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { | |||
| 14534 | switch (E->getBuiltinCallee()) { | |||
| 14535 | case Builtin::BI__builtin_complex: | |||
| 14536 | Result.makeComplexFloat(); | |||
| 14537 | if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) | |||
| 14538 | return false; | |||
| 14539 | if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) | |||
| 14540 | return false; | |||
| 14541 | return true; | |||
| 14542 | ||||
| 14543 | default: | |||
| 14544 | break; | |||
| 14545 | } | |||
| 14546 | ||||
| 14547 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | |||
| 14548 | } | |||
| 14549 | ||||
| 14550 | //===----------------------------------------------------------------------===// | |||
| 14551 | // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic | |||
| 14552 | // implicit conversion. | |||
| 14553 | //===----------------------------------------------------------------------===// | |||
| 14554 | ||||
| 14555 | namespace { | |||
| 14556 | class AtomicExprEvaluator : | |||
| 14557 | public ExprEvaluatorBase<AtomicExprEvaluator> { | |||
| 14558 | const LValue *This; | |||
| 14559 | APValue &Result; | |||
| 14560 | public: | |||
| 14561 | AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) | |||
| 14562 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | |||
| 14563 | ||||
| 14564 | bool Success(const APValue &V, const Expr *E) { | |||
| 14565 | Result = V; | |||
| 14566 | return true; | |||
| 14567 | } | |||
| 14568 | ||||
| 14569 | bool ZeroInitialization(const Expr *E) { | |||
| 14570 | ImplicitValueInitExpr VIE( | |||
| 14571 | E->getType()->castAs<AtomicType>()->getValueType()); | |||
| 14572 | // For atomic-qualified class (and array) types in C++, initialize the | |||
| 14573 | // _Atomic-wrapped subobject directly, in-place. | |||
| 14574 | return This ? EvaluateInPlace(Result, Info, *This, &VIE) | |||
| 14575 | : Evaluate(Result, Info, &VIE); | |||
| 14576 | } | |||
| 14577 | ||||
| 14578 | bool VisitCastExpr(const CastExpr *E) { | |||
| 14579 | switch (E->getCastKind()) { | |||
| 14580 | default: | |||
| 14581 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 14582 | case CK_NonAtomicToAtomic: | |||
| 14583 | return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) | |||
| 14584 | : Evaluate(Result, Info, E->getSubExpr()); | |||
| 14585 | } | |||
| 14586 | } | |||
| 14587 | }; | |||
| 14588 | } // end anonymous namespace | |||
| 14589 | ||||
| 14590 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | |||
| 14591 | EvalInfo &Info) { | |||
| 14592 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14592, __extension__ __PRETTY_FUNCTION__)); | |||
| 14593 | assert(E->isPRValue() && E->getType()->isAtomicType())(static_cast <bool> (E->isPRValue() && E-> getType()->isAtomicType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isAtomicType()" , "clang/lib/AST/ExprConstant.cpp", 14593, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14594 | return AtomicExprEvaluator(Info, This, Result).Visit(E); | |||
| 14595 | } | |||
| 14596 | ||||
| 14597 | //===----------------------------------------------------------------------===// | |||
| 14598 | // Void expression evaluation, primarily for a cast to void on the LHS of a | |||
| 14599 | // comma operator | |||
| 14600 | //===----------------------------------------------------------------------===// | |||
| 14601 | ||||
| 14602 | namespace { | |||
| 14603 | class VoidExprEvaluator | |||
| 14604 | : public ExprEvaluatorBase<VoidExprEvaluator> { | |||
| 14605 | public: | |||
| 14606 | VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} | |||
| 14607 | ||||
| 14608 | bool Success(const APValue &V, const Expr *e) { return true; } | |||
| 14609 | ||||
| 14610 | bool ZeroInitialization(const Expr *E) { return true; } | |||
| 14611 | ||||
| 14612 | bool VisitCastExpr(const CastExpr *E) { | |||
| 14613 | switch (E->getCastKind()) { | |||
| 14614 | default: | |||
| 14615 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | |||
| 14616 | case CK_ToVoid: | |||
| 14617 | VisitIgnoredValue(E->getSubExpr()); | |||
| 14618 | return true; | |||
| 14619 | } | |||
| 14620 | } | |||
| 14621 | ||||
| 14622 | bool VisitCallExpr(const CallExpr *E) { | |||
| 14623 | switch (E->getBuiltinCallee()) { | |||
| 14624 | case Builtin::BI__assume: | |||
| 14625 | case Builtin::BI__builtin_assume: | |||
| 14626 | // The argument is not evaluated! | |||
| 14627 | return true; | |||
| 14628 | ||||
| 14629 | case Builtin::BI__builtin_operator_delete: | |||
| 14630 | return HandleOperatorDeleteCall(Info, E); | |||
| 14631 | ||||
| 14632 | default: | |||
| 14633 | break; | |||
| 14634 | } | |||
| 14635 | ||||
| 14636 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | |||
| 14637 | } | |||
| 14638 | ||||
| 14639 | bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); | |||
| 14640 | }; | |||
| 14641 | } // end anonymous namespace | |||
| 14642 | ||||
| 14643 | bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { | |||
| 14644 | // We cannot speculatively evaluate a delete expression. | |||
| 14645 | if (Info.SpeculativeEvaluationDepth) | |||
| 14646 | return false; | |||
| 14647 | ||||
| 14648 | FunctionDecl *OperatorDelete = E->getOperatorDelete(); | |||
| 14649 | if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { | |||
| 14650 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | |||
| 14651 | << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; | |||
| 14652 | return false; | |||
| 14653 | } | |||
| 14654 | ||||
| 14655 | const Expr *Arg = E->getArgument(); | |||
| 14656 | ||||
| 14657 | LValue Pointer; | |||
| 14658 | if (!EvaluatePointer(Arg, Pointer, Info)) | |||
| 14659 | return false; | |||
| 14660 | if (Pointer.Designator.Invalid) | |||
| 14661 | return false; | |||
| 14662 | ||||
| 14663 | // Deleting a null pointer has no effect. | |||
| 14664 | if (Pointer.isNullPointer()) { | |||
| 14665 | // This is the only case where we need to produce an extension warning: | |||
| 14666 | // the only other way we can succeed is if we find a dynamic allocation, | |||
| 14667 | // and we will have warned when we allocated it in that case. | |||
| 14668 | if (!Info.getLangOpts().CPlusPlus20) | |||
| 14669 | Info.CCEDiag(E, diag::note_constexpr_new); | |||
| 14670 | return true; | |||
| 14671 | } | |||
| 14672 | ||||
| 14673 | Optional<DynAlloc *> Alloc = CheckDeleteKind( | |||
| 14674 | Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); | |||
| 14675 | if (!Alloc) | |||
| 14676 | return false; | |||
| 14677 | QualType AllocType = Pointer.Base.getDynamicAllocType(); | |||
| 14678 | ||||
| 14679 | // For the non-array case, the designator must be empty if the static type | |||
| 14680 | // does not have a virtual destructor. | |||
| 14681 | if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && | |||
| 14682 | !hasVirtualDestructor(Arg->getType()->getPointeeType())) { | |||
| 14683 | Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) | |||
| 14684 | << Arg->getType()->getPointeeType() << AllocType; | |||
| 14685 | return false; | |||
| 14686 | } | |||
| 14687 | ||||
| 14688 | // For a class type with a virtual destructor, the selected operator delete | |||
| 14689 | // is the one looked up when building the destructor. | |||
| 14690 | if (!E->isArrayForm() && !E->isGlobalDelete()) { | |||
| 14691 | const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); | |||
| 14692 | if (VirtualDelete && | |||
| 14693 | !VirtualDelete->isReplaceableGlobalAllocationFunction()) { | |||
| 14694 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | |||
| 14695 | << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; | |||
| 14696 | return false; | |||
| 14697 | } | |||
| 14698 | } | |||
| 14699 | ||||
| 14700 | if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), | |||
| 14701 | (*Alloc)->Value, AllocType)) | |||
| 14702 | return false; | |||
| 14703 | ||||
| 14704 | if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { | |||
| 14705 | // The element was already erased. This means the destructor call also | |||
| 14706 | // deleted the object. | |||
| 14707 | // FIXME: This probably results in undefined behavior before we get this | |||
| 14708 | // far, and should be diagnosed elsewhere first. | |||
| 14709 | Info.FFDiag(E, diag::note_constexpr_double_delete); | |||
| 14710 | return false; | |||
| 14711 | } | |||
| 14712 | ||||
| 14713 | return true; | |||
| 14714 | } | |||
| 14715 | ||||
| 14716 | static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { | |||
| 14717 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14717, __extension__ __PRETTY_FUNCTION__)); | |||
| 14718 | assert(E->isPRValue() && E->getType()->isVoidType())(static_cast <bool> (E->isPRValue() && E-> getType()->isVoidType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVoidType()" , "clang/lib/AST/ExprConstant.cpp", 14718, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14719 | return VoidExprEvaluator(Info).Visit(E); | |||
| 14720 | } | |||
| 14721 | ||||
| 14722 | //===----------------------------------------------------------------------===// | |||
| 14723 | // Top level Expr::EvaluateAsRValue method. | |||
| 14724 | //===----------------------------------------------------------------------===// | |||
| 14725 | ||||
| 14726 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { | |||
| 14727 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14727, __extension__ __PRETTY_FUNCTION__)); | |||
| 14728 | // In C, function designators are not lvalues, but we evaluate them as if they | |||
| 14729 | // are. | |||
| 14730 | QualType T = E->getType(); | |||
| 14731 | if (E->isGLValue() || T->isFunctionType()) { | |||
| 14732 | LValue LV; | |||
| 14733 | if (!EvaluateLValue(E, LV, Info)) | |||
| 14734 | return false; | |||
| 14735 | LV.moveInto(Result); | |||
| 14736 | } else if (T->isVectorType()) { | |||
| 14737 | if (!EvaluateVector(E, Result, Info)) | |||
| 14738 | return false; | |||
| 14739 | } else if (T->isIntegralOrEnumerationType()) { | |||
| 14740 | if (!IntExprEvaluator(Info, Result).Visit(E)) | |||
| 14741 | return false; | |||
| 14742 | } else if (T->hasPointerRepresentation()) { | |||
| 14743 | LValue LV; | |||
| 14744 | if (!EvaluatePointer(E, LV, Info)) | |||
| 14745 | return false; | |||
| 14746 | LV.moveInto(Result); | |||
| 14747 | } else if (T->isRealFloatingType()) { | |||
| 14748 | llvm::APFloat F(0.0); | |||
| 14749 | if (!EvaluateFloat(E, F, Info)) | |||
| 14750 | return false; | |||
| 14751 | Result = APValue(F); | |||
| 14752 | } else if (T->isAnyComplexType()) { | |||
| 14753 | ComplexValue C; | |||
| 14754 | if (!EvaluateComplex(E, C, Info)) | |||
| 14755 | return false; | |||
| 14756 | C.moveInto(Result); | |||
| 14757 | } else if (T->isFixedPointType()) { | |||
| 14758 | if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; | |||
| 14759 | } else if (T->isMemberPointerType()) { | |||
| 14760 | MemberPtr P; | |||
| 14761 | if (!EvaluateMemberPointer(E, P, Info)) | |||
| 14762 | return false; | |||
| 14763 | P.moveInto(Result); | |||
| 14764 | return true; | |||
| 14765 | } else if (T->isArrayType()) { | |||
| 14766 | LValue LV; | |||
| 14767 | APValue &Value = | |||
| 14768 | Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); | |||
| 14769 | if (!EvaluateArray(E, LV, Value, Info)) | |||
| 14770 | return false; | |||
| 14771 | Result = Value; | |||
| 14772 | } else if (T->isRecordType()) { | |||
| 14773 | LValue LV; | |||
| 14774 | APValue &Value = | |||
| 14775 | Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); | |||
| 14776 | if (!EvaluateRecord(E, LV, Value, Info)) | |||
| 14777 | return false; | |||
| 14778 | Result = Value; | |||
| 14779 | } else if (T->isVoidType()) { | |||
| 14780 | if (!Info.getLangOpts().CPlusPlus11) | |||
| 14781 | Info.CCEDiag(E, diag::note_constexpr_nonliteral) | |||
| 14782 | << E->getType(); | |||
| 14783 | if (!EvaluateVoid(E, Info)) | |||
| 14784 | return false; | |||
| 14785 | } else if (T->isAtomicType()) { | |||
| 14786 | QualType Unqual = T.getAtomicUnqualifiedType(); | |||
| 14787 | if (Unqual->isArrayType() || Unqual->isRecordType()) { | |||
| 14788 | LValue LV; | |||
| 14789 | APValue &Value = Info.CurrentCall->createTemporary( | |||
| 14790 | E, Unqual, ScopeKind::FullExpression, LV); | |||
| 14791 | if (!EvaluateAtomic(E, &LV, Value, Info)) | |||
| 14792 | return false; | |||
| 14793 | } else { | |||
| 14794 | if (!EvaluateAtomic(E, nullptr, Result, Info)) | |||
| 14795 | return false; | |||
| 14796 | } | |||
| 14797 | } else if (Info.getLangOpts().CPlusPlus11) { | |||
| 14798 | Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); | |||
| 14799 | return false; | |||
| 14800 | } else { | |||
| 14801 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | |||
| 14802 | return false; | |||
| 14803 | } | |||
| 14804 | ||||
| 14805 | return true; | |||
| 14806 | } | |||
| 14807 | ||||
| 14808 | /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some | |||
| 14809 | /// cases, the in-place evaluation is essential, since later initializers for | |||
| 14810 | /// an object can indirectly refer to subobjects which were initialized earlier. | |||
| 14811 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, | |||
| 14812 | const Expr *E, bool AllowNonLiteralTypes) { | |||
| 14813 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14813, __extension__ __PRETTY_FUNCTION__)); | |||
| 14814 | ||||
| 14815 | if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) | |||
| 14816 | return false; | |||
| 14817 | ||||
| 14818 | if (E->isPRValue()) { | |||
| 14819 | // Evaluate arrays and record types in-place, so that later initializers can | |||
| 14820 | // refer to earlier-initialized members of the object. | |||
| 14821 | QualType T = E->getType(); | |||
| 14822 | if (T->isArrayType()) | |||
| 14823 | return EvaluateArray(E, This, Result, Info); | |||
| 14824 | else if (T->isRecordType()) | |||
| 14825 | return EvaluateRecord(E, This, Result, Info); | |||
| 14826 | else if (T->isAtomicType()) { | |||
| 14827 | QualType Unqual = T.getAtomicUnqualifiedType(); | |||
| 14828 | if (Unqual->isArrayType() || Unqual->isRecordType()) | |||
| 14829 | return EvaluateAtomic(E, &This, Result, Info); | |||
| 14830 | } | |||
| 14831 | } | |||
| 14832 | ||||
| 14833 | // For any other type, in-place evaluation is unimportant. | |||
| 14834 | return Evaluate(Result, Info, E); | |||
| 14835 | } | |||
| 14836 | ||||
| 14837 | /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit | |||
| 14838 | /// lvalue-to-rvalue cast if it is an lvalue. | |||
| 14839 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { | |||
| 14840 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14840, __extension__ __PRETTY_FUNCTION__)); | |||
| 14841 | if (Info.EnableNewConstInterp) { | |||
| 14842 | if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) | |||
| 14843 | return false; | |||
| 14844 | } else { | |||
| 14845 | if (E->getType().isNull()) | |||
| 14846 | return false; | |||
| 14847 | ||||
| 14848 | if (!CheckLiteralType(Info, E)) | |||
| 14849 | return false; | |||
| 14850 | ||||
| 14851 | if (!::Evaluate(Result, Info, E)) | |||
| 14852 | return false; | |||
| 14853 | ||||
| 14854 | if (E->isGLValue()) { | |||
| 14855 | LValue LV; | |||
| 14856 | LV.setFrom(Info.Ctx, Result); | |||
| 14857 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | |||
| 14858 | return false; | |||
| 14859 | } | |||
| 14860 | } | |||
| 14861 | ||||
| 14862 | // Check this core constant expression is a constant expression. | |||
| 14863 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, | |||
| 14864 | ConstantExprKind::Normal) && | |||
| 14865 | CheckMemoryLeaks(Info); | |||
| 14866 | } | |||
| 14867 | ||||
| 14868 | static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, | |||
| 14869 | const ASTContext &Ctx, bool &IsConst) { | |||
| 14870 | // Fast-path evaluations of integer literals, since we sometimes see files | |||
| 14871 | // containing vast quantities of these. | |||
| 14872 | if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { | |||
| 14873 | Result.Val = APValue(APSInt(L->getValue(), | |||
| 14874 | L->getType()->isUnsignedIntegerType())); | |||
| 14875 | IsConst = true; | |||
| 14876 | return true; | |||
| 14877 | } | |||
| 14878 | ||||
| 14879 | // This case should be rare, but we need to check it before we check on | |||
| 14880 | // the type below. | |||
| 14881 | if (Exp->getType().isNull()) { | |||
| 14882 | IsConst = false; | |||
| 14883 | return true; | |||
| 14884 | } | |||
| 14885 | ||||
| 14886 | // FIXME: Evaluating values of large array and record types can cause | |||
| 14887 | // performance problems. Only do so in C++11 for now. | |||
| 14888 | if (Exp->isPRValue() && | |||
| 14889 | (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && | |||
| 14890 | !Ctx.getLangOpts().CPlusPlus11) { | |||
| 14891 | IsConst = false; | |||
| 14892 | return true; | |||
| 14893 | } | |||
| 14894 | return false; | |||
| 14895 | } | |||
| 14896 | ||||
| 14897 | static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, | |||
| 14898 | Expr::SideEffectsKind SEK) { | |||
| 14899 | return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || | |||
| 14900 | (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); | |||
| 14901 | } | |||
| 14902 | ||||
| 14903 | static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, | |||
| 14904 | const ASTContext &Ctx, EvalInfo &Info) { | |||
| 14905 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14905, __extension__ __PRETTY_FUNCTION__)); | |||
| 14906 | bool IsConst; | |||
| 14907 | if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) | |||
| 14908 | return IsConst; | |||
| 14909 | ||||
| 14910 | return EvaluateAsRValue(Info, E, Result.Val); | |||
| 14911 | } | |||
| 14912 | ||||
| 14913 | static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, | |||
| 14914 | const ASTContext &Ctx, | |||
| 14915 | Expr::SideEffectsKind AllowSideEffects, | |||
| 14916 | EvalInfo &Info) { | |||
| 14917 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14917, __extension__ __PRETTY_FUNCTION__)); | |||
| 14918 | if (!E->getType()->isIntegralOrEnumerationType()) | |||
| 14919 | return false; | |||
| 14920 | ||||
| 14921 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || | |||
| 14922 | !ExprResult.Val.isInt() || | |||
| 14923 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | |||
| 14924 | return false; | |||
| 14925 | ||||
| 14926 | return true; | |||
| 14927 | } | |||
| 14928 | ||||
| 14929 | static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, | |||
| 14930 | const ASTContext &Ctx, | |||
| 14931 | Expr::SideEffectsKind AllowSideEffects, | |||
| 14932 | EvalInfo &Info) { | |||
| 14933 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 14933, __extension__ __PRETTY_FUNCTION__)); | |||
| 14934 | if (!E->getType()->isFixedPointType()) | |||
| 14935 | return false; | |||
| 14936 | ||||
| 14937 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) | |||
| 14938 | return false; | |||
| 14939 | ||||
| 14940 | if (!ExprResult.Val.isFixedPoint() || | |||
| 14941 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | |||
| 14942 | return false; | |||
| 14943 | ||||
| 14944 | return true; | |||
| 14945 | } | |||
| 14946 | ||||
| 14947 | /// EvaluateAsRValue - Return true if this is a constant which we can fold using | |||
| 14948 | /// any crazy technique (that has nothing to do with language standards) that | |||
| 14949 | /// we want to. If this function returns true, it returns the folded constant | |||
| 14950 | /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion | |||
| 14951 | /// will be applied to the result. | |||
| 14952 | bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, | |||
| 14953 | bool InConstantContext) const { | |||
| 14954 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14955, __extension__ __PRETTY_FUNCTION__ )) | |||
| 14955 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14955, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14956 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | |||
| 14957 | Info.InConstantContext = InConstantContext; | |||
| 14958 | return ::EvaluateAsRValue(this, Result, Ctx, Info); | |||
| 14959 | } | |||
| 14960 | ||||
| 14961 | bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, | |||
| 14962 | bool InConstantContext) const { | |||
| 14963 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14964, __extension__ __PRETTY_FUNCTION__ )) | |||
| 14964 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14964, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14965 | EvalResult Scratch; | |||
| 14966 | return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && | |||
| 14967 | HandleConversionToBool(Scratch.Val, Result); | |||
| 14968 | } | |||
| 14969 | ||||
| 14970 | bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, | |||
| 14971 | SideEffectsKind AllowSideEffects, | |||
| 14972 | bool InConstantContext) const { | |||
| 14973 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14974, __extension__ __PRETTY_FUNCTION__ )) | |||
| 14974 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14974, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14975 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | |||
| 14976 | Info.InConstantContext = InConstantContext; | |||
| 14977 | return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); | |||
| 14978 | } | |||
| 14979 | ||||
| 14980 | bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, | |||
| 14981 | SideEffectsKind AllowSideEffects, | |||
| 14982 | bool InConstantContext) const { | |||
| 14983 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14984, __extension__ __PRETTY_FUNCTION__ )) | |||
| 14984 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14984, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14985 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | |||
| 14986 | Info.InConstantContext = InConstantContext; | |||
| 14987 | return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); | |||
| 14988 | } | |||
| 14989 | ||||
| 14990 | bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, | |||
| 14991 | SideEffectsKind AllowSideEffects, | |||
| 14992 | bool InConstantContext) const { | |||
| 14993 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14994, __extension__ __PRETTY_FUNCTION__ )) | |||
| 14994 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 14994, __extension__ __PRETTY_FUNCTION__ )); | |||
| 14995 | ||||
| 14996 | if (!getType()->isRealFloatingType()) | |||
| 14997 | return false; | |||
| 14998 | ||||
| 14999 | EvalResult ExprResult; | |||
| 15000 | if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || | |||
| 15001 | !ExprResult.Val.isFloat() || | |||
| 15002 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | |||
| 15003 | return false; | |||
| 15004 | ||||
| 15005 | Result = ExprResult.Val.getFloat(); | |||
| 15006 | return true; | |||
| 15007 | } | |||
| 15008 | ||||
| 15009 | bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, | |||
| 15010 | bool InConstantContext) const { | |||
| 15011 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15012, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15012 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15012, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15013 | ||||
| 15014 | EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); | |||
| 15015 | Info.InConstantContext = InConstantContext; | |||
| 15016 | LValue LV; | |||
| 15017 | CheckedTemporaries CheckedTemps; | |||
| 15018 | if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || | |||
| 15019 | Result.HasSideEffects || | |||
| 15020 | !CheckLValueConstantExpression(Info, getExprLoc(), | |||
| 15021 | Ctx.getLValueReferenceType(getType()), LV, | |||
| 15022 | ConstantExprKind::Normal, CheckedTemps)) | |||
| 15023 | return false; | |||
| 15024 | ||||
| 15025 | LV.moveInto(Result.Val); | |||
| 15026 | return true; | |||
| 15027 | } | |||
| 15028 | ||||
| 15029 | static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, | |||
| 15030 | APValue DestroyedValue, QualType Type, | |||
| 15031 | SourceLocation Loc, Expr::EvalStatus &EStatus, | |||
| 15032 | bool IsConstantDestruction) { | |||
| 15033 | EvalInfo Info(Ctx, EStatus, | |||
| 15034 | IsConstantDestruction ? EvalInfo::EM_ConstantExpression | |||
| 15035 | : EvalInfo::EM_ConstantFold); | |||
| 15036 | Info.setEvaluatingDecl(Base, DestroyedValue, | |||
| 15037 | EvalInfo::EvaluatingDeclKind::Dtor); | |||
| 15038 | Info.InConstantContext = IsConstantDestruction; | |||
| 15039 | ||||
| 15040 | LValue LVal; | |||
| 15041 | LVal.set(Base); | |||
| 15042 | ||||
| 15043 | if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || | |||
| 15044 | EStatus.HasSideEffects) | |||
| 15045 | return false; | |||
| 15046 | ||||
| 15047 | if (!Info.discardCleanups()) | |||
| 15048 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "clang/lib/AST/ExprConstant.cpp", 15048); | |||
| 15049 | ||||
| 15050 | return true; | |||
| 15051 | } | |||
| 15052 | ||||
| 15053 | bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, | |||
| 15054 | ConstantExprKind Kind) const { | |||
| 15055 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15056, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15056 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15056, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15057 | ||||
| 15058 | EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; | |||
| 15059 | EvalInfo Info(Ctx, Result, EM); | |||
| 15060 | Info.InConstantContext = true; | |||
| 15061 | ||||
| 15062 | // The type of the object we're initializing is 'const T' for a class NTTP. | |||
| 15063 | QualType T = getType(); | |||
| 15064 | if (Kind == ConstantExprKind::ClassTemplateArgument) | |||
| 15065 | T.addConst(); | |||
| 15066 | ||||
| 15067 | // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to | |||
| 15068 | // represent the result of the evaluation. CheckConstantExpression ensures | |||
| 15069 | // this doesn't escape. | |||
| 15070 | MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); | |||
| 15071 | APValue::LValueBase Base(&BaseMTE); | |||
| 15072 | ||||
| 15073 | Info.setEvaluatingDecl(Base, Result.Val); | |||
| 15074 | LValue LVal; | |||
| 15075 | LVal.set(Base); | |||
| 15076 | ||||
| 15077 | if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) | |||
| 15078 | return false; | |||
| 15079 | ||||
| 15080 | if (!Info.discardCleanups()) | |||
| 15081 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "clang/lib/AST/ExprConstant.cpp", 15081); | |||
| 15082 | ||||
| 15083 | if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), | |||
| 15084 | Result.Val, Kind)) | |||
| 15085 | return false; | |||
| 15086 | if (!CheckMemoryLeaks(Info)) | |||
| 15087 | return false; | |||
| 15088 | ||||
| 15089 | // If this is a class template argument, it's required to have constant | |||
| 15090 | // destruction too. | |||
| 15091 | if (Kind == ConstantExprKind::ClassTemplateArgument && | |||
| 15092 | (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, | |||
| 15093 | true) || | |||
| 15094 | Result.HasSideEffects)) { | |||
| 15095 | // FIXME: Prefix a note to indicate that the problem is lack of constant | |||
| 15096 | // destruction. | |||
| 15097 | return false; | |||
| 15098 | } | |||
| 15099 | ||||
| 15100 | return true; | |||
| 15101 | } | |||
| 15102 | ||||
| 15103 | bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, | |||
| 15104 | const VarDecl *VD, | |||
| 15105 | SmallVectorImpl<PartialDiagnosticAt> &Notes, | |||
| 15106 | bool IsConstantInitialization) const { | |||
| 15107 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15108, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15108 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15108, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15109 | ||||
| 15110 | // FIXME: Evaluating initializers for large array and record types can cause | |||
| 15111 | // performance problems. Only do so in C++11 for now. | |||
| 15112 | if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && | |||
| 15113 | !Ctx.getLangOpts().CPlusPlus11) | |||
| 15114 | return false; | |||
| 15115 | ||||
| 15116 | Expr::EvalStatus EStatus; | |||
| 15117 | EStatus.Diag = &Notes; | |||
| 15118 | ||||
| 15119 | EvalInfo Info(Ctx, EStatus, | |||
| 15120 | (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) | |||
| 15121 | ? EvalInfo::EM_ConstantExpression | |||
| 15122 | : EvalInfo::EM_ConstantFold); | |||
| 15123 | Info.setEvaluatingDecl(VD, Value); | |||
| 15124 | Info.InConstantContext = IsConstantInitialization; | |||
| 15125 | ||||
| 15126 | SourceLocation DeclLoc = VD->getLocation(); | |||
| 15127 | QualType DeclTy = VD->getType(); | |||
| 15128 | ||||
| 15129 | if (Info.EnableNewConstInterp) { | |||
| 15130 | auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); | |||
| 15131 | if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) | |||
| 15132 | return false; | |||
| 15133 | } else { | |||
| 15134 | LValue LVal; | |||
| 15135 | LVal.set(VD); | |||
| 15136 | ||||
| 15137 | if (!EvaluateInPlace(Value, Info, LVal, this, | |||
| 15138 | /*AllowNonLiteralTypes=*/true) || | |||
| 15139 | EStatus.HasSideEffects) | |||
| 15140 | return false; | |||
| 15141 | ||||
| 15142 | // At this point, any lifetime-extended temporaries are completely | |||
| 15143 | // initialized. | |||
| 15144 | Info.performLifetimeExtension(); | |||
| 15145 | ||||
| 15146 | if (!Info.discardCleanups()) | |||
| 15147 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "clang/lib/AST/ExprConstant.cpp", 15147); | |||
| 15148 | } | |||
| 15149 | return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, | |||
| 15150 | ConstantExprKind::Normal) && | |||
| 15151 | CheckMemoryLeaks(Info); | |||
| 15152 | } | |||
| 15153 | ||||
| 15154 | bool VarDecl::evaluateDestruction( | |||
| 15155 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { | |||
| 15156 | Expr::EvalStatus EStatus; | |||
| 15157 | EStatus.Diag = &Notes; | |||
| 15158 | ||||
| 15159 | // Only treat the destruction as constant destruction if we formally have | |||
| 15160 | // constant initialization (or are usable in a constant expression). | |||
| 15161 | bool IsConstantDestruction = hasConstantInitialization(); | |||
| 15162 | ||||
| 15163 | // Make a copy of the value for the destructor to mutate, if we know it. | |||
| 15164 | // Otherwise, treat the value as default-initialized; if the destructor works | |||
| 15165 | // anyway, then the destruction is constant (and must be essentially empty). | |||
| 15166 | APValue DestroyedValue; | |||
| 15167 | if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) | |||
| 15168 | DestroyedValue = *getEvaluatedValue(); | |||
| 15169 | else if (!getDefaultInitValue(getType(), DestroyedValue)) | |||
| 15170 | return false; | |||
| 15171 | ||||
| 15172 | if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), | |||
| 15173 | getType(), getLocation(), EStatus, | |||
| 15174 | IsConstantDestruction) || | |||
| 15175 | EStatus.HasSideEffects) | |||
| 15176 | return false; | |||
| 15177 | ||||
| 15178 | ensureEvaluatedStmt()->HasConstantDestruction = true; | |||
| 15179 | return true; | |||
| 15180 | } | |||
| 15181 | ||||
| 15182 | /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be | |||
| 15183 | /// constant folded, but discard the result. | |||
| 15184 | bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { | |||
| 15185 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15186, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15186 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15186, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15187 | ||||
| 15188 | EvalResult Result; | |||
| 15189 | return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && | |||
| 15190 | !hasUnacceptableSideEffect(Result, SEK); | |||
| 15191 | } | |||
| 15192 | ||||
| 15193 | APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, | |||
| 15194 | SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | |||
| 15195 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15196, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15196 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15196, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15197 | ||||
| 15198 | EvalResult EVResult; | |||
| 15199 | EVResult.Diag = Diag; | |||
| 15200 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | |||
| 15201 | Info.InConstantContext = true; | |||
| 15202 | ||||
| 15203 | bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); | |||
| 15204 | (void)Result; | |||
| 15205 | assert(Result && "Could not evaluate expression")(static_cast <bool> (Result && "Could not evaluate expression" ) ? void (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "clang/lib/AST/ExprConstant.cpp", 15205, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15206 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")(static_cast <bool> (EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? void (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "clang/lib/AST/ExprConstant.cpp", 15206, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15207 | ||||
| 15208 | return EVResult.Val.getInt(); | |||
| 15209 | } | |||
| 15210 | ||||
| 15211 | APSInt Expr::EvaluateKnownConstIntCheckOverflow( | |||
| 15212 | const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | |||
| 15213 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15214, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15214 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15214, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15215 | ||||
| 15216 | EvalResult EVResult; | |||
| 15217 | EVResult.Diag = Diag; | |||
| 15218 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | |||
| 15219 | Info.InConstantContext = true; | |||
| 15220 | Info.CheckingForUndefinedBehavior = true; | |||
| 15221 | ||||
| 15222 | bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); | |||
| 15223 | (void)Result; | |||
| 15224 | assert(Result && "Could not evaluate expression")(static_cast <bool> (Result && "Could not evaluate expression" ) ? void (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "clang/lib/AST/ExprConstant.cpp", 15224, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15225 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")(static_cast <bool> (EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? void (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "clang/lib/AST/ExprConstant.cpp", 15225, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15226 | ||||
| 15227 | return EVResult.Val.getInt(); | |||
| 15228 | } | |||
| 15229 | ||||
| 15230 | void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { | |||
| 15231 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15232, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15232 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15232, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15233 | ||||
| 15234 | bool IsConst; | |||
| 15235 | EvalResult EVResult; | |||
| 15236 | if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { | |||
| 15237 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | |||
| 15238 | Info.CheckingForUndefinedBehavior = true; | |||
| 15239 | (void)::EvaluateAsRValue(Info, this, EVResult.Val); | |||
| 15240 | } | |||
| 15241 | } | |||
| 15242 | ||||
| 15243 | bool Expr::EvalResult::isGlobalLValue() const { | |||
| 15244 | assert(Val.isLValue())(static_cast <bool> (Val.isLValue()) ? void (0) : __assert_fail ("Val.isLValue()", "clang/lib/AST/ExprConstant.cpp", 15244, __extension__ __PRETTY_FUNCTION__)); | |||
| 15245 | return IsGlobalLValue(Val.getLValueBase()); | |||
| 15246 | } | |||
| 15247 | ||||
| 15248 | /// isIntegerConstantExpr - this recursive routine will test if an expression is | |||
| 15249 | /// an integer constant expression. | |||
| 15250 | ||||
| 15251 | /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, | |||
| 15252 | /// comma, etc | |||
| 15253 | ||||
| 15254 | // CheckICE - This function does the fundamental ICE checking: the returned | |||
| 15255 | // ICEDiag contains an ICEKind indicating whether the expression is an ICE, | |||
| 15256 | // and a (possibly null) SourceLocation indicating the location of the problem. | |||
| 15257 | // | |||
| 15258 | // Note that to reduce code duplication, this helper does no evaluation | |||
| 15259 | // itself; the caller checks whether the expression is evaluatable, and | |||
| 15260 | // in the rare cases where CheckICE actually cares about the evaluated | |||
| 15261 | // value, it calls into Evaluate. | |||
| 15262 | ||||
| 15263 | namespace { | |||
| 15264 | ||||
| 15265 | enum ICEKind { | |||
| 15266 | /// This expression is an ICE. | |||
| 15267 | IK_ICE, | |||
| 15268 | /// This expression is not an ICE, but if it isn't evaluated, it's | |||
| 15269 | /// a legal subexpression for an ICE. This return value is used to handle | |||
| 15270 | /// the comma operator in C99 mode, and non-constant subexpressions. | |||
| 15271 | IK_ICEIfUnevaluated, | |||
| 15272 | /// This expression is not an ICE, and is not a legal subexpression for one. | |||
| 15273 | IK_NotICE | |||
| 15274 | }; | |||
| 15275 | ||||
| 15276 | struct ICEDiag { | |||
| 15277 | ICEKind Kind; | |||
| 15278 | SourceLocation Loc; | |||
| 15279 | ||||
| 15280 | ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} | |||
| 15281 | }; | |||
| 15282 | ||||
| 15283 | } | |||
| 15284 | ||||
| 15285 | static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } | |||
| 15286 | ||||
| 15287 | static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } | |||
| 15288 | ||||
| 15289 | static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { | |||
| 15290 | Expr::EvalResult EVResult; | |||
| 15291 | Expr::EvalStatus Status; | |||
| 15292 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | |||
| 15293 | ||||
| 15294 | Info.InConstantContext = true; | |||
| 15295 | if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || | |||
| 15296 | !EVResult.Val.isInt()) | |||
| 15297 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15298 | ||||
| 15299 | return NoDiag(); | |||
| 15300 | } | |||
| 15301 | ||||
| 15302 | static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { | |||
| 15303 | assert(!E->isValueDependent() && "Should not see value dependent exprs!")(static_cast <bool> (!E->isValueDependent() && "Should not see value dependent exprs!") ? void (0) : __assert_fail ("!E->isValueDependent() && \"Should not see value dependent exprs!\"" , "clang/lib/AST/ExprConstant.cpp", 15303, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15304 | if (!E->getType()->isIntegralOrEnumerationType()) | |||
| 15305 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15306 | ||||
| 15307 | switch (E->getStmtClass()) { | |||
| 15308 | #define ABSTRACT_STMT(Node) | |||
| 15309 | #define STMT(Node, Base) case Expr::Node##Class: | |||
| 15310 | #define EXPR(Node, Base) | |||
| 15311 | #include "clang/AST/StmtNodes.inc" | |||
| 15312 | case Expr::PredefinedExprClass: | |||
| 15313 | case Expr::FloatingLiteralClass: | |||
| 15314 | case Expr::ImaginaryLiteralClass: | |||
| 15315 | case Expr::StringLiteralClass: | |||
| 15316 | case Expr::ArraySubscriptExprClass: | |||
| 15317 | case Expr::MatrixSubscriptExprClass: | |||
| 15318 | case Expr::OMPArraySectionExprClass: | |||
| 15319 | case Expr::OMPArrayShapingExprClass: | |||
| 15320 | case Expr::OMPIteratorExprClass: | |||
| 15321 | case Expr::MemberExprClass: | |||
| 15322 | case Expr::CompoundAssignOperatorClass: | |||
| 15323 | case Expr::CompoundLiteralExprClass: | |||
| 15324 | case Expr::ExtVectorElementExprClass: | |||
| 15325 | case Expr::DesignatedInitExprClass: | |||
| 15326 | case Expr::ArrayInitLoopExprClass: | |||
| 15327 | case Expr::ArrayInitIndexExprClass: | |||
| 15328 | case Expr::NoInitExprClass: | |||
| 15329 | case Expr::DesignatedInitUpdateExprClass: | |||
| 15330 | case Expr::ImplicitValueInitExprClass: | |||
| 15331 | case Expr::ParenListExprClass: | |||
| 15332 | case Expr::VAArgExprClass: | |||
| 15333 | case Expr::AddrLabelExprClass: | |||
| 15334 | case Expr::StmtExprClass: | |||
| 15335 | case Expr::CXXMemberCallExprClass: | |||
| 15336 | case Expr::CUDAKernelCallExprClass: | |||
| 15337 | case Expr::CXXAddrspaceCastExprClass: | |||
| 15338 | case Expr::CXXDynamicCastExprClass: | |||
| 15339 | case Expr::CXXTypeidExprClass: | |||
| 15340 | case Expr::CXXUuidofExprClass: | |||
| 15341 | case Expr::MSPropertyRefExprClass: | |||
| 15342 | case Expr::MSPropertySubscriptExprClass: | |||
| 15343 | case Expr::CXXNullPtrLiteralExprClass: | |||
| 15344 | case Expr::UserDefinedLiteralClass: | |||
| 15345 | case Expr::CXXThisExprClass: | |||
| 15346 | case Expr::CXXThrowExprClass: | |||
| 15347 | case Expr::CXXNewExprClass: | |||
| 15348 | case Expr::CXXDeleteExprClass: | |||
| 15349 | case Expr::CXXPseudoDestructorExprClass: | |||
| 15350 | case Expr::UnresolvedLookupExprClass: | |||
| 15351 | case Expr::TypoExprClass: | |||
| 15352 | case Expr::RecoveryExprClass: | |||
| 15353 | case Expr::DependentScopeDeclRefExprClass: | |||
| 15354 | case Expr::CXXConstructExprClass: | |||
| 15355 | case Expr::CXXInheritedCtorInitExprClass: | |||
| 15356 | case Expr::CXXStdInitializerListExprClass: | |||
| 15357 | case Expr::CXXBindTemporaryExprClass: | |||
| 15358 | case Expr::ExprWithCleanupsClass: | |||
| 15359 | case Expr::CXXTemporaryObjectExprClass: | |||
| 15360 | case Expr::CXXUnresolvedConstructExprClass: | |||
| 15361 | case Expr::CXXDependentScopeMemberExprClass: | |||
| 15362 | case Expr::UnresolvedMemberExprClass: | |||
| 15363 | case Expr::ObjCStringLiteralClass: | |||
| 15364 | case Expr::ObjCBoxedExprClass: | |||
| 15365 | case Expr::ObjCArrayLiteralClass: | |||
| 15366 | case Expr::ObjCDictionaryLiteralClass: | |||
| 15367 | case Expr::ObjCEncodeExprClass: | |||
| 15368 | case Expr::ObjCMessageExprClass: | |||
| 15369 | case Expr::ObjCSelectorExprClass: | |||
| 15370 | case Expr::ObjCProtocolExprClass: | |||
| 15371 | case Expr::ObjCIvarRefExprClass: | |||
| 15372 | case Expr::ObjCPropertyRefExprClass: | |||
| 15373 | case Expr::ObjCSubscriptRefExprClass: | |||
| 15374 | case Expr::ObjCIsaExprClass: | |||
| 15375 | case Expr::ObjCAvailabilityCheckExprClass: | |||
| 15376 | case Expr::ShuffleVectorExprClass: | |||
| 15377 | case Expr::ConvertVectorExprClass: | |||
| 15378 | case Expr::BlockExprClass: | |||
| 15379 | case Expr::NoStmtClass: | |||
| 15380 | case Expr::OpaqueValueExprClass: | |||
| 15381 | case Expr::PackExpansionExprClass: | |||
| 15382 | case Expr::SubstNonTypeTemplateParmPackExprClass: | |||
| 15383 | case Expr::FunctionParmPackExprClass: | |||
| 15384 | case Expr::AsTypeExprClass: | |||
| 15385 | case Expr::ObjCIndirectCopyRestoreExprClass: | |||
| 15386 | case Expr::MaterializeTemporaryExprClass: | |||
| 15387 | case Expr::PseudoObjectExprClass: | |||
| 15388 | case Expr::AtomicExprClass: | |||
| 15389 | case Expr::LambdaExprClass: | |||
| 15390 | case Expr::CXXFoldExprClass: | |||
| 15391 | case Expr::CoawaitExprClass: | |||
| 15392 | case Expr::DependentCoawaitExprClass: | |||
| 15393 | case Expr::CoyieldExprClass: | |||
| 15394 | case Expr::SYCLUniqueStableNameExprClass: | |||
| 15395 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15396 | ||||
| 15397 | case Expr::InitListExprClass: { | |||
| 15398 | // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the | |||
| 15399 | // form "T x = { a };" is equivalent to "T x = a;". | |||
| 15400 | // Unless we're initializing a reference, T is a scalar as it is known to be | |||
| 15401 | // of integral or enumeration type. | |||
| 15402 | if (E->isPRValue()) | |||
| 15403 | if (cast<InitListExpr>(E)->getNumInits() == 1) | |||
| 15404 | return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); | |||
| 15405 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15406 | } | |||
| 15407 | ||||
| 15408 | case Expr::SizeOfPackExprClass: | |||
| 15409 | case Expr::GNUNullExprClass: | |||
| 15410 | case Expr::SourceLocExprClass: | |||
| 15411 | return NoDiag(); | |||
| 15412 | ||||
| 15413 | case Expr::SubstNonTypeTemplateParmExprClass: | |||
| 15414 | return | |||
| 15415 | CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); | |||
| 15416 | ||||
| 15417 | case Expr::ConstantExprClass: | |||
| 15418 | return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); | |||
| 15419 | ||||
| 15420 | case Expr::ParenExprClass: | |||
| 15421 | return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); | |||
| 15422 | case Expr::GenericSelectionExprClass: | |||
| 15423 | return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); | |||
| 15424 | case Expr::IntegerLiteralClass: | |||
| 15425 | case Expr::FixedPointLiteralClass: | |||
| 15426 | case Expr::CharacterLiteralClass: | |||
| 15427 | case Expr::ObjCBoolLiteralExprClass: | |||
| 15428 | case Expr::CXXBoolLiteralExprClass: | |||
| 15429 | case Expr::CXXScalarValueInitExprClass: | |||
| 15430 | case Expr::TypeTraitExprClass: | |||
| 15431 | case Expr::ConceptSpecializationExprClass: | |||
| 15432 | case Expr::RequiresExprClass: | |||
| 15433 | case Expr::ArrayTypeTraitExprClass: | |||
| 15434 | case Expr::ExpressionTraitExprClass: | |||
| 15435 | case Expr::CXXNoexceptExprClass: | |||
| 15436 | return NoDiag(); | |||
| 15437 | case Expr::CallExprClass: | |||
| 15438 | case Expr::CXXOperatorCallExprClass: { | |||
| 15439 | // C99 6.6/3 allows function calls within unevaluated subexpressions of | |||
| 15440 | // constant expressions, but they can never be ICEs because an ICE cannot | |||
| 15441 | // contain an operand of (pointer to) function type. | |||
| 15442 | const CallExpr *CE = cast<CallExpr>(E); | |||
| 15443 | if (CE->getBuiltinCallee()) | |||
| 15444 | return CheckEvalInICE(E, Ctx); | |||
| 15445 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15446 | } | |||
| 15447 | case Expr::CXXRewrittenBinaryOperatorClass: | |||
| 15448 | return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), | |||
| 15449 | Ctx); | |||
| 15450 | case Expr::DeclRefExprClass: { | |||
| 15451 | const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); | |||
| 15452 | if (isa<EnumConstantDecl>(D)) | |||
| 15453 | return NoDiag(); | |||
| 15454 | ||||
| 15455 | // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified | |||
| 15456 | // integer variables in constant expressions: | |||
| 15457 | // | |||
| 15458 | // C++ 7.1.5.1p2 | |||
| 15459 | // A variable of non-volatile const-qualified integral or enumeration | |||
| 15460 | // type initialized by an ICE can be used in ICEs. | |||
| 15461 | // | |||
| 15462 | // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In | |||
| 15463 | // that mode, use of reference variables should not be allowed. | |||
| 15464 | const VarDecl *VD = dyn_cast<VarDecl>(D); | |||
| 15465 | if (VD && VD->isUsableInConstantExpressions(Ctx) && | |||
| 15466 | !VD->getType()->isReferenceType()) | |||
| 15467 | return NoDiag(); | |||
| 15468 | ||||
| 15469 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15470 | } | |||
| 15471 | case Expr::UnaryOperatorClass: { | |||
| 15472 | const UnaryOperator *Exp = cast<UnaryOperator>(E); | |||
| 15473 | switch (Exp->getOpcode()) { | |||
| 15474 | case UO_PostInc: | |||
| 15475 | case UO_PostDec: | |||
| 15476 | case UO_PreInc: | |||
| 15477 | case UO_PreDec: | |||
| 15478 | case UO_AddrOf: | |||
| 15479 | case UO_Deref: | |||
| 15480 | case UO_Coawait: | |||
| 15481 | // C99 6.6/3 allows increment and decrement within unevaluated | |||
| 15482 | // subexpressions of constant expressions, but they can never be ICEs | |||
| 15483 | // because an ICE cannot contain an lvalue operand. | |||
| 15484 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15485 | case UO_Extension: | |||
| 15486 | case UO_LNot: | |||
| 15487 | case UO_Plus: | |||
| 15488 | case UO_Minus: | |||
| 15489 | case UO_Not: | |||
| 15490 | case UO_Real: | |||
| 15491 | case UO_Imag: | |||
| 15492 | return CheckICE(Exp->getSubExpr(), Ctx); | |||
| 15493 | } | |||
| 15494 | llvm_unreachable("invalid unary operator class")::llvm::llvm_unreachable_internal("invalid unary operator class" , "clang/lib/AST/ExprConstant.cpp", 15494); | |||
| 15495 | } | |||
| 15496 | case Expr::OffsetOfExprClass: { | |||
| 15497 | // Note that per C99, offsetof must be an ICE. And AFAIK, using | |||
| 15498 | // EvaluateAsRValue matches the proposed gcc behavior for cases like | |||
| 15499 | // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect | |||
| 15500 | // compliance: we should warn earlier for offsetof expressions with | |||
| 15501 | // array subscripts that aren't ICEs, and if the array subscripts | |||
| 15502 | // are ICEs, the value of the offsetof must be an integer constant. | |||
| 15503 | return CheckEvalInICE(E, Ctx); | |||
| 15504 | } | |||
| 15505 | case Expr::UnaryExprOrTypeTraitExprClass: { | |||
| 15506 | const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); | |||
| 15507 | if ((Exp->getKind() == UETT_SizeOf) && | |||
| 15508 | Exp->getTypeOfArgument()->isVariableArrayType()) | |||
| 15509 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15510 | return NoDiag(); | |||
| 15511 | } | |||
| 15512 | case Expr::BinaryOperatorClass: { | |||
| 15513 | const BinaryOperator *Exp = cast<BinaryOperator>(E); | |||
| 15514 | switch (Exp->getOpcode()) { | |||
| 15515 | case BO_PtrMemD: | |||
| 15516 | case BO_PtrMemI: | |||
| 15517 | case BO_Assign: | |||
| 15518 | case BO_MulAssign: | |||
| 15519 | case BO_DivAssign: | |||
| 15520 | case BO_RemAssign: | |||
| 15521 | case BO_AddAssign: | |||
| 15522 | case BO_SubAssign: | |||
| 15523 | case BO_ShlAssign: | |||
| 15524 | case BO_ShrAssign: | |||
| 15525 | case BO_AndAssign: | |||
| 15526 | case BO_XorAssign: | |||
| 15527 | case BO_OrAssign: | |||
| 15528 | // C99 6.6/3 allows assignments within unevaluated subexpressions of | |||
| 15529 | // constant expressions, but they can never be ICEs because an ICE cannot | |||
| 15530 | // contain an lvalue operand. | |||
| 15531 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15532 | ||||
| 15533 | case BO_Mul: | |||
| 15534 | case BO_Div: | |||
| 15535 | case BO_Rem: | |||
| 15536 | case BO_Add: | |||
| 15537 | case BO_Sub: | |||
| 15538 | case BO_Shl: | |||
| 15539 | case BO_Shr: | |||
| 15540 | case BO_LT: | |||
| 15541 | case BO_GT: | |||
| 15542 | case BO_LE: | |||
| 15543 | case BO_GE: | |||
| 15544 | case BO_EQ: | |||
| 15545 | case BO_NE: | |||
| 15546 | case BO_And: | |||
| 15547 | case BO_Xor: | |||
| 15548 | case BO_Or: | |||
| 15549 | case BO_Comma: | |||
| 15550 | case BO_Cmp: { | |||
| 15551 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | |||
| 15552 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | |||
| 15553 | if (Exp->getOpcode() == BO_Div || | |||
| 15554 | Exp->getOpcode() == BO_Rem) { | |||
| 15555 | // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure | |||
| 15556 | // we don't evaluate one. | |||
| 15557 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { | |||
| 15558 | llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); | |||
| 15559 | if (REval == 0) | |||
| 15560 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | |||
| 15561 | if (REval.isSigned() && REval.isAllOnes()) { | |||
| 15562 | llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); | |||
| 15563 | if (LEval.isMinSignedValue()) | |||
| 15564 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | |||
| 15565 | } | |||
| 15566 | } | |||
| 15567 | } | |||
| 15568 | if (Exp->getOpcode() == BO_Comma) { | |||
| 15569 | if (Ctx.getLangOpts().C99) { | |||
| 15570 | // C99 6.6p3 introduces a strange edge case: comma can be in an ICE | |||
| 15571 | // if it isn't evaluated. | |||
| 15572 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) | |||
| 15573 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | |||
| 15574 | } else { | |||
| 15575 | // In both C89 and C++, commas in ICEs are illegal. | |||
| 15576 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15577 | } | |||
| 15578 | } | |||
| 15579 | return Worst(LHSResult, RHSResult); | |||
| 15580 | } | |||
| 15581 | case BO_LAnd: | |||
| 15582 | case BO_LOr: { | |||
| 15583 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | |||
| 15584 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | |||
| 15585 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { | |||
| 15586 | // Rare case where the RHS has a comma "side-effect"; we need | |||
| 15587 | // to actually check the condition to see whether the side | |||
| 15588 | // with the comma is evaluated. | |||
| 15589 | if ((Exp->getOpcode() == BO_LAnd) != | |||
| 15590 | (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) | |||
| 15591 | return RHSResult; | |||
| 15592 | return NoDiag(); | |||
| 15593 | } | |||
| 15594 | ||||
| 15595 | return Worst(LHSResult, RHSResult); | |||
| 15596 | } | |||
| 15597 | } | |||
| 15598 | llvm_unreachable("invalid binary operator kind")::llvm::llvm_unreachable_internal("invalid binary operator kind" , "clang/lib/AST/ExprConstant.cpp", 15598); | |||
| 15599 | } | |||
| 15600 | case Expr::ImplicitCastExprClass: | |||
| 15601 | case Expr::CStyleCastExprClass: | |||
| 15602 | case Expr::CXXFunctionalCastExprClass: | |||
| 15603 | case Expr::CXXStaticCastExprClass: | |||
| 15604 | case Expr::CXXReinterpretCastExprClass: | |||
| 15605 | case Expr::CXXConstCastExprClass: | |||
| 15606 | case Expr::ObjCBridgedCastExprClass: { | |||
| 15607 | const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); | |||
| 15608 | if (isa<ExplicitCastExpr>(E)) { | |||
| 15609 | if (const FloatingLiteral *FL | |||
| 15610 | = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { | |||
| 15611 | unsigned DestWidth = Ctx.getIntWidth(E->getType()); | |||
| 15612 | bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); | |||
| 15613 | APSInt IgnoredVal(DestWidth, !DestSigned); | |||
| 15614 | bool Ignored; | |||
| 15615 | // If the value does not fit in the destination type, the behavior is | |||
| 15616 | // undefined, so we are not required to treat it as a constant | |||
| 15617 | // expression. | |||
| 15618 | if (FL->getValue().convertToInteger(IgnoredVal, | |||
| 15619 | llvm::APFloat::rmTowardZero, | |||
| 15620 | &Ignored) & APFloat::opInvalidOp) | |||
| 15621 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15622 | return NoDiag(); | |||
| 15623 | } | |||
| 15624 | } | |||
| 15625 | switch (cast<CastExpr>(E)->getCastKind()) { | |||
| 15626 | case CK_LValueToRValue: | |||
| 15627 | case CK_AtomicToNonAtomic: | |||
| 15628 | case CK_NonAtomicToAtomic: | |||
| 15629 | case CK_NoOp: | |||
| 15630 | case CK_IntegralToBoolean: | |||
| 15631 | case CK_IntegralCast: | |||
| 15632 | return CheckICE(SubExpr, Ctx); | |||
| 15633 | default: | |||
| 15634 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15635 | } | |||
| 15636 | } | |||
| 15637 | case Expr::BinaryConditionalOperatorClass: { | |||
| 15638 | const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); | |||
| 15639 | ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); | |||
| 15640 | if (CommonResult.Kind == IK_NotICE) return CommonResult; | |||
| 15641 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | |||
| 15642 | if (FalseResult.Kind == IK_NotICE) return FalseResult; | |||
| 15643 | if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; | |||
| 15644 | if (FalseResult.Kind == IK_ICEIfUnevaluated && | |||
| 15645 | Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); | |||
| 15646 | return FalseResult; | |||
| 15647 | } | |||
| 15648 | case Expr::ConditionalOperatorClass: { | |||
| 15649 | const ConditionalOperator *Exp = cast<ConditionalOperator>(E); | |||
| 15650 | // If the condition (ignoring parens) is a __builtin_constant_p call, | |||
| 15651 | // then only the true side is actually considered in an integer constant | |||
| 15652 | // expression, and it is fully evaluated. This is an important GNU | |||
| 15653 | // extension. See GCC PR38377 for discussion. | |||
| 15654 | if (const CallExpr *CallCE | |||
| 15655 | = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) | |||
| 15656 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | |||
| 15657 | return CheckEvalInICE(E, Ctx); | |||
| 15658 | ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); | |||
| 15659 | if (CondResult.Kind == IK_NotICE) | |||
| 15660 | return CondResult; | |||
| 15661 | ||||
| 15662 | ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); | |||
| 15663 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | |||
| 15664 | ||||
| 15665 | if (TrueResult.Kind == IK_NotICE) | |||
| 15666 | return TrueResult; | |||
| 15667 | if (FalseResult.Kind == IK_NotICE) | |||
| 15668 | return FalseResult; | |||
| 15669 | if (CondResult.Kind == IK_ICEIfUnevaluated) | |||
| 15670 | return CondResult; | |||
| 15671 | if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) | |||
| 15672 | return NoDiag(); | |||
| 15673 | // Rare case where the diagnostics depend on which side is evaluated | |||
| 15674 | // Note that if we get here, CondResult is 0, and at least one of | |||
| 15675 | // TrueResult and FalseResult is non-zero. | |||
| 15676 | if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) | |||
| 15677 | return FalseResult; | |||
| 15678 | return TrueResult; | |||
| 15679 | } | |||
| 15680 | case Expr::CXXDefaultArgExprClass: | |||
| 15681 | return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); | |||
| 15682 | case Expr::CXXDefaultInitExprClass: | |||
| 15683 | return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); | |||
| 15684 | case Expr::ChooseExprClass: { | |||
| 15685 | return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); | |||
| 15686 | } | |||
| 15687 | case Expr::BuiltinBitCastExprClass: { | |||
| 15688 | if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) | |||
| 15689 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | |||
| 15690 | return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); | |||
| 15691 | } | |||
| 15692 | } | |||
| 15693 | ||||
| 15694 | llvm_unreachable("Invalid StmtClass!")::llvm::llvm_unreachable_internal("Invalid StmtClass!", "clang/lib/AST/ExprConstant.cpp" , 15694); | |||
| 15695 | } | |||
| 15696 | ||||
| 15697 | /// Evaluate an expression as a C++11 integral constant expression. | |||
| 15698 | static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, | |||
| 15699 | const Expr *E, | |||
| 15700 | llvm::APSInt *Value, | |||
| 15701 | SourceLocation *Loc) { | |||
| 15702 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
| 15703 | if (Loc) *Loc = E->getExprLoc(); | |||
| 15704 | return false; | |||
| 15705 | } | |||
| 15706 | ||||
| 15707 | APValue Result; | |||
| 15708 | if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) | |||
| 15709 | return false; | |||
| 15710 | ||||
| 15711 | if (!Result.isInt()) { | |||
| 15712 | if (Loc) *Loc = E->getExprLoc(); | |||
| 15713 | return false; | |||
| 15714 | } | |||
| 15715 | ||||
| 15716 | if (Value) *Value = Result.getInt(); | |||
| 15717 | return true; | |||
| 15718 | } | |||
| 15719 | ||||
| 15720 | bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, | |||
| 15721 | SourceLocation *Loc) const { | |||
| 15722 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15723, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15723 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15723, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15724 | ||||
| 15725 | if (Ctx.getLangOpts().CPlusPlus11) | |||
| 15726 | return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); | |||
| 15727 | ||||
| 15728 | ICEDiag D = CheckICE(this, Ctx); | |||
| 15729 | if (D.Kind != IK_ICE) { | |||
| 15730 | if (Loc) *Loc = D.Loc; | |||
| 15731 | return false; | |||
| 15732 | } | |||
| 15733 | return true; | |||
| 15734 | } | |||
| 15735 | ||||
| 15736 | Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, | |||
| 15737 | SourceLocation *Loc, | |||
| 15738 | bool isEvaluated) const { | |||
| 15739 | if (isValueDependent()) { | |||
| 15740 | // Expression evaluator can't succeed on a dependent expression. | |||
| 15741 | return None; | |||
| 15742 | } | |||
| 15743 | ||||
| 15744 | APSInt Value; | |||
| 15745 | ||||
| 15746 | if (Ctx.getLangOpts().CPlusPlus11) { | |||
| 15747 | if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) | |||
| 15748 | return Value; | |||
| 15749 | return None; | |||
| 15750 | } | |||
| 15751 | ||||
| 15752 | if (!isIntegerConstantExpr(Ctx, Loc)) | |||
| 15753 | return None; | |||
| 15754 | ||||
| 15755 | // The only possible side-effects here are due to UB discovered in the | |||
| 15756 | // evaluation (for instance, INT_MAX + 1). In such a case, we are still | |||
| 15757 | // required to treat the expression as an ICE, so we produce the folded | |||
| 15758 | // value. | |||
| 15759 | EvalResult ExprResult; | |||
| 15760 | Expr::EvalStatus Status; | |||
| 15761 | EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); | |||
| 15762 | Info.InConstantContext = true; | |||
| 15763 | ||||
| 15764 | if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) | |||
| 15765 | llvm_unreachable("ICE cannot be evaluated!")::llvm::llvm_unreachable_internal("ICE cannot be evaluated!", "clang/lib/AST/ExprConstant.cpp", 15765); | |||
| 15766 | ||||
| 15767 | return ExprResult.Val.getInt(); | |||
| 15768 | } | |||
| 15769 | ||||
| 15770 | bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { | |||
| 15771 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15772, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15772 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15772, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15773 | ||||
| 15774 | return CheckICE(this, Ctx).Kind == IK_ICE; | |||
| 15775 | } | |||
| 15776 | ||||
| 15777 | bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, | |||
| 15778 | SourceLocation *Loc) const { | |||
| 15779 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15780, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15780 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15780, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15781 | ||||
| 15782 | // We support this checking in C++98 mode in order to diagnose compatibility | |||
| 15783 | // issues. | |||
| 15784 | assert(Ctx.getLangOpts().CPlusPlus)(static_cast <bool> (Ctx.getLangOpts().CPlusPlus) ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus", "clang/lib/AST/ExprConstant.cpp" , 15784, __extension__ __PRETTY_FUNCTION__)); | |||
| 15785 | ||||
| 15786 | // Build evaluation settings. | |||
| 15787 | Expr::EvalStatus Status; | |||
| 15788 | SmallVector<PartialDiagnosticAt, 8> Diags; | |||
| 15789 | Status.Diag = &Diags; | |||
| 15790 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | |||
| 15791 | ||||
| 15792 | APValue Scratch; | |||
| 15793 | bool IsConstExpr = | |||
| 15794 | ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && | |||
| 15795 | // FIXME: We don't produce a diagnostic for this, but the callers that | |||
| 15796 | // call us on arbitrary full-expressions should generally not care. | |||
| 15797 | Info.discardCleanups() && !Status.HasSideEffects; | |||
| 15798 | ||||
| 15799 | if (!Diags.empty()) { | |||
| 15800 | IsConstExpr = false; | |||
| 15801 | if (Loc) *Loc = Diags[0].first; | |||
| 15802 | } else if (!IsConstExpr) { | |||
| 15803 | // FIXME: This shouldn't happen. | |||
| 15804 | if (Loc) *Loc = getExprLoc(); | |||
| 15805 | } | |||
| 15806 | ||||
| 15807 | return IsConstExpr; | |||
| 15808 | } | |||
| 15809 | ||||
| 15810 | bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, | |||
| 15811 | const FunctionDecl *Callee, | |||
| 15812 | ArrayRef<const Expr*> Args, | |||
| 15813 | const Expr *This) const { | |||
| 15814 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15815, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15815 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15815, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15816 | ||||
| 15817 | Expr::EvalStatus Status; | |||
| 15818 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); | |||
| 15819 | Info.InConstantContext = true; | |||
| 15820 | ||||
| 15821 | LValue ThisVal; | |||
| 15822 | const LValue *ThisPtr = nullptr; | |||
| 15823 | if (This) { | |||
| 15824 | #ifndef NDEBUG | |||
| 15825 | auto *MD = dyn_cast<CXXMethodDecl>(Callee); | |||
| 15826 | assert(MD && "Don't provide `this` for non-methods.")(static_cast <bool> (MD && "Don't provide `this` for non-methods." ) ? void (0) : __assert_fail ("MD && \"Don't provide `this` for non-methods.\"" , "clang/lib/AST/ExprConstant.cpp", 15826, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15827 | assert(!MD->isStatic() && "Don't provide `this` for static methods.")(static_cast <bool> (!MD->isStatic() && "Don't provide `this` for static methods." ) ? void (0) : __assert_fail ("!MD->isStatic() && \"Don't provide `this` for static methods.\"" , "clang/lib/AST/ExprConstant.cpp", 15827, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15828 | #endif | |||
| 15829 | if (!This->isValueDependent() && | |||
| 15830 | EvaluateObjectArgument(Info, This, ThisVal) && | |||
| 15831 | !Info.EvalStatus.HasSideEffects) | |||
| 15832 | ThisPtr = &ThisVal; | |||
| 15833 | ||||
| 15834 | // Ignore any side-effects from a failed evaluation. This is safe because | |||
| 15835 | // they can't interfere with any other argument evaluation. | |||
| 15836 | Info.EvalStatus.HasSideEffects = false; | |||
| 15837 | } | |||
| 15838 | ||||
| 15839 | CallRef Call = Info.CurrentCall->createCall(Callee); | |||
| 15840 | for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); | |||
| 15841 | I != E; ++I) { | |||
| 15842 | unsigned Idx = I - Args.begin(); | |||
| 15843 | if (Idx >= Callee->getNumParams()) | |||
| 15844 | break; | |||
| 15845 | const ParmVarDecl *PVD = Callee->getParamDecl(Idx); | |||
| 15846 | if ((*I)->isValueDependent() || | |||
| 15847 | !EvaluateCallArg(PVD, *I, Call, Info) || | |||
| 15848 | Info.EvalStatus.HasSideEffects) { | |||
| 15849 | // If evaluation fails, throw away the argument entirely. | |||
| 15850 | if (APValue *Slot = Info.getParamSlot(Call, PVD)) | |||
| 15851 | *Slot = APValue(); | |||
| 15852 | } | |||
| 15853 | ||||
| 15854 | // Ignore any side-effects from a failed evaluation. This is safe because | |||
| 15855 | // they can't interfere with any other argument evaluation. | |||
| 15856 | Info.EvalStatus.HasSideEffects = false; | |||
| 15857 | } | |||
| 15858 | ||||
| 15859 | // Parameter cleanups happen in the caller and are not part of this | |||
| 15860 | // evaluation. | |||
| 15861 | Info.discardCleanups(); | |||
| 15862 | Info.EvalStatus.HasSideEffects = false; | |||
| 15863 | ||||
| 15864 | // Build fake call to Callee. | |||
| 15865 | CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); | |||
| 15866 | // FIXME: Missing ExprWithCleanups in enable_if conditions? | |||
| 15867 | FullExpressionRAII Scope(Info); | |||
| 15868 | return Evaluate(Value, Info, this) && Scope.destroy() && | |||
| 15869 | !Info.EvalStatus.HasSideEffects; | |||
| 15870 | } | |||
| 15871 | ||||
| 15872 | bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, | |||
| 15873 | SmallVectorImpl< | |||
| 15874 | PartialDiagnosticAt> &Diags) { | |||
| 15875 | // FIXME: It would be useful to check constexpr function templates, but at the | |||
| 15876 | // moment the constant expression evaluator cannot cope with the non-rigorous | |||
| 15877 | // ASTs which we build for dependent expressions. | |||
| 15878 | if (FD->isDependentContext()) | |||
| 15879 | return true; | |||
| 15880 | ||||
| 15881 | Expr::EvalStatus Status; | |||
| 15882 | Status.Diag = &Diags; | |||
| 15883 | ||||
| 15884 | EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); | |||
| 15885 | Info.InConstantContext = true; | |||
| 15886 | Info.CheckingPotentialConstantExpression = true; | |||
| 15887 | ||||
| 15888 | // The constexpr VM attempts to compile all methods to bytecode here. | |||
| 15889 | if (Info.EnableNewConstInterp) { | |||
| 15890 | Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); | |||
| 15891 | return Diags.empty(); | |||
| 15892 | } | |||
| 15893 | ||||
| 15894 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | |||
| 15895 | const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; | |||
| 15896 | ||||
| 15897 | // Fabricate an arbitrary expression on the stack and pretend that it | |||
| 15898 | // is a temporary being used as the 'this' pointer. | |||
| 15899 | LValue This; | |||
| 15900 | ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); | |||
| 15901 | This.set({&VIE, Info.CurrentCall->Index}); | |||
| 15902 | ||||
| 15903 | ArrayRef<const Expr*> Args; | |||
| 15904 | ||||
| 15905 | APValue Scratch; | |||
| 15906 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { | |||
| 15907 | // Evaluate the call as a constant initializer, to allow the construction | |||
| 15908 | // of objects of non-literal types. | |||
| 15909 | Info.setEvaluatingDecl(This.getLValueBase(), Scratch); | |||
| 15910 | HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); | |||
| 15911 | } else { | |||
| 15912 | SourceLocation Loc = FD->getLocation(); | |||
| 15913 | HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, | |||
| 15914 | Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); | |||
| 15915 | } | |||
| 15916 | ||||
| 15917 | return Diags.empty(); | |||
| 15918 | } | |||
| 15919 | ||||
| 15920 | bool Expr::isPotentialConstantExprUnevaluated(Expr *E, | |||
| 15921 | const FunctionDecl *FD, | |||
| 15922 | SmallVectorImpl< | |||
| 15923 | PartialDiagnosticAt> &Diags) { | |||
| 15924 | assert(!E->isValueDependent() &&(static_cast <bool> (!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15925, __extension__ __PRETTY_FUNCTION__ )) | |||
| 15925 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "clang/lib/AST/ExprConstant.cpp", 15925, __extension__ __PRETTY_FUNCTION__ )); | |||
| 15926 | ||||
| 15927 | Expr::EvalStatus Status; | |||
| 15928 | Status.Diag = &Diags; | |||
| 15929 | ||||
| 15930 | EvalInfo Info(FD->getASTContext(), Status, | |||
| 15931 | EvalInfo::EM_ConstantExpressionUnevaluated); | |||
| 15932 | Info.InConstantContext = true; | |||
| 15933 | Info.CheckingPotentialConstantExpression = true; | |||
| 15934 | ||||
| 15935 | // Fabricate a call stack frame to give the arguments a plausible cover story. | |||
| 15936 | CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); | |||
| 15937 | ||||
| 15938 | APValue ResultScratch; | |||
| 15939 | Evaluate(ResultScratch, Info, E); | |||
| 15940 | return Diags.empty(); | |||
| 15941 | } | |||
| 15942 | ||||
| 15943 | bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, | |||
| 15944 | unsigned Type) const { | |||
| 15945 | if (!getType()->isPointerType()) | |||
| 15946 | return false; | |||
| 15947 | ||||
| 15948 | Expr::EvalStatus Status; | |||
| 15949 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); | |||
| 15950 | return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); | |||
| 15951 | } | |||
| 15952 | ||||
| 15953 | static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, | |||
| 15954 | EvalInfo &Info) { | |||
| 15955 | if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) | |||
| 15956 | return false; | |||
| 15957 | ||||
| 15958 | LValue String; | |||
| 15959 | ||||
| 15960 | if (!EvaluatePointer(E, String, Info)) | |||
| 15961 | return false; | |||
| 15962 | ||||
| 15963 | QualType CharTy = E->getType()->getPointeeType(); | |||
| 15964 | ||||
| 15965 | // Fast path: if it's a string literal, search the string value. | |||
| 15966 | if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( | |||
| 15967 | String.getLValueBase().dyn_cast<const Expr *>())) { | |||
| 15968 | StringRef Str = S->getBytes(); | |||
| 15969 | int64_t Off = String.Offset.getQuantity(); | |||
| 15970 | if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && | |||
| 15971 | S->getCharByteWidth() == 1 && | |||
| 15972 | // FIXME: Add fast-path for wchar_t too. | |||
| 15973 | Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { | |||
| 15974 | Str = Str.substr(Off); | |||
| 15975 | ||||
| 15976 | StringRef::size_type Pos = Str.find(0); | |||
| 15977 | if (Pos != StringRef::npos) | |||
| 15978 | Str = Str.substr(0, Pos); | |||
| 15979 | ||||
| 15980 | Result = Str.size(); | |||
| 15981 | return true; | |||
| 15982 | } | |||
| 15983 | ||||
| 15984 | // Fall through to slow path. | |||
| 15985 | } | |||
| 15986 | ||||
| 15987 | // Slow path: scan the bytes of the string looking for the terminating 0. | |||
| 15988 | for (uint64_t Strlen = 0; /**/; ++Strlen) { | |||
| 15989 | APValue Char; | |||
| 15990 | if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || | |||
| 15991 | !Char.isInt()) | |||
| 15992 | return false; | |||
| 15993 | if (!Char.getInt()) { | |||
| 15994 | Result = Strlen; | |||
| 15995 | return true; | |||
| 15996 | } | |||
| 15997 | if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) | |||
| 15998 | return false; | |||
| 15999 | } | |||
| 16000 | } | |||
| 16001 | ||||
| 16002 | bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { | |||
| 16003 | Expr::EvalStatus Status; | |||
| 16004 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); | |||
| 16005 | return EvaluateBuiltinStrLen(this, Result, Info); | |||
| 16006 | } |